Postgres / CockroachDB
PostgreSQL、CockroachDB 和 Amazon Aurora Postgres 都被支持为 TypeORM 驱动。
与 PostgreSQL 兼容的数据库也可以通过 postgres 数据源类型与 TypeORM 一起使用。
要使用 YugabyteDB,请参阅他们的 ORM 文档上手。注意,由于 YugabyteDB 不支持某些 Postgres 特性,部分 TypeORM 功能可能会受限。
要使用 Appwrite 托管的 PostgreSQL,请参阅他们的 TypeORM 指南。Appwrite 托管的 PostgreSQL 与标准 Postgres 一样工作,但需要 sslmode=require。
安装
npm install pg如需流式支持:
npm install pg-query-stream数据源选项
通用数据源选项请参阅数据源选项。你可以使用数据源类型 postgres、cockroachdb 或 aurora-postgres 来连接相应的数据库。
url- 建立连接的连接 url。请注意,其他数据源选项会覆盖从 url 中设置的参数。host- 数据库主机。port- 数据库主机端口。Postgres 默认端口是5432。username- 数据库用户名。password- 数据库密码。database- 数据库名。schema- 模式名。默认是 "public"。connectTimeoutMS- 初始连接 postgres 服务器期间发生超时前的毫秒数。如果为undefined或设为0,则没有超时。默认为undefined。ssl- 带 ssl 参数的对象。参见 TLS/SSL。uuidExtension- 生成 UUID 时使用的 Postgres 扩展。默认是uuid-ossp。如果uuid-ossp扩展不可用,可以改成pgcrypto。poolErrorHandler- 当底层连接池触发'error'事件时调用的函数。它接收一个参数(error 实例),默认以warn级别记录日志。maxTransactionRetries- 出现 40001 错误时事务重试的最大次数。默认是 5。logNotifications- 一个布尔值,决定是否把 postgres 服务器的通知消息和通知事件以info级别包含进客户端日志中(默认:false)。installExtensions- 一个布尔值,控制是否自动安装所需的 postgres 扩展(默认:true)extensions- 要在数据库中额外安装的 Postgres 扩展列表(默认:undefined)applicationName- 一个在统计和日志中可见的字符串,用于把某个应用与连接关联起来(默认:undefined)parseInt8- 一个布尔值,启用后会把 64 位整数(int8)解析为 JavaScript number。默认情况下,int8(bigint)值以字符串返回以避免溢出。JavaScript number 是 IEEE-754,超过最大安全整数(Number.MAX_SAFE_INTEGER = +2^53)就会丢失精度。如果你需要完整的 64 位范围,请考虑使用返回的字符串或把它们转换为原生bigint,而不是使用该选项。
更多选项可以加到 extra 对象中,它们会被直接传给客户端库。更多内容见 pg 关于 Pool 和 Client 的文档。
列类型
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 距离(欧氏距离)- <->
const results = await dataSource.sql`
SELECT id, embedding
FROM post
ORDER BY embedding <-> ${"[1,2,3]"}
LIMIT 5`
// 余弦距离 - <=>
const results = await dataSource.sql`
SELECT id, embedding
FROM post
ORDER BY embedding <=> ${"[1,2,3]"}
LIMIT 5`
// 内积 - <#>
const results = await dataSource.sql`
SELECT id, embedding
FROM post
ORDER BY embedding <#> ${"[1,2,3]"}
LIMIT 5`空间列
TypeORM 对 PostgreSQL 和 CockroachDB 的支持使用 GeoJSON 作为交换格式,因此在引入 geojson 类型或使用 TypeORM 内置的 GeoJSON 类型之后,几何列应标记为 object 或 Geometry(或其子类,例如 Point):
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")
// 把字符串化的 GeoJSON 转换为几何体,其 SRID 与
// 表定义相匹配
.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({
// 把 GeoJSON 字符串化
origin: JSON.stringify(origin),
})
.getMany()
await dataSource.manager
.createQueryBuilder(Thing, "thing")
// 把几何体结果转换成 GeoJSON,并当作 JSON 处理(这样 TypeORM
// 才知道要反序列化它)
.select("ST_AsGeoJSON(ST_Buffer(geom, 0.1))::json geom")
.from("thing")
.getMany()PostgreSQL, CockroachDB and Amazon Aurora Postgres are supported as TypeORM drivers.
Databases that are PostgreSQL-compatible can also be used with TypeORM via the postgres data source type.
To use YugabyteDB, refer to their ORM docs to get started. Note that because some Postgres features are not supported by YugabyteDB, some TypeORM functionality may be limited.
To use Appwrite Managed PostgreSQL, refer to their TypeORM guide. Appwrite managed PostgreSQL works as standard Postgres with sslmode=require.
Installation
npm install pgFor streaming support:
npm install pg-query-streamData Source Options
See Data Source Options for the common data source options. You can use the data source type postgres, cockroachdb or aurora-postgres to connect to the respective databases.
url- Connection url where the connection is performed. Please note that other data source options will override parameters set from url.host- Database host.port- Database host port. The default Postgres port is5432.username- Database username.password- Database password.database- Database name.schema- Schema name. Default is "public".connectTimeoutMS- The milliseconds before a timeout occurs during the initial connection to the postgres server. Ifundefined, or set to0, there is no timeout. Defaults toundefined.ssl- Object with ssl parameters. See TLS/SSL.uuidExtension- The Postgres extension to use when generating UUIDs. Defaults touuid-ossp. It can be changed topgcryptoif theuuid-osspextension is unavailable.poolErrorHandler- A function that gets called when the underlying pool emits'error'event. Takes a single parameter (error instance) and defaults to logging withwarnlevel.maxTransactionRetries- A maximum number of transaction retries in case of a 40001 error. Defaults to 5.logNotifications- A boolean to determine whether postgres server notice messages and notification events should be included in client's logs withinfolevel (default:false).installExtensions- A boolean to control whether to install necessary postgres extensions automatically or not (default:true)extensions- List of additional Postgres extensions to be installed in the database (default:undefined)applicationName- A string visible in statistics and logs to help referencing an application to a connection (default:undefined)parseInt8- A boolean to enable parsing 64-bit integers (int8) as JavaScript numbers. By default,int8(bigint) values are returned as strings to avoid overflows. JavaScript numbers are IEEE-754 and lose precision over the maximum safe integer (Number.MAX_SAFE_INTEGER = +2^53). If you require the full 64-bit range consider working with the returned strings or converting them to nativebigintinstead of using this option.
Additional options can be added to the extra object and will be passed directly to the client library. See more in pg's documentation for Pool and Client.
Column Types
Column types for 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.
Column types for 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
Note: CockroachDB returns all numeric data types as string. However, if you omit the column type and define your property as number ORM will parseInt string into number.
Vector columns
Vector columns can be used for similarity searches using PostgreSQL's vector operators:
// 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`Spatial columns
TypeORM's PostgreSQL and CockroachDB support uses GeoJSON as an interchange format, so geometry columns should be tagged either as object or Geometry (or subclasses, e.g. Point) after importing geojson types or using the TypeORM built-in GeoJSON types:
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 tries to do the right thing, but it's not always possible to determine when a value being inserted or the result of a PostGIS function should be treated as a geometry. As a result, you may find yourself writing code similar to the following, where values are converted into PostGIS geometrys from GeoJSON and into GeoJSON as json:
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()