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.mjs
CHANGED
|
@@ -432,9 +432,14 @@ var RawSql = class extends Expression {
|
|
|
432
432
|
};
|
|
433
433
|
const isRawSQL = (arg) => arg instanceof RawSql;
|
|
434
434
|
RawSql.prototype.type = ExpressionTypeMethod.prototype.type;
|
|
435
|
-
const rawSqlToCode = (rawSql,
|
|
435
|
+
const rawSqlToCode = (rawSql, ctx) => {
|
|
436
436
|
const { _sql: sql, _values: values } = rawSql;
|
|
437
|
-
let code
|
|
437
|
+
let code;
|
|
438
|
+
if (typeof ctx === "string") code = `${ctx}.sql`;
|
|
439
|
+
else {
|
|
440
|
+
ctx.isSqlUsed = true;
|
|
441
|
+
code = ctx.sql ?? `${ctx.t}.sql`;
|
|
442
|
+
}
|
|
438
443
|
code += typeof sql === "string" ? values ? `({ raw: '${sql.replace(/'/g, "\\'")}' })` : `\`${sql.replace(/`/g, "\\`")}\`` : templateLiteralSQLToCode(sql);
|
|
439
444
|
if (values) code += `.values(${JSON.stringify(values)})`;
|
|
440
445
|
return code;
|
|
@@ -570,6 +575,15 @@ const parseIndexOrExclude = (item) => {
|
|
|
570
575
|
for (let i = item.columns.length - 1; i >= 0; i--) if (typeof item.columns[i] === "string") item.columns[i] = { column: item.columns[i] };
|
|
571
576
|
return item;
|
|
572
577
|
};
|
|
578
|
+
const getForeignKeyTableInstance = (table) => {
|
|
579
|
+
const item = "instance" in table ? table.instance() : new table();
|
|
580
|
+
if (!item.table) throw new Error("Referenced table is missing table property");
|
|
581
|
+
return {
|
|
582
|
+
...item,
|
|
583
|
+
schema: typeof item.schema === "function" ? item.schema() : item.schema,
|
|
584
|
+
table: item.table
|
|
585
|
+
};
|
|
586
|
+
};
|
|
573
587
|
function makeColumnNullable(column, inputSchema, outputSchema, querySchema) {
|
|
574
588
|
const c = setColumnData(column, "isNullable", true);
|
|
575
589
|
c.inputSchema = inputSchema;
|
|
@@ -641,20 +655,17 @@ var Column = class {
|
|
|
641
655
|
* 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.
|
|
642
656
|
*
|
|
643
657
|
* ```ts
|
|
644
|
-
* export
|
|
645
|
-
*
|
|
646
|
-
*
|
|
647
|
-
*
|
|
648
|
-
* int: t.integer().default(123),
|
|
649
|
-
* text: t.text().default('text'),
|
|
658
|
+
* export const Table = defineTable('table', (t) => ({
|
|
659
|
+
* // values as defaults:
|
|
660
|
+
* int: t.integer().default(123),
|
|
661
|
+
* text: t.text().default('text'),
|
|
650
662
|
*
|
|
651
|
-
*
|
|
652
|
-
*
|
|
663
|
+
* // raw SQL default:
|
|
664
|
+
* timestamp: t.timestamp().default(t.sql`now()`),
|
|
653
665
|
*
|
|
654
|
-
*
|
|
655
|
-
*
|
|
656
|
-
*
|
|
657
|
-
* }
|
|
666
|
+
* // runtime default, each new records gets a new random value:
|
|
667
|
+
* random: t.numeric().default(() => Math.random()),
|
|
668
|
+
* }));
|
|
658
669
|
* ```
|
|
659
670
|
*
|
|
660
671
|
* @param value - default value or a function returning a value
|
|
@@ -749,14 +760,11 @@ var Column = class {
|
|
|
749
760
|
* It won't be selected with `selectAll` or `select('*')` as well.
|
|
750
761
|
*
|
|
751
762
|
* ```ts
|
|
752
|
-
* export
|
|
753
|
-
*
|
|
754
|
-
*
|
|
755
|
-
*
|
|
756
|
-
*
|
|
757
|
-
* password: t.string().select(false),
|
|
758
|
-
* }));
|
|
759
|
-
* }
|
|
763
|
+
* export const UserTable = defineTable('user', (t) => ({
|
|
764
|
+
* id: t.identity().primaryKey(),
|
|
765
|
+
* name: t.string(),
|
|
766
|
+
* password: t.string().select(false),
|
|
767
|
+
* }));
|
|
760
768
|
*
|
|
761
769
|
* // only id and name are selected, without password
|
|
762
770
|
* const user = await db.user.find(123);
|
|
@@ -799,20 +807,17 @@ var Column = class {
|
|
|
799
807
|
* `readOnly` column can be used together with a `default`.
|
|
800
808
|
*
|
|
801
809
|
* ```ts
|
|
802
|
-
* export
|
|
803
|
-
*
|
|
804
|
-
*
|
|
805
|
-
*
|
|
806
|
-
*
|
|
807
|
-
*
|
|
808
|
-
*
|
|
809
|
-
*
|
|
810
|
-
* init(orm: typeof db) {
|
|
811
|
-
* this.beforeSave(({ set }) => {
|
|
810
|
+
* export const Table = defineTable('table', (t) => ({
|
|
811
|
+
* id: t.identity().primaryKey(),
|
|
812
|
+
* column: t.string().default(() => 'default value'),
|
|
813
|
+
* another: t.string().nullable().readOnly(),
|
|
814
|
+
* })).init((orm: typeof db, hooks) => {
|
|
815
|
+
* hooks.beforeSave(({ columns, set }) => {
|
|
816
|
+
* if (columns.include('column')) {
|
|
812
817
|
* set({ another: 'value' });
|
|
813
|
-
* }
|
|
814
|
-
* }
|
|
815
|
-
* }
|
|
818
|
+
* }
|
|
819
|
+
* });
|
|
820
|
+
* });
|
|
816
821
|
*
|
|
817
822
|
* // later in the code
|
|
818
823
|
* db.table.create({ column: 'value' }); // TS error, runtime error
|
|
@@ -828,13 +833,15 @@ var Column = class {
|
|
|
828
833
|
* If no value or undefined is returned, the hook won't have any effect.
|
|
829
834
|
*
|
|
830
835
|
* ```ts
|
|
831
|
-
* export
|
|
832
|
-
*
|
|
833
|
-
*
|
|
834
|
-
*
|
|
835
|
-
*
|
|
836
|
-
*
|
|
837
|
-
*
|
|
836
|
+
* export const Table = defineTable('table', (t) => ({
|
|
837
|
+
* id: t.identity().primaryKey(),
|
|
838
|
+
* some: t.number(),
|
|
839
|
+
* column: t
|
|
840
|
+
* .string()
|
|
841
|
+
* .setOnCreate(({ columns }) =>
|
|
842
|
+
* columns.include('some') ? 'value' : undefined,
|
|
843
|
+
* ),
|
|
844
|
+
* }));
|
|
838
845
|
* ```
|
|
839
846
|
*/
|
|
840
847
|
setOnCreate(fn) {
|
|
@@ -847,13 +854,15 @@ var Column = class {
|
|
|
847
854
|
* If no value or undefined is returned, the hook won't have any effect.
|
|
848
855
|
*
|
|
849
856
|
* ```ts
|
|
850
|
-
* export
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
*
|
|
854
|
-
*
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
+
* export const Table = defineTable('table', (t) => ({
|
|
858
|
+
* id: t.identity().primaryKey(),
|
|
859
|
+
* some: t.number(),
|
|
860
|
+
* column: t
|
|
861
|
+
* .string()
|
|
862
|
+
* .setOnUpdate(({ columns }) =>
|
|
863
|
+
* columns.include('some') ? 'value' : undefined,
|
|
864
|
+
* ),
|
|
865
|
+
* }));
|
|
857
866
|
* ```
|
|
858
867
|
*/
|
|
859
868
|
setOnUpdate(fn) {
|
|
@@ -866,13 +875,15 @@ var Column = class {
|
|
|
866
875
|
* If no value or undefined is returned, the hook won't have any effect.
|
|
867
876
|
*
|
|
868
877
|
* ```ts
|
|
869
|
-
* export
|
|
870
|
-
*
|
|
871
|
-
*
|
|
872
|
-
*
|
|
873
|
-
*
|
|
874
|
-
*
|
|
875
|
-
*
|
|
878
|
+
* export const Table = defineTable('table', (t) => ({
|
|
879
|
+
* id: t.identity().primaryKey(),
|
|
880
|
+
* some: t.number(),
|
|
881
|
+
* column: t
|
|
882
|
+
* .string()
|
|
883
|
+
* .setOnSave(({ columns }) =>
|
|
884
|
+
* columns.include('some') ? 'value' : undefined,
|
|
885
|
+
* ),
|
|
886
|
+
* }));
|
|
876
887
|
* ```
|
|
877
888
|
*/
|
|
878
889
|
setOnSave(fn) {
|
|
@@ -887,14 +898,11 @@ var Column = class {
|
|
|
887
898
|
* Using `primaryKey` on a `uuid` column will automatically add a [gen_random_uuid](https://www.postgresql.org/docs/current/functions-uuid.html) default.
|
|
888
899
|
*
|
|
889
900
|
* ```ts
|
|
890
|
-
* export
|
|
891
|
-
*
|
|
892
|
-
*
|
|
893
|
-
*
|
|
894
|
-
*
|
|
895
|
-
* id: t.uuid().primaryKey('primary_key_name'),
|
|
896
|
-
* }));
|
|
897
|
-
* }
|
|
901
|
+
* export const Table = defineTable('table', (t) => ({
|
|
902
|
+
* id: t.uuid().primaryKey(),
|
|
903
|
+
* // optionally, specify a database-level constraint name:
|
|
904
|
+
* id: t.uuid().primaryKey('primary_key_name'),
|
|
905
|
+
* }));
|
|
898
906
|
*
|
|
899
907
|
* // primary key can be used by `find` later:
|
|
900
908
|
* db.table.find('97ba9e78-7510-415a-9c03-23d440aec443');
|
|
@@ -1284,8 +1292,8 @@ const codeToString = (code, tabs, shift) => {
|
|
|
1284
1292
|
* @param t - column types variable name
|
|
1285
1293
|
* @param value - column default
|
|
1286
1294
|
*/
|
|
1287
|
-
const columnDefaultArgumentToCode = (
|
|
1288
|
-
if (typeof value === "object" && value && isRawSQL(value)) return rawSqlToCode(value,
|
|
1295
|
+
const columnDefaultArgumentToCode = (ctx, value) => {
|
|
1296
|
+
if (typeof value === "object" && value && isRawSQL(value)) return rawSqlToCode(value, ctx);
|
|
1289
1297
|
else if (typeof value === "function") return value.toString();
|
|
1290
1298
|
else if (typeof value === "string") return singleQuote(value);
|
|
1291
1299
|
else return JSON.stringify(value);
|
|
@@ -1529,26 +1537,26 @@ const excludeInnerToCode = (item, t) => {
|
|
|
1529
1537
|
return code;
|
|
1530
1538
|
};
|
|
1531
1539
|
const excludeToCode = indexOrExcludeToCode(excludeInnerToCode);
|
|
1532
|
-
const constraintToCode = (item, t, m, prefix) => {
|
|
1533
|
-
const code = constraintInnerToCode(item, t, m);
|
|
1540
|
+
const constraintToCode = (item, t, m, prefix, ctx) => {
|
|
1541
|
+
const code = constraintInnerToCode(item, t, m, ctx);
|
|
1534
1542
|
if (prefix) code[0] = prefix + code[0];
|
|
1535
1543
|
const last = code[code.length - 1];
|
|
1536
1544
|
if (typeof last === "string" && !last.endsWith(",")) code[code.length - 1] += ",";
|
|
1537
1545
|
return code;
|
|
1538
1546
|
};
|
|
1539
|
-
const constraintInnerToCode = (item, t, m) => {
|
|
1547
|
+
const constraintInnerToCode = (item, t, m, ctx) => {
|
|
1540
1548
|
if (item.references) return [
|
|
1541
1549
|
`${t}.foreignKey(`,
|
|
1542
1550
|
referencesArgsToCode(item.references, item.name, m),
|
|
1543
1551
|
"),"
|
|
1544
1552
|
];
|
|
1545
|
-
return [`${t}.check(${rawSqlToCode(item.check, t)}${item.name ? `, ${singleQuote(item.name)}` : ""})`];
|
|
1553
|
+
return [`${t}.check(${rawSqlToCode(item.check, ctx ?? t)}${item.name ? `, ${singleQuote(item.name)}` : ""})`];
|
|
1546
1554
|
};
|
|
1547
1555
|
const referencesArgsToCode = ({ columns, fnOrTable, foreignColumns, options }, name = options?.name || false, m) => {
|
|
1548
1556
|
const args = [];
|
|
1549
1557
|
args.push(`${singleQuoteArray(columns)},`);
|
|
1550
1558
|
if (m && typeof fnOrTable !== "string") {
|
|
1551
|
-
const { schema, table } =
|
|
1559
|
+
const { schema, table } = getForeignKeyTableInstance(fnOrTable());
|
|
1552
1560
|
fnOrTable = schema ? `${schema}.${table}` : table;
|
|
1553
1561
|
}
|
|
1554
1562
|
args.push(`${typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString()},`);
|
|
@@ -1577,7 +1585,7 @@ const columnForeignKeysToCode = (foreignKeys, migration) => {
|
|
|
1577
1585
|
const foreignKeyArgumentToCode = ({ fnOrTable, foreignColumns, options = emptyObject }, migration) => {
|
|
1578
1586
|
const code = [];
|
|
1579
1587
|
if (migration && typeof fnOrTable !== "string") {
|
|
1580
|
-
const { schema, table } =
|
|
1588
|
+
const { schema, table } = getForeignKeyTableInstance(fnOrTable());
|
|
1581
1589
|
fnOrTable = schema ? `${schema}.${table}` : table;
|
|
1582
1590
|
}
|
|
1583
1591
|
code.push(typeof fnOrTable === "string" ? singleQuote(fnOrTable) : fnOrTable.toString());
|
|
@@ -1645,7 +1653,7 @@ const columnExcludesToCode = (items) => {
|
|
|
1645
1653
|
return code;
|
|
1646
1654
|
};
|
|
1647
1655
|
const columnCheckToCode = (ctx, checks) => {
|
|
1648
|
-
return checks.map(({ sql, name }) => `.check(${rawSqlToCode(sql, ctx
|
|
1656
|
+
return checks.map(({ sql, name }) => `.check(${rawSqlToCode(sql, ctx)}${name ? `, '${name}'` : ""})`).join("");
|
|
1649
1657
|
};
|
|
1650
1658
|
const identityToCode = (identity, dataType) => {
|
|
1651
1659
|
const code = [];
|
|
@@ -1681,7 +1689,7 @@ const columnCode = (type, ctx, key, code) => {
|
|
|
1681
1689
|
if (data.explicitSelect) addCode(code, ".select(false)");
|
|
1682
1690
|
if (data.isNullable) addCode(code, ".nullable()");
|
|
1683
1691
|
if (data.as && !ctx.migration) addCode(code, `.as(${data.as.toCode(ctx, key)})`);
|
|
1684
|
-
if (data.default !== void 0 && data.default !== data.defaultDefault && (!ctx.migration || typeof data.default !== "function")) addCode(code, `.default(${columnDefaultArgumentToCode(ctx
|
|
1692
|
+
if (data.default !== void 0 && data.default !== data.defaultDefault && (!ctx.migration || typeof data.default !== "function")) addCode(code, `.default(${columnDefaultArgumentToCode(ctx, data.default)})`);
|
|
1685
1693
|
if (data.indexes) for (const part of columnIndexesToCode(data.indexes)) addCode(code, part);
|
|
1686
1694
|
if (data.excludes) for (const part of columnExcludesToCode(data.excludes)) addCode(code, part);
|
|
1687
1695
|
if (data.comment) addCode(code, `.comment(${singleQuote(data.comment)})`);
|
|
@@ -2283,6 +2291,17 @@ const make = (_op) => {
|
|
|
2283
2291
|
(q.chain ??= []).push(_op, val || value);
|
|
2284
2292
|
if (getValueParser(q.parsers)) setValueParser(q, void 0);
|
|
2285
2293
|
q.getColumn = BooleanColumn.instance;
|
|
2294
|
+
if (this instanceof Expression && this.result) {
|
|
2295
|
+
let column;
|
|
2296
|
+
if (this.result.value?.data.name) {
|
|
2297
|
+
column = Object.create(BooleanColumn.instance);
|
|
2298
|
+
column.data = {
|
|
2299
|
+
...column.data,
|
|
2300
|
+
name: this.result.value.data.name
|
|
2301
|
+
};
|
|
2302
|
+
} else column = BooleanColumn.instance;
|
|
2303
|
+
this.result.value = column;
|
|
2304
|
+
}
|
|
2286
2305
|
return setQueryOperators(this, boolean);
|
|
2287
2306
|
}, { _op });
|
|
2288
2307
|
};
|
|
@@ -2789,7 +2808,8 @@ var SimpleRawSQL = class extends RawSql {
|
|
|
2789
2808
|
};
|
|
2790
2809
|
const raw$1 = (sql) => new SimpleRawSQL(sql);
|
|
2791
2810
|
const makeTimestamps = (timestamp) => {
|
|
2792
|
-
const
|
|
2811
|
+
const now = getDefaultNowFn();
|
|
2812
|
+
const nowRaw = raw$1(now);
|
|
2793
2813
|
const updatedAt = timestamp().default(nowRaw);
|
|
2794
2814
|
let updater;
|
|
2795
2815
|
updatedAt.data.modifyQuery = (q, column) => {
|
|
@@ -2822,7 +2842,7 @@ const timestampHelpers = {
|
|
|
2822
2842
|
};
|
|
2823
2843
|
const defaultSrid = 4326;
|
|
2824
2844
|
const encode = ({ srid = defaultSrid, lon, lat }) => {
|
|
2825
|
-
const arr = new Uint8Array(25);
|
|
2845
|
+
const arr = /* @__PURE__ */ new Uint8Array(25);
|
|
2826
2846
|
const view = new DataView(arr.buffer);
|
|
2827
2847
|
view.setInt8(0, 1);
|
|
2828
2848
|
view.setInt8(1, 1);
|
|
@@ -2851,7 +2871,7 @@ var PostgisGeographyPointColumn = class extends Column {
|
|
|
2851
2871
|
}
|
|
2852
2872
|
};
|
|
2853
2873
|
const parse = (input) => {
|
|
2854
|
-
const bytes = new Uint8Array(20);
|
|
2874
|
+
const bytes = /* @__PURE__ */ new Uint8Array(20);
|
|
2855
2875
|
for (let i = 0; i < 40; i += 2) bytes[i / 2] = parseInt(input.slice(10 + i, 12 + i), 16);
|
|
2856
2876
|
const view = new DataView(bytes.buffer);
|
|
2857
2877
|
const srid = view.getUint32(0, true);
|
|
@@ -3719,24 +3739,19 @@ var QueryStorage = class {
|
|
|
3719
3739
|
* so later they can be identified when handling after commit errors.
|
|
3720
3740
|
*
|
|
3721
3741
|
* ```ts
|
|
3722
|
-
*
|
|
3723
|
-
*
|
|
3724
|
-
*
|
|
3725
|
-
*
|
|
3726
|
-
*
|
|
3727
|
-
*
|
|
3728
|
-
*
|
|
3729
|
-
* // anonymous funciton - has no name
|
|
3730
|
-
* this.afterCreateCommit([], async () => {
|
|
3731
|
-
* // ...
|
|
3732
|
-
* });
|
|
3742
|
+
* export const SomeTable = defineTable('someTable', (t) => ({
|
|
3743
|
+
* ...someColumns,
|
|
3744
|
+
* })).init((orm: typeof db, hooks) => {
|
|
3745
|
+
* // anonymous funciton - has no name
|
|
3746
|
+
* hooks.afterCreateCommit([], async () => {
|
|
3747
|
+
* // ...
|
|
3748
|
+
* });
|
|
3733
3749
|
*
|
|
3734
|
-
*
|
|
3735
|
-
*
|
|
3736
|
-
*
|
|
3737
|
-
*
|
|
3738
|
-
*
|
|
3739
|
-
* }
|
|
3750
|
+
* // named function
|
|
3751
|
+
* hooks.afterCreateCommit([], function myHook() {
|
|
3752
|
+
* // ...
|
|
3753
|
+
* });
|
|
3754
|
+
* });
|
|
3740
3755
|
* ```
|
|
3741
3756
|
*/
|
|
3742
3757
|
var AfterCommitError = class extends OrchidOrmError {
|
|
@@ -3801,7 +3816,8 @@ var QueryTransaction = class QueryTransaction {
|
|
|
3801
3816
|
return QueryTransaction.prototype.transaction.call(this, cb);
|
|
3802
3817
|
}
|
|
3803
3818
|
isInTransaction() {
|
|
3804
|
-
|
|
3819
|
+
const trx = this.internal.asyncStorage.getStore();
|
|
3820
|
+
return isInUserTransaction(trx);
|
|
3805
3821
|
}
|
|
3806
3822
|
/**
|
|
3807
3823
|
* Schedules a hook to run after the outermost transaction commits:
|
|
@@ -4489,21 +4505,16 @@ const _unscope = (q, scope) => {
|
|
|
4489
4505
|
* If you define a scope with name `default`, it will be applied for all table queries by default.
|
|
4490
4506
|
*
|
|
4491
4507
|
* ```ts
|
|
4492
|
-
* import {
|
|
4508
|
+
* import { defineTable } from './table-factory';
|
|
4493
4509
|
*
|
|
4494
|
-
* export
|
|
4495
|
-
*
|
|
4496
|
-
*
|
|
4497
|
-
*
|
|
4498
|
-
*
|
|
4499
|
-
*
|
|
4500
|
-
* })
|
|
4501
|
-
*
|
|
4502
|
-
* scopes = this.setScopes({
|
|
4503
|
-
* default: (q) => q.where({ hidden: false }),
|
|
4504
|
-
* active: (q) => q.where({ active: true }),
|
|
4505
|
-
* });
|
|
4506
|
-
* }
|
|
4510
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
4511
|
+
* id: t.identity().primaryKey(),
|
|
4512
|
+
* hidden: t.boolean(),
|
|
4513
|
+
* active: t.boolean(),
|
|
4514
|
+
* })).scopes({
|
|
4515
|
+
* default: (q) => q.where({ hidden: false }),
|
|
4516
|
+
* active: (q) => q.where({ active: true }),
|
|
4517
|
+
* });
|
|
4507
4518
|
*
|
|
4508
4519
|
* const db = orchidORM(
|
|
4509
4520
|
* { databaseURL: '...' },
|
|
@@ -5666,7 +5677,8 @@ const resolveCallbacksInArgs = (q, args) => {
|
|
|
5666
5677
|
qb.q.and = qb.q.or = qb.q.scopes = void 0;
|
|
5667
5678
|
qb.q.subQuery = 1;
|
|
5668
5679
|
_setSubQueryAliases(qb);
|
|
5669
|
-
|
|
5680
|
+
const resolved = resolveSubQueryCallback(qb, arg);
|
|
5681
|
+
args[i] = prepareSubQueryForSql(q, resolved);
|
|
5670
5682
|
} else if (arg.constructor === Object) {
|
|
5671
5683
|
const copy = args[i] = { ...arg };
|
|
5672
5684
|
for (const key in arg) {
|
|
@@ -5811,7 +5823,7 @@ var Where = class {
|
|
|
5811
5823
|
* Constructing `WHERE` conditions:
|
|
5812
5824
|
*
|
|
5813
5825
|
* ```ts
|
|
5814
|
-
* import { sql } from './
|
|
5826
|
+
* import { sql } from './table-factory';
|
|
5815
5827
|
*
|
|
5816
5828
|
* db.table.where({
|
|
5817
5829
|
* // column of the current table
|
|
@@ -5827,7 +5839,7 @@ var Where = class {
|
|
|
5827
5839
|
* },
|
|
5828
5840
|
*
|
|
5829
5841
|
* // where column equals to raw SQL
|
|
5830
|
-
* // import `sql` from your
|
|
5842
|
+
* // import `sql` from your table factory
|
|
5831
5843
|
* column: sql`sql expression`,
|
|
5832
5844
|
* // or use `(q) => sql` for the same
|
|
5833
5845
|
* column2: (q) => sql`sql expression`,
|
|
@@ -6438,7 +6450,8 @@ var Where = class {
|
|
|
6438
6450
|
* @param args - no arguments needed when the first argument is a relation name, or conditions to join the table with.
|
|
6439
6451
|
*/
|
|
6440
6452
|
whereNotExists(arg, ...args) {
|
|
6441
|
-
|
|
6453
|
+
const q = _clone(this);
|
|
6454
|
+
return _queryWhereNotExists(q, arg, args);
|
|
6442
6455
|
}
|
|
6443
6456
|
/**
|
|
6444
6457
|
* Acts as `whereExists`, but prepends the condition with `OR` and negates it with `NOT`:
|
|
@@ -6585,7 +6598,11 @@ const tableColumnToSql = (ctx, queryData, shape, table, key, quotedAs, select, a
|
|
|
6585
6598
|
const columnToSqlNotSelect = (ctx, data, shape, column, quotedAs, useSelectList) => columnToSql(ctx, data, shape, column, quotedAs, void 0, void 0, void 0, useSelectList, true);
|
|
6586
6599
|
const columnToSql = (ctx, data, shape, column, quotedAs, select, as, jsonList, useSelectList, skipValueToArray) => {
|
|
6587
6600
|
let index = column.indexOf(".");
|
|
6588
|
-
if (index !== -1)
|
|
6601
|
+
if (index !== -1) {
|
|
6602
|
+
const table = column.slice(0, index);
|
|
6603
|
+
const key = column.slice(index + 1);
|
|
6604
|
+
return tableColumnToSql(ctx, data, shape, table, key, quotedAs, select, as, jsonList, skipValueToArray);
|
|
6605
|
+
}
|
|
6589
6606
|
return simpleColumnToSQL(ctx, data, shape, column, shape[column], quotedAs, select, as, jsonList, useSelectList, void 0, skipValueToArray);
|
|
6590
6607
|
};
|
|
6591
6608
|
const rawOrColumnToSql = (ctx, data, shape, expr, quotedAs, select, skipValueToArray) => {
|
|
@@ -6828,11 +6845,20 @@ const _addToHookSelectWithTable = (query, selects, table) => {
|
|
|
6828
6845
|
};
|
|
6829
6846
|
const moveQueryToCte = (ctx, query, type, dontAddTableHook) => {
|
|
6830
6847
|
const { returnType } = query.q;
|
|
6848
|
+
const throwOnNotFound = returnType === "valueOrThrow";
|
|
6831
6849
|
let valueAs;
|
|
6832
6850
|
if (returnType === "value" || returnType === "valueOrThrow" || returnType === "pluck") {
|
|
6833
6851
|
const first = query.q.select[0];
|
|
6834
|
-
if (first instanceof SelectItemExpression && typeof first.item === "string")
|
|
6835
|
-
|
|
6852
|
+
if (first instanceof SelectItemExpression && typeof first.item === "string") {
|
|
6853
|
+
const columnName = first.result.value?.data.name;
|
|
6854
|
+
if (columnName && columnName !== first.item) {
|
|
6855
|
+
query = _clone(query);
|
|
6856
|
+
query.q.returnType = "one";
|
|
6857
|
+
query.q.select = [{ selectAs: { [first.item]: first } }];
|
|
6858
|
+
if (throwOnNotFound && query.q.type !== "upsert") query.q.cteThrowOnNotFound = true;
|
|
6859
|
+
}
|
|
6860
|
+
valueAs = first.item;
|
|
6861
|
+
} else {
|
|
6836
6862
|
query = _clone(query);
|
|
6837
6863
|
query.q.returnType = "one";
|
|
6838
6864
|
query.q.select = [{ selectAs: { value: query.q.select[0] } }];
|
|
@@ -6889,7 +6915,7 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
|
|
|
6889
6915
|
const afterUpdateCommit = data.afterUpdateCommit;
|
|
6890
6916
|
const afterSaveCommit = data.afterSaveCommit;
|
|
6891
6917
|
const afterDeleteCommit = data.afterDeleteCommit;
|
|
6892
|
-
const throwOnNotFound = hookPurpose !== "Create" && (data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
|
|
6918
|
+
const throwOnNotFound = hookPurpose !== "Create" && (data.cteThrowOnNotFound || data.returnType === "oneOrThrow" || data.returnType === "valueOrThrow");
|
|
6893
6919
|
const hasAfterHook = afterCreate || afterUpdate || afterSave || afterDelete || afterCreateCommit || afterUpdateCommit || afterSaveCommit || afterDeleteCommit;
|
|
6894
6920
|
if (!select && !hasAfterHook && !throwOnNotFound) return;
|
|
6895
6921
|
const tableHook = {
|
|
@@ -6914,7 +6940,8 @@ const addTableHook = (ctx, q, data, select, hookPurpose, dontAddTableHook) => {
|
|
|
6914
6940
|
tableHook,
|
|
6915
6941
|
throwOnNotFound
|
|
6916
6942
|
};
|
|
6917
|
-
const
|
|
6943
|
+
const hasSelect = throwOnNotFound || !!tableHook.select;
|
|
6944
|
+
const cteHooks = setCteHooks(ctx, hasSelect);
|
|
6918
6945
|
(cteHooks.tableHooks ??= {})[ctx.cteName] ??= item;
|
|
6919
6946
|
}
|
|
6920
6947
|
} else ctx.topCtx.tableHook = tableHook;
|
|
@@ -7307,7 +7334,8 @@ const processWhere = (ands, ctx, table, query, data, quotedAs) => {
|
|
|
7307
7334
|
const value = data[key];
|
|
7308
7335
|
if (value === void 0) continue;
|
|
7309
7336
|
if (key === "AND") {
|
|
7310
|
-
const
|
|
7337
|
+
const arr = toArray(value);
|
|
7338
|
+
const sql = processAnds(arr, ctx, table, query, quotedAs);
|
|
7311
7339
|
if (sql) ands.push(sql);
|
|
7312
7340
|
} else if (key === "OR") {
|
|
7313
7341
|
const sqls = value.map(toArray).reduce((acc, and) => {
|
|
@@ -8950,7 +8978,9 @@ const _queryCreate = (q, data) => {
|
|
|
8950
8978
|
};
|
|
8951
8979
|
const _queryInsert = (query, data) => {
|
|
8952
8980
|
throwIfReadOnly(query);
|
|
8953
|
-
|
|
8981
|
+
const ctx = createCtx();
|
|
8982
|
+
const obj = handleOneData(query, data, ctx);
|
|
8983
|
+
return insert(query, obj);
|
|
8954
8984
|
};
|
|
8955
8985
|
const _queryCreateMany = (q, data) => {
|
|
8956
8986
|
throwIfReadOnly(q);
|
|
@@ -8959,7 +8989,8 @@ const _queryCreateMany = (q, data) => {
|
|
|
8959
8989
|
};
|
|
8960
8990
|
const _queryInsertMany = (q, data) => {
|
|
8961
8991
|
throwIfReadOnly(q);
|
|
8962
|
-
|
|
8992
|
+
const ctx = createCtx();
|
|
8993
|
+
let result = insert(q, handleManyData(q, data, ctx), true);
|
|
8963
8994
|
if (!data.length) result = result.none();
|
|
8964
8995
|
return result;
|
|
8965
8996
|
};
|
|
@@ -9150,31 +9181,26 @@ var QueryCreate = class {
|
|
|
9150
9181
|
* A primary key or a unique index for a **single** column can be fined on a column:
|
|
9151
9182
|
*
|
|
9152
9183
|
* ```ts
|
|
9153
|
-
* export
|
|
9154
|
-
*
|
|
9155
|
-
*
|
|
9156
|
-
*
|
|
9157
|
-
* }));
|
|
9158
|
-
* }
|
|
9184
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9185
|
+
* pkey: t.uuid().primaryKey(),
|
|
9186
|
+
* unique: t.string().unique(),
|
|
9187
|
+
* }));
|
|
9159
9188
|
* ```
|
|
9160
9189
|
*
|
|
9161
9190
|
* But for composite primary keys or indexes (having multiple columns), define it in a separate function:
|
|
9162
9191
|
*
|
|
9163
9192
|
* ```ts
|
|
9164
|
-
* export
|
|
9165
|
-
*
|
|
9166
|
-
*
|
|
9167
|
-
*
|
|
9168
|
-
*
|
|
9169
|
-
*
|
|
9170
|
-
*
|
|
9171
|
-
* (t) => [t.primaryKey(['one', 'two']), t.unique(['two', 'three'])],
|
|
9172
|
-
* );
|
|
9173
|
-
* }
|
|
9193
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9194
|
+
* one: t.integer(),
|
|
9195
|
+
* two: t.string(),
|
|
9196
|
+
* three: t.boolean(),
|
|
9197
|
+
* }))
|
|
9198
|
+
* .primaryKey(['one', 'two'])
|
|
9199
|
+
* .unique(['two', 'three']);
|
|
9174
9200
|
* ```
|
|
9175
9201
|
* :::
|
|
9176
9202
|
*
|
|
9177
|
-
* You can use the `sql` function exported from your
|
|
9203
|
+
* You can use the `sql` function exported from your table factory file in onConflict.
|
|
9178
9204
|
* It can be useful to specify a condition when you have a partial index:
|
|
9179
9205
|
*
|
|
9180
9206
|
* ```ts
|
|
@@ -9564,12 +9590,15 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
|
|
|
9564
9590
|
if (upsertOrCreate.q.returnType === "oneOrThrow") upsertOrCreate.q.returnType = "one";
|
|
9565
9591
|
else if (upsertOrCreate.q.returnType === "valueOrThrow") upsertOrCreate.q.returnType = "value";
|
|
9566
9592
|
const { as, makeSql: makeFirstSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, upsertUpdate ? "update" : null);
|
|
9593
|
+
query.upsertUpdateAsFns?.forEach((fn) => fn(as));
|
|
9567
9594
|
upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
|
|
9568
9595
|
upsertOrCreate.q.and = [new RawSql(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
|
|
9569
9596
|
if (query.upsertInsert) {
|
|
9570
|
-
|
|
9597
|
+
const insertData = query.upsertInsert();
|
|
9598
|
+
_queryInsert(upsertOrCreate, insertData);
|
|
9571
9599
|
upsertOrCreate.q.type = "upsert";
|
|
9572
9600
|
}
|
|
9601
|
+
upsertOrCreate.q.with = query.upsertCreateWith;
|
|
9573
9602
|
upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
|
|
9574
9603
|
upsertOrCreate.q.asFns = query.upsertCreateAsFns;
|
|
9575
9604
|
const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
|
|
@@ -9679,7 +9708,8 @@ const cteToSqlGiveAs = (ctx, item, type, dontAddTableHook) => {
|
|
|
9679
9708
|
let as;
|
|
9680
9709
|
if (typeof item.n === "string") as = item.n;
|
|
9681
9710
|
else if (ctx === ctx.topCtx) {
|
|
9682
|
-
|
|
9711
|
+
const topCTE = ctx.topCtx.topCTE ??= newTopCte(ctx);
|
|
9712
|
+
as = setFreeAlias(topCTE.names, "q", true);
|
|
9683
9713
|
item.n(as);
|
|
9684
9714
|
} else throw new Error("not implemented yet");
|
|
9685
9715
|
if (item.q) inner = getSqlText(toSql(item.q, type, ctx.topCtx, true, as, void 0, dontAddTableHook));
|
|
@@ -10141,36 +10171,21 @@ var QueryJoin = class {
|
|
|
10141
10171
|
* 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:
|
|
10142
10172
|
*
|
|
10143
10173
|
* ```ts
|
|
10144
|
-
* export
|
|
10145
|
-
*
|
|
10146
|
-
*
|
|
10147
|
-
*
|
|
10148
|
-
*
|
|
10149
|
-
*
|
|
10150
|
-
*
|
|
10151
|
-
* relations = {
|
|
10152
|
-
* messages: this.hasMany(() => MessageTable, {
|
|
10153
|
-
* primaryKey: 'id',
|
|
10154
|
-
* foreignKey: 'userId',
|
|
10155
|
-
* }),
|
|
10156
|
-
* };
|
|
10157
|
-
* }
|
|
10158
|
-
*
|
|
10159
|
-
* export class MessageTable extends BaseTable {
|
|
10160
|
-
* readonly table = 'message';
|
|
10161
|
-
* columns = this.setColumns((t) => ({
|
|
10162
|
-
* id: t.identity().primaryKey(),
|
|
10163
|
-
* text: t.text(),
|
|
10164
|
-
* ...t.timestamps(),
|
|
10165
|
-
* }));
|
|
10174
|
+
* export const UserTable = defineTable('user', (t) => ({
|
|
10175
|
+
* id: t.identity().primaryKey(),
|
|
10176
|
+
* name: t.text(),
|
|
10177
|
+
* })).relations((user) => ({
|
|
10178
|
+
* messages: user('id').hasMany(() => MessageTable('userId')),
|
|
10179
|
+
* }));
|
|
10166
10180
|
*
|
|
10167
|
-
*
|
|
10168
|
-
*
|
|
10169
|
-
*
|
|
10170
|
-
*
|
|
10171
|
-
*
|
|
10172
|
-
*
|
|
10173
|
-
*
|
|
10181
|
+
* export const MessageTable = defineTable('message', (t) => ({
|
|
10182
|
+
* id: t.identity().primaryKey(),
|
|
10183
|
+
* userId: t.integer(),
|
|
10184
|
+
* text: t.text(),
|
|
10185
|
+
* ...t.timestamps(),
|
|
10186
|
+
* })).relations((message) => ({
|
|
10187
|
+
* user: message('userId').belongsTo(() => UserTable('id')),
|
|
10188
|
+
* }));
|
|
10174
10189
|
* ```
|
|
10175
10190
|
*
|
|
10176
10191
|
* `join` is a method for SQL `JOIN`, which is equivalent to `INNER JOIN`, `LEFT INNERT JOIN`.
|
|
@@ -10367,7 +10382,7 @@ var QueryJoin = class {
|
|
|
10367
10382
|
* ```ts
|
|
10368
10383
|
* db.user.join(
|
|
10369
10384
|
* db.message,
|
|
10370
|
-
* // `sql` can be imported from your
|
|
10385
|
+
* // `sql` can be imported from your table factory file
|
|
10371
10386
|
* sql`lower("message"."text") = lower("user"."name")`,
|
|
10372
10387
|
* );
|
|
10373
10388
|
* ```
|
|
@@ -10818,12 +10833,15 @@ var OnMethods = class {
|
|
|
10818
10833
|
const setSelectRelation = (q) => {
|
|
10819
10834
|
q.selectRelation = true;
|
|
10820
10835
|
};
|
|
10821
|
-
const
|
|
10836
|
+
const addParsersForSelectJoinedWildcard = (q, arg, as = arg) => {
|
|
10822
10837
|
const parsers = q.q.joinedParsers?.[arg];
|
|
10823
10838
|
if (parsers) setParserToQuery(q.q, as, (row) => parseRecord(parsers, row));
|
|
10824
10839
|
const batchParsers = q.q.joinedBatchParsers?.[arg];
|
|
10825
10840
|
if (batchParsers) pushQueryArrayImmutable(q, "batchParsers", batchParsers.map((x) => ({
|
|
10826
|
-
path: [{
|
|
10841
|
+
path: [{
|
|
10842
|
+
key: as,
|
|
10843
|
+
returnType: "one"
|
|
10844
|
+
}, ...x.path],
|
|
10827
10845
|
fn: x.fn
|
|
10828
10846
|
})));
|
|
10829
10847
|
};
|
|
@@ -11005,7 +11023,8 @@ const processSelectAsArg = (q, selectAs, as, key, arg, columnAlias, outerReturnT
|
|
|
11005
11023
|
subQuery = value;
|
|
11006
11024
|
} else subQuery = value.json(false);
|
|
11007
11025
|
else subQuery = value;
|
|
11008
|
-
const
|
|
11026
|
+
const joinLateral = innerJoinLateral || query.q.returnType === "valueOrThrow";
|
|
11027
|
+
const as = _joinLateral(q, joinLateral ? "JOIN" : "LEFT JOIN", subQuery, key, innerJoinLateral && returnType !== "one" && returnType !== "oneOrThrow");
|
|
11009
11028
|
if (as) value.q.joinedForSelect = _copyQueryAliasToQuery(value, q, as);
|
|
11010
11029
|
}
|
|
11011
11030
|
if (value.q.getColumn?.data.skipValueToArray) value.q.notFoundDefault ??= null;
|
|
@@ -11037,7 +11056,7 @@ const setParserForSelectedString = (query, arg, as, columnAs, columnAlias) => {
|
|
|
11037
11056
|
const table = getFullColumnTable(query, arg, index, as);
|
|
11038
11057
|
const column = arg.slice(index + 1);
|
|
11039
11058
|
if (column === "*") {
|
|
11040
|
-
|
|
11059
|
+
addParsersForSelectJoinedWildcard(query, table, columnAs);
|
|
11041
11060
|
return table === as ? column : arg;
|
|
11042
11061
|
}
|
|
11043
11062
|
if (table === as) return selectColumn(query, q, column, columnAs, columnAlias);
|
|
@@ -11463,6 +11482,7 @@ function _orCreate(query, data, updateData, mergeData) {
|
|
|
11463
11482
|
const { q } = query;
|
|
11464
11483
|
q.returnsOne = true;
|
|
11465
11484
|
if (!q.select) q.returnType = "void";
|
|
11485
|
+
q.type = "upsert";
|
|
11466
11486
|
if (typeof data === "function") q.upsertInsert = () => mergeData ? {
|
|
11467
11487
|
...mergeData,
|
|
11468
11488
|
...data(updateData)
|
|
@@ -12452,7 +12472,17 @@ const _appendQuery = (main, append, asFn) => {
|
|
|
12452
12472
|
const _appendQueryOnUpsertCreate = (main, append, asFn) => {
|
|
12453
12473
|
return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
|
|
12454
12474
|
};
|
|
12455
|
-
const
|
|
12475
|
+
const _onUpsertUpdate = (q, asFn) => {
|
|
12476
|
+
return pushQueryValueImmutable(q, "upsertUpdateAsFns", asFn);
|
|
12477
|
+
};
|
|
12478
|
+
const _prependWithOnUpsertCreate = (q, name, query) => {
|
|
12479
|
+
const prev = q.q.with;
|
|
12480
|
+
q.q.with = q.q.upsertCreateWith;
|
|
12481
|
+
_prependWith(q, name, query);
|
|
12482
|
+
q.q.upsertCreateWith = q.q.with;
|
|
12483
|
+
q.q.with = prev;
|
|
12484
|
+
};
|
|
12485
|
+
const mergableObjects = /* @__PURE__ */ new Set([
|
|
12456
12486
|
"selectShape",
|
|
12457
12487
|
"withShapes",
|
|
12458
12488
|
"defaultParsers",
|
|
@@ -12464,7 +12494,7 @@ const mergableObjects = new Set([
|
|
|
12464
12494
|
"joinedBatchParsers",
|
|
12465
12495
|
"selectedComputeds"
|
|
12466
12496
|
]);
|
|
12467
|
-
const dontMergeArrays = new Set(["selectAllColumns"]);
|
|
12497
|
+
const dontMergeArrays = /* @__PURE__ */ new Set(["selectAllColumns"]);
|
|
12468
12498
|
var MergeQueryMethods = class {
|
|
12469
12499
|
merge(q) {
|
|
12470
12500
|
const query = _clone(this);
|
|
@@ -12478,20 +12508,18 @@ var MergeQueryMethods = class {
|
|
|
12478
12508
|
case "number":
|
|
12479
12509
|
a[key] = value;
|
|
12480
12510
|
break;
|
|
12481
|
-
case "object":
|
|
12482
|
-
if (
|
|
12483
|
-
|
|
12484
|
-
|
|
12485
|
-
|
|
12486
|
-
|
|
12487
|
-
|
|
12488
|
-
|
|
12489
|
-
|
|
12490
|
-
|
|
12491
|
-
|
|
12492
|
-
|
|
12493
|
-
else a[key] = value;
|
|
12494
|
-
break;
|
|
12511
|
+
case "object": if (Array.isArray(value)) {
|
|
12512
|
+
if (!dontMergeArrays.has(key)) a[key] = a[key] ? [...a[key], ...value] : value;
|
|
12513
|
+
} else if (mergableObjects.has(key)) a[key] = a[key] ? {
|
|
12514
|
+
...a[key],
|
|
12515
|
+
...value
|
|
12516
|
+
} : value;
|
|
12517
|
+
else if (key === "union") a[key] = a[key] ? {
|
|
12518
|
+
b: a[key].b,
|
|
12519
|
+
u: [...a[key].u, ...value.u]
|
|
12520
|
+
} : value;
|
|
12521
|
+
else if (value instanceof Set) a[key] = a[key] ? /* @__PURE__ */ new Set([...a[key], ...value]) : value;
|
|
12522
|
+
else a[key] = value;
|
|
12495
12523
|
}
|
|
12496
12524
|
}
|
|
12497
12525
|
if (b.returnType) a.returnType = b.returnType;
|
|
@@ -12675,12 +12703,12 @@ var SearchMethods = class {
|
|
|
12675
12703
|
*
|
|
12676
12704
|
* By default, the search language is English.
|
|
12677
12705
|
*
|
|
12678
|
-
* You can set a different default language in the `
|
|
12706
|
+
* You can set a different default language in the `createTableFactory` config:
|
|
12679
12707
|
*
|
|
12680
12708
|
* ```ts
|
|
12681
|
-
* import {
|
|
12709
|
+
* import { createTableFactory } from 'orchid-orm';
|
|
12682
12710
|
*
|
|
12683
|
-
* export const
|
|
12711
|
+
* export const { defineTable, defineView, sql } = createTableFactory({
|
|
12684
12712
|
* language: 'swedish',
|
|
12685
12713
|
* });
|
|
12686
12714
|
* ```
|
|
@@ -13066,20 +13094,20 @@ const _softDelete = (column, customNowSQL) => {
|
|
|
13066
13094
|
* All queries on such table will filter out deleted records by default.
|
|
13067
13095
|
*
|
|
13068
13096
|
* ```ts
|
|
13069
|
-
* import {
|
|
13070
|
-
*
|
|
13071
|
-
* export class SomeTable extends BaseTable {
|
|
13072
|
-
* readonly table = 'some';
|
|
13073
|
-
* columns = this.setColumns((t) => ({
|
|
13074
|
-
* id: t.identity().primaryKey(),
|
|
13075
|
-
* deletedAt: t.timestamp().nullable(),
|
|
13076
|
-
* }));
|
|
13097
|
+
* import { defineTable } from './table-factory';
|
|
13077
13098
|
*
|
|
13099
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
13100
|
+
* id: t.identity().primaryKey(),
|
|
13101
|
+
* deletedAt: t.timestamp().nullable(),
|
|
13102
|
+
* }))
|
|
13078
13103
|
* // true is for using `deletedAt` column
|
|
13079
|
-
*
|
|
13080
|
-
*
|
|
13081
|
-
*
|
|
13082
|
-
*
|
|
13104
|
+
* .softDelete();
|
|
13105
|
+
*
|
|
13106
|
+
* // or provide a different column name
|
|
13107
|
+
* export const OtherTable = defineTable('other', (t) => ({
|
|
13108
|
+
* id: t.identity().primaryKey(),
|
|
13109
|
+
* myDeletedAt: t.timestamp().nullable(),
|
|
13110
|
+
* })).softDelete('myDeletedAt');
|
|
13083
13111
|
*
|
|
13084
13112
|
* const db = orchidORM(
|
|
13085
13113
|
* { databaseURL: '...' },
|
|
@@ -13469,7 +13497,8 @@ var QueryMethods = class {
|
|
|
13469
13497
|
* @param args - SQL expression
|
|
13470
13498
|
*/
|
|
13471
13499
|
findBySql(...args) {
|
|
13472
|
-
|
|
13500
|
+
const q = _clone(this);
|
|
13501
|
+
return _queryTake(_queryWhereSql(q, args));
|
|
13473
13502
|
}
|
|
13474
13503
|
/**
|
|
13475
13504
|
* Finds a single record by the primary key (id), returns `undefined` when not found.
|
|
@@ -14009,7 +14038,8 @@ var Db = class extends QueryMethods {
|
|
|
14009
14038
|
if (options.noPrimaryKey === "error") throw new Error(message);
|
|
14010
14039
|
else logger.warn(message);
|
|
14011
14040
|
}
|
|
14012
|
-
|
|
14041
|
+
const columns = Object.keys(shape);
|
|
14042
|
+
this.columns = columns;
|
|
14013
14043
|
if (options.computed) applyComputedColumns(this, options.computed);
|
|
14014
14044
|
if (prepareSelectAll) {
|
|
14015
14045
|
const selectAllShape = this.q.selectAllShape = {};
|
|
@@ -14376,11 +14406,14 @@ function getColumnInfo(query, column) {
|
|
|
14376
14406
|
};
|
|
14377
14407
|
return q;
|
|
14378
14408
|
}
|
|
14409
|
+
const columnsSql = (shape, columns) => {
|
|
14410
|
+
return columns.map((item) => `"${shape[item]?.data.name || item}"`).join(", ");
|
|
14411
|
+
};
|
|
14379
14412
|
const makeCopySql = (table, copy) => {
|
|
14380
14413
|
const ctx = newToSqlCtx(table);
|
|
14381
14414
|
const { q } = table;
|
|
14382
14415
|
const quotedAs = `"${q.as || table.table}"`;
|
|
14383
|
-
const columns = copy.columns ? `(${
|
|
14416
|
+
const columns = copy.columns ? `(${columnsSql(table.shape, copy.columns)})` : "";
|
|
14384
14417
|
const target = "from" in copy ? copy.from : copy.to;
|
|
14385
14418
|
const quotedTable = quoteTableWithSchema(table);
|
|
14386
14419
|
ctx.sql.push(`COPY ${quotedTable}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? escapeString(target) : `PROGRAM ${escapeString(target.program)}`}`);
|
|
@@ -14393,9 +14426,9 @@ const makeCopySql = (table, copy) => {
|
|
|
14393
14426
|
if (copy.header) options.push(`HEADER ${copy.header}`);
|
|
14394
14427
|
if (copy.quote) options.push(`QUOTE ${escapeString(copy.quote)}`);
|
|
14395
14428
|
if (copy.escape) options.push(`ESCAPE ${escapeString(copy.escape)}`);
|
|
14396
|
-
if (copy.forceQuote) options.push(`FORCE_QUOTE ${copy.forceQuote === "*" ? "*" : `(${
|
|
14397
|
-
if (copy.forceNotNull) options.push(`FORCE_NOT_NULL (${
|
|
14398
|
-
if (copy.forceNull) options.push(`FORCE_NULL (${
|
|
14429
|
+
if (copy.forceQuote) options.push(`FORCE_QUOTE ${copy.forceQuote === "*" ? "*" : `(${columnsSql(table.shape, copy.forceQuote)})`}`);
|
|
14430
|
+
if (copy.forceNotNull) options.push(`FORCE_NOT_NULL (${columnsSql(table.shape, copy.forceNotNull)})`);
|
|
14431
|
+
if (copy.forceNull) options.push(`FORCE_NULL (${columnsSql(table.shape, copy.forceNull)})`);
|
|
14399
14432
|
if (copy.encoding) options.push(`ENCODING ${escapeString(copy.encoding)}`);
|
|
14400
14433
|
ctx.sql.push(`WITH (${options.join(", ")})`);
|
|
14401
14434
|
}
|
|
@@ -14462,6 +14495,12 @@ var Rollback = class extends Error {};
|
|
|
14462
14495
|
const trxForTest = Symbol("trxForTest");
|
|
14463
14496
|
const argToDb = (arg) => "$qb" in arg ? arg.$qb : arg;
|
|
14464
14497
|
const testTransaction = {
|
|
14498
|
+
/**
|
|
14499
|
+
* Start a test transaction.
|
|
14500
|
+
* The returned promise is resolved immediately when transaction starts, not waiting for it to end.
|
|
14501
|
+
*
|
|
14502
|
+
* @param arg - ORM instance or a queryable instance (such as db.someTable).
|
|
14503
|
+
*/
|
|
14465
14504
|
start(arg) {
|
|
14466
14505
|
const db = argToDb(arg);
|
|
14467
14506
|
const { asyncStorage } = db.internal;
|
|
@@ -14497,6 +14536,11 @@ const testTransaction = {
|
|
|
14497
14536
|
});
|
|
14498
14537
|
});
|
|
14499
14538
|
},
|
|
14539
|
+
/**
|
|
14540
|
+
* Rollback a test transaction.
|
|
14541
|
+
*
|
|
14542
|
+
* @param arg - the same ORM or query argument passed into the `testTransaction.start`.
|
|
14543
|
+
*/
|
|
14500
14544
|
rollback(arg) {
|
|
14501
14545
|
const db = argToDb(arg);
|
|
14502
14546
|
const data = db.internal[trxForTest];
|
|
@@ -14506,12 +14550,18 @@ const testTransaction = {
|
|
|
14506
14550
|
last.reject?.(new Rollback());
|
|
14507
14551
|
return last.promise;
|
|
14508
14552
|
},
|
|
14553
|
+
/**
|
|
14554
|
+
* Will roll back the current `testTransaction` (won't have any effect if it was rolled back already),
|
|
14555
|
+
* and if there's no nested test transactions left, it will close the db connection.
|
|
14556
|
+
*
|
|
14557
|
+
* @param arg - the same ORM or query argument passed into the `testTransaction.start`.
|
|
14558
|
+
*/
|
|
14509
14559
|
async close(arg) {
|
|
14510
14560
|
const db = argToDb(arg);
|
|
14511
14561
|
await this.rollback(db);
|
|
14512
14562
|
if (db.internal[trxForTest]?.length === 0) return db.q.adapter.close();
|
|
14513
14563
|
}
|
|
14514
14564
|
};
|
|
14515
|
-
export { AdapterClass, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Column, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, Expression, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, Operators, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryError, QueryHookUtils, QueryHooks, RawSql, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, TransactionAdapterClass, TsQueryColumn, TsVectorColumn, UUIDColumn, UnknownColumn, VarCharColumn, VirtualColumn, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _orCreate, _prependWith, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, queryToSql, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, rawSqlToSql, referencesArgsToCode, refreshMaterializedView, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, sqlToRawSql, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
|
|
14565
|
+
export { AdapterClass, ArrayColumn, BigIntColumn, BigSerialColumn, BitColumn, BitVaryingColumn, BooleanColumn, BoxColumn, ByteaColumn, CidrColumn, CircleColumn, CitextColumn, Column, CustomTypeColumn, DateBaseColumn, DateColumn, DateTimeBaseClass, DateTimeTzBaseClass, Db, DecimalColumn, DomainColumn, DoublePrecisionColumn, DynamicRawSQL, EnumColumn, Expression, InetColumn, IntegerBaseColumn, IntegerColumn, IntervalColumn, JSONColumn, JSONTextColumn, LimitedTextBaseColumn, LineColumn, LsegColumn, MacAddr8Column, MacAddrColumn, MoneyColumn, NotFoundError, NumberAsStringBaseColumn, NumberBaseColumn, Operators, OrchidOrmInternalError, PathColumn, PointColumn, PolygonColumn, PostgisGeographyPointColumn, QueryError, QueryHookUtils, QueryHooks, RawSql, RealColumn, SerialColumn, SmallIntColumn, SmallSerialColumn, StringColumn, TextBaseColumn, TextColumn, TimeColumn, TimestampColumn, TimestampTZColumn, TransactionAdapterClass, TsQueryColumn, TsVectorColumn, UUIDColumn, UnknownColumn, VarCharColumn, VirtualColumn, XMLColumn, _appendQuery, _appendQueryOnUpsertCreate, _clone, _createDbSqlMethod, _hookSelectColumns, _initQueryBuilder, _onUpsertUpdate, _orCreate, _prependWith, _prependWithOnUpsertCreate, _queryCreate, _queryCreateMany, _queryCreateManyFrom, _queryDefaults, _queryDelete, _queryFindBy, _queryFindByOptional, _queryHookAfterCreate, _queryHookAfterUpdate, _queryInsert, _queryInsertMany, _queryJoinOn, _queryRows, _querySelect, _queryTake, _queryTakeOptional, _queryUpdate, _queryUpdateOrThrow, _queryUpsert, _queryWhere, _queryWhereExists, _queryWhereIn, addCode, addTopCte, addTopCteSql, applyMixins, assignDbDataToColumn, backtickQuote, cloneQueryBaseUnscoped, codeToString, colors, columnsShapeToCode, constraintInnerToCode, constraintToCode, consumeColumnName, copyTableData, createDbWithAdapter, deepCompare, defaultSchemaConfig, emptyArray, emptyObject, escapeForMigration, escapeString, excludeInnerToCode, excludeToCode, exhaustive, getCallerFilePath, getClonedQueryData, getColumnBaseType, getColumnInfo, getColumnTypes, getDateAsDateFn, getDateAsNumberFn, getDriverErrorCode, getFreeAlias, getFreeSetAlias, getImportPath, getPrimaryKeys, getQueryAs, getQuerySchema, getShapeFromSelect, getSqlText, getStackTrace, getSupportedDefaultPrivileges, indexInnerToCode, indexToCode, internalSchemaConfig, isExpression, isQueryReturnsAll, isRawSQL, logColors, logParamToLogObject, makeColumnNullable, makeColumnTypes, makeColumnsByType, makeConnectRetryConfig, noop, objectHasValues, omit, parseTableData, parseTableDataInput, pathToLog, pick, pluralize, prepareSubQueryForSql, primaryKeyInnerToCode, pushQueryOnForOuter, pushQueryValueImmutable, pushTableDataCode, queryToSql, quoteIdentifier, quoteObjectKey, quoteTableWithSchema, raw, rawSqlToCode, rawSqlToSql, referencesArgsToCode, refreshMaterializedView, returnArg, setColumnData, setColumnEncode, setColumnParse, setColumnParseNull, setCurrentColumnName, setDataValue, setDefaultLanguage, setFreeAlias, setQueryObjectValueImmutable, singleQuote, sqlToRawSql, tableDataMethods, testTransaction, toArray, toCamelCase, toPascalCase, toSnakeCase, wrapAdapterFnWithConnectRetry };
|
|
14516
14566
|
|
|
14517
14567
|
//# sourceMappingURL=index.mjs.map
|