Drizzle | PostgreSQL 中的 Point 数据类型

PostgreSQL 有一个特殊的几何数据类型叫做 point。它用于表示二维空间中的一个点。point 数据类型表示为一对 (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));