@coffre/cli 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/access-CO1kGjWW.js +74 -0
- package/dist/connect-BONR52al.js +770 -0
- package/dist/connect-BZdPYNbZ.js +2 -0
- package/dist/esm-B69mMLcR.js +2 -0
- package/dist/esm-Bts-esAl.js +4202 -0
- package/dist/keys-RhB7ayOY.js +726 -0
- package/dist/main.js +10 -137
- package/dist/migrations/postgres/0000_baseline.sql +505 -0
- package/dist/migrations/postgres/meta/0000_snapshot.json +1939 -0
- package/dist/migrations/postgres/meta/_journal.json +13 -0
- package/dist/migrator-W1a-ooWi.js +37 -0
- package/dist/node-postgres-BlNvYfq_.js +2 -0
- package/dist/node-postgres-_y-EeSHQ.js +2831 -0
- package/dist/portable-CPh2thNN.js +87 -0
- package/dist/relations-CJCGPRst.js +2712 -0
- package/dist/schema-sqlite-Byp7B3yI.js +1078 -0
- package/dist/setup-3OJc_VCA.js +756 -0
- package/dist/templates/node/README.md +41 -48
- package/dist/templates/node/package.json +3 -3
- package/dist/templates/node/server.env.example +5 -4
- package/dist/templates/node/src/server.ts +3 -3
- package/dist/templates/node/src/vault.ts +7 -5
- package/dist/templates/node/vault.env.example +7 -7
- package/dist/templates/workers/README.md +47 -57
- package/dist/templates/workers/app/src/worker.ts +2 -2
- package/dist/templates/workers/app/wrangler.jsonc +4 -4
- package/dist/templates/workers/package.json +4 -4
- package/dist/templates/workers/vault/src/worker.ts +8 -7
- package/dist/templates/workers/vault/wrangler.jsonc +8 -6
- package/package.json +7 -4
|
@@ -0,0 +1,2831 @@
|
|
|
1
|
+
import { d as esm_default } from "./esm-Bts-esAl.js";
|
|
2
|
+
import { $ as Subquery, C as PgJsonb, D as PgDateString, E as PgDate, F as haveSameKeys, G as sql, H as SQL, I as isConfig, J as Table, K as Columns, L as mapResultRow, N as getTableColumns, P as getTableLikeName, Q as tracer, R as mapUpdateSet, S as PgNumeric, U as View, V as Param, W as fillPlaceholders, X as getTableUniqueName, Y as getTableName, Z as ViewBaseConfig, _ as PgTimestamp, a as getOperators, b as PgTime, c as normalizeRelation, ct as entityKind, d as eq, et as WithSubquery, h as PgUUID, i as extractTablesRelationalConfig, j as applyMixins, lt as is, n as One, nt as PgColumn, o as getOrderByOperators, p as PgTable, q as Schema, r as createTableRelationsHelpers, s as mapRelationalRow, st as Column, t as Many, u as and, v as PgTimestampString, w as PgJson, z as orderSelectedFields } from "./relations-CJCGPRst.js";
|
|
3
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/logger.js
|
|
4
|
+
var ConsoleLogWriter = class {
|
|
5
|
+
static [entityKind] = "ConsoleLogWriter";
|
|
6
|
+
write(message) {
|
|
7
|
+
console.log(message);
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var DefaultLogger = class {
|
|
11
|
+
static [entityKind] = "DefaultLogger";
|
|
12
|
+
writer;
|
|
13
|
+
constructor(config) {
|
|
14
|
+
this.writer = config?.writer ?? new ConsoleLogWriter();
|
|
15
|
+
}
|
|
16
|
+
logQuery(query, params) {
|
|
17
|
+
const stringifiedParams = params.map((p) => {
|
|
18
|
+
try {
|
|
19
|
+
return JSON.stringify(p);
|
|
20
|
+
} catch {
|
|
21
|
+
return String(p);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
|
|
25
|
+
this.writer.write(`Query: ${query}${paramsStr}`);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
var NoopLogger = class {
|
|
29
|
+
static [entityKind] = "NoopLogger";
|
|
30
|
+
logQuery() {}
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/query-promise.js
|
|
34
|
+
var QueryPromise = class {
|
|
35
|
+
static [entityKind] = "QueryPromise";
|
|
36
|
+
[Symbol.toStringTag] = "QueryPromise";
|
|
37
|
+
catch(onRejected) {
|
|
38
|
+
return this.then(void 0, onRejected);
|
|
39
|
+
}
|
|
40
|
+
finally(onFinally) {
|
|
41
|
+
return this.then((value) => {
|
|
42
|
+
onFinally?.();
|
|
43
|
+
return value;
|
|
44
|
+
}, (reason) => {
|
|
45
|
+
onFinally?.();
|
|
46
|
+
throw reason;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
then(onFulfilled, onRejected) {
|
|
50
|
+
return this.execute().then(onFulfilled, onRejected);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/alias.js
|
|
55
|
+
var ColumnAliasProxyHandler = class {
|
|
56
|
+
constructor(table) {
|
|
57
|
+
this.table = table;
|
|
58
|
+
}
|
|
59
|
+
static [entityKind] = "ColumnAliasProxyHandler";
|
|
60
|
+
get(columnObj, prop) {
|
|
61
|
+
if (prop === "table") return this.table;
|
|
62
|
+
return columnObj[prop];
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
var TableAliasProxyHandler = class {
|
|
66
|
+
constructor(alias, replaceOriginalName) {
|
|
67
|
+
this.alias = alias;
|
|
68
|
+
this.replaceOriginalName = replaceOriginalName;
|
|
69
|
+
}
|
|
70
|
+
static [entityKind] = "TableAliasProxyHandler";
|
|
71
|
+
get(target, prop) {
|
|
72
|
+
if (prop === Table.Symbol.IsAlias) return true;
|
|
73
|
+
if (prop === Table.Symbol.Name) return this.alias;
|
|
74
|
+
if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) return this.alias;
|
|
75
|
+
if (prop === ViewBaseConfig) return {
|
|
76
|
+
...target[ViewBaseConfig],
|
|
77
|
+
name: this.alias,
|
|
78
|
+
isAlias: true
|
|
79
|
+
};
|
|
80
|
+
if (prop === Table.Symbol.Columns) {
|
|
81
|
+
const columns = target[Table.Symbol.Columns];
|
|
82
|
+
if (!columns) return columns;
|
|
83
|
+
const proxiedColumns = {};
|
|
84
|
+
Object.keys(columns).map((key) => {
|
|
85
|
+
proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
|
|
86
|
+
});
|
|
87
|
+
return proxiedColumns;
|
|
88
|
+
}
|
|
89
|
+
const value = target[prop];
|
|
90
|
+
if (is(value, Column)) return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
function aliasedTable(table, tableAlias) {
|
|
95
|
+
return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
|
|
96
|
+
}
|
|
97
|
+
function aliasedTableColumn(column, tableAlias) {
|
|
98
|
+
return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
|
|
99
|
+
}
|
|
100
|
+
function mapColumnsInAliasedSQLToAlias(query, alias) {
|
|
101
|
+
return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
|
|
102
|
+
}
|
|
103
|
+
function mapColumnsInSQLToAlias(query, alias) {
|
|
104
|
+
return sql.join(query.queryChunks.map((c) => {
|
|
105
|
+
if (is(c, Column)) return aliasedTableColumn(c, alias);
|
|
106
|
+
if (is(c, SQL)) return mapColumnsInSQLToAlias(c, alias);
|
|
107
|
+
if (is(c, SQL.Aliased)) return mapColumnsInAliasedSQLToAlias(c, alias);
|
|
108
|
+
return c;
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/selection-proxy.js
|
|
113
|
+
var SelectionProxyHandler = class SelectionProxyHandler {
|
|
114
|
+
static [entityKind] = "SelectionProxyHandler";
|
|
115
|
+
config;
|
|
116
|
+
constructor(config) {
|
|
117
|
+
this.config = { ...config };
|
|
118
|
+
}
|
|
119
|
+
get(subquery, prop) {
|
|
120
|
+
if (prop === "_") return {
|
|
121
|
+
...subquery["_"],
|
|
122
|
+
selectedFields: new Proxy(subquery._.selectedFields, this)
|
|
123
|
+
};
|
|
124
|
+
if (prop === ViewBaseConfig) return {
|
|
125
|
+
...subquery[ViewBaseConfig],
|
|
126
|
+
selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
|
|
127
|
+
};
|
|
128
|
+
if (typeof prop === "symbol") return subquery[prop];
|
|
129
|
+
const value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];
|
|
130
|
+
if (is(value, SQL.Aliased)) {
|
|
131
|
+
if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) return value.sql;
|
|
132
|
+
const newValue = value.clone();
|
|
133
|
+
newValue.isSelectionField = true;
|
|
134
|
+
return newValue;
|
|
135
|
+
}
|
|
136
|
+
if (is(value, SQL)) {
|
|
137
|
+
if (this.config.sqlBehavior === "sql") return value;
|
|
138
|
+
throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
|
|
139
|
+
}
|
|
140
|
+
if (is(value, Column)) {
|
|
141
|
+
if (this.config.alias) return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
144
|
+
if (typeof value !== "object" || value === null) return value;
|
|
145
|
+
return new Proxy(value, new SelectionProxyHandler(this.config));
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/casing.js
|
|
150
|
+
function toSnakeCase(input) {
|
|
151
|
+
return (input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).map((word) => word.toLowerCase()).join("_");
|
|
152
|
+
}
|
|
153
|
+
function toCamelCase(input) {
|
|
154
|
+
return (input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []).reduce((acc, word, i) => {
|
|
155
|
+
return acc + (i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`);
|
|
156
|
+
}, "");
|
|
157
|
+
}
|
|
158
|
+
function noopCase(input) {
|
|
159
|
+
return input;
|
|
160
|
+
}
|
|
161
|
+
var CasingCache = class {
|
|
162
|
+
static [entityKind] = "CasingCache";
|
|
163
|
+
/** @internal */
|
|
164
|
+
cache = {};
|
|
165
|
+
cachedTables = {};
|
|
166
|
+
convert;
|
|
167
|
+
constructor(casing) {
|
|
168
|
+
this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
|
|
169
|
+
}
|
|
170
|
+
getColumnCasing(column) {
|
|
171
|
+
if (!column.keyAsName) return column.name;
|
|
172
|
+
const key = `${column.table[Table.Symbol.Schema] ?? "public"}.${column.table[Table.Symbol.OriginalName]}.${column.name}`;
|
|
173
|
+
if (!this.cache[key]) this.cacheTable(column.table);
|
|
174
|
+
return this.cache[key];
|
|
175
|
+
}
|
|
176
|
+
cacheTable(table) {
|
|
177
|
+
const tableKey = `${table[Table.Symbol.Schema] ?? "public"}.${table[Table.Symbol.OriginalName]}`;
|
|
178
|
+
if (!this.cachedTables[tableKey]) {
|
|
179
|
+
for (const column of Object.values(table[Table.Symbol.Columns])) {
|
|
180
|
+
const columnKey = `${tableKey}.${column.name}`;
|
|
181
|
+
this.cache[columnKey] = this.convert(column.name);
|
|
182
|
+
}
|
|
183
|
+
this.cachedTables[tableKey] = true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
clearCache() {
|
|
187
|
+
this.cache = {};
|
|
188
|
+
this.cachedTables = {};
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/errors.js
|
|
193
|
+
var DrizzleError = class extends Error {
|
|
194
|
+
static [entityKind] = "DrizzleError";
|
|
195
|
+
constructor({ message, cause }) {
|
|
196
|
+
super(message);
|
|
197
|
+
this.name = "DrizzleError";
|
|
198
|
+
this.cause = cause;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
var DrizzleQueryError = class DrizzleQueryError extends Error {
|
|
202
|
+
constructor(query, params, cause) {
|
|
203
|
+
super(`Failed query: ${query}
|
|
204
|
+
params: ${params}`);
|
|
205
|
+
this.query = query;
|
|
206
|
+
this.params = params;
|
|
207
|
+
this.cause = cause;
|
|
208
|
+
Error.captureStackTrace(this, DrizzleQueryError);
|
|
209
|
+
if (cause) this.cause = cause;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
var TransactionRollbackError = class extends DrizzleError {
|
|
213
|
+
static [entityKind] = "TransactionRollbackError";
|
|
214
|
+
constructor() {
|
|
215
|
+
super({ message: "Rollback" });
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/view-base.js
|
|
220
|
+
var PgViewBase = class extends View {
|
|
221
|
+
static [entityKind] = "PgViewBase";
|
|
222
|
+
};
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/dialect.js
|
|
225
|
+
var PgDialect = class {
|
|
226
|
+
static [entityKind] = "PgDialect";
|
|
227
|
+
/** @internal */
|
|
228
|
+
casing;
|
|
229
|
+
constructor(config) {
|
|
230
|
+
this.casing = new CasingCache(config?.casing);
|
|
231
|
+
}
|
|
232
|
+
async migrate(migrations, session, config) {
|
|
233
|
+
const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
|
|
234
|
+
const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
|
|
235
|
+
const migrationTableCreate = sql`
|
|
236
|
+
CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
|
|
237
|
+
id SERIAL PRIMARY KEY,
|
|
238
|
+
hash text NOT NULL,
|
|
239
|
+
created_at bigint
|
|
240
|
+
)
|
|
241
|
+
`;
|
|
242
|
+
await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
|
|
243
|
+
await session.execute(migrationTableCreate);
|
|
244
|
+
const lastDbMigration = (await session.all(sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`))[0];
|
|
245
|
+
await session.transaction(async (tx) => {
|
|
246
|
+
for await (const migration of migrations) if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
|
|
247
|
+
for (const stmt of migration.sql) await tx.execute(sql.raw(stmt));
|
|
248
|
+
await tx.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
escapeName(name) {
|
|
253
|
+
return `"${name.replace(/"/g, "\"\"")}"`;
|
|
254
|
+
}
|
|
255
|
+
escapeParam(num) {
|
|
256
|
+
return `$${num + 1}`;
|
|
257
|
+
}
|
|
258
|
+
escapeString(str) {
|
|
259
|
+
return `'${str.replace(/'/g, "''")}'`;
|
|
260
|
+
}
|
|
261
|
+
buildWithCTE(queries) {
|
|
262
|
+
if (!queries?.length) return void 0;
|
|
263
|
+
const withSqlChunks = [sql`with `];
|
|
264
|
+
for (const [i, w] of queries.entries()) {
|
|
265
|
+
withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
|
|
266
|
+
if (i < queries.length - 1) withSqlChunks.push(sql`, `);
|
|
267
|
+
}
|
|
268
|
+
withSqlChunks.push(sql` `);
|
|
269
|
+
return sql.join(withSqlChunks);
|
|
270
|
+
}
|
|
271
|
+
buildDeleteQuery({ table, where, returning, withList }) {
|
|
272
|
+
const withSql = this.buildWithCTE(withList);
|
|
273
|
+
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
|
|
274
|
+
const whereSql = where ? sql` where ${where}` : void 0;
|
|
275
|
+
return sql`${withSql}delete from ${table}${whereSql}${returningSql}`;
|
|
276
|
+
}
|
|
277
|
+
buildUpdateSet(table, set) {
|
|
278
|
+
const tableColumns = table[Table.Symbol.Columns];
|
|
279
|
+
const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0);
|
|
280
|
+
const setSize = columnNames.length;
|
|
281
|
+
return sql.join(columnNames.flatMap((colName, i) => {
|
|
282
|
+
const col = tableColumns[colName];
|
|
283
|
+
const onUpdateFnResult = col.onUpdateFn?.();
|
|
284
|
+
const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));
|
|
285
|
+
const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
|
|
286
|
+
if (i < setSize - 1) return [res, sql.raw(", ")];
|
|
287
|
+
return [res];
|
|
288
|
+
}));
|
|
289
|
+
}
|
|
290
|
+
buildUpdateQuery({ table, set, where, returning, withList, from, joins }) {
|
|
291
|
+
const withSql = this.buildWithCTE(withList);
|
|
292
|
+
const tableName = table[PgTable.Symbol.Name];
|
|
293
|
+
const tableSchema = table[PgTable.Symbol.Schema];
|
|
294
|
+
const origTableName = table[PgTable.Symbol.OriginalName];
|
|
295
|
+
const alias = tableName === origTableName ? void 0 : tableName;
|
|
296
|
+
const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
|
|
297
|
+
const setSql = this.buildUpdateSet(table, set);
|
|
298
|
+
const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
|
|
299
|
+
const joinsSql = this.buildJoins(joins);
|
|
300
|
+
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
|
|
301
|
+
const whereSql = where ? sql` where ${where}` : void 0;
|
|
302
|
+
return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Builds selection SQL with provided fields/expressions
|
|
306
|
+
*
|
|
307
|
+
* Examples:
|
|
308
|
+
*
|
|
309
|
+
* `select <selection> from`
|
|
310
|
+
*
|
|
311
|
+
* `insert ... returning <selection>`
|
|
312
|
+
*
|
|
313
|
+
* If `isSingleTable` is true, then columns won't be prefixed with table name
|
|
314
|
+
*/
|
|
315
|
+
buildSelection(fields, { isSingleTable = false } = {}) {
|
|
316
|
+
const columnsLen = fields.length;
|
|
317
|
+
const chunks = fields.flatMap(({ field }, i) => {
|
|
318
|
+
const chunk = [];
|
|
319
|
+
if (is(field, SQL.Aliased) && field.isSelectionField) chunk.push(sql.identifier(field.fieldAlias));
|
|
320
|
+
else if (is(field, SQL.Aliased) || is(field, SQL)) {
|
|
321
|
+
const query = is(field, SQL.Aliased) ? field.sql : field;
|
|
322
|
+
if (isSingleTable) chunk.push(new SQL(query.queryChunks.map((c) => {
|
|
323
|
+
if (is(c, PgColumn)) return sql.identifier(this.casing.getColumnCasing(c));
|
|
324
|
+
return c;
|
|
325
|
+
})));
|
|
326
|
+
else chunk.push(query);
|
|
327
|
+
if (is(field, SQL.Aliased)) chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
|
|
328
|
+
} else if (is(field, Column)) {
|
|
329
|
+
if (isSingleTable) chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
|
|
330
|
+
else chunk.push(field);
|
|
331
|
+
} else if (is(field, Subquery)) {
|
|
332
|
+
const entries = Object.entries(field._.selectedFields);
|
|
333
|
+
if (entries.length === 1) {
|
|
334
|
+
const entry = entries[0][1];
|
|
335
|
+
const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: (v) => entry.mapFromDriverValue(v) } : entry.sql.decoder;
|
|
336
|
+
if (fieldDecoder) field._.sql.decoder = fieldDecoder;
|
|
337
|
+
}
|
|
338
|
+
chunk.push(field);
|
|
339
|
+
}
|
|
340
|
+
if (i < columnsLen - 1) chunk.push(sql`, `);
|
|
341
|
+
return chunk;
|
|
342
|
+
});
|
|
343
|
+
return sql.join(chunks);
|
|
344
|
+
}
|
|
345
|
+
buildJoins(joins) {
|
|
346
|
+
if (!joins || joins.length === 0) return;
|
|
347
|
+
const joinsArray = [];
|
|
348
|
+
for (const [index, joinMeta] of joins.entries()) {
|
|
349
|
+
if (index === 0) joinsArray.push(sql` `);
|
|
350
|
+
const table = joinMeta.table;
|
|
351
|
+
const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
|
|
352
|
+
const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
|
|
353
|
+
if (is(table, PgTable)) {
|
|
354
|
+
const tableName = table[PgTable.Symbol.Name];
|
|
355
|
+
const tableSchema = table[PgTable.Symbol.Schema];
|
|
356
|
+
const origTableName = table[PgTable.Symbol.OriginalName];
|
|
357
|
+
const alias = tableName === origTableName ? void 0 : joinMeta.alias;
|
|
358
|
+
joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
|
|
359
|
+
} else if (is(table, View)) {
|
|
360
|
+
const viewName = table[ViewBaseConfig].name;
|
|
361
|
+
const viewSchema = table[ViewBaseConfig].schema;
|
|
362
|
+
const origViewName = table[ViewBaseConfig].originalName;
|
|
363
|
+
const alias = viewName === origViewName ? void 0 : joinMeta.alias;
|
|
364
|
+
joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);
|
|
365
|
+
} else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`);
|
|
366
|
+
if (index < joins.length - 1) joinsArray.push(sql` `);
|
|
367
|
+
}
|
|
368
|
+
return sql.join(joinsArray);
|
|
369
|
+
}
|
|
370
|
+
buildFromTable(table) {
|
|
371
|
+
if (is(table, Table) && table[Table.Symbol.IsAlias]) {
|
|
372
|
+
let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;
|
|
373
|
+
if (table[Table.Symbol.Schema]) fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;
|
|
374
|
+
return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;
|
|
375
|
+
}
|
|
376
|
+
return table;
|
|
377
|
+
}
|
|
378
|
+
buildSelectQuery({ withList, fields, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, lockingClause, distinct, setOperators }) {
|
|
379
|
+
const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
|
|
380
|
+
for (const f of fieldsList) if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) {
|
|
381
|
+
const tableName = getTableName(f.field.table);
|
|
382
|
+
throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
|
|
383
|
+
}
|
|
384
|
+
const isSingleTable = !joins || joins.length === 0;
|
|
385
|
+
const withSql = this.buildWithCTE(withList);
|
|
386
|
+
let distinctSql;
|
|
387
|
+
if (distinct) distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
|
|
388
|
+
const selection = this.buildSelection(fieldsList, { isSingleTable });
|
|
389
|
+
const tableSql = this.buildFromTable(table);
|
|
390
|
+
const joinsSql = this.buildJoins(joins);
|
|
391
|
+
const whereSql = where ? sql` where ${where}` : void 0;
|
|
392
|
+
const havingSql = having ? sql` having ${having}` : void 0;
|
|
393
|
+
let orderBySql;
|
|
394
|
+
if (orderBy && orderBy.length > 0) orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
|
|
395
|
+
let groupBySql;
|
|
396
|
+
if (groupBy && groupBy.length > 0) groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
|
|
397
|
+
const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
|
|
398
|
+
const offsetSql = offset ? sql` offset ${offset}` : void 0;
|
|
399
|
+
const lockingClauseSql = sql.empty();
|
|
400
|
+
if (lockingClause) {
|
|
401
|
+
const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
|
|
402
|
+
if (lockingClause.config.of) clauseSql.append(sql` of ${sql.join(Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], sql`, `)}`);
|
|
403
|
+
if (lockingClause.config.noWait) clauseSql.append(sql` nowait`);
|
|
404
|
+
else if (lockingClause.config.skipLocked) clauseSql.append(sql` skip locked`);
|
|
405
|
+
lockingClauseSql.append(clauseSql);
|
|
406
|
+
}
|
|
407
|
+
const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
|
|
408
|
+
if (setOperators.length > 0) return this.buildSetOperations(finalQuery, setOperators);
|
|
409
|
+
return finalQuery;
|
|
410
|
+
}
|
|
411
|
+
buildSetOperations(leftSelect, setOperators) {
|
|
412
|
+
const [setOperator, ...rest] = setOperators;
|
|
413
|
+
if (!setOperator) throw new Error("Cannot pass undefined values to any set operator");
|
|
414
|
+
if (rest.length === 0) return this.buildSetOperationQuery({
|
|
415
|
+
leftSelect,
|
|
416
|
+
setOperator
|
|
417
|
+
});
|
|
418
|
+
return this.buildSetOperations(this.buildSetOperationQuery({
|
|
419
|
+
leftSelect,
|
|
420
|
+
setOperator
|
|
421
|
+
}), rest);
|
|
422
|
+
}
|
|
423
|
+
buildSetOperationQuery({ leftSelect, setOperator: { type, isAll, rightSelect, limit, orderBy, offset } }) {
|
|
424
|
+
const leftChunk = sql`(${leftSelect.getSQL()}) `;
|
|
425
|
+
const rightChunk = sql`(${rightSelect.getSQL()})`;
|
|
426
|
+
let orderBySql;
|
|
427
|
+
if (orderBy && orderBy.length > 0) {
|
|
428
|
+
const orderByValues = [];
|
|
429
|
+
for (const singleOrderBy of orderBy) if (is(singleOrderBy, PgColumn)) orderByValues.push(sql.identifier(singleOrderBy.name));
|
|
430
|
+
else if (is(singleOrderBy, SQL)) {
|
|
431
|
+
for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
|
|
432
|
+
const chunk = singleOrderBy.queryChunks[i];
|
|
433
|
+
if (is(chunk, PgColumn)) singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
|
|
434
|
+
}
|
|
435
|
+
orderByValues.push(sql`${singleOrderBy}`);
|
|
436
|
+
} else orderByValues.push(sql`${singleOrderBy}`);
|
|
437
|
+
orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
|
|
438
|
+
}
|
|
439
|
+
const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
|
|
440
|
+
const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
|
|
441
|
+
const offsetSql = offset ? sql` offset ${offset}` : void 0;
|
|
442
|
+
return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
|
|
443
|
+
}
|
|
444
|
+
buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
|
|
445
|
+
const valuesSqlList = [];
|
|
446
|
+
const columns = table[Table.Symbol.Columns];
|
|
447
|
+
const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
|
|
448
|
+
const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
|
|
449
|
+
if (select) {
|
|
450
|
+
const select2 = valuesOrSelect;
|
|
451
|
+
if (is(select2, SQL)) valuesSqlList.push(select2);
|
|
452
|
+
else valuesSqlList.push(select2.getSQL());
|
|
453
|
+
} else {
|
|
454
|
+
const values = valuesOrSelect;
|
|
455
|
+
valuesSqlList.push(sql.raw("values "));
|
|
456
|
+
for (const [valueIndex, value] of values.entries()) {
|
|
457
|
+
const valueList = [];
|
|
458
|
+
for (const [fieldName, col] of colEntries) {
|
|
459
|
+
const colValue = value[fieldName];
|
|
460
|
+
if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
|
|
461
|
+
if (col.defaultFn !== void 0) {
|
|
462
|
+
const defaultFnResult = col.defaultFn();
|
|
463
|
+
const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
|
|
464
|
+
valueList.push(defaultValue);
|
|
465
|
+
} else if (!col.default && col.onUpdateFn !== void 0) {
|
|
466
|
+
const onUpdateFnResult = col.onUpdateFn();
|
|
467
|
+
const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
|
|
468
|
+
valueList.push(newValue);
|
|
469
|
+
} else valueList.push(sql`default`);
|
|
470
|
+
} else valueList.push(colValue);
|
|
471
|
+
}
|
|
472
|
+
valuesSqlList.push(valueList);
|
|
473
|
+
if (valueIndex < values.length - 1) valuesSqlList.push(sql`, `);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const withSql = this.buildWithCTE(withList);
|
|
477
|
+
const valuesSql = sql.join(valuesSqlList);
|
|
478
|
+
const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
|
|
479
|
+
const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
|
|
480
|
+
const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0;
|
|
481
|
+
return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
|
|
482
|
+
}
|
|
483
|
+
buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {
|
|
484
|
+
const concurrentlySql = concurrently ? sql` concurrently` : void 0;
|
|
485
|
+
const withNoDataSql = withNoData ? sql` with no data` : void 0;
|
|
486
|
+
return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;
|
|
487
|
+
}
|
|
488
|
+
prepareTyping(encoder) {
|
|
489
|
+
if (is(encoder, PgJsonb) || is(encoder, PgJson)) return "json";
|
|
490
|
+
else if (is(encoder, PgNumeric)) return "decimal";
|
|
491
|
+
else if (is(encoder, PgTime)) return "time";
|
|
492
|
+
else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) return "timestamp";
|
|
493
|
+
else if (is(encoder, PgDate) || is(encoder, PgDateString)) return "date";
|
|
494
|
+
else if (is(encoder, PgUUID)) return "uuid";
|
|
495
|
+
else return "none";
|
|
496
|
+
}
|
|
497
|
+
sqlToQuery(sql2, invokeSource) {
|
|
498
|
+
return sql2.toQuery({
|
|
499
|
+
casing: this.casing,
|
|
500
|
+
escapeName: this.escapeName,
|
|
501
|
+
escapeParam: this.escapeParam,
|
|
502
|
+
escapeString: this.escapeString,
|
|
503
|
+
prepareTyping: this.prepareTyping,
|
|
504
|
+
invokeSource
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
buildRelationalQueryWithoutPK({ fullSchema, schema, tableNamesMap, table, tableConfig, queryConfig: config, tableAlias, nestedQueryRelation, joinOn }) {
|
|
508
|
+
let selection = [];
|
|
509
|
+
let limit, offset, orderBy = [], where;
|
|
510
|
+
const joins = [];
|
|
511
|
+
if (config === true) selection = Object.entries(tableConfig.columns).map(([key, value]) => ({
|
|
512
|
+
dbKey: value.name,
|
|
513
|
+
tsKey: key,
|
|
514
|
+
field: aliasedTableColumn(value, tableAlias),
|
|
515
|
+
relationTableTsKey: void 0,
|
|
516
|
+
isJson: false,
|
|
517
|
+
selection: []
|
|
518
|
+
}));
|
|
519
|
+
else {
|
|
520
|
+
const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
|
|
521
|
+
if (config.where) {
|
|
522
|
+
const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
|
|
523
|
+
where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
|
|
524
|
+
}
|
|
525
|
+
const fieldsSelection = [];
|
|
526
|
+
let selectedColumns = [];
|
|
527
|
+
if (config.columns) {
|
|
528
|
+
let isIncludeMode = false;
|
|
529
|
+
for (const [field, value] of Object.entries(config.columns)) {
|
|
530
|
+
if (value === void 0) continue;
|
|
531
|
+
if (field in tableConfig.columns) {
|
|
532
|
+
if (!isIncludeMode && value === true) isIncludeMode = true;
|
|
533
|
+
selectedColumns.push(field);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (selectedColumns.length > 0) selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
|
|
537
|
+
} else selectedColumns = Object.keys(tableConfig.columns);
|
|
538
|
+
for (const field of selectedColumns) {
|
|
539
|
+
const column = tableConfig.columns[field];
|
|
540
|
+
fieldsSelection.push({
|
|
541
|
+
tsKey: field,
|
|
542
|
+
value: column
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
let selectedRelations = [];
|
|
546
|
+
if (config.with) selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({
|
|
547
|
+
tsKey,
|
|
548
|
+
queryConfig,
|
|
549
|
+
relation: tableConfig.relations[tsKey]
|
|
550
|
+
}));
|
|
551
|
+
let extras;
|
|
552
|
+
if (config.extras) {
|
|
553
|
+
extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
|
|
554
|
+
for (const [tsKey, value] of Object.entries(extras)) fieldsSelection.push({
|
|
555
|
+
tsKey,
|
|
556
|
+
value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
for (const { tsKey, value } of fieldsSelection) selection.push({
|
|
560
|
+
dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
|
|
561
|
+
tsKey,
|
|
562
|
+
field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
|
|
563
|
+
relationTableTsKey: void 0,
|
|
564
|
+
isJson: false,
|
|
565
|
+
selection: []
|
|
566
|
+
});
|
|
567
|
+
let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
|
|
568
|
+
if (!Array.isArray(orderByOrig)) orderByOrig = [orderByOrig];
|
|
569
|
+
orderBy = orderByOrig.map((orderByValue) => {
|
|
570
|
+
if (is(orderByValue, Column)) return aliasedTableColumn(orderByValue, tableAlias);
|
|
571
|
+
return mapColumnsInSQLToAlias(orderByValue, tableAlias);
|
|
572
|
+
});
|
|
573
|
+
limit = config.limit;
|
|
574
|
+
offset = config.offset;
|
|
575
|
+
for (const { tsKey: selectedRelationTsKey, queryConfig: selectedRelationConfigValue, relation } of selectedRelations) {
|
|
576
|
+
const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
|
|
577
|
+
const relationTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
|
|
578
|
+
const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
|
|
579
|
+
const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
|
|
580
|
+
const builtRelation = this.buildRelationalQueryWithoutPK({
|
|
581
|
+
fullSchema,
|
|
582
|
+
schema,
|
|
583
|
+
tableNamesMap,
|
|
584
|
+
table: fullSchema[relationTableTsName],
|
|
585
|
+
tableConfig: schema[relationTableTsName],
|
|
586
|
+
queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : {
|
|
587
|
+
...selectedRelationConfigValue,
|
|
588
|
+
limit: 1
|
|
589
|
+
} : selectedRelationConfigValue,
|
|
590
|
+
tableAlias: relationTableAlias,
|
|
591
|
+
joinOn: joinOn2,
|
|
592
|
+
nestedQueryRelation: relation
|
|
593
|
+
});
|
|
594
|
+
const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
|
|
595
|
+
joins.push({
|
|
596
|
+
on: sql`true`,
|
|
597
|
+
table: new Subquery(builtRelation.sql, {}, relationTableAlias),
|
|
598
|
+
alias: relationTableAlias,
|
|
599
|
+
joinType: "left",
|
|
600
|
+
lateral: true
|
|
601
|
+
});
|
|
602
|
+
selection.push({
|
|
603
|
+
dbKey: selectedRelationTsKey,
|
|
604
|
+
tsKey: selectedRelationTsKey,
|
|
605
|
+
field,
|
|
606
|
+
relationTableTsKey: relationTableTsName,
|
|
607
|
+
isJson: true,
|
|
608
|
+
selection: builtRelation.selection
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (selection.length === 0) throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
|
|
613
|
+
let result;
|
|
614
|
+
where = and(joinOn, where);
|
|
615
|
+
if (nestedQueryRelation) {
|
|
616
|
+
let field = sql`json_build_array(${sql.join(selection.map(({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
|
|
617
|
+
if (is(nestedQueryRelation, Many)) field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
|
|
618
|
+
const nestedSelection = [{
|
|
619
|
+
dbKey: "data",
|
|
620
|
+
tsKey: "data",
|
|
621
|
+
field: field.as("data"),
|
|
622
|
+
isJson: true,
|
|
623
|
+
relationTableTsKey: tableConfig.tsName,
|
|
624
|
+
selection
|
|
625
|
+
}];
|
|
626
|
+
if (limit !== void 0 || offset !== void 0 || orderBy.length > 0) {
|
|
627
|
+
result = this.buildSelectQuery({
|
|
628
|
+
table: aliasedTable(table, tableAlias),
|
|
629
|
+
fields: {},
|
|
630
|
+
fieldsFlat: [{
|
|
631
|
+
path: [],
|
|
632
|
+
field: sql.raw("*")
|
|
633
|
+
}],
|
|
634
|
+
where,
|
|
635
|
+
limit,
|
|
636
|
+
offset,
|
|
637
|
+
orderBy,
|
|
638
|
+
setOperators: []
|
|
639
|
+
});
|
|
640
|
+
where = void 0;
|
|
641
|
+
limit = void 0;
|
|
642
|
+
offset = void 0;
|
|
643
|
+
orderBy = [];
|
|
644
|
+
} else result = aliasedTable(table, tableAlias);
|
|
645
|
+
result = this.buildSelectQuery({
|
|
646
|
+
table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
|
|
647
|
+
fields: {},
|
|
648
|
+
fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
|
|
649
|
+
path: [],
|
|
650
|
+
field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
|
|
651
|
+
})),
|
|
652
|
+
joins,
|
|
653
|
+
where,
|
|
654
|
+
limit,
|
|
655
|
+
offset,
|
|
656
|
+
orderBy,
|
|
657
|
+
setOperators: []
|
|
658
|
+
});
|
|
659
|
+
} else result = this.buildSelectQuery({
|
|
660
|
+
table: aliasedTable(table, tableAlias),
|
|
661
|
+
fields: {},
|
|
662
|
+
fieldsFlat: selection.map(({ field }) => ({
|
|
663
|
+
path: [],
|
|
664
|
+
field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
|
|
665
|
+
})),
|
|
666
|
+
joins,
|
|
667
|
+
where,
|
|
668
|
+
limit,
|
|
669
|
+
offset,
|
|
670
|
+
orderBy,
|
|
671
|
+
setOperators: []
|
|
672
|
+
});
|
|
673
|
+
return {
|
|
674
|
+
tableTsKey: tableConfig.tsName,
|
|
675
|
+
sql: result,
|
|
676
|
+
selection
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
//#endregion
|
|
681
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/query-builders/query-builder.js
|
|
682
|
+
var TypedQueryBuilder = class {
|
|
683
|
+
static [entityKind] = "TypedQueryBuilder";
|
|
684
|
+
/** @internal */
|
|
685
|
+
getSelectedFields() {
|
|
686
|
+
return this._.selectedFields;
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
//#endregion
|
|
690
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/select.js
|
|
691
|
+
var PgSelectBuilder = class {
|
|
692
|
+
static [entityKind] = "PgSelectBuilder";
|
|
693
|
+
fields;
|
|
694
|
+
session;
|
|
695
|
+
dialect;
|
|
696
|
+
withList = [];
|
|
697
|
+
distinct;
|
|
698
|
+
constructor(config) {
|
|
699
|
+
this.fields = config.fields;
|
|
700
|
+
this.session = config.session;
|
|
701
|
+
this.dialect = config.dialect;
|
|
702
|
+
if (config.withList) this.withList = config.withList;
|
|
703
|
+
this.distinct = config.distinct;
|
|
704
|
+
}
|
|
705
|
+
authToken;
|
|
706
|
+
/** @internal */
|
|
707
|
+
setToken(token) {
|
|
708
|
+
this.authToken = token;
|
|
709
|
+
return this;
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Specify the table, subquery, or other target that you're
|
|
713
|
+
* building a select query against.
|
|
714
|
+
*
|
|
715
|
+
* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
|
|
716
|
+
*/
|
|
717
|
+
from(source) {
|
|
718
|
+
const isPartialSelect = !!this.fields;
|
|
719
|
+
const src = source;
|
|
720
|
+
let fields;
|
|
721
|
+
if (this.fields) fields = this.fields;
|
|
722
|
+
else if (is(src, Subquery)) fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [key, src[key]]));
|
|
723
|
+
else if (is(src, PgViewBase)) fields = src[ViewBaseConfig].selectedFields;
|
|
724
|
+
else if (is(src, SQL)) fields = {};
|
|
725
|
+
else fields = getTableColumns(src);
|
|
726
|
+
return new PgSelectBase({
|
|
727
|
+
table: src,
|
|
728
|
+
fields,
|
|
729
|
+
isPartialSelect,
|
|
730
|
+
session: this.session,
|
|
731
|
+
dialect: this.dialect,
|
|
732
|
+
withList: this.withList,
|
|
733
|
+
distinct: this.distinct
|
|
734
|
+
}).setToken(this.authToken);
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
var PgSelectQueryBuilderBase = class extends TypedQueryBuilder {
|
|
738
|
+
static [entityKind] = "PgSelectQueryBuilder";
|
|
739
|
+
_;
|
|
740
|
+
config;
|
|
741
|
+
joinsNotNullableMap;
|
|
742
|
+
tableName;
|
|
743
|
+
isPartialSelect;
|
|
744
|
+
session;
|
|
745
|
+
dialect;
|
|
746
|
+
cacheConfig = void 0;
|
|
747
|
+
usedTables = /* @__PURE__ */ new Set();
|
|
748
|
+
constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
|
|
749
|
+
super();
|
|
750
|
+
this.config = {
|
|
751
|
+
withList,
|
|
752
|
+
table,
|
|
753
|
+
fields: { ...fields },
|
|
754
|
+
distinct,
|
|
755
|
+
setOperators: []
|
|
756
|
+
};
|
|
757
|
+
this.isPartialSelect = isPartialSelect;
|
|
758
|
+
this.session = session;
|
|
759
|
+
this.dialect = dialect;
|
|
760
|
+
this._ = {
|
|
761
|
+
selectedFields: fields,
|
|
762
|
+
config: this.config
|
|
763
|
+
};
|
|
764
|
+
this.tableName = getTableLikeName(table);
|
|
765
|
+
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
|
|
766
|
+
for (const item of extractUsedTable(table)) this.usedTables.add(item);
|
|
767
|
+
}
|
|
768
|
+
/** @internal */
|
|
769
|
+
getUsedTables() {
|
|
770
|
+
return [...this.usedTables];
|
|
771
|
+
}
|
|
772
|
+
createJoin(joinType, lateral) {
|
|
773
|
+
return (table, on) => {
|
|
774
|
+
const baseTableName = this.tableName;
|
|
775
|
+
const tableName = getTableLikeName(table);
|
|
776
|
+
for (const item of extractUsedTable(table)) this.usedTables.add(item);
|
|
777
|
+
if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
|
|
778
|
+
if (!this.isPartialSelect) {
|
|
779
|
+
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
|
|
780
|
+
if (typeof tableName === "string" && !is(table, SQL)) {
|
|
781
|
+
const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
|
|
782
|
+
this.config.fields[tableName] = selection;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (typeof on === "function") on = on(new Proxy(this.config.fields, new SelectionProxyHandler({
|
|
786
|
+
sqlAliasedBehavior: "sql",
|
|
787
|
+
sqlBehavior: "sql"
|
|
788
|
+
})));
|
|
789
|
+
if (!this.config.joins) this.config.joins = [];
|
|
790
|
+
this.config.joins.push({
|
|
791
|
+
on,
|
|
792
|
+
table,
|
|
793
|
+
joinType,
|
|
794
|
+
alias: tableName,
|
|
795
|
+
lateral
|
|
796
|
+
});
|
|
797
|
+
if (typeof tableName === "string") switch (joinType) {
|
|
798
|
+
case "left":
|
|
799
|
+
this.joinsNotNullableMap[tableName] = false;
|
|
800
|
+
break;
|
|
801
|
+
case "right":
|
|
802
|
+
this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
|
|
803
|
+
this.joinsNotNullableMap[tableName] = true;
|
|
804
|
+
break;
|
|
805
|
+
case "cross":
|
|
806
|
+
case "inner":
|
|
807
|
+
this.joinsNotNullableMap[tableName] = true;
|
|
808
|
+
break;
|
|
809
|
+
case "full":
|
|
810
|
+
this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
|
|
811
|
+
this.joinsNotNullableMap[tableName] = false;
|
|
812
|
+
}
|
|
813
|
+
return this;
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Executes a `left join` operation by adding another table to the current query.
|
|
818
|
+
*
|
|
819
|
+
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
|
|
820
|
+
*
|
|
821
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
|
|
822
|
+
*
|
|
823
|
+
* @param table the table to join.
|
|
824
|
+
* @param on the `on` clause.
|
|
825
|
+
*
|
|
826
|
+
* @example
|
|
827
|
+
*
|
|
828
|
+
* ```ts
|
|
829
|
+
* // Select all users and their pets
|
|
830
|
+
* const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
|
|
831
|
+
* .from(users)
|
|
832
|
+
* .leftJoin(pets, eq(users.id, pets.ownerId))
|
|
833
|
+
*
|
|
834
|
+
* // Select userId and petId
|
|
835
|
+
* const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
|
|
836
|
+
* userId: users.id,
|
|
837
|
+
* petId: pets.id,
|
|
838
|
+
* })
|
|
839
|
+
* .from(users)
|
|
840
|
+
* .leftJoin(pets, eq(users.id, pets.ownerId))
|
|
841
|
+
* ```
|
|
842
|
+
*/
|
|
843
|
+
leftJoin = this.createJoin("left", false);
|
|
844
|
+
/**
|
|
845
|
+
* Executes a `left join lateral` operation by adding subquery to the current query.
|
|
846
|
+
*
|
|
847
|
+
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
|
|
848
|
+
*
|
|
849
|
+
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
|
|
850
|
+
*
|
|
851
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
|
|
852
|
+
*
|
|
853
|
+
* @param table the subquery to join.
|
|
854
|
+
* @param on the `on` clause.
|
|
855
|
+
*/
|
|
856
|
+
leftJoinLateral = this.createJoin("left", true);
|
|
857
|
+
/**
|
|
858
|
+
* Executes a `right join` operation by adding another table to the current query.
|
|
859
|
+
*
|
|
860
|
+
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
|
|
861
|
+
*
|
|
862
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
|
|
863
|
+
*
|
|
864
|
+
* @param table the table to join.
|
|
865
|
+
* @param on the `on` clause.
|
|
866
|
+
*
|
|
867
|
+
* @example
|
|
868
|
+
*
|
|
869
|
+
* ```ts
|
|
870
|
+
* // Select all users and their pets
|
|
871
|
+
* const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
|
|
872
|
+
* .from(users)
|
|
873
|
+
* .rightJoin(pets, eq(users.id, pets.ownerId))
|
|
874
|
+
*
|
|
875
|
+
* // Select userId and petId
|
|
876
|
+
* const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
|
|
877
|
+
* userId: users.id,
|
|
878
|
+
* petId: pets.id,
|
|
879
|
+
* })
|
|
880
|
+
* .from(users)
|
|
881
|
+
* .rightJoin(pets, eq(users.id, pets.ownerId))
|
|
882
|
+
* ```
|
|
883
|
+
*/
|
|
884
|
+
rightJoin = this.createJoin("right", false);
|
|
885
|
+
/**
|
|
886
|
+
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
|
|
887
|
+
*
|
|
888
|
+
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
|
|
889
|
+
*
|
|
890
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
|
|
891
|
+
*
|
|
892
|
+
* @param table the table to join.
|
|
893
|
+
* @param on the `on` clause.
|
|
894
|
+
*
|
|
895
|
+
* @example
|
|
896
|
+
*
|
|
897
|
+
* ```ts
|
|
898
|
+
* // Select all users and their pets
|
|
899
|
+
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
|
|
900
|
+
* .from(users)
|
|
901
|
+
* .innerJoin(pets, eq(users.id, pets.ownerId))
|
|
902
|
+
*
|
|
903
|
+
* // Select userId and petId
|
|
904
|
+
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
|
|
905
|
+
* userId: users.id,
|
|
906
|
+
* petId: pets.id,
|
|
907
|
+
* })
|
|
908
|
+
* .from(users)
|
|
909
|
+
* .innerJoin(pets, eq(users.id, pets.ownerId))
|
|
910
|
+
* ```
|
|
911
|
+
*/
|
|
912
|
+
innerJoin = this.createJoin("inner", false);
|
|
913
|
+
/**
|
|
914
|
+
* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
|
|
915
|
+
*
|
|
916
|
+
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
|
|
917
|
+
*
|
|
918
|
+
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
|
|
919
|
+
*
|
|
920
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
|
|
921
|
+
*
|
|
922
|
+
* @param table the subquery to join.
|
|
923
|
+
* @param on the `on` clause.
|
|
924
|
+
*/
|
|
925
|
+
innerJoinLateral = this.createJoin("inner", true);
|
|
926
|
+
/**
|
|
927
|
+
* Executes a `full join` operation by combining rows from two tables into a new table.
|
|
928
|
+
*
|
|
929
|
+
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
|
|
930
|
+
*
|
|
931
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
|
|
932
|
+
*
|
|
933
|
+
* @param table the table to join.
|
|
934
|
+
* @param on the `on` clause.
|
|
935
|
+
*
|
|
936
|
+
* @example
|
|
937
|
+
*
|
|
938
|
+
* ```ts
|
|
939
|
+
* // Select all users and their pets
|
|
940
|
+
* const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
|
|
941
|
+
* .from(users)
|
|
942
|
+
* .fullJoin(pets, eq(users.id, pets.ownerId))
|
|
943
|
+
*
|
|
944
|
+
* // Select userId and petId
|
|
945
|
+
* const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
|
|
946
|
+
* userId: users.id,
|
|
947
|
+
* petId: pets.id,
|
|
948
|
+
* })
|
|
949
|
+
* .from(users)
|
|
950
|
+
* .fullJoin(pets, eq(users.id, pets.ownerId))
|
|
951
|
+
* ```
|
|
952
|
+
*/
|
|
953
|
+
fullJoin = this.createJoin("full", false);
|
|
954
|
+
/**
|
|
955
|
+
* Executes a `cross join` operation by combining rows from two tables into a new table.
|
|
956
|
+
*
|
|
957
|
+
* Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
|
|
958
|
+
*
|
|
959
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
|
|
960
|
+
*
|
|
961
|
+
* @param table the table to join.
|
|
962
|
+
*
|
|
963
|
+
* @example
|
|
964
|
+
*
|
|
965
|
+
* ```ts
|
|
966
|
+
* // Select all users, each user with every pet
|
|
967
|
+
* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
|
|
968
|
+
* .from(users)
|
|
969
|
+
* .crossJoin(pets)
|
|
970
|
+
*
|
|
971
|
+
* // Select userId and petId
|
|
972
|
+
* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
|
|
973
|
+
* userId: users.id,
|
|
974
|
+
* petId: pets.id,
|
|
975
|
+
* })
|
|
976
|
+
* .from(users)
|
|
977
|
+
* .crossJoin(pets)
|
|
978
|
+
* ```
|
|
979
|
+
*/
|
|
980
|
+
crossJoin = this.createJoin("cross", false);
|
|
981
|
+
/**
|
|
982
|
+
* Executes a `cross join lateral` operation by combining rows from two queries into a new table.
|
|
983
|
+
*
|
|
984
|
+
* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
|
|
985
|
+
*
|
|
986
|
+
* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
|
|
987
|
+
*
|
|
988
|
+
* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
|
|
989
|
+
*
|
|
990
|
+
* @param table the query to join.
|
|
991
|
+
*/
|
|
992
|
+
crossJoinLateral = this.createJoin("cross", true);
|
|
993
|
+
createSetOperator(type, isAll) {
|
|
994
|
+
return (rightSelection) => {
|
|
995
|
+
const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
|
|
996
|
+
if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
|
|
997
|
+
this.config.setOperators.push({
|
|
998
|
+
type,
|
|
999
|
+
isAll,
|
|
1000
|
+
rightSelect
|
|
1001
|
+
});
|
|
1002
|
+
return this;
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Adds `union` set operator to the query.
|
|
1007
|
+
*
|
|
1008
|
+
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
|
|
1009
|
+
*
|
|
1010
|
+
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
|
|
1011
|
+
*
|
|
1012
|
+
* @example
|
|
1013
|
+
*
|
|
1014
|
+
* ```ts
|
|
1015
|
+
* // Select all unique names from customers and users tables
|
|
1016
|
+
* await db.select({ name: users.name })
|
|
1017
|
+
* .from(users)
|
|
1018
|
+
* .union(
|
|
1019
|
+
* db.select({ name: customers.name }).from(customers)
|
|
1020
|
+
* );
|
|
1021
|
+
* // or
|
|
1022
|
+
* import { union } from 'drizzle-orm/pg-core'
|
|
1023
|
+
*
|
|
1024
|
+
* await union(
|
|
1025
|
+
* db.select({ name: users.name }).from(users),
|
|
1026
|
+
* db.select({ name: customers.name }).from(customers)
|
|
1027
|
+
* );
|
|
1028
|
+
* ```
|
|
1029
|
+
*/
|
|
1030
|
+
union = this.createSetOperator("union", false);
|
|
1031
|
+
/**
|
|
1032
|
+
* Adds `union all` set operator to the query.
|
|
1033
|
+
*
|
|
1034
|
+
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
|
|
1035
|
+
*
|
|
1036
|
+
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
|
|
1037
|
+
*
|
|
1038
|
+
* @example
|
|
1039
|
+
*
|
|
1040
|
+
* ```ts
|
|
1041
|
+
* // Select all transaction ids from both online and in-store sales
|
|
1042
|
+
* await db.select({ transaction: onlineSales.transactionId })
|
|
1043
|
+
* .from(onlineSales)
|
|
1044
|
+
* .unionAll(
|
|
1045
|
+
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
|
|
1046
|
+
* );
|
|
1047
|
+
* // or
|
|
1048
|
+
* import { unionAll } from 'drizzle-orm/pg-core'
|
|
1049
|
+
*
|
|
1050
|
+
* await unionAll(
|
|
1051
|
+
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
|
|
1052
|
+
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
|
|
1053
|
+
* );
|
|
1054
|
+
* ```
|
|
1055
|
+
*/
|
|
1056
|
+
unionAll = this.createSetOperator("union", true);
|
|
1057
|
+
/**
|
|
1058
|
+
* Adds `intersect` set operator to the query.
|
|
1059
|
+
*
|
|
1060
|
+
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
|
|
1061
|
+
*
|
|
1062
|
+
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
|
|
1063
|
+
*
|
|
1064
|
+
* @example
|
|
1065
|
+
*
|
|
1066
|
+
* ```ts
|
|
1067
|
+
* // Select course names that are offered in both departments A and B
|
|
1068
|
+
* await db.select({ courseName: depA.courseName })
|
|
1069
|
+
* .from(depA)
|
|
1070
|
+
* .intersect(
|
|
1071
|
+
* db.select({ courseName: depB.courseName }).from(depB)
|
|
1072
|
+
* );
|
|
1073
|
+
* // or
|
|
1074
|
+
* import { intersect } from 'drizzle-orm/pg-core'
|
|
1075
|
+
*
|
|
1076
|
+
* await intersect(
|
|
1077
|
+
* db.select({ courseName: depA.courseName }).from(depA),
|
|
1078
|
+
* db.select({ courseName: depB.courseName }).from(depB)
|
|
1079
|
+
* );
|
|
1080
|
+
* ```
|
|
1081
|
+
*/
|
|
1082
|
+
intersect = this.createSetOperator("intersect", false);
|
|
1083
|
+
/**
|
|
1084
|
+
* Adds `intersect all` set operator to the query.
|
|
1085
|
+
*
|
|
1086
|
+
* Calling this method will retain only the rows that are present in both result sets including all duplicates.
|
|
1087
|
+
*
|
|
1088
|
+
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
|
|
1089
|
+
*
|
|
1090
|
+
* @example
|
|
1091
|
+
*
|
|
1092
|
+
* ```ts
|
|
1093
|
+
* // Select all products and quantities that are ordered by both regular and VIP customers
|
|
1094
|
+
* await db.select({
|
|
1095
|
+
* productId: regularCustomerOrders.productId,
|
|
1096
|
+
* quantityOrdered: regularCustomerOrders.quantityOrdered
|
|
1097
|
+
* })
|
|
1098
|
+
* .from(regularCustomerOrders)
|
|
1099
|
+
* .intersectAll(
|
|
1100
|
+
* db.select({
|
|
1101
|
+
* productId: vipCustomerOrders.productId,
|
|
1102
|
+
* quantityOrdered: vipCustomerOrders.quantityOrdered
|
|
1103
|
+
* })
|
|
1104
|
+
* .from(vipCustomerOrders)
|
|
1105
|
+
* );
|
|
1106
|
+
* // or
|
|
1107
|
+
* import { intersectAll } from 'drizzle-orm/pg-core'
|
|
1108
|
+
*
|
|
1109
|
+
* await intersectAll(
|
|
1110
|
+
* db.select({
|
|
1111
|
+
* productId: regularCustomerOrders.productId,
|
|
1112
|
+
* quantityOrdered: regularCustomerOrders.quantityOrdered
|
|
1113
|
+
* })
|
|
1114
|
+
* .from(regularCustomerOrders),
|
|
1115
|
+
* db.select({
|
|
1116
|
+
* productId: vipCustomerOrders.productId,
|
|
1117
|
+
* quantityOrdered: vipCustomerOrders.quantityOrdered
|
|
1118
|
+
* })
|
|
1119
|
+
* .from(vipCustomerOrders)
|
|
1120
|
+
* );
|
|
1121
|
+
* ```
|
|
1122
|
+
*/
|
|
1123
|
+
intersectAll = this.createSetOperator("intersect", true);
|
|
1124
|
+
/**
|
|
1125
|
+
* Adds `except` set operator to the query.
|
|
1126
|
+
*
|
|
1127
|
+
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
|
|
1128
|
+
*
|
|
1129
|
+
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
|
|
1130
|
+
*
|
|
1131
|
+
* @example
|
|
1132
|
+
*
|
|
1133
|
+
* ```ts
|
|
1134
|
+
* // Select all courses offered in department A but not in department B
|
|
1135
|
+
* await db.select({ courseName: depA.courseName })
|
|
1136
|
+
* .from(depA)
|
|
1137
|
+
* .except(
|
|
1138
|
+
* db.select({ courseName: depB.courseName }).from(depB)
|
|
1139
|
+
* );
|
|
1140
|
+
* // or
|
|
1141
|
+
* import { except } from 'drizzle-orm/pg-core'
|
|
1142
|
+
*
|
|
1143
|
+
* await except(
|
|
1144
|
+
* db.select({ courseName: depA.courseName }).from(depA),
|
|
1145
|
+
* db.select({ courseName: depB.courseName }).from(depB)
|
|
1146
|
+
* );
|
|
1147
|
+
* ```
|
|
1148
|
+
*/
|
|
1149
|
+
except = this.createSetOperator("except", false);
|
|
1150
|
+
/**
|
|
1151
|
+
* Adds `except all` set operator to the query.
|
|
1152
|
+
*
|
|
1153
|
+
* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
|
|
1154
|
+
*
|
|
1155
|
+
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
|
|
1156
|
+
*
|
|
1157
|
+
* @example
|
|
1158
|
+
*
|
|
1159
|
+
* ```ts
|
|
1160
|
+
* // Select all products that are ordered by regular customers but not by VIP customers
|
|
1161
|
+
* await db.select({
|
|
1162
|
+
* productId: regularCustomerOrders.productId,
|
|
1163
|
+
* quantityOrdered: regularCustomerOrders.quantityOrdered,
|
|
1164
|
+
* })
|
|
1165
|
+
* .from(regularCustomerOrders)
|
|
1166
|
+
* .exceptAll(
|
|
1167
|
+
* db.select({
|
|
1168
|
+
* productId: vipCustomerOrders.productId,
|
|
1169
|
+
* quantityOrdered: vipCustomerOrders.quantityOrdered,
|
|
1170
|
+
* })
|
|
1171
|
+
* .from(vipCustomerOrders)
|
|
1172
|
+
* );
|
|
1173
|
+
* // or
|
|
1174
|
+
* import { exceptAll } from 'drizzle-orm/pg-core'
|
|
1175
|
+
*
|
|
1176
|
+
* await exceptAll(
|
|
1177
|
+
* db.select({
|
|
1178
|
+
* productId: regularCustomerOrders.productId,
|
|
1179
|
+
* quantityOrdered: regularCustomerOrders.quantityOrdered
|
|
1180
|
+
* })
|
|
1181
|
+
* .from(regularCustomerOrders),
|
|
1182
|
+
* db.select({
|
|
1183
|
+
* productId: vipCustomerOrders.productId,
|
|
1184
|
+
* quantityOrdered: vipCustomerOrders.quantityOrdered
|
|
1185
|
+
* })
|
|
1186
|
+
* .from(vipCustomerOrders)
|
|
1187
|
+
* );
|
|
1188
|
+
* ```
|
|
1189
|
+
*/
|
|
1190
|
+
exceptAll = this.createSetOperator("except", true);
|
|
1191
|
+
/** @internal */
|
|
1192
|
+
addSetOperators(setOperators) {
|
|
1193
|
+
this.config.setOperators.push(...setOperators);
|
|
1194
|
+
return this;
|
|
1195
|
+
}
|
|
1196
|
+
/**
|
|
1197
|
+
* Adds a `where` clause to the query.
|
|
1198
|
+
*
|
|
1199
|
+
* Calling this method will select only those rows that fulfill a specified condition.
|
|
1200
|
+
*
|
|
1201
|
+
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
|
|
1202
|
+
*
|
|
1203
|
+
* @param where the `where` clause.
|
|
1204
|
+
*
|
|
1205
|
+
* @example
|
|
1206
|
+
* You can use conditional operators and `sql function` to filter the rows to be selected.
|
|
1207
|
+
*
|
|
1208
|
+
* ```ts
|
|
1209
|
+
* // Select all cars with green color
|
|
1210
|
+
* await db.select().from(cars).where(eq(cars.color, 'green'));
|
|
1211
|
+
* // or
|
|
1212
|
+
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
|
|
1213
|
+
* ```
|
|
1214
|
+
*
|
|
1215
|
+
* You can logically combine conditional operators with `and()` and `or()` operators:
|
|
1216
|
+
*
|
|
1217
|
+
* ```ts
|
|
1218
|
+
* // Select all BMW cars with a green color
|
|
1219
|
+
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
|
|
1220
|
+
*
|
|
1221
|
+
* // Select all cars with the green or blue color
|
|
1222
|
+
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
|
|
1223
|
+
* ```
|
|
1224
|
+
*/
|
|
1225
|
+
where(where) {
|
|
1226
|
+
if (typeof where === "function") where = where(new Proxy(this.config.fields, new SelectionProxyHandler({
|
|
1227
|
+
sqlAliasedBehavior: "sql",
|
|
1228
|
+
sqlBehavior: "sql"
|
|
1229
|
+
})));
|
|
1230
|
+
this.config.where = where;
|
|
1231
|
+
return this;
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* Adds a `having` clause to the query.
|
|
1235
|
+
*
|
|
1236
|
+
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
|
|
1237
|
+
*
|
|
1238
|
+
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
|
|
1239
|
+
*
|
|
1240
|
+
* @param having the `having` clause.
|
|
1241
|
+
*
|
|
1242
|
+
* @example
|
|
1243
|
+
*
|
|
1244
|
+
* ```ts
|
|
1245
|
+
* // Select all brands with more than one car
|
|
1246
|
+
* await db.select({
|
|
1247
|
+
* brand: cars.brand,
|
|
1248
|
+
* count: sql<number>`cast(count(${cars.id}) as int)`,
|
|
1249
|
+
* })
|
|
1250
|
+
* .from(cars)
|
|
1251
|
+
* .groupBy(cars.brand)
|
|
1252
|
+
* .having(({ count }) => gt(count, 1));
|
|
1253
|
+
* ```
|
|
1254
|
+
*/
|
|
1255
|
+
having(having) {
|
|
1256
|
+
if (typeof having === "function") having = having(new Proxy(this.config.fields, new SelectionProxyHandler({
|
|
1257
|
+
sqlAliasedBehavior: "sql",
|
|
1258
|
+
sqlBehavior: "sql"
|
|
1259
|
+
})));
|
|
1260
|
+
this.config.having = having;
|
|
1261
|
+
return this;
|
|
1262
|
+
}
|
|
1263
|
+
groupBy(...columns) {
|
|
1264
|
+
if (typeof columns[0] === "function") {
|
|
1265
|
+
const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({
|
|
1266
|
+
sqlAliasedBehavior: "alias",
|
|
1267
|
+
sqlBehavior: "sql"
|
|
1268
|
+
})));
|
|
1269
|
+
this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
|
|
1270
|
+
} else this.config.groupBy = columns;
|
|
1271
|
+
return this;
|
|
1272
|
+
}
|
|
1273
|
+
orderBy(...columns) {
|
|
1274
|
+
if (typeof columns[0] === "function") {
|
|
1275
|
+
const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({
|
|
1276
|
+
sqlAliasedBehavior: "alias",
|
|
1277
|
+
sqlBehavior: "sql"
|
|
1278
|
+
})));
|
|
1279
|
+
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
1280
|
+
if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
|
|
1281
|
+
else this.config.orderBy = orderByArray;
|
|
1282
|
+
} else {
|
|
1283
|
+
const orderByArray = columns;
|
|
1284
|
+
if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;
|
|
1285
|
+
else this.config.orderBy = orderByArray;
|
|
1286
|
+
}
|
|
1287
|
+
return this;
|
|
1288
|
+
}
|
|
1289
|
+
/**
|
|
1290
|
+
* Adds a `limit` clause to the query.
|
|
1291
|
+
*
|
|
1292
|
+
* Calling this method will set the maximum number of rows that will be returned by this query.
|
|
1293
|
+
*
|
|
1294
|
+
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
|
|
1295
|
+
*
|
|
1296
|
+
* @param limit the `limit` clause.
|
|
1297
|
+
*
|
|
1298
|
+
* @example
|
|
1299
|
+
*
|
|
1300
|
+
* ```ts
|
|
1301
|
+
* // Get the first 10 people from this query.
|
|
1302
|
+
* await db.select().from(people).limit(10);
|
|
1303
|
+
* ```
|
|
1304
|
+
*/
|
|
1305
|
+
limit(limit) {
|
|
1306
|
+
if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).limit = limit;
|
|
1307
|
+
else this.config.limit = limit;
|
|
1308
|
+
return this;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Adds an `offset` clause to the query.
|
|
1312
|
+
*
|
|
1313
|
+
* Calling this method will skip a number of rows when returning results from this query.
|
|
1314
|
+
*
|
|
1315
|
+
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
|
|
1316
|
+
*
|
|
1317
|
+
* @param offset the `offset` clause.
|
|
1318
|
+
*
|
|
1319
|
+
* @example
|
|
1320
|
+
*
|
|
1321
|
+
* ```ts
|
|
1322
|
+
* // Get the 10th-20th people from this query.
|
|
1323
|
+
* await db.select().from(people).offset(10).limit(10);
|
|
1324
|
+
* ```
|
|
1325
|
+
*/
|
|
1326
|
+
offset(offset) {
|
|
1327
|
+
if (this.config.setOperators.length > 0) this.config.setOperators.at(-1).offset = offset;
|
|
1328
|
+
else this.config.offset = offset;
|
|
1329
|
+
return this;
|
|
1330
|
+
}
|
|
1331
|
+
/**
|
|
1332
|
+
* Adds a `for` clause to the query.
|
|
1333
|
+
*
|
|
1334
|
+
* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
|
|
1335
|
+
*
|
|
1336
|
+
* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
|
|
1337
|
+
*
|
|
1338
|
+
* @param strength the lock strength.
|
|
1339
|
+
* @param config the lock configuration.
|
|
1340
|
+
*/
|
|
1341
|
+
for(strength, config = {}) {
|
|
1342
|
+
this.config.lockingClause = {
|
|
1343
|
+
strength,
|
|
1344
|
+
config
|
|
1345
|
+
};
|
|
1346
|
+
return this;
|
|
1347
|
+
}
|
|
1348
|
+
/** @internal */
|
|
1349
|
+
getSQL() {
|
|
1350
|
+
return this.dialect.buildSelectQuery(this.config);
|
|
1351
|
+
}
|
|
1352
|
+
toSQL() {
|
|
1353
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
1354
|
+
return rest;
|
|
1355
|
+
}
|
|
1356
|
+
as(alias) {
|
|
1357
|
+
const usedTables = [];
|
|
1358
|
+
usedTables.push(...extractUsedTable(this.config.table));
|
|
1359
|
+
if (this.config.joins) for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
|
|
1360
|
+
return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({
|
|
1361
|
+
alias,
|
|
1362
|
+
sqlAliasedBehavior: "alias",
|
|
1363
|
+
sqlBehavior: "error"
|
|
1364
|
+
}));
|
|
1365
|
+
}
|
|
1366
|
+
/** @internal */
|
|
1367
|
+
getSelectedFields() {
|
|
1368
|
+
return new Proxy(this.config.fields, new SelectionProxyHandler({
|
|
1369
|
+
alias: this.tableName,
|
|
1370
|
+
sqlAliasedBehavior: "alias",
|
|
1371
|
+
sqlBehavior: "error"
|
|
1372
|
+
}));
|
|
1373
|
+
}
|
|
1374
|
+
$dynamic() {
|
|
1375
|
+
return this;
|
|
1376
|
+
}
|
|
1377
|
+
$withCache(config) {
|
|
1378
|
+
this.cacheConfig = config === void 0 ? {
|
|
1379
|
+
config: {},
|
|
1380
|
+
enable: true,
|
|
1381
|
+
autoInvalidate: true
|
|
1382
|
+
} : config === false ? { enable: false } : {
|
|
1383
|
+
enable: true,
|
|
1384
|
+
autoInvalidate: true,
|
|
1385
|
+
...config
|
|
1386
|
+
};
|
|
1387
|
+
return this;
|
|
1388
|
+
}
|
|
1389
|
+
};
|
|
1390
|
+
var PgSelectBase = class extends PgSelectQueryBuilderBase {
|
|
1391
|
+
static [entityKind] = "PgSelect";
|
|
1392
|
+
/** @internal */
|
|
1393
|
+
_prepare(name) {
|
|
1394
|
+
const { session, config, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this;
|
|
1395
|
+
if (!session) throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
|
|
1396
|
+
const { fields } = config;
|
|
1397
|
+
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
|
|
1398
|
+
const fieldsList = orderSelectedFields(fields);
|
|
1399
|
+
const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, void 0, {
|
|
1400
|
+
type: "select",
|
|
1401
|
+
tables: [...usedTables]
|
|
1402
|
+
}, cacheConfig);
|
|
1403
|
+
query.joinsNotNullableMap = joinsNotNullableMap;
|
|
1404
|
+
return query.setToken(authToken);
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
/**
|
|
1408
|
+
* Create a prepared statement for this query. This allows
|
|
1409
|
+
* the database to remember this query for the given session
|
|
1410
|
+
* and call it by name, rather than specifying the full query.
|
|
1411
|
+
*
|
|
1412
|
+
* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
|
|
1413
|
+
*/
|
|
1414
|
+
prepare(name) {
|
|
1415
|
+
return this._prepare(name);
|
|
1416
|
+
}
|
|
1417
|
+
authToken;
|
|
1418
|
+
/** @internal */
|
|
1419
|
+
setToken(token) {
|
|
1420
|
+
this.authToken = token;
|
|
1421
|
+
return this;
|
|
1422
|
+
}
|
|
1423
|
+
execute = (placeholderValues) => {
|
|
1424
|
+
return tracer.startActiveSpan("drizzle.operation", () => {
|
|
1425
|
+
return this._prepare().execute(placeholderValues, this.authToken);
|
|
1426
|
+
});
|
|
1427
|
+
};
|
|
1428
|
+
};
|
|
1429
|
+
applyMixins(PgSelectBase, [QueryPromise]);
|
|
1430
|
+
function createSetOperator(type, isAll) {
|
|
1431
|
+
return (leftSelect, rightSelect, ...restSelects) => {
|
|
1432
|
+
const setOperators = [rightSelect, ...restSelects].map((select) => ({
|
|
1433
|
+
type,
|
|
1434
|
+
isAll,
|
|
1435
|
+
rightSelect: select
|
|
1436
|
+
}));
|
|
1437
|
+
for (const setOperator of setOperators) if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
|
|
1438
|
+
return leftSelect.addSetOperators(setOperators);
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
const getPgSetOperators = () => ({
|
|
1442
|
+
union,
|
|
1443
|
+
unionAll,
|
|
1444
|
+
intersect,
|
|
1445
|
+
intersectAll,
|
|
1446
|
+
except,
|
|
1447
|
+
exceptAll
|
|
1448
|
+
});
|
|
1449
|
+
const union = createSetOperator("union", false);
|
|
1450
|
+
const unionAll = createSetOperator("union", true);
|
|
1451
|
+
const intersect = createSetOperator("intersect", false);
|
|
1452
|
+
const intersectAll = createSetOperator("intersect", true);
|
|
1453
|
+
const except = createSetOperator("except", false);
|
|
1454
|
+
const exceptAll = createSetOperator("except", true);
|
|
1455
|
+
//#endregion
|
|
1456
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js
|
|
1457
|
+
var QueryBuilder = class {
|
|
1458
|
+
static [entityKind] = "PgQueryBuilder";
|
|
1459
|
+
dialect;
|
|
1460
|
+
dialectConfig;
|
|
1461
|
+
constructor(dialect) {
|
|
1462
|
+
this.dialect = is(dialect, PgDialect) ? dialect : void 0;
|
|
1463
|
+
this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;
|
|
1464
|
+
}
|
|
1465
|
+
$with = (alias, selection) => {
|
|
1466
|
+
const queryBuilder = this;
|
|
1467
|
+
const as = (qb) => {
|
|
1468
|
+
if (typeof qb === "function") qb = qb(queryBuilder);
|
|
1469
|
+
return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
|
|
1470
|
+
alias,
|
|
1471
|
+
sqlAliasedBehavior: "alias",
|
|
1472
|
+
sqlBehavior: "error"
|
|
1473
|
+
}));
|
|
1474
|
+
};
|
|
1475
|
+
return { as };
|
|
1476
|
+
};
|
|
1477
|
+
with(...queries) {
|
|
1478
|
+
const self = this;
|
|
1479
|
+
function select(fields) {
|
|
1480
|
+
return new PgSelectBuilder({
|
|
1481
|
+
fields: fields ?? void 0,
|
|
1482
|
+
session: void 0,
|
|
1483
|
+
dialect: self.getDialect(),
|
|
1484
|
+
withList: queries
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
function selectDistinct(fields) {
|
|
1488
|
+
return new PgSelectBuilder({
|
|
1489
|
+
fields: fields ?? void 0,
|
|
1490
|
+
session: void 0,
|
|
1491
|
+
dialect: self.getDialect(),
|
|
1492
|
+
distinct: true
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
function selectDistinctOn(on, fields) {
|
|
1496
|
+
return new PgSelectBuilder({
|
|
1497
|
+
fields: fields ?? void 0,
|
|
1498
|
+
session: void 0,
|
|
1499
|
+
dialect: self.getDialect(),
|
|
1500
|
+
distinct: { on }
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
return {
|
|
1504
|
+
select,
|
|
1505
|
+
selectDistinct,
|
|
1506
|
+
selectDistinctOn
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
1509
|
+
select(fields) {
|
|
1510
|
+
return new PgSelectBuilder({
|
|
1511
|
+
fields: fields ?? void 0,
|
|
1512
|
+
session: void 0,
|
|
1513
|
+
dialect: this.getDialect()
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
selectDistinct(fields) {
|
|
1517
|
+
return new PgSelectBuilder({
|
|
1518
|
+
fields: fields ?? void 0,
|
|
1519
|
+
session: void 0,
|
|
1520
|
+
dialect: this.getDialect(),
|
|
1521
|
+
distinct: true
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
selectDistinctOn(on, fields) {
|
|
1525
|
+
return new PgSelectBuilder({
|
|
1526
|
+
fields: fields ?? void 0,
|
|
1527
|
+
session: void 0,
|
|
1528
|
+
dialect: this.getDialect(),
|
|
1529
|
+
distinct: { on }
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
getDialect() {
|
|
1533
|
+
if (!this.dialect) this.dialect = new PgDialect(this.dialectConfig);
|
|
1534
|
+
return this.dialect;
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
//#endregion
|
|
1538
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/utils.js
|
|
1539
|
+
function extractUsedTable(table) {
|
|
1540
|
+
if (is(table, PgTable)) return [table[Schema] ? `${table[Schema]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]];
|
|
1541
|
+
if (is(table, Subquery)) return table._.usedTables ?? [];
|
|
1542
|
+
if (is(table, SQL)) return table.usedTables ?? [];
|
|
1543
|
+
return [];
|
|
1544
|
+
}
|
|
1545
|
+
//#endregion
|
|
1546
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/delete.js
|
|
1547
|
+
var PgDeleteBase = class extends QueryPromise {
|
|
1548
|
+
constructor(table, session, dialect, withList) {
|
|
1549
|
+
super();
|
|
1550
|
+
this.session = session;
|
|
1551
|
+
this.dialect = dialect;
|
|
1552
|
+
this.config = {
|
|
1553
|
+
table,
|
|
1554
|
+
withList
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
static [entityKind] = "PgDelete";
|
|
1558
|
+
config;
|
|
1559
|
+
cacheConfig;
|
|
1560
|
+
/**
|
|
1561
|
+
* Adds a `where` clause to the query.
|
|
1562
|
+
*
|
|
1563
|
+
* Calling this method will delete only those rows that fulfill a specified condition.
|
|
1564
|
+
*
|
|
1565
|
+
* See docs: {@link https://orm.drizzle.team/docs/delete}
|
|
1566
|
+
*
|
|
1567
|
+
* @param where the `where` clause.
|
|
1568
|
+
*
|
|
1569
|
+
* @example
|
|
1570
|
+
* You can use conditional operators and `sql function` to filter the rows to be deleted.
|
|
1571
|
+
*
|
|
1572
|
+
* ```ts
|
|
1573
|
+
* // Delete all cars with green color
|
|
1574
|
+
* await db.delete(cars).where(eq(cars.color, 'green'));
|
|
1575
|
+
* // or
|
|
1576
|
+
* await db.delete(cars).where(sql`${cars.color} = 'green'`)
|
|
1577
|
+
* ```
|
|
1578
|
+
*
|
|
1579
|
+
* You can logically combine conditional operators with `and()` and `or()` operators:
|
|
1580
|
+
*
|
|
1581
|
+
* ```ts
|
|
1582
|
+
* // Delete all BMW cars with a green color
|
|
1583
|
+
* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
|
|
1584
|
+
*
|
|
1585
|
+
* // Delete all cars with the green or blue color
|
|
1586
|
+
* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
|
|
1587
|
+
* ```
|
|
1588
|
+
*/
|
|
1589
|
+
where(where) {
|
|
1590
|
+
this.config.where = where;
|
|
1591
|
+
return this;
|
|
1592
|
+
}
|
|
1593
|
+
returning(fields = this.config.table[Table.Symbol.Columns]) {
|
|
1594
|
+
this.config.returningFields = fields;
|
|
1595
|
+
this.config.returning = orderSelectedFields(fields);
|
|
1596
|
+
return this;
|
|
1597
|
+
}
|
|
1598
|
+
/** @internal */
|
|
1599
|
+
getSQL() {
|
|
1600
|
+
return this.dialect.buildDeleteQuery(this.config);
|
|
1601
|
+
}
|
|
1602
|
+
toSQL() {
|
|
1603
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
1604
|
+
return rest;
|
|
1605
|
+
}
|
|
1606
|
+
/** @internal */
|
|
1607
|
+
_prepare(name) {
|
|
1608
|
+
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
|
|
1609
|
+
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
|
|
1610
|
+
type: "delete",
|
|
1611
|
+
tables: extractUsedTable(this.config.table)
|
|
1612
|
+
}, this.cacheConfig);
|
|
1613
|
+
});
|
|
1614
|
+
}
|
|
1615
|
+
prepare(name) {
|
|
1616
|
+
return this._prepare(name);
|
|
1617
|
+
}
|
|
1618
|
+
authToken;
|
|
1619
|
+
/** @internal */
|
|
1620
|
+
setToken(token) {
|
|
1621
|
+
this.authToken = token;
|
|
1622
|
+
return this;
|
|
1623
|
+
}
|
|
1624
|
+
execute = (placeholderValues) => {
|
|
1625
|
+
return tracer.startActiveSpan("drizzle.operation", () => {
|
|
1626
|
+
return this._prepare().execute(placeholderValues, this.authToken);
|
|
1627
|
+
});
|
|
1628
|
+
};
|
|
1629
|
+
/** @internal */
|
|
1630
|
+
getSelectedFields() {
|
|
1631
|
+
return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({
|
|
1632
|
+
alias: getTableName(this.config.table),
|
|
1633
|
+
sqlAliasedBehavior: "alias",
|
|
1634
|
+
sqlBehavior: "error"
|
|
1635
|
+
})) : void 0;
|
|
1636
|
+
}
|
|
1637
|
+
$dynamic() {
|
|
1638
|
+
return this;
|
|
1639
|
+
}
|
|
1640
|
+
};
|
|
1641
|
+
//#endregion
|
|
1642
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/insert.js
|
|
1643
|
+
var PgInsertBuilder = class {
|
|
1644
|
+
constructor(table, session, dialect, withList, overridingSystemValue_) {
|
|
1645
|
+
this.table = table;
|
|
1646
|
+
this.session = session;
|
|
1647
|
+
this.dialect = dialect;
|
|
1648
|
+
this.withList = withList;
|
|
1649
|
+
this.overridingSystemValue_ = overridingSystemValue_;
|
|
1650
|
+
}
|
|
1651
|
+
static [entityKind] = "PgInsertBuilder";
|
|
1652
|
+
authToken;
|
|
1653
|
+
/** @internal */
|
|
1654
|
+
setToken(token) {
|
|
1655
|
+
this.authToken = token;
|
|
1656
|
+
return this;
|
|
1657
|
+
}
|
|
1658
|
+
overridingSystemValue() {
|
|
1659
|
+
this.overridingSystemValue_ = true;
|
|
1660
|
+
return this;
|
|
1661
|
+
}
|
|
1662
|
+
values(values) {
|
|
1663
|
+
values = Array.isArray(values) ? values : [values];
|
|
1664
|
+
if (values.length === 0) throw new Error("values() must be called with at least one value");
|
|
1665
|
+
const mappedValues = values.map((entry) => {
|
|
1666
|
+
const result = {};
|
|
1667
|
+
const cols = this.table[Table.Symbol.Columns];
|
|
1668
|
+
for (const colKey of Object.keys(entry)) {
|
|
1669
|
+
const colValue = entry[colKey];
|
|
1670
|
+
result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
|
|
1671
|
+
}
|
|
1672
|
+
return result;
|
|
1673
|
+
});
|
|
1674
|
+
return new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList, false, this.overridingSystemValue_).setToken(this.authToken);
|
|
1675
|
+
}
|
|
1676
|
+
select(selectQuery) {
|
|
1677
|
+
const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
|
|
1678
|
+
if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
|
|
1679
|
+
return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
|
|
1680
|
+
}
|
|
1681
|
+
};
|
|
1682
|
+
var PgInsertBase = class extends QueryPromise {
|
|
1683
|
+
constructor(table, values, session, dialect, withList, select, overridingSystemValue_) {
|
|
1684
|
+
super();
|
|
1685
|
+
this.session = session;
|
|
1686
|
+
this.dialect = dialect;
|
|
1687
|
+
this.config = {
|
|
1688
|
+
table,
|
|
1689
|
+
values,
|
|
1690
|
+
withList,
|
|
1691
|
+
select,
|
|
1692
|
+
overridingSystemValue_
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
static [entityKind] = "PgInsert";
|
|
1696
|
+
config;
|
|
1697
|
+
cacheConfig;
|
|
1698
|
+
returning(fields = this.config.table[Table.Symbol.Columns]) {
|
|
1699
|
+
this.config.returningFields = fields;
|
|
1700
|
+
this.config.returning = orderSelectedFields(fields);
|
|
1701
|
+
return this;
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* Adds an `on conflict do nothing` clause to the query.
|
|
1705
|
+
*
|
|
1706
|
+
* Calling this method simply avoids inserting a row as its alternative action.
|
|
1707
|
+
*
|
|
1708
|
+
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
|
|
1709
|
+
*
|
|
1710
|
+
* @param config The `target` and `where` clauses.
|
|
1711
|
+
*
|
|
1712
|
+
* @example
|
|
1713
|
+
* ```ts
|
|
1714
|
+
* // Insert one row and cancel the insert if there's a conflict
|
|
1715
|
+
* await db.insert(cars)
|
|
1716
|
+
* .values({ id: 1, brand: 'BMW' })
|
|
1717
|
+
* .onConflictDoNothing();
|
|
1718
|
+
*
|
|
1719
|
+
* // Explicitly specify conflict target
|
|
1720
|
+
* await db.insert(cars)
|
|
1721
|
+
* .values({ id: 1, brand: 'BMW' })
|
|
1722
|
+
* .onConflictDoNothing({ target: cars.id });
|
|
1723
|
+
* ```
|
|
1724
|
+
*/
|
|
1725
|
+
onConflictDoNothing(config = {}) {
|
|
1726
|
+
if (config.target === void 0) this.config.onConflict = sql`do nothing`;
|
|
1727
|
+
else {
|
|
1728
|
+
let targetColumn = "";
|
|
1729
|
+
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
|
|
1730
|
+
const whereSql = config.where ? sql` where ${config.where}` : void 0;
|
|
1731
|
+
this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
|
|
1732
|
+
}
|
|
1733
|
+
return this;
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Adds an `on conflict do update` clause to the query.
|
|
1737
|
+
*
|
|
1738
|
+
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
|
|
1739
|
+
*
|
|
1740
|
+
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
|
|
1741
|
+
*
|
|
1742
|
+
* @param config The `target`, `set` and `where` clauses.
|
|
1743
|
+
*
|
|
1744
|
+
* @example
|
|
1745
|
+
* ```ts
|
|
1746
|
+
* // Update the row if there's a conflict
|
|
1747
|
+
* await db.insert(cars)
|
|
1748
|
+
* .values({ id: 1, brand: 'BMW' })
|
|
1749
|
+
* .onConflictDoUpdate({
|
|
1750
|
+
* target: cars.id,
|
|
1751
|
+
* set: { brand: 'Porsche' }
|
|
1752
|
+
* });
|
|
1753
|
+
*
|
|
1754
|
+
* // Upsert with 'where' clause
|
|
1755
|
+
* await db.insert(cars)
|
|
1756
|
+
* .values({ id: 1, brand: 'BMW' })
|
|
1757
|
+
* .onConflictDoUpdate({
|
|
1758
|
+
* target: cars.id,
|
|
1759
|
+
* set: { brand: 'newBMW' },
|
|
1760
|
+
* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
|
|
1761
|
+
* });
|
|
1762
|
+
* ```
|
|
1763
|
+
*/
|
|
1764
|
+
onConflictDoUpdate(config) {
|
|
1765
|
+
if (config.where && (config.targetWhere || config.setWhere)) throw new Error("You cannot use both \"where\" and \"targetWhere\"/\"setWhere\" at the same time - \"where\" is deprecated, use \"targetWhere\" or \"setWhere\" instead.");
|
|
1766
|
+
const whereSql = config.where ? sql` where ${config.where}` : void 0;
|
|
1767
|
+
const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
|
|
1768
|
+
const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
|
|
1769
|
+
const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
|
|
1770
|
+
let targetColumn = "";
|
|
1771
|
+
targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
|
|
1772
|
+
this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
|
|
1773
|
+
return this;
|
|
1774
|
+
}
|
|
1775
|
+
/** @internal */
|
|
1776
|
+
getSQL() {
|
|
1777
|
+
return this.dialect.buildInsertQuery(this.config);
|
|
1778
|
+
}
|
|
1779
|
+
toSQL() {
|
|
1780
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
1781
|
+
return rest;
|
|
1782
|
+
}
|
|
1783
|
+
/** @internal */
|
|
1784
|
+
_prepare(name) {
|
|
1785
|
+
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
|
|
1786
|
+
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
|
|
1787
|
+
type: "insert",
|
|
1788
|
+
tables: extractUsedTable(this.config.table)
|
|
1789
|
+
}, this.cacheConfig);
|
|
1790
|
+
});
|
|
1791
|
+
}
|
|
1792
|
+
prepare(name) {
|
|
1793
|
+
return this._prepare(name);
|
|
1794
|
+
}
|
|
1795
|
+
authToken;
|
|
1796
|
+
/** @internal */
|
|
1797
|
+
setToken(token) {
|
|
1798
|
+
this.authToken = token;
|
|
1799
|
+
return this;
|
|
1800
|
+
}
|
|
1801
|
+
execute = (placeholderValues) => {
|
|
1802
|
+
return tracer.startActiveSpan("drizzle.operation", () => {
|
|
1803
|
+
return this._prepare().execute(placeholderValues, this.authToken);
|
|
1804
|
+
});
|
|
1805
|
+
};
|
|
1806
|
+
/** @internal */
|
|
1807
|
+
getSelectedFields() {
|
|
1808
|
+
return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({
|
|
1809
|
+
alias: getTableName(this.config.table),
|
|
1810
|
+
sqlAliasedBehavior: "alias",
|
|
1811
|
+
sqlBehavior: "error"
|
|
1812
|
+
})) : void 0;
|
|
1813
|
+
}
|
|
1814
|
+
$dynamic() {
|
|
1815
|
+
return this;
|
|
1816
|
+
}
|
|
1817
|
+
};
|
|
1818
|
+
//#endregion
|
|
1819
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js
|
|
1820
|
+
var PgRefreshMaterializedView = class extends QueryPromise {
|
|
1821
|
+
constructor(view, session, dialect) {
|
|
1822
|
+
super();
|
|
1823
|
+
this.session = session;
|
|
1824
|
+
this.dialect = dialect;
|
|
1825
|
+
this.config = { view };
|
|
1826
|
+
}
|
|
1827
|
+
static [entityKind] = "PgRefreshMaterializedView";
|
|
1828
|
+
config;
|
|
1829
|
+
concurrently() {
|
|
1830
|
+
if (this.config.withNoData !== void 0) throw new Error("Cannot use concurrently and withNoData together");
|
|
1831
|
+
this.config.concurrently = true;
|
|
1832
|
+
return this;
|
|
1833
|
+
}
|
|
1834
|
+
withNoData() {
|
|
1835
|
+
if (this.config.concurrently !== void 0) throw new Error("Cannot use concurrently and withNoData together");
|
|
1836
|
+
this.config.withNoData = true;
|
|
1837
|
+
return this;
|
|
1838
|
+
}
|
|
1839
|
+
/** @internal */
|
|
1840
|
+
getSQL() {
|
|
1841
|
+
return this.dialect.buildRefreshMaterializedViewQuery(this.config);
|
|
1842
|
+
}
|
|
1843
|
+
toSQL() {
|
|
1844
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
1845
|
+
return rest;
|
|
1846
|
+
}
|
|
1847
|
+
/** @internal */
|
|
1848
|
+
_prepare(name) {
|
|
1849
|
+
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
|
|
1850
|
+
return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true);
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
prepare(name) {
|
|
1854
|
+
return this._prepare(name);
|
|
1855
|
+
}
|
|
1856
|
+
authToken;
|
|
1857
|
+
/** @internal */
|
|
1858
|
+
setToken(token) {
|
|
1859
|
+
this.authToken = token;
|
|
1860
|
+
return this;
|
|
1861
|
+
}
|
|
1862
|
+
execute = (placeholderValues) => {
|
|
1863
|
+
return tracer.startActiveSpan("drizzle.operation", () => {
|
|
1864
|
+
return this._prepare().execute(placeholderValues, this.authToken);
|
|
1865
|
+
});
|
|
1866
|
+
};
|
|
1867
|
+
};
|
|
1868
|
+
//#endregion
|
|
1869
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/update.js
|
|
1870
|
+
var PgUpdateBuilder = class {
|
|
1871
|
+
constructor(table, session, dialect, withList) {
|
|
1872
|
+
this.table = table;
|
|
1873
|
+
this.session = session;
|
|
1874
|
+
this.dialect = dialect;
|
|
1875
|
+
this.withList = withList;
|
|
1876
|
+
}
|
|
1877
|
+
static [entityKind] = "PgUpdateBuilder";
|
|
1878
|
+
authToken;
|
|
1879
|
+
setToken(token) {
|
|
1880
|
+
this.authToken = token;
|
|
1881
|
+
return this;
|
|
1882
|
+
}
|
|
1883
|
+
set(values) {
|
|
1884
|
+
return new PgUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList).setToken(this.authToken);
|
|
1885
|
+
}
|
|
1886
|
+
};
|
|
1887
|
+
var PgUpdateBase = class extends QueryPromise {
|
|
1888
|
+
constructor(table, set, session, dialect, withList) {
|
|
1889
|
+
super();
|
|
1890
|
+
this.session = session;
|
|
1891
|
+
this.dialect = dialect;
|
|
1892
|
+
this.config = {
|
|
1893
|
+
set,
|
|
1894
|
+
table,
|
|
1895
|
+
withList,
|
|
1896
|
+
joins: []
|
|
1897
|
+
};
|
|
1898
|
+
this.tableName = getTableLikeName(table);
|
|
1899
|
+
this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
|
|
1900
|
+
}
|
|
1901
|
+
static [entityKind] = "PgUpdate";
|
|
1902
|
+
config;
|
|
1903
|
+
tableName;
|
|
1904
|
+
joinsNotNullableMap;
|
|
1905
|
+
cacheConfig;
|
|
1906
|
+
from(source) {
|
|
1907
|
+
const src = source;
|
|
1908
|
+
const tableName = getTableLikeName(src);
|
|
1909
|
+
if (typeof tableName === "string") this.joinsNotNullableMap[tableName] = true;
|
|
1910
|
+
this.config.from = src;
|
|
1911
|
+
return this;
|
|
1912
|
+
}
|
|
1913
|
+
getTableLikeFields(table) {
|
|
1914
|
+
if (is(table, PgTable)) return table[Table.Symbol.Columns];
|
|
1915
|
+
else if (is(table, Subquery)) return table._.selectedFields;
|
|
1916
|
+
return table[ViewBaseConfig].selectedFields;
|
|
1917
|
+
}
|
|
1918
|
+
createJoin(joinType) {
|
|
1919
|
+
return (table, on) => {
|
|
1920
|
+
const tableName = getTableLikeName(table);
|
|
1921
|
+
if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
|
|
1922
|
+
if (typeof on === "function") {
|
|
1923
|
+
const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
|
|
1924
|
+
on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
|
|
1925
|
+
sqlAliasedBehavior: "sql",
|
|
1926
|
+
sqlBehavior: "sql"
|
|
1927
|
+
})), from && new Proxy(from, new SelectionProxyHandler({
|
|
1928
|
+
sqlAliasedBehavior: "sql",
|
|
1929
|
+
sqlBehavior: "sql"
|
|
1930
|
+
})));
|
|
1931
|
+
}
|
|
1932
|
+
this.config.joins.push({
|
|
1933
|
+
on,
|
|
1934
|
+
table,
|
|
1935
|
+
joinType,
|
|
1936
|
+
alias: tableName
|
|
1937
|
+
});
|
|
1938
|
+
if (typeof tableName === "string") switch (joinType) {
|
|
1939
|
+
case "left":
|
|
1940
|
+
this.joinsNotNullableMap[tableName] = false;
|
|
1941
|
+
break;
|
|
1942
|
+
case "right":
|
|
1943
|
+
this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
|
|
1944
|
+
this.joinsNotNullableMap[tableName] = true;
|
|
1945
|
+
break;
|
|
1946
|
+
case "inner":
|
|
1947
|
+
this.joinsNotNullableMap[tableName] = true;
|
|
1948
|
+
break;
|
|
1949
|
+
case "full":
|
|
1950
|
+
this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
|
|
1951
|
+
this.joinsNotNullableMap[tableName] = false;
|
|
1952
|
+
}
|
|
1953
|
+
return this;
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
leftJoin = this.createJoin("left");
|
|
1957
|
+
rightJoin = this.createJoin("right");
|
|
1958
|
+
innerJoin = this.createJoin("inner");
|
|
1959
|
+
fullJoin = this.createJoin("full");
|
|
1960
|
+
/**
|
|
1961
|
+
* Adds a 'where' clause to the query.
|
|
1962
|
+
*
|
|
1963
|
+
* Calling this method will update only those rows that fulfill a specified condition.
|
|
1964
|
+
*
|
|
1965
|
+
* See docs: {@link https://orm.drizzle.team/docs/update}
|
|
1966
|
+
*
|
|
1967
|
+
* @param where the 'where' clause.
|
|
1968
|
+
*
|
|
1969
|
+
* @example
|
|
1970
|
+
* You can use conditional operators and `sql function` to filter the rows to be updated.
|
|
1971
|
+
*
|
|
1972
|
+
* ```ts
|
|
1973
|
+
* // Update all cars with green color
|
|
1974
|
+
* await db.update(cars).set({ color: 'red' })
|
|
1975
|
+
* .where(eq(cars.color, 'green'));
|
|
1976
|
+
* // or
|
|
1977
|
+
* await db.update(cars).set({ color: 'red' })
|
|
1978
|
+
* .where(sql`${cars.color} = 'green'`)
|
|
1979
|
+
* ```
|
|
1980
|
+
*
|
|
1981
|
+
* You can logically combine conditional operators with `and()` and `or()` operators:
|
|
1982
|
+
*
|
|
1983
|
+
* ```ts
|
|
1984
|
+
* // Update all BMW cars with a green color
|
|
1985
|
+
* await db.update(cars).set({ color: 'red' })
|
|
1986
|
+
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
|
|
1987
|
+
*
|
|
1988
|
+
* // Update all cars with the green or blue color
|
|
1989
|
+
* await db.update(cars).set({ color: 'red' })
|
|
1990
|
+
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
|
|
1991
|
+
* ```
|
|
1992
|
+
*/
|
|
1993
|
+
where(where) {
|
|
1994
|
+
this.config.where = where;
|
|
1995
|
+
return this;
|
|
1996
|
+
}
|
|
1997
|
+
returning(fields) {
|
|
1998
|
+
if (!fields) {
|
|
1999
|
+
fields = Object.assign({}, this.config.table[Table.Symbol.Columns]);
|
|
2000
|
+
if (this.config.from) {
|
|
2001
|
+
const tableName = getTableLikeName(this.config.from);
|
|
2002
|
+
if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
|
|
2003
|
+
const fromFields = this.getTableLikeFields(this.config.from);
|
|
2004
|
+
fields[tableName] = fromFields;
|
|
2005
|
+
}
|
|
2006
|
+
for (const join of this.config.joins) {
|
|
2007
|
+
const tableName2 = getTableLikeName(join.table);
|
|
2008
|
+
if (typeof tableName2 === "string" && !is(join.table, SQL)) {
|
|
2009
|
+
const fromFields = this.getTableLikeFields(join.table);
|
|
2010
|
+
fields[tableName2] = fromFields;
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
this.config.returningFields = fields;
|
|
2016
|
+
this.config.returning = orderSelectedFields(fields);
|
|
2017
|
+
return this;
|
|
2018
|
+
}
|
|
2019
|
+
/** @internal */
|
|
2020
|
+
getSQL() {
|
|
2021
|
+
return this.dialect.buildUpdateQuery(this.config);
|
|
2022
|
+
}
|
|
2023
|
+
toSQL() {
|
|
2024
|
+
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
|
|
2025
|
+
return rest;
|
|
2026
|
+
}
|
|
2027
|
+
/** @internal */
|
|
2028
|
+
_prepare(name) {
|
|
2029
|
+
const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, void 0, {
|
|
2030
|
+
type: "insert",
|
|
2031
|
+
tables: extractUsedTable(this.config.table)
|
|
2032
|
+
}, this.cacheConfig);
|
|
2033
|
+
query.joinsNotNullableMap = this.joinsNotNullableMap;
|
|
2034
|
+
return query;
|
|
2035
|
+
}
|
|
2036
|
+
prepare(name) {
|
|
2037
|
+
return this._prepare(name);
|
|
2038
|
+
}
|
|
2039
|
+
authToken;
|
|
2040
|
+
/** @internal */
|
|
2041
|
+
setToken(token) {
|
|
2042
|
+
this.authToken = token;
|
|
2043
|
+
return this;
|
|
2044
|
+
}
|
|
2045
|
+
execute = (placeholderValues) => {
|
|
2046
|
+
return this._prepare().execute(placeholderValues, this.authToken);
|
|
2047
|
+
};
|
|
2048
|
+
/** @internal */
|
|
2049
|
+
getSelectedFields() {
|
|
2050
|
+
return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({
|
|
2051
|
+
alias: getTableName(this.config.table),
|
|
2052
|
+
sqlAliasedBehavior: "alias",
|
|
2053
|
+
sqlBehavior: "error"
|
|
2054
|
+
})) : void 0;
|
|
2055
|
+
}
|
|
2056
|
+
$dynamic() {
|
|
2057
|
+
return this;
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
//#endregion
|
|
2061
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/count.js
|
|
2062
|
+
var PgCountBuilder = class PgCountBuilder extends SQL {
|
|
2063
|
+
constructor(params) {
|
|
2064
|
+
super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
|
|
2065
|
+
this.params = params;
|
|
2066
|
+
this.mapWith(Number);
|
|
2067
|
+
this.session = params.session;
|
|
2068
|
+
this.sql = PgCountBuilder.buildCount(params.source, params.filters);
|
|
2069
|
+
}
|
|
2070
|
+
sql;
|
|
2071
|
+
token;
|
|
2072
|
+
static [entityKind] = "PgCountBuilder";
|
|
2073
|
+
[Symbol.toStringTag] = "PgCountBuilder";
|
|
2074
|
+
session;
|
|
2075
|
+
static buildEmbeddedCount(source, filters) {
|
|
2076
|
+
return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
|
|
2077
|
+
}
|
|
2078
|
+
static buildCount(source, filters) {
|
|
2079
|
+
return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
|
|
2080
|
+
}
|
|
2081
|
+
/** @intrnal */
|
|
2082
|
+
setToken(token) {
|
|
2083
|
+
this.token = token;
|
|
2084
|
+
return this;
|
|
2085
|
+
}
|
|
2086
|
+
then(onfulfilled, onrejected) {
|
|
2087
|
+
return Promise.resolve(this.session.count(this.sql, this.token)).then(onfulfilled, onrejected);
|
|
2088
|
+
}
|
|
2089
|
+
catch(onRejected) {
|
|
2090
|
+
return this.then(void 0, onRejected);
|
|
2091
|
+
}
|
|
2092
|
+
finally(onFinally) {
|
|
2093
|
+
return this.then((value) => {
|
|
2094
|
+
onFinally?.();
|
|
2095
|
+
return value;
|
|
2096
|
+
}, (reason) => {
|
|
2097
|
+
onFinally?.();
|
|
2098
|
+
throw reason;
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
//#endregion
|
|
2103
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/query.js
|
|
2104
|
+
var RelationalQueryBuilder = class {
|
|
2105
|
+
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
|
|
2106
|
+
this.fullSchema = fullSchema;
|
|
2107
|
+
this.schema = schema;
|
|
2108
|
+
this.tableNamesMap = tableNamesMap;
|
|
2109
|
+
this.table = table;
|
|
2110
|
+
this.tableConfig = tableConfig;
|
|
2111
|
+
this.dialect = dialect;
|
|
2112
|
+
this.session = session;
|
|
2113
|
+
}
|
|
2114
|
+
static [entityKind] = "PgRelationalQueryBuilder";
|
|
2115
|
+
findMany(config) {
|
|
2116
|
+
return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
|
|
2117
|
+
}
|
|
2118
|
+
findFirst(config) {
|
|
2119
|
+
return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? {
|
|
2120
|
+
...config,
|
|
2121
|
+
limit: 1
|
|
2122
|
+
} : { limit: 1 }, "first");
|
|
2123
|
+
}
|
|
2124
|
+
};
|
|
2125
|
+
var PgRelationalQuery = class extends QueryPromise {
|
|
2126
|
+
constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
|
|
2127
|
+
super();
|
|
2128
|
+
this.fullSchema = fullSchema;
|
|
2129
|
+
this.schema = schema;
|
|
2130
|
+
this.tableNamesMap = tableNamesMap;
|
|
2131
|
+
this.table = table;
|
|
2132
|
+
this.tableConfig = tableConfig;
|
|
2133
|
+
this.dialect = dialect;
|
|
2134
|
+
this.session = session;
|
|
2135
|
+
this.config = config;
|
|
2136
|
+
this.mode = mode;
|
|
2137
|
+
}
|
|
2138
|
+
static [entityKind] = "PgRelationalQuery";
|
|
2139
|
+
/** @internal */
|
|
2140
|
+
_prepare(name) {
|
|
2141
|
+
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
|
|
2142
|
+
const { query, builtQuery } = this._toSQL();
|
|
2143
|
+
return this.session.prepareQuery(builtQuery, void 0, name, true, (rawRows, mapColumnValue) => {
|
|
2144
|
+
const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
|
|
2145
|
+
if (this.mode === "first") return rows[0];
|
|
2146
|
+
return rows;
|
|
2147
|
+
});
|
|
2148
|
+
});
|
|
2149
|
+
}
|
|
2150
|
+
prepare(name) {
|
|
2151
|
+
return this._prepare(name);
|
|
2152
|
+
}
|
|
2153
|
+
_getQuery() {
|
|
2154
|
+
return this.dialect.buildRelationalQueryWithoutPK({
|
|
2155
|
+
fullSchema: this.fullSchema,
|
|
2156
|
+
schema: this.schema,
|
|
2157
|
+
tableNamesMap: this.tableNamesMap,
|
|
2158
|
+
table: this.table,
|
|
2159
|
+
tableConfig: this.tableConfig,
|
|
2160
|
+
queryConfig: this.config,
|
|
2161
|
+
tableAlias: this.tableConfig.tsName
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
/** @internal */
|
|
2165
|
+
getSQL() {
|
|
2166
|
+
return this._getQuery().sql;
|
|
2167
|
+
}
|
|
2168
|
+
_toSQL() {
|
|
2169
|
+
const query = this._getQuery();
|
|
2170
|
+
return {
|
|
2171
|
+
query,
|
|
2172
|
+
builtQuery: this.dialect.sqlToQuery(query.sql)
|
|
2173
|
+
};
|
|
2174
|
+
}
|
|
2175
|
+
toSQL() {
|
|
2176
|
+
return this._toSQL().builtQuery;
|
|
2177
|
+
}
|
|
2178
|
+
authToken;
|
|
2179
|
+
/** @internal */
|
|
2180
|
+
setToken(token) {
|
|
2181
|
+
this.authToken = token;
|
|
2182
|
+
return this;
|
|
2183
|
+
}
|
|
2184
|
+
execute() {
|
|
2185
|
+
return tracer.startActiveSpan("drizzle.operation", () => {
|
|
2186
|
+
return this._prepare().execute(void 0, this.authToken);
|
|
2187
|
+
});
|
|
2188
|
+
}
|
|
2189
|
+
};
|
|
2190
|
+
//#endregion
|
|
2191
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/query-builders/raw.js
|
|
2192
|
+
var PgRaw = class extends QueryPromise {
|
|
2193
|
+
constructor(execute, sql, query, mapBatchResult) {
|
|
2194
|
+
super();
|
|
2195
|
+
this.execute = execute;
|
|
2196
|
+
this.sql = sql;
|
|
2197
|
+
this.query = query;
|
|
2198
|
+
this.mapBatchResult = mapBatchResult;
|
|
2199
|
+
}
|
|
2200
|
+
static [entityKind] = "PgRaw";
|
|
2201
|
+
/** @internal */
|
|
2202
|
+
getSQL() {
|
|
2203
|
+
return this.sql;
|
|
2204
|
+
}
|
|
2205
|
+
getQuery() {
|
|
2206
|
+
return this.query;
|
|
2207
|
+
}
|
|
2208
|
+
mapResult(result, isFromBatch) {
|
|
2209
|
+
return isFromBatch ? this.mapBatchResult(result) : result;
|
|
2210
|
+
}
|
|
2211
|
+
_prepare() {
|
|
2212
|
+
return this;
|
|
2213
|
+
}
|
|
2214
|
+
/** @internal */
|
|
2215
|
+
isResponseInArrayMode() {
|
|
2216
|
+
return false;
|
|
2217
|
+
}
|
|
2218
|
+
};
|
|
2219
|
+
//#endregion
|
|
2220
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/db.js
|
|
2221
|
+
var PgDatabase = class {
|
|
2222
|
+
constructor(dialect, session, schema) {
|
|
2223
|
+
this.dialect = dialect;
|
|
2224
|
+
this.session = session;
|
|
2225
|
+
this._ = schema ? {
|
|
2226
|
+
schema: schema.schema,
|
|
2227
|
+
fullSchema: schema.fullSchema,
|
|
2228
|
+
tableNamesMap: schema.tableNamesMap,
|
|
2229
|
+
session
|
|
2230
|
+
} : {
|
|
2231
|
+
schema: void 0,
|
|
2232
|
+
fullSchema: {},
|
|
2233
|
+
tableNamesMap: {},
|
|
2234
|
+
session
|
|
2235
|
+
};
|
|
2236
|
+
this.query = {};
|
|
2237
|
+
if (this._.schema) for (const [tableName, columns] of Object.entries(this._.schema)) this.query[tableName] = new RelationalQueryBuilder(schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
|
|
2238
|
+
this.$cache = { invalidate: async (_params) => {} };
|
|
2239
|
+
}
|
|
2240
|
+
static [entityKind] = "PgDatabase";
|
|
2241
|
+
query;
|
|
2242
|
+
/**
|
|
2243
|
+
* Creates a subquery that defines a temporary named result set as a CTE.
|
|
2244
|
+
*
|
|
2245
|
+
* It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
|
|
2246
|
+
*
|
|
2247
|
+
* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
|
|
2248
|
+
*
|
|
2249
|
+
* @param alias The alias for the subquery.
|
|
2250
|
+
*
|
|
2251
|
+
* Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
|
|
2252
|
+
*
|
|
2253
|
+
* @example
|
|
2254
|
+
*
|
|
2255
|
+
* ```ts
|
|
2256
|
+
* // Create a subquery with alias 'sq' and use it in the select query
|
|
2257
|
+
* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
|
|
2258
|
+
*
|
|
2259
|
+
* const result = await db.with(sq).select().from(sq);
|
|
2260
|
+
* ```
|
|
2261
|
+
*
|
|
2262
|
+
* To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
|
|
2263
|
+
*
|
|
2264
|
+
* ```ts
|
|
2265
|
+
* // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
|
|
2266
|
+
* const sq = db.$with('sq').as(db.select({
|
|
2267
|
+
* name: sql<string>`upper(${users.name})`.as('name'),
|
|
2268
|
+
* })
|
|
2269
|
+
* .from(users));
|
|
2270
|
+
*
|
|
2271
|
+
* const result = await db.with(sq).select({ name: sq.name }).from(sq);
|
|
2272
|
+
* ```
|
|
2273
|
+
*/
|
|
2274
|
+
$with = (alias, selection) => {
|
|
2275
|
+
const self = this;
|
|
2276
|
+
const as = (qb) => {
|
|
2277
|
+
if (typeof qb === "function") qb = qb(new QueryBuilder(self.dialect));
|
|
2278
|
+
return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({
|
|
2279
|
+
alias,
|
|
2280
|
+
sqlAliasedBehavior: "alias",
|
|
2281
|
+
sqlBehavior: "error"
|
|
2282
|
+
}));
|
|
2283
|
+
};
|
|
2284
|
+
return { as };
|
|
2285
|
+
};
|
|
2286
|
+
$count(source, filters) {
|
|
2287
|
+
return new PgCountBuilder({
|
|
2288
|
+
source,
|
|
2289
|
+
filters,
|
|
2290
|
+
session: this.session
|
|
2291
|
+
});
|
|
2292
|
+
}
|
|
2293
|
+
$cache;
|
|
2294
|
+
/**
|
|
2295
|
+
* Incorporates a previously defined CTE (using `$with`) into the main query.
|
|
2296
|
+
*
|
|
2297
|
+
* This method allows the main query to reference a temporary named result set.
|
|
2298
|
+
*
|
|
2299
|
+
* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
|
|
2300
|
+
*
|
|
2301
|
+
* @param queries The CTEs to incorporate into the main query.
|
|
2302
|
+
*
|
|
2303
|
+
* @example
|
|
2304
|
+
*
|
|
2305
|
+
* ```ts
|
|
2306
|
+
* // Define a subquery 'sq' as a CTE using $with
|
|
2307
|
+
* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
|
|
2308
|
+
*
|
|
2309
|
+
* // Incorporate the CTE 'sq' into the main query and select from it
|
|
2310
|
+
* const result = await db.with(sq).select().from(sq);
|
|
2311
|
+
* ```
|
|
2312
|
+
*/
|
|
2313
|
+
with(...queries) {
|
|
2314
|
+
const self = this;
|
|
2315
|
+
function select(fields) {
|
|
2316
|
+
return new PgSelectBuilder({
|
|
2317
|
+
fields: fields ?? void 0,
|
|
2318
|
+
session: self.session,
|
|
2319
|
+
dialect: self.dialect,
|
|
2320
|
+
withList: queries
|
|
2321
|
+
});
|
|
2322
|
+
}
|
|
2323
|
+
function selectDistinct(fields) {
|
|
2324
|
+
return new PgSelectBuilder({
|
|
2325
|
+
fields: fields ?? void 0,
|
|
2326
|
+
session: self.session,
|
|
2327
|
+
dialect: self.dialect,
|
|
2328
|
+
withList: queries,
|
|
2329
|
+
distinct: true
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
function selectDistinctOn(on, fields) {
|
|
2333
|
+
return new PgSelectBuilder({
|
|
2334
|
+
fields: fields ?? void 0,
|
|
2335
|
+
session: self.session,
|
|
2336
|
+
dialect: self.dialect,
|
|
2337
|
+
withList: queries,
|
|
2338
|
+
distinct: { on }
|
|
2339
|
+
});
|
|
2340
|
+
}
|
|
2341
|
+
function update(table) {
|
|
2342
|
+
return new PgUpdateBuilder(table, self.session, self.dialect, queries);
|
|
2343
|
+
}
|
|
2344
|
+
function insert(table) {
|
|
2345
|
+
return new PgInsertBuilder(table, self.session, self.dialect, queries);
|
|
2346
|
+
}
|
|
2347
|
+
function delete_(table) {
|
|
2348
|
+
return new PgDeleteBase(table, self.session, self.dialect, queries);
|
|
2349
|
+
}
|
|
2350
|
+
return {
|
|
2351
|
+
select,
|
|
2352
|
+
selectDistinct,
|
|
2353
|
+
selectDistinctOn,
|
|
2354
|
+
update,
|
|
2355
|
+
insert,
|
|
2356
|
+
delete: delete_
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
select(fields) {
|
|
2360
|
+
return new PgSelectBuilder({
|
|
2361
|
+
fields: fields ?? void 0,
|
|
2362
|
+
session: this.session,
|
|
2363
|
+
dialect: this.dialect
|
|
2364
|
+
});
|
|
2365
|
+
}
|
|
2366
|
+
selectDistinct(fields) {
|
|
2367
|
+
return new PgSelectBuilder({
|
|
2368
|
+
fields: fields ?? void 0,
|
|
2369
|
+
session: this.session,
|
|
2370
|
+
dialect: this.dialect,
|
|
2371
|
+
distinct: true
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
selectDistinctOn(on, fields) {
|
|
2375
|
+
return new PgSelectBuilder({
|
|
2376
|
+
fields: fields ?? void 0,
|
|
2377
|
+
session: this.session,
|
|
2378
|
+
dialect: this.dialect,
|
|
2379
|
+
distinct: { on }
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
/**
|
|
2383
|
+
* Creates an update query.
|
|
2384
|
+
*
|
|
2385
|
+
* Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
|
|
2386
|
+
*
|
|
2387
|
+
* Use `.set()` method to specify which values to update.
|
|
2388
|
+
*
|
|
2389
|
+
* See docs: {@link https://orm.drizzle.team/docs/update}
|
|
2390
|
+
*
|
|
2391
|
+
* @param table The table to update.
|
|
2392
|
+
*
|
|
2393
|
+
* @example
|
|
2394
|
+
*
|
|
2395
|
+
* ```ts
|
|
2396
|
+
* // Update all rows in the 'cars' table
|
|
2397
|
+
* await db.update(cars).set({ color: 'red' });
|
|
2398
|
+
*
|
|
2399
|
+
* // Update rows with filters and conditions
|
|
2400
|
+
* await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
|
|
2401
|
+
*
|
|
2402
|
+
* // Update with returning clause
|
|
2403
|
+
* const updatedCar: Car[] = await db.update(cars)
|
|
2404
|
+
* .set({ color: 'red' })
|
|
2405
|
+
* .where(eq(cars.id, 1))
|
|
2406
|
+
* .returning();
|
|
2407
|
+
* ```
|
|
2408
|
+
*/
|
|
2409
|
+
update(table) {
|
|
2410
|
+
return new PgUpdateBuilder(table, this.session, this.dialect);
|
|
2411
|
+
}
|
|
2412
|
+
/**
|
|
2413
|
+
* Creates an insert query.
|
|
2414
|
+
*
|
|
2415
|
+
* Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
|
|
2416
|
+
*
|
|
2417
|
+
* See docs: {@link https://orm.drizzle.team/docs/insert}
|
|
2418
|
+
*
|
|
2419
|
+
* @param table The table to insert into.
|
|
2420
|
+
*
|
|
2421
|
+
* @example
|
|
2422
|
+
*
|
|
2423
|
+
* ```ts
|
|
2424
|
+
* // Insert one row
|
|
2425
|
+
* await db.insert(cars).values({ brand: 'BMW' });
|
|
2426
|
+
*
|
|
2427
|
+
* // Insert multiple rows
|
|
2428
|
+
* await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
|
|
2429
|
+
*
|
|
2430
|
+
* // Insert with returning clause
|
|
2431
|
+
* const insertedCar: Car[] = await db.insert(cars)
|
|
2432
|
+
* .values({ brand: 'BMW' })
|
|
2433
|
+
* .returning();
|
|
2434
|
+
* ```
|
|
2435
|
+
*/
|
|
2436
|
+
insert(table) {
|
|
2437
|
+
return new PgInsertBuilder(table, this.session, this.dialect);
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Creates a delete query.
|
|
2441
|
+
*
|
|
2442
|
+
* Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
|
|
2443
|
+
*
|
|
2444
|
+
* See docs: {@link https://orm.drizzle.team/docs/delete}
|
|
2445
|
+
*
|
|
2446
|
+
* @param table The table to delete from.
|
|
2447
|
+
*
|
|
2448
|
+
* @example
|
|
2449
|
+
*
|
|
2450
|
+
* ```ts
|
|
2451
|
+
* // Delete all rows in the 'cars' table
|
|
2452
|
+
* await db.delete(cars);
|
|
2453
|
+
*
|
|
2454
|
+
* // Delete rows with filters and conditions
|
|
2455
|
+
* await db.delete(cars).where(eq(cars.color, 'green'));
|
|
2456
|
+
*
|
|
2457
|
+
* // Delete with returning clause
|
|
2458
|
+
* const deletedCar: Car[] = await db.delete(cars)
|
|
2459
|
+
* .where(eq(cars.id, 1))
|
|
2460
|
+
* .returning();
|
|
2461
|
+
* ```
|
|
2462
|
+
*/
|
|
2463
|
+
delete(table) {
|
|
2464
|
+
return new PgDeleteBase(table, this.session, this.dialect);
|
|
2465
|
+
}
|
|
2466
|
+
refreshMaterializedView(view) {
|
|
2467
|
+
return new PgRefreshMaterializedView(view, this.session, this.dialect);
|
|
2468
|
+
}
|
|
2469
|
+
authToken;
|
|
2470
|
+
execute(query) {
|
|
2471
|
+
const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
|
|
2472
|
+
const builtQuery = this.dialect.sqlToQuery(sequel);
|
|
2473
|
+
const prepared = this.session.prepareQuery(builtQuery, void 0, void 0, false);
|
|
2474
|
+
return new PgRaw(() => prepared.execute(void 0, this.authToken), sequel, builtQuery, (result) => prepared.mapResult(result, true));
|
|
2475
|
+
}
|
|
2476
|
+
transaction(transaction, config) {
|
|
2477
|
+
return this.session.transaction(transaction, config);
|
|
2478
|
+
}
|
|
2479
|
+
};
|
|
2480
|
+
//#endregion
|
|
2481
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/cache/core/cache.js
|
|
2482
|
+
var Cache = class {
|
|
2483
|
+
static [entityKind] = "Cache";
|
|
2484
|
+
};
|
|
2485
|
+
var NoopCache = class extends Cache {
|
|
2486
|
+
strategy() {
|
|
2487
|
+
return "all";
|
|
2488
|
+
}
|
|
2489
|
+
static [entityKind] = "NoopCache";
|
|
2490
|
+
async get(_key) {}
|
|
2491
|
+
async put(_hashedQuery, _response, _tables, _config) {}
|
|
2492
|
+
async onMutate(_params) {}
|
|
2493
|
+
};
|
|
2494
|
+
async function hashQuery(sql, params) {
|
|
2495
|
+
const dataToHash = `${sql}-${JSON.stringify(params)}`;
|
|
2496
|
+
const data = new TextEncoder().encode(dataToHash);
|
|
2497
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
2498
|
+
return [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2499
|
+
}
|
|
2500
|
+
//#endregion
|
|
2501
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/pg-core/session.js
|
|
2502
|
+
var PgPreparedQuery = class {
|
|
2503
|
+
constructor(query, cache, queryMetadata, cacheConfig) {
|
|
2504
|
+
this.query = query;
|
|
2505
|
+
this.cache = cache;
|
|
2506
|
+
this.queryMetadata = queryMetadata;
|
|
2507
|
+
this.cacheConfig = cacheConfig;
|
|
2508
|
+
if (cache && cache.strategy() === "all" && cacheConfig === void 0) this.cacheConfig = {
|
|
2509
|
+
enable: true,
|
|
2510
|
+
autoInvalidate: true
|
|
2511
|
+
};
|
|
2512
|
+
if (!this.cacheConfig?.enable) this.cacheConfig = void 0;
|
|
2513
|
+
}
|
|
2514
|
+
authToken;
|
|
2515
|
+
getQuery() {
|
|
2516
|
+
return this.query;
|
|
2517
|
+
}
|
|
2518
|
+
mapResult(response, _isFromBatch) {
|
|
2519
|
+
return response;
|
|
2520
|
+
}
|
|
2521
|
+
/** @internal */
|
|
2522
|
+
setToken(token) {
|
|
2523
|
+
this.authToken = token;
|
|
2524
|
+
return this;
|
|
2525
|
+
}
|
|
2526
|
+
static [entityKind] = "PgPreparedQuery";
|
|
2527
|
+
/** @internal */
|
|
2528
|
+
joinsNotNullableMap;
|
|
2529
|
+
/** @internal */
|
|
2530
|
+
async queryWithCache(queryString, params, query) {
|
|
2531
|
+
if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) try {
|
|
2532
|
+
return await query();
|
|
2533
|
+
} catch (e) {
|
|
2534
|
+
throw new DrizzleQueryError(queryString, params, e);
|
|
2535
|
+
}
|
|
2536
|
+
if (this.cacheConfig && !this.cacheConfig.enable) try {
|
|
2537
|
+
return await query();
|
|
2538
|
+
} catch (e) {
|
|
2539
|
+
throw new DrizzleQueryError(queryString, params, e);
|
|
2540
|
+
}
|
|
2541
|
+
if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) try {
|
|
2542
|
+
const [res] = await Promise.all([query(), this.cache.onMutate({ tables: this.queryMetadata.tables })]);
|
|
2543
|
+
return res;
|
|
2544
|
+
} catch (e) {
|
|
2545
|
+
throw new DrizzleQueryError(queryString, params, e);
|
|
2546
|
+
}
|
|
2547
|
+
if (!this.cacheConfig) try {
|
|
2548
|
+
return await query();
|
|
2549
|
+
} catch (e) {
|
|
2550
|
+
throw new DrizzleQueryError(queryString, params, e);
|
|
2551
|
+
}
|
|
2552
|
+
if (this.queryMetadata.type === "select") {
|
|
2553
|
+
const fromCache = await this.cache.get(this.cacheConfig.tag ?? await hashQuery(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== void 0, this.cacheConfig.autoInvalidate);
|
|
2554
|
+
if (fromCache === void 0) {
|
|
2555
|
+
let result;
|
|
2556
|
+
try {
|
|
2557
|
+
result = await query();
|
|
2558
|
+
} catch (e) {
|
|
2559
|
+
throw new DrizzleQueryError(queryString, params, e);
|
|
2560
|
+
}
|
|
2561
|
+
await this.cache.put(this.cacheConfig.tag ?? await hashQuery(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== void 0, this.cacheConfig.config);
|
|
2562
|
+
return result;
|
|
2563
|
+
}
|
|
2564
|
+
return fromCache;
|
|
2565
|
+
}
|
|
2566
|
+
try {
|
|
2567
|
+
return await query();
|
|
2568
|
+
} catch (e) {
|
|
2569
|
+
throw new DrizzleQueryError(queryString, params, e);
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
};
|
|
2573
|
+
var PgSession = class {
|
|
2574
|
+
constructor(dialect) {
|
|
2575
|
+
this.dialect = dialect;
|
|
2576
|
+
}
|
|
2577
|
+
static [entityKind] = "PgSession";
|
|
2578
|
+
/** @internal */
|
|
2579
|
+
execute(query, token) {
|
|
2580
|
+
return tracer.startActiveSpan("drizzle.operation", () => {
|
|
2581
|
+
return tracer.startActiveSpan("drizzle.prepareQuery", () => {
|
|
2582
|
+
return this.prepareQuery(this.dialect.sqlToQuery(query), void 0, void 0, false);
|
|
2583
|
+
}).setToken(token).execute(void 0, token);
|
|
2584
|
+
});
|
|
2585
|
+
}
|
|
2586
|
+
all(query) {
|
|
2587
|
+
return this.prepareQuery(this.dialect.sqlToQuery(query), void 0, void 0, false).all();
|
|
2588
|
+
}
|
|
2589
|
+
/** @internal */
|
|
2590
|
+
async count(sql2, token) {
|
|
2591
|
+
const res = await this.execute(sql2, token);
|
|
2592
|
+
return Number(res[0]["count"]);
|
|
2593
|
+
}
|
|
2594
|
+
};
|
|
2595
|
+
var PgTransaction = class extends PgDatabase {
|
|
2596
|
+
constructor(dialect, session, schema, nestedIndex = 0) {
|
|
2597
|
+
super(dialect, session, schema);
|
|
2598
|
+
this.schema = schema;
|
|
2599
|
+
this.nestedIndex = nestedIndex;
|
|
2600
|
+
}
|
|
2601
|
+
static [entityKind] = "PgTransaction";
|
|
2602
|
+
rollback() {
|
|
2603
|
+
throw new TransactionRollbackError();
|
|
2604
|
+
}
|
|
2605
|
+
/** @internal */
|
|
2606
|
+
getTransactionConfigSQL(config) {
|
|
2607
|
+
const chunks = [];
|
|
2608
|
+
if (config.isolationLevel) chunks.push(`isolation level ${config.isolationLevel}`);
|
|
2609
|
+
if (config.accessMode) chunks.push(config.accessMode);
|
|
2610
|
+
if (typeof config.deferrable === "boolean") chunks.push(config.deferrable ? "deferrable" : "not deferrable");
|
|
2611
|
+
return sql.raw(chunks.join(" "));
|
|
2612
|
+
}
|
|
2613
|
+
setTransaction(config) {
|
|
2614
|
+
return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
|
|
2615
|
+
}
|
|
2616
|
+
};
|
|
2617
|
+
//#endregion
|
|
2618
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/node-postgres/session.js
|
|
2619
|
+
const { Pool, types } = esm_default;
|
|
2620
|
+
var NodePgPreparedQuery = class extends PgPreparedQuery {
|
|
2621
|
+
constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, name, _isResponseInArrayMode, customResultMapper) {
|
|
2622
|
+
super({
|
|
2623
|
+
sql: queryString,
|
|
2624
|
+
params
|
|
2625
|
+
}, cache, queryMetadata, cacheConfig);
|
|
2626
|
+
this.client = client;
|
|
2627
|
+
this.queryString = queryString;
|
|
2628
|
+
this.params = params;
|
|
2629
|
+
this.logger = logger;
|
|
2630
|
+
this.fields = fields;
|
|
2631
|
+
this._isResponseInArrayMode = _isResponseInArrayMode;
|
|
2632
|
+
this.customResultMapper = customResultMapper;
|
|
2633
|
+
this.rawQueryConfig = {
|
|
2634
|
+
name,
|
|
2635
|
+
text: queryString,
|
|
2636
|
+
types: { getTypeParser: (typeId, format) => {
|
|
2637
|
+
if (typeId === types.builtins.TIMESTAMPTZ) return (val) => val;
|
|
2638
|
+
if (typeId === types.builtins.TIMESTAMP) return (val) => val;
|
|
2639
|
+
if (typeId === types.builtins.DATE) return (val) => val;
|
|
2640
|
+
if (typeId === types.builtins.INTERVAL) return (val) => val;
|
|
2641
|
+
if (typeId === 1231) return (val) => val;
|
|
2642
|
+
if (typeId === 1115) return (val) => val;
|
|
2643
|
+
if (typeId === 1185) return (val) => val;
|
|
2644
|
+
if (typeId === 1187) return (val) => val;
|
|
2645
|
+
if (typeId === 1182) return (val) => val;
|
|
2646
|
+
return types.getTypeParser(typeId, format);
|
|
2647
|
+
} }
|
|
2648
|
+
};
|
|
2649
|
+
this.queryConfig = {
|
|
2650
|
+
name,
|
|
2651
|
+
text: queryString,
|
|
2652
|
+
rowMode: "array",
|
|
2653
|
+
types: { getTypeParser: (typeId, format) => {
|
|
2654
|
+
if (typeId === types.builtins.TIMESTAMPTZ) return (val) => val;
|
|
2655
|
+
if (typeId === types.builtins.TIMESTAMP) return (val) => val;
|
|
2656
|
+
if (typeId === types.builtins.DATE) return (val) => val;
|
|
2657
|
+
if (typeId === types.builtins.INTERVAL) return (val) => val;
|
|
2658
|
+
if (typeId === 1231) return (val) => val;
|
|
2659
|
+
if (typeId === 1115) return (val) => val;
|
|
2660
|
+
if (typeId === 1185) return (val) => val;
|
|
2661
|
+
if (typeId === 1187) return (val) => val;
|
|
2662
|
+
if (typeId === 1182) return (val) => val;
|
|
2663
|
+
return types.getTypeParser(typeId, format);
|
|
2664
|
+
} }
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
static [entityKind] = "NodePgPreparedQuery";
|
|
2668
|
+
rawQueryConfig;
|
|
2669
|
+
queryConfig;
|
|
2670
|
+
async execute(placeholderValues = {}) {
|
|
2671
|
+
return tracer.startActiveSpan("drizzle.execute", async () => {
|
|
2672
|
+
const params = fillPlaceholders(this.params, placeholderValues);
|
|
2673
|
+
this.logger.logQuery(this.rawQueryConfig.text, params);
|
|
2674
|
+
const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } = this;
|
|
2675
|
+
if (!fields && !customResultMapper) return tracer.startActiveSpan("drizzle.driver.execute", async (span) => {
|
|
2676
|
+
span?.setAttributes({
|
|
2677
|
+
"drizzle.query.name": rawQuery.name,
|
|
2678
|
+
"drizzle.query.text": rawQuery.text,
|
|
2679
|
+
"drizzle.query.params": JSON.stringify(params)
|
|
2680
|
+
});
|
|
2681
|
+
return this.queryWithCache(rawQuery.text, params, async () => {
|
|
2682
|
+
return await client.query(rawQuery, params);
|
|
2683
|
+
});
|
|
2684
|
+
});
|
|
2685
|
+
const result = await tracer.startActiveSpan("drizzle.driver.execute", (span) => {
|
|
2686
|
+
span?.setAttributes({
|
|
2687
|
+
"drizzle.query.name": query.name,
|
|
2688
|
+
"drizzle.query.text": query.text,
|
|
2689
|
+
"drizzle.query.params": JSON.stringify(params)
|
|
2690
|
+
});
|
|
2691
|
+
return this.queryWithCache(query.text, params, async () => {
|
|
2692
|
+
return await client.query(query, params);
|
|
2693
|
+
});
|
|
2694
|
+
});
|
|
2695
|
+
return tracer.startActiveSpan("drizzle.mapResponse", () => {
|
|
2696
|
+
return customResultMapper ? customResultMapper(result.rows) : result.rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
|
|
2697
|
+
});
|
|
2698
|
+
});
|
|
2699
|
+
}
|
|
2700
|
+
all(placeholderValues = {}) {
|
|
2701
|
+
return tracer.startActiveSpan("drizzle.execute", () => {
|
|
2702
|
+
const params = fillPlaceholders(this.params, placeholderValues);
|
|
2703
|
+
this.logger.logQuery(this.rawQueryConfig.text, params);
|
|
2704
|
+
return tracer.startActiveSpan("drizzle.driver.execute", (span) => {
|
|
2705
|
+
span?.setAttributes({
|
|
2706
|
+
"drizzle.query.name": this.rawQueryConfig.name,
|
|
2707
|
+
"drizzle.query.text": this.rawQueryConfig.text,
|
|
2708
|
+
"drizzle.query.params": JSON.stringify(params)
|
|
2709
|
+
});
|
|
2710
|
+
return this.queryWithCache(this.rawQueryConfig.text, params, async () => {
|
|
2711
|
+
return this.client.query(this.rawQueryConfig, params);
|
|
2712
|
+
}).then((result) => result.rows);
|
|
2713
|
+
});
|
|
2714
|
+
});
|
|
2715
|
+
}
|
|
2716
|
+
/** @internal */
|
|
2717
|
+
isResponseInArrayMode() {
|
|
2718
|
+
return this._isResponseInArrayMode;
|
|
2719
|
+
}
|
|
2720
|
+
};
|
|
2721
|
+
var NodePgSession = class NodePgSession extends PgSession {
|
|
2722
|
+
constructor(client, dialect, schema, options = {}) {
|
|
2723
|
+
super(dialect);
|
|
2724
|
+
this.client = client;
|
|
2725
|
+
this.schema = schema;
|
|
2726
|
+
this.options = options;
|
|
2727
|
+
this.logger = options.logger ?? new NoopLogger();
|
|
2728
|
+
this.cache = options.cache ?? new NoopCache();
|
|
2729
|
+
}
|
|
2730
|
+
static [entityKind] = "NodePgSession";
|
|
2731
|
+
logger;
|
|
2732
|
+
cache;
|
|
2733
|
+
prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
|
|
2734
|
+
return new NodePgPreparedQuery(this.client, query.sql, query.params, this.logger, this.cache, queryMetadata, cacheConfig, fields, name, isResponseInArrayMode, customResultMapper);
|
|
2735
|
+
}
|
|
2736
|
+
async transaction(transaction, config) {
|
|
2737
|
+
const isPool = this.client instanceof Pool || Object.getPrototypeOf(this.client).constructor.name.includes("Pool");
|
|
2738
|
+
const session = isPool ? new NodePgSession(await this.client.connect(), this.dialect, this.schema, this.options) : this;
|
|
2739
|
+
const tx = new NodePgTransaction(this.dialect, session, this.schema);
|
|
2740
|
+
await tx.execute(sql`begin${config ? sql` ${tx.getTransactionConfigSQL(config)}` : void 0}`);
|
|
2741
|
+
try {
|
|
2742
|
+
const result = await transaction(tx);
|
|
2743
|
+
await tx.execute(sql`commit`);
|
|
2744
|
+
return result;
|
|
2745
|
+
} catch (error) {
|
|
2746
|
+
await tx.execute(sql`rollback`);
|
|
2747
|
+
throw error;
|
|
2748
|
+
} finally {
|
|
2749
|
+
if (isPool) session.client.release();
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
async count(sql2) {
|
|
2753
|
+
const res = await this.execute(sql2);
|
|
2754
|
+
return Number(res["rows"][0]["count"]);
|
|
2755
|
+
}
|
|
2756
|
+
};
|
|
2757
|
+
var NodePgTransaction = class NodePgTransaction extends PgTransaction {
|
|
2758
|
+
static [entityKind] = "NodePgTransaction";
|
|
2759
|
+
async transaction(transaction) {
|
|
2760
|
+
const savepointName = `sp${this.nestedIndex + 1}`;
|
|
2761
|
+
const tx = new NodePgTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1);
|
|
2762
|
+
await tx.execute(sql.raw(`savepoint ${savepointName}`));
|
|
2763
|
+
try {
|
|
2764
|
+
const result = await transaction(tx);
|
|
2765
|
+
await tx.execute(sql.raw(`release savepoint ${savepointName}`));
|
|
2766
|
+
return result;
|
|
2767
|
+
} catch (err) {
|
|
2768
|
+
await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
|
|
2769
|
+
throw err;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
};
|
|
2773
|
+
//#endregion
|
|
2774
|
+
//#region ../../node_modules/.pnpm/drizzle-orm@0.45.2_@cloudflare+workers-types@5.20260920.1_@libsql+client@0.18.0_@types+pg@8.20.0_pg@8.16.3/node_modules/drizzle-orm/node-postgres/driver.js
|
|
2775
|
+
var NodePgDriver = class {
|
|
2776
|
+
constructor(client, dialect, options = {}) {
|
|
2777
|
+
this.client = client;
|
|
2778
|
+
this.dialect = dialect;
|
|
2779
|
+
this.options = options;
|
|
2780
|
+
}
|
|
2781
|
+
static [entityKind] = "NodePgDriver";
|
|
2782
|
+
createSession(schema) {
|
|
2783
|
+
return new NodePgSession(this.client, this.dialect, schema, {
|
|
2784
|
+
logger: this.options.logger,
|
|
2785
|
+
cache: this.options.cache
|
|
2786
|
+
});
|
|
2787
|
+
}
|
|
2788
|
+
};
|
|
2789
|
+
var NodePgDatabase = class extends PgDatabase {
|
|
2790
|
+
static [entityKind] = "NodePgDatabase";
|
|
2791
|
+
};
|
|
2792
|
+
function construct(client, config = {}) {
|
|
2793
|
+
const dialect = new PgDialect({ casing: config.casing });
|
|
2794
|
+
let logger;
|
|
2795
|
+
if (config.logger === true) logger = new DefaultLogger();
|
|
2796
|
+
else if (config.logger !== false) logger = config.logger;
|
|
2797
|
+
let schema;
|
|
2798
|
+
if (config.schema) {
|
|
2799
|
+
const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
|
|
2800
|
+
schema = {
|
|
2801
|
+
fullSchema: config.schema,
|
|
2802
|
+
schema: tablesConfig.tables,
|
|
2803
|
+
tableNamesMap: tablesConfig.tableNamesMap
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
const db = new NodePgDatabase(dialect, new NodePgDriver(client, dialect, {
|
|
2807
|
+
logger,
|
|
2808
|
+
cache: config.cache
|
|
2809
|
+
}).createSession(schema), schema);
|
|
2810
|
+
db.$client = client;
|
|
2811
|
+
db.$cache = config.cache;
|
|
2812
|
+
if (db.$cache) db.$cache["invalidate"] = config.cache?.onMutate;
|
|
2813
|
+
return db;
|
|
2814
|
+
}
|
|
2815
|
+
function drizzle(...params) {
|
|
2816
|
+
if (typeof params[0] === "string") return construct(new esm_default.Pool({ connectionString: params[0] }), params[1]);
|
|
2817
|
+
if (isConfig(params[0])) {
|
|
2818
|
+
const { connection, client, ...drizzleConfig } = params[0];
|
|
2819
|
+
if (client) return construct(client, drizzleConfig);
|
|
2820
|
+
return construct(typeof connection === "string" ? new esm_default.Pool({ connectionString: connection }) : new esm_default.Pool(connection), drizzleConfig);
|
|
2821
|
+
}
|
|
2822
|
+
return construct(params[0], params[1]);
|
|
2823
|
+
}
|
|
2824
|
+
((drizzle2) => {
|
|
2825
|
+
function mock(config) {
|
|
2826
|
+
return construct({}, config);
|
|
2827
|
+
}
|
|
2828
|
+
drizzle2.mock = mock;
|
|
2829
|
+
})(drizzle || (drizzle = {}));
|
|
2830
|
+
//#endregion
|
|
2831
|
+
export { NodePgSession as a, NodePgPreparedQuery as i, NodePgDriver as n, NodePgTransaction as o, drizzle as r, NodePgDatabase as t };
|