-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathpostgres.ts
More file actions
290 lines (278 loc) · 8.66 KB
/
postgres.ts
File metadata and controls
290 lines (278 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import { types } from 'pg'
import { Expression } from '../expression/expression.js'
import { RawBuilder } from '../raw-builder/raw-builder.js'
import { sql } from '../raw-builder/sql.js'
import {
ShallowDehydrateValue,
ShallowDehydrateObject,
Simplify,
} from '../util/type-utils.js'
/**
* A postgres helper for aggregating a subquery (or other expression) into a JSONB array.
*
* ### Examples
*
* <!-- siteExample("select", "Nested array", 110) -->
*
* While kysely is not an ORM and it doesn't have the concept of relations, we do provide
* helpers for fetching nested objects and arrays in a single query. In this example we
* use the `jsonArrayFrom` helper to fetch person's pets along with the person's id.
*
* Please keep in mind that the helpers under the `kysely/helpers` folder, including
* `jsonArrayFrom`, are not guaranteed to work with third party dialects. In order for
* them to work, the dialect must automatically parse the `json` data type into
* JavaScript JSON values like objects and arrays. Some dialects might simply return
* the data as a JSON string. In these cases you can use the built in `ParseJSONResultsPlugin`
* to parse the results.
*
* ```ts
* import { jsonArrayFrom } from 'kysely/helpers/postgres'
*
* const result = await db
* .selectFrom('person')
* .select((eb) => [
* 'id',
* jsonArrayFrom(
* eb.selectFrom('pet')
* .select(['pet.id as pet_id', 'pet.name'])
* .whereRef('pet.owner_id', '=', 'person.id')
* .orderBy('pet.name')
* ).as('pets')
* ])
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "id", (
* select coalesce(json_agg(agg), '[]') from (
* select "pet"."id" as "pet_id", "pet"."name"
* from "pet"
* where "pet"."owner_id" = "person"."id"
* order by "pet"."name"
* ) as agg
* ) as "pets"
* from "person"
* ```
*/
export function jsonArrayFrom<O>(
expr: Expression<O>,
): RawBuilder<Simplify<ShallowDehydrateObject<O>>[]> {
return sql`(select coalesce(json_agg(agg), '[]') from ${expr} as agg)`
}
/**
* A postgres helper for turning a subquery (or other expression) into a JSON object.
*
* The subquery must only return one row.
*
* ### Examples
*
* <!-- siteExample("select", "Nested object", 120) -->
*
* While kysely is not an ORM and it doesn't have the concept of relations, we do provide
* helpers for fetching nested objects and arrays in a single query. In this example we
* use the `jsonObjectFrom` helper to fetch person's favorite pet along with the person's id.
*
* Please keep in mind that the helpers under the `kysely/helpers` folder, including
* `jsonObjectFrom`, are not guaranteed to work with third-party dialects. In order for
* them to work, the dialect must automatically parse the `json` data type into
* JavaScript JSON values like objects and arrays. Some dialects might simply return
* the data as a JSON string. In these cases you can use the built in `ParseJSONResultsPlugin`
* to parse the results.
*
* ```ts
* import { jsonObjectFrom } from 'kysely/helpers/postgres'
*
* const result = await db
* .selectFrom('person')
* .select((eb) => [
* 'id',
* jsonObjectFrom(
* eb.selectFrom('pet')
* .select(['pet.id as pet_id', 'pet.name'])
* .whereRef('pet.owner_id', '=', 'person.id')
* .where('pet.is_favorite', '=', true)
* ).as('favorite_pet')
* ])
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "id", (
* select to_json(obj) from (
* select "pet"."id" as "pet_id", "pet"."name"
* from "pet"
* where "pet"."owner_id" = "person"."id"
* and "pet"."is_favorite" = $1
* ) as obj
* ) as "favorite_pet"
* from "person"
* ```
*/
export function jsonObjectFrom<O>(
expr: Expression<O>,
): RawBuilder<Simplify<ShallowDehydrateObject<O>> | null> {
return sql`(select to_json(obj) from ${expr} as obj)`
}
/**
* The PostgreSQL `json_build_object` function.
*
* NOTE: This helper is only guaranteed to fully work with the built-in `PostgresDialect`.
* While the produced SQL is compatible with all PostgreSQL databases, some third-party dialects
* may not parse the nested JSON into objects. In these cases you can use the built in
* `ParseJSONResultsPlugin` to parse the results.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
* import { jsonBuildObject } from 'kysely/helpers/postgres'
*
* const result = await db
* .selectFrom('person')
* .select((eb) => [
* 'id',
* jsonBuildObject({
* first: eb.ref('first_name'),
* last: eb.ref('last_name'),
* full: sql<string>`first_name || ' ' || last_name`
* }).as('name')
* ])
* .execute()
*
* result[0]?.id
* result[0]?.name.first
* result[0]?.name.last
* result[0]?.name.full
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "id", json_build_object(
* 'first', first_name,
* 'last', last_name,
* 'full', first_name || ' ' || last_name
* ) as "name"
* from "person"
* ```
*/
export function jsonBuildObject<O extends Record<string, Expression<unknown>>>(
obj: O,
): RawBuilder<
Simplify<{
[K in keyof O]: O[K] extends Expression<infer V>
? ShallowDehydrateValue<V>
: never
}>
> {
return sql`json_build_object(${sql.join(
Object.keys(obj).flatMap((k) => [sql.lit(k), obj[k]]),
)})`
}
export type MergeAction = 'INSERT' | 'UPDATE' | 'DELETE'
/**
* The PostgreSQL `merge_action` function.
*
* This function can be used in a `returning` clause to get the action that was
* performed in a `mergeInto` query. The function returns one of the following
* strings: `'INSERT'`, `'UPDATE'`, or `'DELETE'`.
*
* ### Examples
*
* ```ts
* import { mergeAction } from 'kysely/helpers/postgres'
*
* const result = await db
* .mergeInto('person as p')
* .using('person_backup as pb', 'p.id', 'pb.id')
* .whenMatched()
* .thenUpdateSet(({ ref }) => ({
* first_name: ref('pb.first_name'),
* updated_at: ref('pb.updated_at').$castTo<string | null>(),
* }))
* .whenNotMatched()
* .thenInsertValues(({ ref}) => ({
* id: ref('pb.id'),
* first_name: ref('pb.first_name'),
* created_at: ref('pb.updated_at'),
* updated_at: ref('pb.updated_at').$castTo<string | null>(),
* }))
* .returning([mergeAction().as('action'), 'p.id', 'p.updated_at'])
* .execute()
*
* result[0].action
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person" as "p"
* using "person_backup" as "pb" on "p"."id" = "pb"."id"
* when matched then update set
* "first_name" = "pb"."first_name",
* "updated_at" = "pb"."updated_at"::text
* when not matched then insert values ("id", "first_name", "created_at", "updated_at")
* values ("pb"."id", "pb"."first_name", "pb"."updated_at", "pb"."updated_at")
* returning merge_action() as "action", "p"."id", "p"."updated_at"
* ```
*/
export function mergeAction(): RawBuilder<MergeAction> {
return sql`merge_action()`
}
/**
* We can't use `new Date(v).toISOString()` because `Date` has less precision (milliseconds)
* compared to Postgres' (microseconds). @todo: check, it seems that it truncates fractionals to 3 digits (from 6)
*
* @private
*/
function postgresTimestamptzToIsoString(value: string): string {
/*
Anatomy:
(\d{4}-\d{2}-\d{2}) = Date
\s+ = Space between date and time
(\d{2}:\d{2}:\d{2}\.\d+) = Time (HH:mm:ss.ZZZZZZ)
([+-]\d{2})(:\d{2})? = Timezone offset (+HH[:MM] or -HH[:MM])
Example: 2025-08-10 14:44:40.687342+02
*/
const match = value.match(
/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d+)?([+-]\d{2})(:\d{2})?$/,
)
if (!match) {
throw new Error(`Invalid timestamptz format: ${value}`)
}
const [, date, time, offsetHour, offsetMinute = ':00'] = match
return `${date}T${time}${offsetHour}${offsetMinute}`
}
/**
* We can't use `new Date(v).toISOString()` because `Date` has less precision (milliseconds)
* compared to Postgres' (microseconds).
*
* @private
*/
function postgresTimestampToIsoString(value: string): string {
/*
Anatomy:
(\d{4}-\d{2}-\d{2}) = Date
\s+ = Space between date and time
(\d{2}:\d{2}:\d{2}\.\d+) = Time (HH:mm:ss.ZZZZZZ)
Example: 2025-08-10 14:44:40.687342
*/
const match = value.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d+)?$/)
if (!match) {
throw new Error(`Invalid timestamptz format: ${value}`)
}
const [, date, time] = match
return `${date}T${time}`
}
/**
* @todo: document
*/
export const SENSIBLE_TYPES: Record<number, (value: string) => any> = {
[types.builtins.TIMESTAMPTZ]: (v) => postgresTimestamptzToIsoString(v),
[types.builtins.TIMESTAMP]: (v) => postgresTimestampToIsoString(v),
[types.builtins.DATE]: (v) => v,
}