Drizzle | PostgreSQL의 Point 데이터 타입
This guide assumes familiarity with:
PostgreSQL은 point
라는 이름의 기하학적 데이터를 저장하기 위한 특별한 데이터 타입을 제공합니다. 이 데이터 타입은 2차원 공간에서의 점을 나타내며, (x, y)
좌표 쌍으로 표현됩니다. point
데이터 타입은 경도를 먼저, 그 다음에 위도를 받습니다.
import { sql } from 'drizzle-orm';
const db = drizzle(...);
await db.execute(
sql`select point(-90.9, 18.7)`,
);
[
{
point: '(-90.9,18.7)'
}
]
Drizzle에서 point
데이터 타입을 사용하여 테이블을 생성하는 방법은 다음과 같습니다:
import { pgTable, point, serial, text } from 'drizzle-orm/pg-core';
export const stores = pgTable('stores', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
location: point('location', { mode: 'xy' }).notNull(),
});
Drizzle에서 point
데이터를 테이블에 삽입하는 방법은 다음과 같습니다:
// mode: 'xy'
await db.insert(stores).values({
name: 'Test',
location: { x: -90.9, y: 18.7 },
});
// mode: 'tuple'
await db.insert(stores).values({
name: 'Test',
location: [-90.9, 18.7],
});
// sql raw
await db.insert(stores).values({
name: 'Test',
location: sql`point(-90.9, 18.7)`,
});
객체 간의 거리를 계산하려면 <->
연산자를 사용할 수 있습니다. Drizzle에서 좌표를 기준으로 가장 가까운 위치를 쿼리하는 방법은 다음과 같습니다:
import { getTableColumns, sql } from 'drizzle-orm';
import { stores } from './schema';
const point = {
x: -73.935_242,
y: 40.730_61,
};
const sqlDistance = sql`location point(${point.x}, ${point.y})`;
await db
.select({
...getTableColumns(stores),
distance: sql`round((${sqlDistance})::numeric, 2)`,
})
.from(stores)
.orderBy(sqlDistance)
.limit(1);
select *, round((location point(-73.935242, 40.73061))::numeric, 2)
from stores order by location point(-73.935242, 40.73061)
limit 1;
point
타입의 location
이 두 대각선 점으로 정의된 특정 직사각형 경계 내에 있는 행만 포함하도록 필터링하려면 <@
연산자를 사용할 수 있습니다. 이 연산자는 첫 번째 객체가 두 번째 객체 내부 또는 위에 있는지 확인합니다:
const point = {
x1: -88,
x2: -73,
y1: 40,
y2: 43,
};
await db
.select()
.from(stores)
.where(
sql`${stores.location} <@ box(point(${point.x1}, ${point.y1}), point(${point.x2}, ${point.y2}))`
);
select * from stores where location <@ box(point(-88, 40), point(-73, 43));