PostgreSQL / CockroachDB
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
TypeORM 驱动程序支持 PostgreSQL、CockroachDB 和 Amazon Aurora Postgres。
与 PostgreSQL 兼容的数据库也可通过 postgres 数据源类型在 TypeORM 中使用。
如需使用 YugabyteDB,请参考其 ORM 文档开始使用。请注意,由于 YugabyteDB 不支持部分 PostgreSQL 特性,某些 TypeORM 功能可能会受限。
安装
npm install pg
如需流式传输支持:
npm install pg-query-stream
数据源选项
通用数据源选项请参阅数据源选项。您可使用数据源类型 postgres、cockroachdb 或 aurora-postgres 连接对应数据库。
-
url- 执行连接操作的 URL。请注意,其他数据源选项会覆盖 URL 中设置的参数。 -
host- 数据库主机地址。 -
port- 数据库主机端口。PostgreSQL 默认端口为5432。 -
username- 数据库用户名。 -
password- 数据库密码。 -
database- 数据库名称。 -
schema- 模式名称。默认为 "public"。 -
connectTimeoutMS- 初始连接 PostgreSQL 服务器的超时时间(毫秒)。若设为undefined或0表示无超时限制,默认值为undefined。 -
ssl- 包含 SSL 参数的对象,详见 TLS/SSL。 -
uuidExtension- 生成 UUID 时使用的 PostgreSQL 扩展。默认为uuid-ossp。若uuid-ossp扩展不可用,可改为pgcrypto。 -
poolErrorHandler- 底层连接池触发'error'事件时调用的函数。接收单个参数(错误实例),默认使用warn级别记录日志。 -
maxTransactionRetries- 发生 40001 错误时的最大事务重试次数,默认为 5。 -
logNotifications- 布尔值,控制是否在客户端日志中以info级别记录 PostgreSQL 服务器的通知消息和通知事件(默认:false)。 -
installExtensions- 布尔值,控制是否自动安装必要的 PostgreSQL 扩展(默认:true)。 -
extensions- 需在数据库中安装的额外 PostgreSQL 扩展列表(默认:undefined)。 -
applicationName- 用于在统计和日志中标识连接的字符串(默认:undefined)。 -
parseInt8- 布尔值,控制是否将 64 位整数(int8)解析为 JavaScript 数字。默认情况下int8(bigint)值以字符串形式返回以避免溢出。JavaScript 数字采用 IEEE-754 标准,超过最大安全整数(Number.MAX_SAFE_INTEGER = +2^53)会丢失精度。若需完整 64 位范围,建议直接使用返回的字符串或转换为原生bigint而非启用此选项。
可在 extra 对象中添加额外选项,这些选项将直接传递给客户端库。详见 pg 文档中的连接池和客户端部分。
列类型
postgres 的列类型
int, int2, int4, int8, smallint, integer, bigint, decimal, numeric, real, float, float4, float8, double precision, money, character varying, varchar, character, char, text, citext, hstore, bytea, bit, varbit, bit varying, timetz, timestamptz, timestamp, timestamp without time zone, timestamp with time zone, date, time, time without time zone, time with time zone, interval, bool, boolean, enum, point, line, lseg, box, path, polygon, circle, cidr, inet, macaddr, macaddr8, tsvector, tsquery, uuid, xml, json, jsonb, jsonpath, int4range, int8range, numrange, tsrange, tstzrange, daterange, int4multirange, int8multirange, nummultirange, tsmultirange, tstzmultirange, multidaterange, geometry, geography, cube, ltree, vector, halfvec.
cockroachdb 列类型
array, bool, boolean, bytes, bytea, blob, date, numeric, decimal, dec, float, float4, float8, double precision, real, inet, int, integer, int2, int8, int64, smallint, bigint, interval, string, character varying, character, char, char varying, varchar, text, time, time without time zone, timestamp, timestamptz, timestamp without time zone, timestamp with time zone, json, jsonb, uuid
注意:CockroachDB 将所有数值类型的数据作为 string 返回。但如果省略列类型并将属性定义为 number,ORM 会将字符串通过 parseInt 转换为数字。
向量列
向量列可通过 PostgreSQL 的向量运算符进行相似性搜索:
// L2 distance (Euclidean) - <->
const results = await dataSource.sql`
SELECT id, embedding
FROM post
ORDER BY embedding <-> ${"[1,2,3]"}
LIMIT 5`
// Cosine distance - <=>
const results = await dataSource.sql`
SELECT id, embedding
FROM post
ORDER BY embedding <=> ${"[1,2,3]"}
LIMIT 5`
// Inner product - <#>
const results = await dataSource.sql`
SELECT id, embedding
FROM post
ORDER BY embedding <#> ${"[1,2,3]"}
LIMIT 5`
空间列
TypeORM 的 PostgreSQL 和 CockroachDB 支持使用 GeoJSON 作为交换格式,因此几何列应标记为 object 或 Geometry(或其子类,如 Point),这需要导入 geojson 类型 或使用 TypeORM 内置的 GeoJSON 类型:
import {
Entity,
PrimaryColumn,
Column,
Point,
LineString,
MultiPoint
} from "typeorm"
@Entity()
export class Thing {
@PrimaryColumn()
id: number
@Column("geometry")
point: Point
@Column("geometry")
linestring: LineString
@Column("geometry", {
spatialFeatureType: "MultiPoint",
srid: 4326,
})
multiPointWithSRID: MultiPoint
}
...
const thing = new Thing()
thing.point = {
type: "Point",
coordinates: [116.443987, 39.920843],
}
thing.linestring = {
type: "LineString",
coordinates: [
[-87.623177, 41.881832],
[-90.199402, 38.627003],
[-82.446732, 38.413651],
[-87.623177, 41.881832],
],
}
thing.multiPointWithSRID = {
type: "MultiPoint",
coordinates: [
[100.0, 0.0],
[101.0, 1.0],
],
}
TypeORM 会尝试正确处理,但并非总能确定插入的值或 PostGIS 函数的返回结果是否应视为几何体。因此您可能需要编写类似以下的代码,其中将值从 GeoJSON 转换为 PostGIS 的 geometry 类型,并将结果作为 json 转换为 GeoJSON:
import { Point } from "typeorm"
const origin: Point = {
type: "Point",
coordinates: [0, 0],
}
await dataSource.manager
.createQueryBuilder(Thing, "thing")
// convert stringified GeoJSON into a geometry with an SRID that matches the
// table specification
.where(
"ST_Distance(geom, ST_SetSRID(ST_GeomFromGeoJSON(:origin), ST_SRID(geom))) > 0",
)
.orderBy(
"ST_Distance(geom, ST_SetSRID(ST_GeomFromGeoJSON(:origin), ST_SRID(geom)))",
"ASC",
)
.setParameters({
// stringify GeoJSON
origin: JSON.stringify(origin),
})
.getMany()
await dataSource.manager
.createQueryBuilder(Thing, "thing")
// convert geometry result into GeoJSON, treated as JSON (so that TypeORM
// will know to deserialize it)
.select("ST_AsGeoJSON(ST_Buffer(geom, 0.1))::json geom")
.from("thing")
.getMany()