pqb 0.71.4 → 0.72.1
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/dist/bun.d.ts +1 -4
- package/dist/bun.js.map +1 -1
- package/dist/bun.mjs.map +1 -1
- package/dist/index.d.ts +546 -594
- package/dist/index.js +267 -212
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +262 -212
- package/dist/index.mjs.map +1 -1
- package/dist/internal.d.ts +6576 -6631
- package/dist/internal.js +6158 -0
- package/dist/internal.js.map +1 -1
- package/dist/internal.mjs +6136 -7
- package/dist/internal.mjs.map +1 -1
- package/dist/node-postgres.d.ts +1 -4
- package/dist/node-postgres.js +1 -1
- package/dist/node-postgres.js.map +1 -1
- package/dist/node-postgres.mjs.map +1 -1
- package/dist/postgres-js.js +1 -1
- package/dist/postgres-js.js.map +1 -1
- package/dist/postgres-js.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -15,7 +15,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
15
|
}
|
|
16
16
|
return to;
|
|
17
17
|
};
|
|
18
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
19
19
|
value: mod,
|
|
20
20
|
enumerable: true
|
|
21
21
|
}) : target, mod));
|
|
@@ -455,9 +455,14 @@ var RawSql = class extends Expression {
|
|
|
455
455
|
};
|
|
456
456
|
const isRawSQL = (arg) => arg instanceof RawSql;
|
|
457
457
|
RawSql.prototype.type = ExpressionTypeMethod.prototype.type;
|
|
458
|
-
const rawSqlToCode = (rawSql,
|
|
458
|
+
const rawSqlToCode = (rawSql, ctx) => {
|
|
459
459
|
const { _sql: sql, _values: values } = rawSql;
|
|
460
|
-
let code
|
|
460
|
+
let code;
|
|
461
|
+
if (typeof ctx === "string") code = `${ctx}.sql`;
|
|
462
|
+
else {
|
|
463
|
+
ctx.isSqlUsed = true;
|
|
464
|
+
code = ctx.sql ?? `${ctx.t}.sql`;
|
|
465
|
+
}
|
|
461
466
|
code += typeof sql === "string" ? values ? `({ raw: '${sql.replace(/'/g, "\\'")}' })` : `\`${sql.replace(/`/g, "\\`")}\`` : templateLiteralSQLToCode(sql);
|
|
462
467
|
if (values) code += `.values(${JSON.stringify(values)})`;
|
|
463
468
|
return code;
|
|
@@ -593,6 +598,15 @@ const parseIndexOrExclude = (item) => {
|
|
|
593
598
|
for (let i = item.columns.length - 1; i >= 0; i--) if (typeof item.columns[i] === "string") item.columns[i] = { column: item.columns[i] };
|
|
594
599
|
return item;
|
|
595
600
|
};
|
|
601
|
+
const getForeignKeyTableInstance = (table) => {
|
|
602
|
+
const item = "instance" in table ? table.instance() : new table();
|
|
603
|
+
if (!item.table) throw new Error("Referenced table is missing table property");
|
|
604
|
+
return {
|
|
605
|
+
...item,
|
|
606
|
+
schema: typeof item.schema === "function" ? item.schema() : item.schema,
|
|
607
|
+
table: item.table
|
|
608
|
+
};
|
|
609
|
+
};
|
|
596
610
|
function makeColumnNullable(column, inputSchema, outputSchema, querySchema) {
|
|
597
611
|
const c = setColumnData(column, "isNullable", true);
|
|
598
612
|
c.inputSchema = inputSchema;
|
|
@@ -664,20 +678,17 @@ var Column = class {
|
|
|
664
678
|
* Or you can specify a callback that returns a value. This function will be called for each creating record. Such a default won't be applied to a database.
|
|
665
679
|
*
|
|
666
680
|
* ```ts
|
|
667
|
-
* export
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
*
|
|
671
|
-
* int: t.integer().default(123),
|
|
672
|
-
* text: t.text().default('text'),
|
|
681
|
+
* export const Table = defineTable('table', (t) => ({
|
|
682
|
+
* // values as defaults:
|
|
683
|
+
* int: t.integer().default(123),
|
|
684
|
+
* text: t.text().default('text'),
|
|
673
685
|
*
|
|
674
|
-
*
|
|
675
|
-
*
|
|
686
|
+
* // raw SQL default:
|
|
687
|
+
* timestamp: t.timestamp().default(t.sql`now()`),
|
|
676
688
|
*
|
|
677
|
-
*
|
|
678
|
-
*
|
|
679
|
-
*
|
|
680
|
-
* }
|
|
689
|
+
* // runtime default, each new records gets a new random value:
|
|
690
|
+
* random: t.numeric().default(() => Math.random()),
|
|
691
|
+
* }));
|
|
681
692
|
* ```
|
|
682
693
|
*
|
|
683
694
|
* @param value - default value or a function returning a value
|
|
@@ -772,14 +783,11 @@ var Column = class {
|
|
|
772
783
|
* It won't be selected with `selectAll` or `select('*')` as well.
|
|
773
784
|
*
|
|
774
785
|
* ```ts
|
|
775
|
-
* export
|
|
776
|
-
*
|
|
777
|
-
*
|
|
778
|
-
*
|
|
779
|
-
*
|
|
780
|
-
* password: t.string().select(false),
|
|
781
|
-
* }));
|
|
782
|
-
* }
|
|
786
|
+
* export const UserTable = defineTable('user', (t) => ({
|
|
787
|
+
* id: t.identity().primaryKey(),
|
|
788
|
+
* name: t.string(),
|
|
789
|
+
* password: t.string().select(false),
|
|
790
|
+
* }));
|
|
783
791
|
*
|
|
784
792
|
* // only id and name are selected, without password
|
|
785
793
|
* const user = await db.user.find(123);
|
|
@@ -822,20 +830,17 @@ var Column = class {
|
|
|
822
830
|
* `readOnly` column can be used together with a `default`.
|
|
823
831
|
*
|
|
824
832
|
* ```ts
|
|
825
|
-
* export
|
|
826
|
-
*
|
|
827
|
-
*
|
|
828
|
-
*
|
|
829
|
-
*
|
|
830
|
-
*
|
|
831
|
-
*
|
|
832
|
-
*
|
|
833
|
-
* init(orm: typeof db) {
|
|
834
|
-
* this.beforeSave(({ set }) => {
|
|
833
|
+
* export const Table = defineTable('table', (t) => ({
|
|
834
|
+
* id: t.identity().primaryKey(),
|
|
835
|
+
* column: t.string().default(() => 'default value'),
|
|
836
|
+
* another: t.string().nullable().readOnly(),
|
|
837
|
+
* })).init((orm: typeof db, hooks) => {
|
|
838
|
+
* hooks.beforeSave(({ columns, set }) => {
|
|
839
|
+
* if (columns.include('column')) {
|
|
835
840
|
* set({ another: 'value' });
|
|
836
|
-
* }
|
|
837
|
-
* }
|
|
838
|
-
* }
|
|
841
|
+
* }
|
|
842
|
+
* });
|
|
843
|
+
* });
|
|
839
844
|
*
|
|
840
845
|
* // later in the code
|
|
841
846
|
* db.table.create({ column: 'value' }); // TS error, runtime error
|
|
@@ -851,13 +856,15 @@ var Column = class {
|
|
|
851
856
|
* If no value or undefined is returned, the hook won't have any effect.
|
|
852
857
|
*
|
|
853
858
|
* ```ts
|
|
854
|
-
* export
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
858
|
-
*
|
|
859
|
-
*
|
|
860
|
-
*
|
|
859
|
+
* export const Table = defineTable('table', (t) => ({
|
|
860
|
+
* id: t.identity().primaryKey(),
|
|
861
|
+
* some: t.number(),
|
|
862
|
+
* column: t
|
|
863
|
+
* .string()
|
|
864
|
+
* .setOnCreate(({ columns }) =>
|
|
865
|
+
* columns.include('some') ? 'value' : undefined,
|
|
866
|
+
* ),
|
|
867
|
+
* }));
|
|
861
868
|
* ```
|
|
862
869
|
*/
|
|
863
870
|
setOnCreate(fn) {
|
|
@@ -870,13 +877,15 @@ var Column = class {
|
|
|
870
877
|
* If no value or undefined is returned, the hook won't have any effect.
|
|
871
878
|
*
|
|
872
879
|
* ```ts
|
|
873
|
-
* export
|
|
874
|
-
*
|
|
875
|
-
*
|
|
876
|
-
*
|
|
877
|
-
*
|
|
878
|
-
*
|
|
879
|
-
*
|
|
880
|
+
* export const Table = defineTable('table', (t) => ({
|
|
881
|
+
* id: t.identity().primaryKey(),
|
|
882
|
+
* some: t.number(),
|
|
883
|
+
* column: t
|
|
884
|
+
* .string()
|
|
885
|
+
* .setOnUpdate(({ columns }) =>
|
|
886
|
+
* columns.include('some') ? 'value' : undefined,
|
|
887
|
+
* ),
|
|
888
|
+
* }));
|
|
880
889
|
* ```
|
|
881
890
|
*/
|
|
882
891
|
setOnUpdate(fn) {
|
|
@@ -889,13 +898,15 @@ var Column = class {
|
|
|
889
898
|
* If no value or undefined is returned, the hook won't have any effect.
|
|
890
899
|
*
|
|
891
900
|
* ```ts
|
|
892
|
-
* export
|
|
893
|
-
*
|
|
894
|
-
*
|
|
895
|
-
*
|
|
896
|
-
*
|
|
897
|
-
*
|
|
898
|
-
*
|
|
901
|
+
* export const Table = defineTable('table', (t) => ({
|
|
902
|
+
* id: t.identity().primaryKey(),
|
|
903
|
+
* some: t.number(),
|
|
904
|
+
* column: t
|
|
905
|
+
* .string()
|
|
906
|
+
* .setOnSave(({ columns }) =>
|
|
907
|
+
* columns.include('some') ? 'value' : undefined,
|
|
908
|
+
* ),
|
|
909
|
+
* }));
|
|
899
910
|
* ```
|
|
900
911
|
*/
|
|
901
912
|
setOnSave(fn) {
|
|
@@ -910,14 +921,11 @@ var Column = class {
|
|
|
910
921
|
* Using `primaryKey` on a `uuid` column will automatically add a [gen_random_uuid](https://www.postgresql.org/docs/current/functions-uuid.html) default.
|
|
911
922
|
*
|
|
912
923
|
* ```ts
|
|
913
|
-
* export
|
|
914
|
-
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
918
|
-
* id: t.uuid().primaryKey('primary_key_name'),
|
|
919
|
-
* }));
|
|
920
|
-
* }
|
|
924
|
+
* export const Table = defineTable('table', (t) => ({
|
|
925
|
+
* id: t.uuid().primaryKey(),
|
|
926
|
+
* // optionally, specify a database-level constraint name:
|
|
927
|
+
* id: t.uuid().primaryKey('primary_key_name'),
|
|
928
|
+
* }));
|
|
921
929
|
*
|
|
922
930
|
* // primary key can be used by `find` later:
|
|
923
931
|
* db.table.find('97ba9e78-7510-415a-9c03-23d440aec443');
|
|
@@ -1307,8 +1315,8 @@ const codeToString = (code, tabs, shift) => {
|
|
|
1307
1315
|
* @param t - column types variable name
|
|
1308
1316
|
* @param value - column default
|
|
1309
1317
|
*/
|
|
1310
|
-
const columnDefaultArgumentToCode = (
|
|
1311
|
-
if (typeof value === "object" && value && isRawSQL(value)) return rawSqlToCode(value,
|
|
1318
|
+
const columnDefaultArgumentToCode = (ctx, value) => {
|
|
1319
|
+
if (typeof value === "object" && value && isRawSQL(value)) return rawSqlToCode(value, ctx);
|
|
1312
1320
|
else if (typeof value === "function") return value.toString();
|
|
1313
1321
|
else if (typeof value === "string") return singleQuote(value);
|
|
1314
1322
|
else return JSON.stringify(value);
|
|
@@ -1552,26 +1560,26 @@ const excludeInnerToCode = (item, t) => {
|
|
|
1552
1560
|
return code;
|
|
1553
1561
|
};
|
|
1554
1562
|
const excludeToCode = indexOrExcludeToCode(excludeInnerToCode);
|
|
1555
|
-
const constraintToCode = (item, t, m, prefix) => {
|
|
1556
|
-
const code = constraintInnerToCode(item, t, m);
|
|
1563
|
+
const constraintToCode = (item, t, m, prefix, ctx) => {
|
|
1564
|
+
const code = constraintInnerToCode(item, t, m, ctx);
|
|
1557
1565
|
if (prefix) code[0] = prefix + code[0];
|
|
1558
1566
|
const last = code[code.length - 1];
|
|
1559
1567
|
if (typeof last === "string" && !last.endsWith(",")) code[code.length - 1] += ",";
|
|
1560
1568
|
return code;
|
|
1561
1569
|
};
|
|
1562
|
-
const constraintInnerToCode = (item, t, m) => {
|
|
1570
|
+
const constraintInnerToCode = (item, t, m, ctx) => {
|
|
1563
1571
|
if (item.references) return [
|
|
1564
1572
|
`${t}.foreignKey(`,
|
|
1565
1573
|
referencesArgsToCode(item.references, item.name, m),
|
|
1566
1574
|
"),"
|
|
1567
1575
|
];
|
|
1568
|
-
return [`${t}.check(${rawSqlToCode(item.check, t)}${item.name ? `, ${singleQuote(item.name)}` : ""})`];
|
|
1576
|
+
return [`${t}.check(${rawSqlToCode(item.check, ctx ?? t)}${item.name ? `, ${singleQuote(item.name)}` : ""})`];
|
|
1569
1577
|
};
|
|
1570
1578
|
const referencesArgsToCode = ({ columns, fnOrTable, foreignColumns, options }, name = options?.name || false, m) => {
|
|
1571
1579
|
const args = [];
|
|
1572
1580
|
args.push(`${singleQuoteArray(columns)},`);
|
|
1573
1581
|
if (m && typeof fnOrTable !== "string") {
|
|
1574
|
-
const { schema, table } =
|
|
1582
|
+
const { schema, table } = getForeignKeyTableInstance(fnOrTable());
|
|
1575
1583
|
fnOrTable = schema ? `${schema}.${table}` : table;
|
|
1576
1584
|
}
|
|
1577
1585
|
args.push(`${typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()},`);
|
|
@@ -1600,7 +1608,7 @@ const columnForeignKeysToCode = (foreignKeys, migration) => {
|
|
|
1600
1608
|
const foreignKeyArgumentToCode = ({ fnOrTable, foreignColumns, options = emptyObject }, migration) => {
|
|
1601
1609
|
const code = [];
|
|
1602
1610
|
if (migration && typeof fnOrTable !== "string") {
|
|
1603
|
-
const { schema, table } =
|
|
1611
|
+
const { schema, table } = getForeignKeyTableInstance(fnOrTable());
|
|
1604
1612
|
fnOrTable = schema ? `${schema}.${table}` : table;
|
|
1605
1613
|
}
|
|
1606
1614
|
code.push(typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString());
|
|
@@ -1668,7 +1676,7 @@ const columnExcludesToCode = (items) => {
|
|
|
1668
1676
|
return code;
|
|
1669
1677
|
};
|
|
1670
1678
|
const columnCheckToCode = (ctx, checks) => {
|
|
1671
|
-
return checks.map(({ sql, name }) => `.check(${rawSqlToCode(sql, ctx
|
|
1679
|
+
return checks.map(({ sql, name }) => `.check(${rawSqlToCode(sql, ctx)}${name ? `, '${name}'` : ""})`).join("");
|
|
1672
1680
|
};
|
|
1673
1681
|
const identityToCode = (identity, dataType) => {
|
|
1674
1682
|
const code = [];
|
|
@@ -1704,7 +1712,7 @@ const columnCode = (type, ctx, key, code) => {
|
|
|
1704
1712
|
if (data.explicitSelect) addCode(code, ".select(false)");
|
|
1705
1713
|
if (data.isNullable) addCode(code, ".nullable()");
|
|
1706
1714
|
if (data.as && !ctx.migration) addCode(code, `.as(${data.as.toCode(ctx, key)})`);
|
|
1707
|
-
if (data.default !== void 0 && data.default !== data.defaultDefault && (!ctx.migration || typeof data.default !== "function")) addCode(code, `.default(${columnDefaultArgumentToCode(ctx
|
|
1715
|
+
if (data.default !== void 0 && data.default !== data.defaultDefault && (!ctx.migration || typeof data.default !== "function")) addCode(code, `.default(${columnDefaultArgumentToCode(ctx, data.default)})`);
|
|
1708
1716
|
if (data.indexes) for (const part of columnIndexesToCode(data.indexes)) addCode(code, part);
|
|
1709
1717
|
if (data.excludes) for (const part of columnExcludesToCode(data.excludes)) addCode(code, part);
|
|
1710
1718
|
if (data.comment) addCode(code, `.comment(${singleQuote(data.comment)})`);
|
|
@@ -2306,6 +2314,17 @@ const make = (_op) => {
|
|
|
2306
2314
|
(q.chain ??= []).push(_op, val || value);
|
|
2307
2315
|
if (getValueParser(q.parsers)) setValueParser(q, void 0);
|
|
2308
2316
|
q.getColumn = BooleanColumn.instance;
|
|
2317
|
+
if (this instanceof Expression && this.result) {
|
|
2318
|
+
let column;
|
|
2319
|
+
if (this.result.value?.data.name) {
|
|
2320
|
+
column = Object.create(BooleanColumn.instance);
|
|
2321
|
+
column.data = {
|
|
2322
|
+
...column.data,
|
|
2323
|
+
name: this.result.value.data.name
|
|
2324
|
+
};
|
|
2325
|
+
} else column = BooleanColumn.instance;
|
|
2326
|
+
this.result.value = column;
|
|
2327
|
+
}
|
|
2309
2328
|
return setQueryOperators(this, boolean);
|
|
2310
2329
|
}, { _op });
|
|
2311
2330
|
};
|
|
@@ -2812,7 +2831,8 @@ var SimpleRawSQL = class extends RawSql {
|
|
|
2812
2831
|
};
|
|
2813
2832
|
const raw$1 = (sql) => new SimpleRawSQL(sql);
|
|
2814
2833
|
const makeTimestamps = (timestamp) => {
|
|
2815
|
-
const
|
|
2834
|
+
const now = getDefaultNowFn();
|
|
2835
|
+
const nowRaw = raw$1(now);
|
|
2816
2836
|
const updatedAt = timestamp().default(nowRaw);
|
|
2817
2837
|
let updater;
|
|
2818
2838
|
updatedAt.data.modifyQuery = (q, column) => {
|
|
@@ -2845,7 +2865,7 @@ const timestampHelpers = {
|
|
|
2845
2865
|
};
|
|
2846
2866
|
const defaultSrid = 4326;
|
|
2847
2867
|
const encode = ({ srid = defaultSrid, lon, lat }) => {
|
|
2848
|
-
const arr = new Uint8Array(25);
|
|
2868
|
+
const arr = /* @__PURE__ */ new Uint8Array(25);
|
|
2849
2869
|
const view = new DataView(arr.buffer);
|
|
2850
2870
|
view.setInt8(0, 1);
|
|
2851
2871
|
view.setInt8(1, 1);
|
|
@@ -2874,7 +2894,7 @@ var PostgisGeographyPointColumn = class extends Column {
|
|
|
2874
2894
|
}
|
|
2875
2895
|
};
|
|
2876
2896
|
const parse = (input) => {
|
|
2877
|
-
const bytes = new Uint8Array(20);
|
|
2897
|
+
const bytes = /* @__PURE__ */ new Uint8Array(20);
|
|
2878
2898
|
for (let i = 0; i < 40; i += 2) bytes[i / 2] = parseInt(input.slice(10 + i, 12 + i), 16);
|
|
2879
2899
|
const view = new DataView(bytes.buffer);
|
|
2880
2900
|
const srid = view.getUint32(0, true);
|
|
@@ -3742,24 +3762,19 @@ var QueryStorage = class {
|
|
|
3742
3762
|
* so later they can be identified when handling after commit errors.
|
|
3743
3763
|
*
|
|
3744
3764
|
* ```ts
|
|
3745
|
-
*
|
|
3746
|
-
*
|
|
3747
|
-
*
|
|
3748
|
-
*
|
|
3749
|
-
*
|
|
3750
|
-
*
|
|
3751
|
-
*
|
|
3752
|
-
* // anonymous funciton - has no name
|
|
3753
|
-
* this.afterCreateCommit([], async () => {
|
|
3754
|
-
* // ...
|
|
3755
|
-
* });
|
|
3765
|
+
* export const SomeTable = defineTable('someTable', (t) => ({
|
|
3766
|
+
* ...someColumns,
|
|
3767
|
+
* })).init((orm: typeof db, hooks) => {
|
|
3768
|
+
* // anonymous funciton - has no name
|
|
3769
|
+
* hooks.afterCreateCommit([], async () => {
|
|
3770
|
+
* // ...
|
|
3771
|
+
* });
|
|
3756
3772
|
*
|
|
3757
|
-
*
|
|
3758
|
-
*
|
|
3759
|
-
*
|
|
3760
|
-
*
|
|
3761
|
-
*
|
|
3762
|
-
* }
|
|
3773
|
+
* // named function
|
|
3774
|
+
* hooks.afterCreateCommit([], function myHook() {
|
|
3775
|
+
* // ...
|
|
3776
|
+
* });
|
|
3777
|
+
* });
|
|
3763
3778
|
* ```
|
|
3764
3779
|
*/
|
|
3765
3780
|
var AfterCommitError = class extends OrchidOrmError {
|
|
@@ -3824,7 +3839,8 @@ var QueryTransaction = class QueryTransaction {
|
|
|
3824
3839
|
return QueryTransaction.prototype.transaction.call(this, cb);
|
|
3825
3840
|
}
|
|
3826
3841
|
isInTransaction() {
|
|
3827
|
-
|
|
3842
|
+
const trx = this.internal.asyncStorage.getStore();
|
|
3843
|
+
return isInUserTransaction(trx);
|
|
3828
3844
|
}
|
|
3829
3845
|
/**
|
|
3830
3846
|
* Schedules a hook to run after the outermost transaction commits:
|
|
@@ -4512,21 +4528,16 @@ const _unscope = (q, scope) => {
|
|
|
4512
4528
|
* If you define a scope with name `default`, it will be applied for all table queries by default.
|
|
4513
4529
|
*
|
|
4514
4530
|
* ```ts
|
|
4515
|
-
* import {
|
|
4531
|
+
* import { defineTable } from './table-factory';
|
|
4516
4532
|
*
|
|
4517
|
-
* export
|
|
4518
|
-
*
|
|
4519
|
-
*
|
|
4520
|
-
*
|
|
4521
|
-
*
|
|
4522
|
-
*
|
|
4523
|
-
* })
|
|
4524
|
-
*
|
|
4525
|
-
* scopes = this.setScopes({
|
|
4526
|
-
* default: (q) => q.where({ hidden: false }),
|
|
4527
|
-
* active: (q) => q.where({ active: true }),
|
|
4528
|
-
* });
|
|
4529
|
-
* }
|
|
4533
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
4534
|
+
* id: t.identity().primaryKey(),
|
|
4535
|
+
* hidden: t.boolean(),
|
|
4536
|
+
* active: t.boolean(),
|
|
4537
|
+
* })).scopes({
|
|
4538
|
+
* default: (q) => q.where({ hidden: false }),
|
|
4539
|
+
* active: (q) => q.where({ active: true }),
|
|
4540
|
+
* });
|
|
4530
4541
|
*
|
|
4531
4542
|
* const db = orchidORM(
|
|
4532
4543
|
* { databaseURL: '...' },
|
|
@@ -5689,7 +5700,8 @@ const resolveCallbacksInArgs = (q, args) => {
|
|
|
5689
5700
|
qb.q.and = qb.q.or = qb.q.scopes = void 0;
|
|
5690
5701
|
qb.q.subQuery = 1;
|
|
5691
5702
|
_setSubQueryAliases(qb);
|
|
5692
|
-
|
|
5703
|
+
const resolved = resolveSubQueryCallback(qb, arg);
|
|
5704
|
+
args[i] = prepareSubQueryForSql(q, resolved);
|
|
5693
5705
|
} else if (arg.constructor === Object) {
|
|
5694
5706
|
const copy = args[i] = { ...arg };
|
|
5695
5707
|
for (const key in arg) {
|
|
@@ -5834,7 +5846,7 @@ var Where = class {
|
|
|
5834
5846
|
* Constructing `WHERE` conditions:
|
|
5835
5847
|
*
|
|
5836
5848
|
* ```ts
|
|
5837
|
-
* import { sql } from './
|
|
5849
|
+
* import { sql } from './table-factory';
|
|
5838
5850
|
*
|
|
5839
5851
|
* db.table.where({
|
|
5840
5852
|
* // column of the current table
|
|
@@ -5850,7 +5862,7 @@ var Where = class {
|
|
|
5850
5862
|
* },
|
|
5851
5863
|
*
|
|
5852
5864
|
* // where column equals to raw SQL
|
|
5853
|
-
* // import `sql` from your
|
|
5865
|
+
* // import `sql` from your table factory
|
|
5854
5866
|
* column: sql`sql expression`,
|
|
5855
5867
|
* // or use `(q) => sql` for the same
|
|
5856
5868
|
* column2: (q) => sql`sql expression`,
|
|
@@ -6461,7 +6473,8 @@ var Where = class {
|
|
|
6461
6473
|
* @param args - no arguments needed when the first argument is a relation name, or conditions to join the table with.
|
|
6462
6474
|
*/
|
|
6463
6475
|
whereNotExists(arg, ...args) {
|
|
6464
|
-
|
|
6476
|
+
const q = _clone(this);
|
|
6477
|
+
return _queryWhereNotExists(q, arg, args);
|
|
6465
6478
|
}
|
|
6466
6479
|
/**
|
|
6467
6480
|
* Acts as `whereExists`, but prepends the condition with `OR` and negates it with `NOT`:
|
|
@@ -6608,7 +6621,11 @@ const tableColumnToSql = (ctx, queryData, shape, table, key, quotedAs, select, a
|
|
|
6608
6621
|
const columnToSqlNotSelect = (ctx, data, shape, column, quotedAs, useSelectList) => columnToSql(ctx, data, shape, column, quotedAs, void 0, void 0, void 0, useSelectList, true);
|
|
6609
6622
|
const columnToSql = (ctx, data, shape, column, quotedAs, select, as, jsonList, useSelectList, skipValueToArray) => {
|
|
6610
6623
|
let index = column.indexOf(".");
|
|
6611
|
-
if (index !== -1)
|
|
6624
|
+
if (index !== -1) {
|
|
6625
|
+
const table = column.slice(0, index);
|
|
6626
|
+
const key = column.slice(index + 1);
|
|
6627
|
+
return tableColumnToSql(ctx, data, shape, table, key, quotedAs, select, as, jsonList, skipValueToArray);
|
|
6628
|
+
}
|
|
6612
6629
|
return simpleColumnToSQL(ctx, data, shape, column, shape[column], quotedAs, select, as, jsonList, useSelectList, void 0, skipValueToArray);
|
|
6613
6630
|
};
|
|
6614
6631
|
const rawOrColumnToSql = (ctx, data, shape, expr, quotedAs, select, skipValueToArray) => {
|
|
@@ -6851,11 +6868,20 @@ const _addToHookSelectWithTable = (query, selects, table) => {
|
|
|
6851
6868
|
};
|
|
6852
6869
|
const moveQueryToCte = (ctx, query, type, dontAddTableHook) => {
|
|
6853
6870
|
const { returnType } = query.q;
|
|
6871
|
+
const throwOnNotFound = returnType === "valueOrThrow";
|
|
6854
6872
|
let valueAs;
|
|
6855
6873
|
if (returnType === "value" || returnType === "valueOrThrow" || returnType === "pluck") {
|
|
6856
6874
|
const first = query.q.select[0];
|
|
6857
|
-
if (first instanceof SelectItemExpression && typeof first.item === "string")
|
|
6858
|
-
|
|
6875
|
+
if (first instanceof SelectItemExpression && typeof first.item === "string") {
|
|
6876
|
+
const columnName = first.result.value?.data.name;
|
|
6877
|
+
if (columnName && columnName !== first.item) {
|
|
6878
|
+
query = _clone(query);
|
|
6879
|
+
query.q.returnType = "one";
|
|
6880
|
+
query.q.select = [{ selectAs: { [first.item]: first } }];
|
|
6881
|
+
if (throwOnNotFound && query.q.type !== "upsert") query.q.cteThrowOnNotFound = true;
|
|
6882
|
+
}
|
|
6883
|
+
valueAs = first.item;
|
|
6884
|
+
} else {
|
|
6859
6885
|
query = _clone(query);
|
|
6860
6886
|
query.q.returnType = "one";
|
|
6861
6887
|
query.q.select = [{ selectAs: { value: query.q.select[0] } }];
|
|
@@ -6912,7 +6938,7 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
|
|
|
6912
6938
|
const afterUpdateCommit = data.afterUpdateCommit;
|
|
6913
6939
|
const afterSaveCommit = data.afterSaveCommit;
|
|
6914
6940
|
const afterDeleteCommit = data.afterDeleteCommit;
|
|
6915
|
-
const throwOnNotFound = hookPurpose !== "Create" && (data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
|
|
6941
|
+
const throwOnNotFound = hookPurpose !== "Create" && (data.cteThrowOnNotFound || data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
|
|
6916
6942
|
const hasAfterHook = afterCreate || afterUpdate || afterSave || afterDelete || afterCreateCommit || afterUpdateCommit || afterSaveCommit || afterDeleteCommit;
|
|
6917
6943
|
if (!select && !hasAfterHook && !throwOnNotFound) return;
|
|
6918
6944
|
const tableHook = {
|
|
@@ -6937,7 +6963,8 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
|
|
|
6937
6963
|
tableHook,
|
|
6938
6964
|
throwOnNotFound
|
|
6939
6965
|
};
|
|
6940
|
-
const
|
|
6966
|
+
const hasSelect = throwOnNotFound || !!tableHook.select;
|
|
6967
|
+
const cteHooks = setCteHooks(ctx, hasSelect);
|
|
6941
6968
|
(cteHooks.tableHooks ??= {})[ctx.cteName] ??= item;
|
|
6942
6969
|
}
|
|
6943
6970
|
} else ctx.topCtx.tableHook = tableHook;
|
|
@@ -7330,7 +7357,8 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
|
|
|
7330
7357
|
const value = data[key];
|
|
7331
7358
|
if (value === void 0) continue;
|
|
7332
7359
|
if (key === "AND") {
|
|
7333
|
-
const
|
|
7360
|
+
const arr = toArray(value);
|
|
7361
|
+
const sql = processAnds(arr, ctx, table, query, quotedAs);
|
|
7334
7362
|
if (sql) ands.push(sql);
|
|
7335
7363
|
} else if (key === "OR") {
|
|
7336
7364
|
const sqls = value.map(toArray).reduce((acc, and) => {
|
|
@@ -8973,7 +9001,9 @@ const _queryCreate = (q, data) => {
|
|
|
8973
9001
|
};
|
|
8974
9002
|
const _queryInsert = (query, data) => {
|
|
8975
9003
|
throwIfReadOnly(query);
|
|
8976
|
-
|
|
9004
|
+
const ctx = createCtx();
|
|
9005
|
+
const obj = handleOneData(query, data, ctx);
|
|
9006
|
+
return insert(query, obj);
|
|
8977
9007
|
};
|
|
8978
9008
|
const _queryCreateMany = (q, data) => {
|
|
8979
9009
|
throwIfReadOnly(q);
|
|
@@ -8982,7 +9012,8 @@ const _queryCreateMany = (q, data) => {
|
|
|
8982
9012
|
};
|
|
8983
9013
|
const _queryInsertMany = (q, data) => {
|
|
8984
9014
|
throwIfReadOnly(q);
|
|
8985
|
-
|
|
9015
|
+
const ctx = createCtx();
|
|
9016
|
+
let result = insert(q, handleManyData(q, data, ctx), true);
|
|
8986
9017
|
if (!data.length) result = result.none();
|
|
8987
9018
|
return result;
|
|
8988
9019
|
};
|
|
@@ -9173,31 +9204,26 @@ var QueryCreate = class {
|
|
|
9173
9204
|
* A primary key or a unique index for a **single** column can be fined on a column:
|
|
9174
9205
|
*
|
|
9175
9206
|
* ```ts
|
|
9176
|
-
* export
|
|
9177
|
-
*
|
|
9178
|
-
*
|
|
9179
|
-
*
|
|
9180
|
-
* }));
|
|
9181
|
-
* }
|
|
9207
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9208
|
+
* pkey: t.uuid().primaryKey(),
|
|
9209
|
+
* unique: t.string().unique(),
|
|
9210
|
+
* }));
|
|
9182
9211
|
* ```
|
|
9183
9212
|
*
|
|
9184
9213
|
* But for composite primary keys or indexes (having multiple columns), define it in a separate function:
|
|
9185
9214
|
*
|
|
9186
9215
|
* ```ts
|
|
9187
|
-
* export
|
|
9188
|
-
*
|
|
9189
|
-
*
|
|
9190
|
-
*
|
|
9191
|
-
*
|
|
9192
|
-
*
|
|
9193
|
-
*
|
|
9194
|
-
* (t) => [t.primaryKey(['one', 'two']), t.unique(['two', 'three'])],
|
|
9195
|
-
* );
|
|
9196
|
-
* }
|
|
9216
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9217
|
+
* one: t.integer(),
|
|
9218
|
+
* two: t.string(),
|
|
9219
|
+
* three: t.boolean(),
|
|
9220
|
+
* }))
|
|
9221
|
+
* .primaryKey(['one', 'two'])
|
|
9222
|
+
* .unique(['two', 'three']);
|
|
9197
9223
|
* ```
|
|
9198
9224
|
* :::
|
|
9199
9225
|
*
|
|
9200
|
-
* You can use the `sql` function exported from your
|
|
9226
|
+
* You can use the `sql` function exported from your table factory file in onConflict.
|
|
9201
9227
|
* It can be useful to specify a condition when you have a partial index:
|
|
9202
9228
|
*
|
|
9203
9229
|
* ```ts
|
|
@@ -9587,12 +9613,15 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
|
|
|
9587
9613
|
if (upsertOrCreate.q.returnType === "oneOrThrow") upsertOrCreate.q.returnType = "one";
|
|
9588
9614
|
else if (upsertOrCreate.q.returnType === "valueOrThrow") upsertOrCreate.q.returnType = "value";
|
|
9589
9615
|
const { as, makeSql: makeFirstSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, upsertUpdate ? "update" : null);
|
|
9616
|
+
query.upsertUpdateAsFns?.forEach((fn) => fn(as));
|
|
9590
9617
|
upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
|
|
9591
9618
|
upsertOrCreate.q.and = [new RawSql(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
|
|
9592
9619
|
if (query.upsertInsert) {
|
|
9593
|
-
|
|
9620
|
+
const insertData = query.upsertInsert();
|
|
9621
|
+
_queryInsert(upsertOrCreate, insertData);
|
|
9594
9622
|
upsertOrCreate.q.type = "upsert";
|
|
9595
9623
|
}
|
|
9624
|
+
upsertOrCreate.q.with = query.upsertCreateWith;
|
|
9596
9625
|
upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
|
|
9597
9626
|
upsertOrCreate.q.asFns = query.upsertCreateAsFns;
|
|
9598
9627
|
const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
|
|
@@ -9702,7 +9731,8 @@ const cteToSqlGiveAs = (ctx, item, type, dontAddTableHook) => {
|
|
|
9702
9731
|
let as;
|
|
9703
9732
|
if (typeof item.n === "string") as = item.n;
|
|
9704
9733
|
else if (ctx === ctx.topCtx) {
|
|
9705
|
-
|
|
9734
|
+
const topCTE = ctx.topCtx.topCTE ??= newTopCte(ctx);
|
|
9735
|
+
as = setFreeAlias(topCTE.names, "q", true);
|
|
9706
9736
|
item.n(as);
|
|
9707
9737
|
} else throw new Error("not implemented yet");
|
|
9708
9738
|
if (item.q) inner = getSqlText(toSql(item.q, type, ctx.topCtx, true, as, void 0, dontAddTableHook));
|
|
@@ -10164,36 +10194,21 @@ var QueryJoin = class {
|
|
|
10164
10194
|
* For the following examples, imagine you have a `User` table with `id` and `name`, and `Message` table with `id`, `text`, messages belongs to user via `userId` column:
|
|
10165
10195
|
*
|
|
10166
10196
|
* ```ts
|
|
10167
|
-
* export
|
|
10168
|
-
*
|
|
10169
|
-
*
|
|
10170
|
-
*
|
|
10171
|
-
*
|
|
10172
|
-
*
|
|
10173
|
-
*
|
|
10174
|
-
* relations = {
|
|
10175
|
-
* messages: this.hasMany(() => MessageTable, {
|
|
10176
|
-
* primaryKey: 'id',
|
|
10177
|
-
* foreignKey: 'userId',
|
|
10178
|
-
* }),
|
|
10179
|
-
* };
|
|
10180
|
-
* }
|
|
10181
|
-
*
|
|
10182
|
-
* export class MessageTable extends BaseTable {
|
|
10183
|
-
* readonly table = 'message';
|
|
10184
|
-
* columns = this.setColumns((t) => ({
|
|
10185
|
-
* id: t.identity().primaryKey(),
|
|
10186
|
-
* text: t.text(),
|
|
10187
|
-
* ...t.timestamps(),
|
|
10188
|
-
* }));
|
|
10197
|
+
* export const UserTable = defineTable('user', (t) => ({
|
|
10198
|
+
* id: t.identity().primaryKey(),
|
|
10199
|
+
* name: t.text(),
|
|
10200
|
+
* })).relations((user) => ({
|
|
10201
|
+
* messages: user('id').hasMany(() => MessageTable('userId')),
|
|
10202
|
+
* }));
|
|
10189
10203
|
*
|
|
10190
|
-
*
|
|
10191
|
-
*
|
|
10192
|
-
*
|
|
10193
|
-
*
|
|
10194
|
-
*
|
|
10195
|
-
*
|
|
10196
|
-
*
|
|
10204
|
+
* export const MessageTable = defineTable('message', (t) => ({
|
|
10205
|
+
* id: t.identity().primaryKey(),
|
|
10206
|
+
* userId: t.integer(),
|
|
10207
|
+
* text: t.text(),
|
|
10208
|
+
* ...t.timestamps(),
|
|
10209
|
+
* })).relations((message) => ({
|
|
10210
|
+
* user: message('userId').belongsTo(() => UserTable('id')),
|
|
10211
|
+
* }));
|
|
10197
10212
|
* ```
|
|
10198
10213
|
*
|
|
10199
10214
|
* `join` is a method for SQL `JOIN`, which is equivalent to `INNER JOIN`, `LEFT INNERT JOIN`.
|
|
@@ -10390,7 +10405,7 @@ var QueryJoin = class {
|
|
|
10390
10405
|
* ```ts
|
|
10391
10406
|
* db.user.join(
|
|
10392
10407
|
* db.message,
|
|
10393
|
-
* // `sql` can be imported from your
|
|
10408
|
+
* // `sql` can be imported from your table factory file
|
|
10394
10409
|
* sql`lower("message"."text") = lower("user"."name")`,
|
|
10395
10410
|
* );
|
|
10396
10411
|
* ```
|
|
@@ -10841,12 +10856,15 @@ var OnMethods = class {
|
|
|
10841
10856
|
const setSelectRelation = (q) => {
|
|
10842
10857
|
q.selectRelation = true;
|
|
10843
10858
|
};
|
|
10844
|
-
const
|
|
10859
|
+
const addParsersForSelectJoinedWildcard = (q, arg, as = arg) => {
|
|
10845
10860
|
const parsers = q.q.joinedParsers?.[arg];
|
|
10846
10861
|
if (parsers) setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
|
|
10847
10862
|
const batchParsers = q.q.joinedBatchParsers?.[arg];
|
|
10848
10863
|
if (batchParsers) pushQueryArrayImmutable(q, "batchParsers", batchParsers.map((x) => ({
|
|
10849
|
-
path: [{
|
|
10864
|
+
path: [{
|
|
10865
|
+
key: as,
|
|
10866
|
+
returnType: "one"
|
|
10867
|
+
}, ...x.path],
|
|
10850
10868
|
fn: x.fn
|
|
10851
10869
|
})));
|
|
10852
10870
|
};
|
|
@@ -11028,7 +11046,8 @@ const processSelectAsArg = (q, selectAs, as, key, arg, columnAlias, outerReturnT
|
|
|
11028
11046
|
subQuery = value;
|
|
11029
11047
|
} else subQuery = value.json(false);
|
|
11030
11048
|
else subQuery = value;
|
|
11031
|
-
const
|
|
11049
|
+
const joinLateral = innerJoinLateral || query.q.returnType === "valueOrThrow";
|
|
11050
|
+
const as = _joinLateral(q, joinLateral ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
|
|
11032
11051
|
if (as) value.q.joinedForSelect = _copyQueryAliasToQuery(value, q, as);
|
|
11033
11052
|
}
|
|
11034
11053
|
if (value.q.getColumn?.data.skipValueToArray) value.q.notFoundDefault ??= null;
|
|
@@ -11060,7 +11079,7 @@ const setParserForSelectedString = (query, arg, as, columnAs, columnAlias) => {
|
|
|
11060
11079
|
const table = getFullColumnTable(query, arg, index, as);
|
|
11061
11080
|
const column = arg.slice(index + 1);
|
|
11062
11081
|
if (column === "*") {
|
|
11063
|
-
|
|
11082
|
+
addParsersForSelectJoinedWildcard(query, table, columnAs);
|
|
11064
11083
|
return table === as ? column : arg;
|
|
11065
11084
|
}
|
|
11066
11085
|
if (table === as) return selectColumn(query, q, column, columnAs, columnAlias);
|
|
@@ -11486,6 +11505,7 @@ function _orCreate(query, data, updateData, mergeData) {
|
|
|
11486
11505
|
const { q } = query;
|
|
11487
11506
|
q.returnsOne = true;
|
|
11488
11507
|
if (!q.select) q.returnType = "void";
|
|
11508
|
+
q.type = "upsert";
|
|
11489
11509
|
if (typeof data === "function") q.upsertInsert = () => mergeData ? {
|
|
11490
11510
|
...mergeData,
|
|
11491
11511
|
...data(updateData)
|
|
@@ -12475,7 +12495,17 @@ const _appendQuery = (main, append, asFn) => {
|
|
|
12475
12495
|
const _appendQueryOnUpsertCreate = (main, append, asFn) => {
|
|
12476
12496
|
return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
|
|
12477
12497
|
};
|
|
12478
|
-
const
|
|
12498
|
+
const _onUpsertUpdate = (q, asFn) => {
|
|
12499
|
+
return pushQueryValueImmutable(q, "upsertUpdateAsFns", asFn);
|
|
12500
|
+
};
|
|
12501
|
+
const _prependWithOnUpsertCreate = (q, name, query) => {
|
|
12502
|
+
const prev = q.q.with;
|
|
12503
|
+
q.q.with = q.q.upsertCreateWith;
|
|
12504
|
+
_prependWith(q, name, query);
|
|
12505
|
+
q.q.upsertCreateWith = q.q.with;
|
|
12506
|
+
q.q.with = prev;
|
|
12507
|
+
};
|
|
12508
|
+
const mergableObjects = /* @__PURE__ */ new Set([
|
|
12479
12509
|
"selectShape",
|
|
12480
12510
|
"withShapes",
|
|
12481
12511
|
"defaultParsers",
|
|
@@ -12487,7 +12517,7 @@ const mergableObjects = new Set([
|
|
|
12487
12517
|
"joinedBatchParsers",
|
|
12488
12518
|
"selectedComputeds"
|
|
12489
12519
|
]);
|
|
12490
|
-
const dontMergeArrays = new Set(["selectAllColumns"]);
|
|
12520
|
+
const dontMergeArrays = /* @__PURE__ */ new Set(["selectAllColumns"]);
|
|
12491
12521
|
var MergeQueryMethods = class {
|
|
12492
12522
|
merge(q) {
|
|
12493
12523
|
const query = _clone(this);
|
|
@@ -12501,20 +12531,18 @@ var MergeQueryMethods = class {
|
|
|
12501
12531
|
case "number":
|
|
12502
12532
|
a[key] = value;
|
|
12503
12533
|
break;
|
|
12504
|
-
case "object":
|
|
12505
|
-
if (
|
|
12506
|
-
|
|
12507
|
-
|
|
12508
|
-
|
|
12509
|
-
|
|
12510
|
-
|
|
12511
|
-
|
|
12512
|
-
|
|
12513
|
-
|
|
12514
|
-
|
|
12515
|
-
|
|
12516
|
-
else a[key] = value;
|
|
12517
|
-
break;
|
|
12534
|
+
case "object": if (Array.isArray(value)) {
|
|
12535
|
+
if (!dontMergeArrays.has(key)) a[key] = a[key] ? [...a[key], ...value] : value;
|
|
12536
|
+
} else if (mergableObjects.has(key)) a[key] = a[key] ? {
|
|
12537
|
+
...a[key],
|
|
12538
|
+
...value
|
|
12539
|
+
} : value;
|
|
12540
|
+
else if (key === "union") a[key] = a[key] ? {
|
|
12541
|
+
b: a[key].b,
|
|
12542
|
+
u: [...a[key].u, ...value.u]
|
|
12543
|
+
} : value;
|
|
12544
|
+
else if (value instanceof Set) a[key] = a[key] ? /* @__PURE__ */ new Set([...a[key], ...value]) : value;
|
|
12545
|
+
else a[key] = value;
|
|
12518
12546
|
}
|
|
12519
12547
|
}
|
|
12520
12548
|
if (b.returnType) a.returnType = b.returnType;
|
|
@@ -12698,12 +12726,12 @@ var SearchMethods = class {
|
|
|
12698
12726
|
*
|
|
12699
12727
|
* By default, the search language is English.
|
|
12700
12728
|
*
|
|
12701
|
-
* You can set a different default language in the `
|
|
12729
|
+
* You can set a different default language in the `createTableFactory` config:
|
|
12702
12730
|
*
|
|
12703
12731
|
* ```ts
|
|
12704
|
-
* import {
|
|
12732
|
+
* import { createTableFactory } from 'orchid-orm';
|
|
12705
12733
|
*
|
|
12706
|
-
* export const
|
|
12734
|
+
* export const { defineTable, defineView, sql } = createTableFactory({
|
|
12707
12735
|
* language: 'swedish',
|
|
12708
12736
|
* });
|
|
12709
12737
|
* ```
|
|
@@ -13089,20 +13117,20 @@ const _softDelete = (column, customNowSQL) => {
|
|
|
13089
13117
|
* All queries on such table will filter out deleted records by default.
|
|
13090
13118
|
*
|
|
13091
13119
|
* ```ts
|
|
13092
|
-
* import {
|
|
13093
|
-
*
|
|
13094
|
-
* export class SomeTable extends BaseTable {
|
|
13095
|
-
* readonly table = 'some';
|
|
13096
|
-
* columns = this.setColumns((t) => ({
|
|
13097
|
-
* id: t.identity().primaryKey(),
|
|
13098
|
-
* deletedAt: t.timestamp().nullable(),
|
|
13099
|
-
* }));
|
|
13120
|
+
* import { defineTable } from './table-factory';
|
|
13100
13121
|
*
|
|
13122
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
13123
|
+
* id: t.identity().primaryKey(),
|
|
13124
|
+
* deletedAt: t.timestamp().nullable(),
|
|
13125
|
+
* }))
|
|
13101
13126
|
* // true is for using `deletedAt` column
|
|
13102
|
-
*
|
|
13103
|
-
*
|
|
13104
|
-
*
|
|
13105
|
-
*
|
|
13127
|
+
* .softDelete();
|
|
13128
|
+
*
|
|
13129
|
+
* // or provide a different column name
|
|
13130
|
+
* export const OtherTable = defineTable('other', (t) => ({
|
|
13131
|
+
* id: t.identity().primaryKey(),
|
|
13132
|
+
* myDeletedAt: t.timestamp().nullable(),
|
|
13133
|
+
* })).softDelete('myDeletedAt');
|
|
13106
13134
|
*
|
|
13107
13135
|
* const db = orchidORM(
|
|
13108
13136
|
* { databaseURL: '...' },
|
|
@@ -13492,7 +13520,8 @@ var QueryMethods = class {
|
|
|
13492
13520
|
* @param args - SQL expression
|
|
13493
13521
|
*/
|
|
13494
13522
|
findBySql(...args) {
|
|
13495
|
-
|
|
13523
|
+
const q = _clone(this);
|
|
13524
|
+
return _queryTake(_queryWhereSql(q, args));
|
|
13496
13525
|
}
|
|
13497
13526
|
/**
|
|
13498
13527
|
* Finds a single record by the primary key (id), returns `undefined` when not found.
|
|
@@ -14032,7 +14061,8 @@ var Db = class extends QueryMethods {
|
|
|
14032
14061
|
if (options.noPrimaryKey === "error") throw new Error(message);
|
|
14033
14062
|
else logger.warn(message);
|
|
14034
14063
|
}
|
|
14035
|
-
|
|
14064
|
+
const columns = Object.keys(shape);
|
|
14065
|
+
this.columns = columns;
|
|
14036
14066
|
if (options.computed) applyComputedColumns(this, options.computed);
|
|
14037
14067
|
if (prepareSelectAll) {
|
|
14038
14068
|
const selectAllShape = this.q.selectAllShape = {};
|
|
@@ -14399,11 +14429,14 @@ function getColumnInfo(query, column) {
|
|
|
14399
14429
|
};
|
|
14400
14430
|
return q;
|
|
14401
14431
|
}
|
|
14432
|
+
const columnsSql = (shape, columns) => {
|
|
14433
|
+
return columns.map((item) => `"${shape[item]?.data.name || item}"`).join(", ");
|
|
14434
|
+
};
|
|
14402
14435
|
const makeCopySql = (table, copy) => {
|
|
14403
14436
|
const ctx = newToSqlCtx(table);
|
|
14404
14437
|
const { q } = table;
|
|
14405
14438
|
const quotedAs = `"${q.as || table.table}"`;
|
|
14406
|
-
const columns = copy.columns ? `(${
|
|
14439
|
+
const columns = copy.columns ? `(${columnsSql(table.shape, copy.columns)})` : "";
|
|
14407
14440
|
const target = "from" in copy ? copy.from : copy.to;
|
|
14408
14441
|
const quotedTable = quoteTableWithSchema(table);
|
|
14409
14442
|
ctx.sql.push(`COPY ${quotedTable}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? escapeString(target) : `PROGRAM ${escapeString(target.program)}`}`);
|
|
@@ -14416,9 +14449,9 @@ const makeCopySql = (table, copy) => {
|
|
|
14416
14449
|
if (copy.header) options.push(`HEADER ${copy.header}`);
|
|
14417
14450
|
if (copy.quote) options.push(`QUOTE ${escapeString(copy.quote)}`);
|
|
14418
14451
|
if (copy.escape) options.push(`ESCAPE ${escapeString(copy.escape)}`);
|
|
14419
|
-
if (copy.forceQuote) options.push(`FORCE_QUOTE ${copy.forceQuote === "*" ? "*" : `(${
|
|
14420
|
-
if (copy.forceNotNull) options.push(`FORCE_NOT_NULL (${
|
|
14421
|
-
if (copy.forceNull) options.push(`FORCE_NULL (${
|
|
14452
|
+
if (copy.forceQuote) options.push(`FORCE_QUOTE ${copy.forceQuote === "*" ? "*" : `(${columnsSql(table.shape, copy.forceQuote)})`}`);
|
|
14453
|
+
if (copy.forceNotNull) options.push(`FORCE_NOT_NULL (${columnsSql(table.shape, copy.forceNotNull)})`);
|
|
14454
|
+
if (copy.forceNull) options.push(`FORCE_NULL (${columnsSql(table.shape, copy.forceNull)})`);
|
|
14422
14455
|
if (copy.encoding) options.push(`ENCODING ${escapeString(copy.encoding)}`);
|
|
14423
14456
|
ctx.sql.push(`WITH (${options.join(", ")})`);
|
|
14424
14457
|
}
|
|
@@ -14485,6 +14518,12 @@ var Rollback = class extends Error {};
|
|
|
14485
14518
|
const trxForTest = Symbol("trxForTest");
|
|
14486
14519
|
const argToDb = (arg) => "$qb" in arg ? arg.$qb : arg;
|
|
14487
14520
|
const testTransaction = {
|
|
14521
|
+
/**
|
|
14522
|
+
* Start a test transaction.
|
|
14523
|
+
* The returned promise is resolved immediately when transaction starts, not waiting for it to end.
|
|
14524
|
+
*
|
|
14525
|
+
* @param arg - ORM instance or a queryable instance (such as db.someTable).
|
|
14526
|
+
*/
|
|
14488
14527
|
start(arg) {
|
|
14489
14528
|
const db = argToDb(arg);
|
|
14490
14529
|
const { asyncStorage } = db.internal;
|
|
@@ -14520,6 +14559,11 @@ const testTransaction = {
|
|
|
14520
14559
|
});
|
|
14521
14560
|
});
|
|
14522
14561
|
},
|
|
14562
|
+
/**
|
|
14563
|
+
* Rollback a test transaction.
|
|
14564
|
+
*
|
|
14565
|
+
* @param arg - the same ORM or query argument passed into the `testTransaction.start`.
|
|
14566
|
+
*/
|
|
14523
14567
|
rollback(arg) {
|
|
14524
14568
|
const db = argToDb(arg);
|
|
14525
14569
|
const data = db.internal[trxForTest];
|
|
@@ -14529,6 +14573,12 @@ const testTransaction = {
|
|
|
14529
14573
|
last.reject?.(new Rollback());
|
|
14530
14574
|
return last.promise;
|
|
14531
14575
|
},
|
|
14576
|
+
/**
|
|
14577
|
+
* Will roll back the current `testTransaction` (won't have any effect if it was rolled back already),
|
|
14578
|
+
* and if there's no nested test transactions left, it will close the db connection.
|
|
14579
|
+
*
|
|
14580
|
+
* @param arg - the same ORM or query argument passed into the `testTransaction.start`.
|
|
14581
|
+
*/
|
|
14532
14582
|
async close(arg) {
|
|
14533
14583
|
const db = argToDb(arg);
|
|
14534
14584
|
await this.rollback(db);
|
|
@@ -14609,8 +14659,10 @@ exports._clone = _clone;
|
|
|
14609
14659
|
exports._createDbSqlMethod = _createDbSqlMethod;
|
|
14610
14660
|
exports._hookSelectColumns = _hookSelectColumns;
|
|
14611
14661
|
exports._initQueryBuilder = _initQueryBuilder;
|
|
14662
|
+
exports._onUpsertUpdate = _onUpsertUpdate;
|
|
14612
14663
|
exports._orCreate = _orCreate;
|
|
14613
14664
|
exports._prependWith = _prependWith;
|
|
14665
|
+
exports._prependWithOnUpsertCreate = _prependWithOnUpsertCreate;
|
|
14614
14666
|
exports._queryCreate = _queryCreate;
|
|
14615
14667
|
exports._queryCreateMany = _queryCreateMany;
|
|
14616
14668
|
exports._queryCreateManyFrom = _queryCreateManyFrom;
|
|
@@ -14644,6 +14696,7 @@ exports.codeToString = codeToString;
|
|
|
14644
14696
|
exports.colors = colors;
|
|
14645
14697
|
exports.columnsShapeToCode = columnsShapeToCode;
|
|
14646
14698
|
exports.constraintInnerToCode = constraintInnerToCode;
|
|
14699
|
+
exports.constraintToCode = constraintToCode;
|
|
14647
14700
|
exports.consumeColumnName = consumeColumnName;
|
|
14648
14701
|
exports.copyTableData = copyTableData;
|
|
14649
14702
|
exports.createDbWithAdapter = createDbWithAdapter;
|
|
@@ -14654,6 +14707,7 @@ exports.emptyObject = emptyObject;
|
|
|
14654
14707
|
exports.escapeForMigration = escapeForMigration;
|
|
14655
14708
|
exports.escapeString = escapeString;
|
|
14656
14709
|
exports.excludeInnerToCode = excludeInnerToCode;
|
|
14710
|
+
exports.excludeToCode = excludeToCode;
|
|
14657
14711
|
exports.exhaustive = exhaustive;
|
|
14658
14712
|
exports.getCallerFilePath = getCallerFilePath;
|
|
14659
14713
|
exports.getClonedQueryData = getClonedQueryData;
|
|
@@ -14674,6 +14728,7 @@ exports.getSqlText = getSqlText;
|
|
|
14674
14728
|
exports.getStackTrace = getStackTrace;
|
|
14675
14729
|
exports.getSupportedDefaultPrivileges = getSupportedDefaultPrivileges;
|
|
14676
14730
|
exports.indexInnerToCode = indexInnerToCode;
|
|
14731
|
+
exports.indexToCode = indexToCode;
|
|
14677
14732
|
exports.internalSchemaConfig = internalSchemaConfig;
|
|
14678
14733
|
exports.isExpression = isExpression;
|
|
14679
14734
|
exports.isQueryReturnsAll = isQueryReturnsAll;
|