pqb 0.71.4 → 0.72.0
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/index.d.ts +335 -356
- package/dist/index.js +172 -173
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +168 -174
- package/dist/index.mjs.map +1 -1
- package/dist/internal.d.ts +8038 -8072
- package/dist/internal.js +6254 -0
- package/dist/internal.js.map +1 -1
- package/dist/internal.mjs +6232 -7
- package/dist/internal.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)})`);
|
|
@@ -3719,24 +3727,19 @@ var QueryStorage = class {
|
|
|
3719
3727
|
* so later they can be identified when handling after commit errors.
|
|
3720
3728
|
*
|
|
3721
3729
|
* ```ts
|
|
3722
|
-
*
|
|
3723
|
-
*
|
|
3724
|
-
*
|
|
3725
|
-
*
|
|
3726
|
-
*
|
|
3727
|
-
*
|
|
3728
|
-
*
|
|
3729
|
-
* // anonymous funciton - has no name
|
|
3730
|
-
* this.afterCreateCommit([], async () => {
|
|
3731
|
-
* // ...
|
|
3732
|
-
* });
|
|
3730
|
+
* export const SomeTable = defineTable('someTable', (t) => ({
|
|
3731
|
+
* ...someColumns,
|
|
3732
|
+
* })).init((orm: typeof db, hooks) => {
|
|
3733
|
+
* // anonymous funciton - has no name
|
|
3734
|
+
* hooks.afterCreateCommit([], async () => {
|
|
3735
|
+
* // ...
|
|
3736
|
+
* });
|
|
3733
3737
|
*
|
|
3734
|
-
*
|
|
3735
|
-
*
|
|
3736
|
-
*
|
|
3737
|
-
*
|
|
3738
|
-
*
|
|
3739
|
-
* }
|
|
3738
|
+
* // named function
|
|
3739
|
+
* hooks.afterCreateCommit([], function myHook() {
|
|
3740
|
+
* // ...
|
|
3741
|
+
* });
|
|
3742
|
+
* });
|
|
3740
3743
|
* ```
|
|
3741
3744
|
*/
|
|
3742
3745
|
var AfterCommitError = class extends OrchidOrmError {
|
|
@@ -4489,21 +4492,16 @@ const _unscope = (q, scope) => {
|
|
|
4489
4492
|
* If you define a scope with name `default`, it will be applied for all table queries by default.
|
|
4490
4493
|
*
|
|
4491
4494
|
* ```ts
|
|
4492
|
-
* import {
|
|
4495
|
+
* import { defineTable } from './table-factory';
|
|
4493
4496
|
*
|
|
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
|
-
* }
|
|
4497
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
4498
|
+
* id: t.identity().primaryKey(),
|
|
4499
|
+
* hidden: t.boolean(),
|
|
4500
|
+
* active: t.boolean(),
|
|
4501
|
+
* })).scopes({
|
|
4502
|
+
* default: (q) => q.where({ hidden: false }),
|
|
4503
|
+
* active: (q) => q.where({ active: true }),
|
|
4504
|
+
* });
|
|
4507
4505
|
*
|
|
4508
4506
|
* const db = orchidORM(
|
|
4509
4507
|
* { databaseURL: '...' },
|
|
@@ -5811,7 +5809,7 @@ var Where = class {
|
|
|
5811
5809
|
* Constructing `WHERE` conditions:
|
|
5812
5810
|
*
|
|
5813
5811
|
* ```ts
|
|
5814
|
-
* import { sql } from './
|
|
5812
|
+
* import { sql } from './table-factory';
|
|
5815
5813
|
*
|
|
5816
5814
|
* db.table.where({
|
|
5817
5815
|
* // column of the current table
|
|
@@ -5827,7 +5825,7 @@ var Where = class {
|
|
|
5827
5825
|
* },
|
|
5828
5826
|
*
|
|
5829
5827
|
* // where column equals to raw SQL
|
|
5830
|
-
* // import `sql` from your
|
|
5828
|
+
* // import `sql` from your table factory
|
|
5831
5829
|
* column: sql`sql expression`,
|
|
5832
5830
|
* // or use `(q) => sql` for the same
|
|
5833
5831
|
* column2: (q) => sql`sql expression`,
|
|
@@ -9150,31 +9148,26 @@ var QueryCreate = class {
|
|
|
9150
9148
|
* A primary key or a unique index for a **single** column can be fined on a column:
|
|
9151
9149
|
*
|
|
9152
9150
|
* ```ts
|
|
9153
|
-
* export
|
|
9154
|
-
*
|
|
9155
|
-
*
|
|
9156
|
-
*
|
|
9157
|
-
* }));
|
|
9158
|
-
* }
|
|
9151
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9152
|
+
* pkey: t.uuid().primaryKey(),
|
|
9153
|
+
* unique: t.string().unique(),
|
|
9154
|
+
* }));
|
|
9159
9155
|
* ```
|
|
9160
9156
|
*
|
|
9161
9157
|
* But for composite primary keys or indexes (having multiple columns), define it in a separate function:
|
|
9162
9158
|
*
|
|
9163
9159
|
* ```ts
|
|
9164
|
-
* export
|
|
9165
|
-
*
|
|
9166
|
-
*
|
|
9167
|
-
*
|
|
9168
|
-
*
|
|
9169
|
-
*
|
|
9170
|
-
*
|
|
9171
|
-
* (t) => [t.primaryKey(['one', 'two']), t.unique(['two', 'three'])],
|
|
9172
|
-
* );
|
|
9173
|
-
* }
|
|
9160
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9161
|
+
* one: t.integer(),
|
|
9162
|
+
* two: t.string(),
|
|
9163
|
+
* three: t.boolean(),
|
|
9164
|
+
* }))
|
|
9165
|
+
* .primaryKey(['one', 'two'])
|
|
9166
|
+
* .unique(['two', 'three']);
|
|
9174
9167
|
* ```
|
|
9175
9168
|
* :::
|
|
9176
9169
|
*
|
|
9177
|
-
* You can use the `sql` function exported from your
|
|
9170
|
+
* You can use the `sql` function exported from your table factory file in onConflict.
|
|
9178
9171
|
* It can be useful to specify a condition when you have a partial index:
|
|
9179
9172
|
*
|
|
9180
9173
|
* ```ts
|
|
@@ -9564,12 +9557,14 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
|
|
|
9564
9557
|
if (upsertOrCreate.q.returnType === "oneOrThrow") upsertOrCreate.q.returnType = "one";
|
|
9565
9558
|
else if (upsertOrCreate.q.returnType === "valueOrThrow") upsertOrCreate.q.returnType = "value";
|
|
9566
9559
|
const { as, makeSql: makeFirstSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, upsertUpdate ? "update" : null);
|
|
9560
|
+
query.upsertUpdateAsFns?.forEach((fn) => fn(as));
|
|
9567
9561
|
upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
|
|
9568
9562
|
upsertOrCreate.q.and = [new RawSql(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
|
|
9569
9563
|
if (query.upsertInsert) {
|
|
9570
9564
|
_queryInsert(upsertOrCreate, query.upsertInsert());
|
|
9571
9565
|
upsertOrCreate.q.type = "upsert";
|
|
9572
9566
|
}
|
|
9567
|
+
upsertOrCreate.q.with = query.upsertCreateWith;
|
|
9573
9568
|
upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
|
|
9574
9569
|
upsertOrCreate.q.asFns = query.upsertCreateAsFns;
|
|
9575
9570
|
const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
|
|
@@ -10141,36 +10136,21 @@ var QueryJoin = class {
|
|
|
10141
10136
|
* 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
10137
|
*
|
|
10143
10138
|
* ```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
|
-
* }));
|
|
10139
|
+
* export const UserTable = defineTable('user', (t) => ({
|
|
10140
|
+
* id: t.identity().primaryKey(),
|
|
10141
|
+
* name: t.text(),
|
|
10142
|
+
* })).relations((user) => ({
|
|
10143
|
+
* messages: user('id').hasMany(() => MessageTable('userId')),
|
|
10144
|
+
* }));
|
|
10166
10145
|
*
|
|
10167
|
-
*
|
|
10168
|
-
*
|
|
10169
|
-
*
|
|
10170
|
-
*
|
|
10171
|
-
*
|
|
10172
|
-
*
|
|
10173
|
-
*
|
|
10146
|
+
* export const MessageTable = defineTable('message', (t) => ({
|
|
10147
|
+
* id: t.identity().primaryKey(),
|
|
10148
|
+
* userId: t.integer(),
|
|
10149
|
+
* text: t.text(),
|
|
10150
|
+
* ...t.timestamps(),
|
|
10151
|
+
* })).relations((message) => ({
|
|
10152
|
+
* user: message('userId').belongsTo(() => UserTable('id')),
|
|
10153
|
+
* }));
|
|
10174
10154
|
* ```
|
|
10175
10155
|
*
|
|
10176
10156
|
* `join` is a method for SQL `JOIN`, which is equivalent to `INNER JOIN`, `LEFT INNERT JOIN`.
|
|
@@ -10367,7 +10347,7 @@ var QueryJoin = class {
|
|
|
10367
10347
|
* ```ts
|
|
10368
10348
|
* db.user.join(
|
|
10369
10349
|
* db.message,
|
|
10370
|
-
* // `sql` can be imported from your
|
|
10350
|
+
* // `sql` can be imported from your table factory file
|
|
10371
10351
|
* sql`lower("message"."text") = lower("user"."name")`,
|
|
10372
10352
|
* );
|
|
10373
10353
|
* ```
|
|
@@ -11463,6 +11443,7 @@ function _orCreate(query, data, updateData, mergeData) {
|
|
|
11463
11443
|
const { q } = query;
|
|
11464
11444
|
q.returnsOne = true;
|
|
11465
11445
|
if (!q.select) q.returnType = "void";
|
|
11446
|
+
q.type = "upsert";
|
|
11466
11447
|
if (typeof data === "function") q.upsertInsert = () => mergeData ? {
|
|
11467
11448
|
...mergeData,
|
|
11468
11449
|
...data(updateData)
|
|
@@ -12452,6 +12433,16 @@ const _appendQuery = (main, append, asFn) => {
|
|
|
12452
12433
|
const _appendQueryOnUpsertCreate = (main, append, asFn) => {
|
|
12453
12434
|
return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
|
|
12454
12435
|
};
|
|
12436
|
+
const _onUpsertUpdate = (q, asFn) => {
|
|
12437
|
+
return pushQueryValueImmutable(q, "upsertUpdateAsFns", asFn);
|
|
12438
|
+
};
|
|
12439
|
+
const _prependWithOnUpsertCreate = (q, name, query) => {
|
|
12440
|
+
const prev = q.q.with;
|
|
12441
|
+
q.q.with = q.q.upsertCreateWith;
|
|
12442
|
+
_prependWith(q, name, query);
|
|
12443
|
+
q.q.upsertCreateWith = q.q.with;
|
|
12444
|
+
q.q.with = prev;
|
|
12445
|
+
};
|
|
12455
12446
|
const mergableObjects = new Set([
|
|
12456
12447
|
"selectShape",
|
|
12457
12448
|
"withShapes",
|
|
@@ -12675,12 +12666,12 @@ var SearchMethods = class {
|
|
|
12675
12666
|
*
|
|
12676
12667
|
* By default, the search language is English.
|
|
12677
12668
|
*
|
|
12678
|
-
* You can set a different default language in the `
|
|
12669
|
+
* You can set a different default language in the `createTableFactory` config:
|
|
12679
12670
|
*
|
|
12680
12671
|
* ```ts
|
|
12681
|
-
* import {
|
|
12672
|
+
* import { createTableFactory } from 'orchid-orm';
|
|
12682
12673
|
*
|
|
12683
|
-
* export const
|
|
12674
|
+
* export const { defineTable, defineView, sql } = createTableFactory({
|
|
12684
12675
|
* language: 'swedish',
|
|
12685
12676
|
* });
|
|
12686
12677
|
* ```
|
|
@@ -13066,20 +13057,20 @@ const _softDelete = (column, customNowSQL) => {
|
|
|
13066
13057
|
* All queries on such table will filter out deleted records by default.
|
|
13067
13058
|
*
|
|
13068
13059
|
* ```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
|
-
* }));
|
|
13060
|
+
* import { defineTable } from './table-factory';
|
|
13077
13061
|
*
|
|
13062
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
13063
|
+
* id: t.identity().primaryKey(),
|
|
13064
|
+
* deletedAt: t.timestamp().nullable(),
|
|
13065
|
+
* }))
|
|
13078
13066
|
* // true is for using `deletedAt` column
|
|
13079
|
-
*
|
|
13080
|
-
*
|
|
13081
|
-
*
|
|
13082
|
-
*
|
|
13067
|
+
* .softDelete();
|
|
13068
|
+
*
|
|
13069
|
+
* // or provide a different column name
|
|
13070
|
+
* export const OtherTable = defineTable('other', (t) => ({
|
|
13071
|
+
* id: t.identity().primaryKey(),
|
|
13072
|
+
* myDeletedAt: t.timestamp().nullable(),
|
|
13073
|
+
* })).softDelete('myDeletedAt');
|
|
13083
13074
|
*
|
|
13084
13075
|
* const db = orchidORM(
|
|
13085
13076
|
* { databaseURL: '...' },
|
|
@@ -14376,11 +14367,14 @@ function getColumnInfo(query, column) {
|
|
|
14376
14367
|
};
|
|
14377
14368
|
return q;
|
|
14378
14369
|
}
|
|
14370
|
+
const columnsSql = (shape, columns) => {
|
|
14371
|
+
return columns.map((item) => `"${shape[item]?.data.name || item}"`).join(", ");
|
|
14372
|
+
};
|
|
14379
14373
|
const makeCopySql = (table, copy) => {
|
|
14380
14374
|
const ctx = newToSqlCtx(table);
|
|
14381
14375
|
const { q } = table;
|
|
14382
14376
|
const quotedAs = `"${q.as || table.table}"`;
|
|
14383
|
-
const columns = copy.columns ? `(${
|
|
14377
|
+
const columns = copy.columns ? `(${columnsSql(table.shape, copy.columns)})` : "";
|
|
14384
14378
|
const target = "from" in copy ? copy.from : copy.to;
|
|
14385
14379
|
const quotedTable = quoteTableWithSchema(table);
|
|
14386
14380
|
ctx.sql.push(`COPY ${quotedTable}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? escapeString(target) : `PROGRAM ${escapeString(target.program)}`}`);
|
|
@@ -14393,9 +14387,9 @@ const makeCopySql = (table, copy) => {
|
|
|
14393
14387
|
if (copy.header) options.push(`HEADER ${copy.header}`);
|
|
14394
14388
|
if (copy.quote) options.push(`QUOTE ${escapeString(copy.quote)}`);
|
|
14395
14389
|
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 (${
|
|
14390
|
+
if (copy.forceQuote) options.push(`FORCE_QUOTE ${copy.forceQuote === "*" ? "*" : `(${columnsSql(table.shape, copy.forceQuote)})`}`);
|
|
14391
|
+
if (copy.forceNotNull) options.push(`FORCE_NOT_NULL (${columnsSql(table.shape, copy.forceNotNull)})`);
|
|
14392
|
+
if (copy.forceNull) options.push(`FORCE_NULL (${columnsSql(table.shape, copy.forceNull)})`);
|
|
14399
14393
|
if (copy.encoding) options.push(`ENCODING ${escapeString(copy.encoding)}`);
|
|
14400
14394
|
ctx.sql.push(`WITH (${options.join(", ")})`);
|
|
14401
14395
|
}
|
|
@@ -14512,6 +14506,6 @@ const testTransaction = {
|
|
|
14512
14506
|
if (db.internal[trxForTest]?.length === 0) return db.q.adapter.close();
|
|
14513
14507
|
}
|
|
14514
14508
|
};
|
|
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 };
|
|
14509
|
+
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
14510
|
|
|
14517
14511
|
//# sourceMappingURL=index.mjs.map
|