pqb 0.71.3 → 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 +190 -181
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +186 -182
- 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`,
|
|
@@ -6566,7 +6564,8 @@ const tableColumnToSql = (ctx, queryData, shape, table, key, quotedAs, select, a
|
|
|
6566
6564
|
} else {
|
|
6567
6565
|
const tableName = _getQueryAliasOrName(queryData, table);
|
|
6568
6566
|
const quoted = `"${table}"`;
|
|
6569
|
-
const
|
|
6567
|
+
const joined = queryData.joinedShapes?.[tableName];
|
|
6568
|
+
const col = joined ? joined[key] : quoted === quotedAs ? shape[key] : void 0;
|
|
6570
6569
|
if (jsonList && as) jsonList[as] = col && getSelectedColumnData(col);
|
|
6571
6570
|
if (col?.data.selectSql) sql = `(${col.data.selectSql.toSQL(ctx, quoted)})`;
|
|
6572
6571
|
else if (col?.data.name) sql = `"${tableName}"."${col.data.name}"`;
|
|
@@ -9149,31 +9148,26 @@ var QueryCreate = class {
|
|
|
9149
9148
|
* A primary key or a unique index for a **single** column can be fined on a column:
|
|
9150
9149
|
*
|
|
9151
9150
|
* ```ts
|
|
9152
|
-
* export
|
|
9153
|
-
*
|
|
9154
|
-
*
|
|
9155
|
-
*
|
|
9156
|
-
* }));
|
|
9157
|
-
* }
|
|
9151
|
+
* export const MyTable = defineTable('myTable', (t) => ({
|
|
9152
|
+
* pkey: t.uuid().primaryKey(),
|
|
9153
|
+
* unique: t.string().unique(),
|
|
9154
|
+
* }));
|
|
9158
9155
|
* ```
|
|
9159
9156
|
*
|
|
9160
9157
|
* But for composite primary keys or indexes (having multiple columns), define it in a separate function:
|
|
9161
9158
|
*
|
|
9162
9159
|
* ```ts
|
|
9163
|
-
* export
|
|
9164
|
-
*
|
|
9165
|
-
*
|
|
9166
|
-
*
|
|
9167
|
-
*
|
|
9168
|
-
*
|
|
9169
|
-
*
|
|
9170
|
-
* (t) => [t.primaryKey(['one', 'two']), t.unique(['two', 'three'])],
|
|
9171
|
-
* );
|
|
9172
|
-
* }
|
|
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']);
|
|
9173
9167
|
* ```
|
|
9174
9168
|
* :::
|
|
9175
9169
|
*
|
|
9176
|
-
* You can use the `sql` function exported from your
|
|
9170
|
+
* You can use the `sql` function exported from your table factory file in onConflict.
|
|
9177
9171
|
* It can be useful to specify a condition when you have a partial index:
|
|
9178
9172
|
*
|
|
9179
9173
|
* ```ts
|
|
@@ -9563,12 +9557,14 @@ const toSql = (table, type, topCtx, isSubSql, cteName, calledByThen, dontAddTabl
|
|
|
9563
9557
|
if (upsertOrCreate.q.returnType === "oneOrThrow") upsertOrCreate.q.returnType = "one";
|
|
9564
9558
|
else if (upsertOrCreate.q.returnType === "valueOrThrow") upsertOrCreate.q.returnType = "value";
|
|
9565
9559
|
const { as, makeSql: makeFirstSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, upsertUpdate ? "update" : null);
|
|
9560
|
+
query.upsertUpdateAsFns?.forEach((fn) => fn(as));
|
|
9566
9561
|
upsertOrCreate.q.or = upsertOrCreate.q.scopes = void 0;
|
|
9567
9562
|
upsertOrCreate.q.and = [new RawSql(`NOT EXISTS (SELECT 1 FROM "${as}")`)];
|
|
9568
9563
|
if (query.upsertInsert) {
|
|
9569
9564
|
_queryInsert(upsertOrCreate, query.upsertInsert());
|
|
9570
9565
|
upsertOrCreate.q.type = "upsert";
|
|
9571
9566
|
}
|
|
9567
|
+
upsertOrCreate.q.with = query.upsertCreateWith;
|
|
9572
9568
|
upsertOrCreate.q.appendQueries = query.upsertCreateAppendQueries;
|
|
9573
9569
|
upsertOrCreate.q.asFns = query.upsertCreateAsFns;
|
|
9574
9570
|
const { makeSql: makeSecondSql } = moveMutativeQueryToCteBase(toSql, ctx, upsertOrCreate, "insert");
|
|
@@ -10046,7 +10042,16 @@ const _joinLateral = (self, type, joinQuery, as, innerJoinLateral) => {
|
|
|
10046
10042
|
const joinedAs = getQueryAs(query);
|
|
10047
10043
|
setObjectValueImmutable(joinQuery.q, "joinedShapes", joinedAs, query.q.selectShape);
|
|
10048
10044
|
}
|
|
10049
|
-
const
|
|
10045
|
+
const joinedShapeMayHaveNames = joinQuery.table && joinQuery.q.joinedShapes?.[joinQuery.table] || joinQuery.q.joinedShapes?.[joinAs];
|
|
10046
|
+
let joinedShape;
|
|
10047
|
+
if (joinedShapeMayHaveNames) {
|
|
10048
|
+
joinedShape = {};
|
|
10049
|
+
for (const key in joinedShapeMayHaveNames) {
|
|
10050
|
+
const column = joinedShapeMayHaveNames[key];
|
|
10051
|
+
joinedShape[key] = column.data.name ? setColumnData(column, "name", void 0) : column;
|
|
10052
|
+
}
|
|
10053
|
+
}
|
|
10054
|
+
const shape = joinedShape || getShapeFromSelect(joinQuery, true);
|
|
10050
10055
|
setObjectValueImmutable(query.q, "joinedShapes", joinAs, shape);
|
|
10051
10056
|
if (joinValue) setObjectValueImmutable(query.q, "valuesJoinedAs", joinAs, joinValueAs);
|
|
10052
10057
|
setObjectValueImmutable(query.q, "joinedParsers", joinValueAs || joinAs, getQueryParsers(joinQuery));
|
|
@@ -10131,36 +10136,21 @@ var QueryJoin = class {
|
|
|
10131
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:
|
|
10132
10137
|
*
|
|
10133
10138
|
* ```ts
|
|
10134
|
-
* export
|
|
10135
|
-
*
|
|
10136
|
-
*
|
|
10137
|
-
*
|
|
10138
|
-
*
|
|
10139
|
-
*
|
|
10140
|
-
*
|
|
10141
|
-
* relations = {
|
|
10142
|
-
* messages: this.hasMany(() => MessageTable, {
|
|
10143
|
-
* primaryKey: 'id',
|
|
10144
|
-
* foreignKey: 'userId',
|
|
10145
|
-
* }),
|
|
10146
|
-
* };
|
|
10147
|
-
* }
|
|
10148
|
-
*
|
|
10149
|
-
* export class MessageTable extends BaseTable {
|
|
10150
|
-
* readonly table = 'message';
|
|
10151
|
-
* columns = this.setColumns((t) => ({
|
|
10152
|
-
* id: t.identity().primaryKey(),
|
|
10153
|
-
* text: t.text(),
|
|
10154
|
-
* ...t.timestamps(),
|
|
10155
|
-
* }));
|
|
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
|
+
* }));
|
|
10156
10145
|
*
|
|
10157
|
-
*
|
|
10158
|
-
*
|
|
10159
|
-
*
|
|
10160
|
-
*
|
|
10161
|
-
*
|
|
10162
|
-
*
|
|
10163
|
-
*
|
|
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
|
+
* }));
|
|
10164
10154
|
* ```
|
|
10165
10155
|
*
|
|
10166
10156
|
* `join` is a method for SQL `JOIN`, which is equivalent to `INNER JOIN`, `LEFT INNERT JOIN`.
|
|
@@ -10357,7 +10347,7 @@ var QueryJoin = class {
|
|
|
10357
10347
|
* ```ts
|
|
10358
10348
|
* db.user.join(
|
|
10359
10349
|
* db.message,
|
|
10360
|
-
* // `sql` can be imported from your
|
|
10350
|
+
* // `sql` can be imported from your table factory file
|
|
10361
10351
|
* sql`lower("message"."text") = lower("user"."name")`,
|
|
10362
10352
|
* );
|
|
10363
10353
|
* ```
|
|
@@ -11074,7 +11064,7 @@ const selectColumn = (query, q, key, columnAs, columnAlias) => {
|
|
|
11074
11064
|
};
|
|
11075
11065
|
const getShapeFromSelect = (q, isSubQuery) => {
|
|
11076
11066
|
const query = q.q;
|
|
11077
|
-
const { selectShape
|
|
11067
|
+
const { selectShape } = query;
|
|
11078
11068
|
let select;
|
|
11079
11069
|
if (query.selectedComputeds) {
|
|
11080
11070
|
select = query.select ? [...query.select] : [];
|
|
@@ -11084,18 +11074,18 @@ const getShapeFromSelect = (q, isSubQuery) => {
|
|
|
11084
11074
|
if (!select) if (query.type) result = {};
|
|
11085
11075
|
else if (isSubQuery) {
|
|
11086
11076
|
result = {};
|
|
11087
|
-
for (const key in
|
|
11088
|
-
const column =
|
|
11077
|
+
for (const key in selectShape) {
|
|
11078
|
+
const column = selectShape[key];
|
|
11089
11079
|
if (!column.data.explicitSelect) result[key] = column.data.name ? setColumnData(column, "name", void 0) : column;
|
|
11090
11080
|
}
|
|
11091
|
-
} else result =
|
|
11081
|
+
} else result = selectShape;
|
|
11092
11082
|
else {
|
|
11093
11083
|
result = {};
|
|
11094
|
-
for (const item of select) if (typeof item === "string") addColumnToShapeFromSelect(q, item,
|
|
11084
|
+
for (const item of select) if (typeof item === "string") addColumnToShapeFromSelect(q, item, selectShape, query, result, isSubQuery);
|
|
11095
11085
|
else if (isExpression(item)) result.value = item.result.value;
|
|
11096
11086
|
else if (item && "selectAs" in item) for (const key in item.selectAs) {
|
|
11097
11087
|
const it = item.selectAs[key];
|
|
11098
|
-
if (typeof it === "string") addColumnToShapeFromSelect(q, it,
|
|
11088
|
+
if (typeof it === "string") addColumnToShapeFromSelect(q, it, selectShape, query, result, isSubQuery, key);
|
|
11099
11089
|
else if (isExpression(it)) result[key] = it.result.value || UnknownColumn.instance;
|
|
11100
11090
|
else if (it) {
|
|
11101
11091
|
const { returnType } = it.q;
|
|
@@ -11453,6 +11443,7 @@ function _orCreate(query, data, updateData, mergeData) {
|
|
|
11453
11443
|
const { q } = query;
|
|
11454
11444
|
q.returnsOne = true;
|
|
11455
11445
|
if (!q.select) q.returnType = "void";
|
|
11446
|
+
q.type = "upsert";
|
|
11456
11447
|
if (typeof data === "function") q.upsertInsert = () => mergeData ? {
|
|
11457
11448
|
...mergeData,
|
|
11458
11449
|
...data(updateData)
|
|
@@ -12442,6 +12433,16 @@ const _appendQuery = (main, append, asFn) => {
|
|
|
12442
12433
|
const _appendQueryOnUpsertCreate = (main, append, asFn) => {
|
|
12443
12434
|
return pushQueryValueImmutable(pushQueryValueImmutable(main, "upsertCreateAppendQueries", prepareSubQueryForSql(main, append)), "upsertCreateAsFns", asFn);
|
|
12444
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
|
+
};
|
|
12445
12446
|
const mergableObjects = new Set([
|
|
12446
12447
|
"selectShape",
|
|
12447
12448
|
"withShapes",
|
|
@@ -12665,12 +12666,12 @@ var SearchMethods = class {
|
|
|
12665
12666
|
*
|
|
12666
12667
|
* By default, the search language is English.
|
|
12667
12668
|
*
|
|
12668
|
-
* You can set a different default language in the `
|
|
12669
|
+
* You can set a different default language in the `createTableFactory` config:
|
|
12669
12670
|
*
|
|
12670
12671
|
* ```ts
|
|
12671
|
-
* import {
|
|
12672
|
+
* import { createTableFactory } from 'orchid-orm';
|
|
12672
12673
|
*
|
|
12673
|
-
* export const
|
|
12674
|
+
* export const { defineTable, defineView, sql } = createTableFactory({
|
|
12674
12675
|
* language: 'swedish',
|
|
12675
12676
|
* });
|
|
12676
12677
|
* ```
|
|
@@ -13056,20 +13057,20 @@ const _softDelete = (column, customNowSQL) => {
|
|
|
13056
13057
|
* All queries on such table will filter out deleted records by default.
|
|
13057
13058
|
*
|
|
13058
13059
|
* ```ts
|
|
13059
|
-
* import {
|
|
13060
|
-
*
|
|
13061
|
-
* export class SomeTable extends BaseTable {
|
|
13062
|
-
* readonly table = 'some';
|
|
13063
|
-
* columns = this.setColumns((t) => ({
|
|
13064
|
-
* id: t.identity().primaryKey(),
|
|
13065
|
-
* deletedAt: t.timestamp().nullable(),
|
|
13066
|
-
* }));
|
|
13060
|
+
* import { defineTable } from './table-factory';
|
|
13067
13061
|
*
|
|
13062
|
+
* export const SomeTable = defineTable('some', (t) => ({
|
|
13063
|
+
* id: t.identity().primaryKey(),
|
|
13064
|
+
* deletedAt: t.timestamp().nullable(),
|
|
13065
|
+
* }))
|
|
13068
13066
|
* // true is for using `deletedAt` column
|
|
13069
|
-
*
|
|
13070
|
-
*
|
|
13071
|
-
*
|
|
13072
|
-
*
|
|
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');
|
|
13073
13074
|
*
|
|
13074
13075
|
* const db = orchidORM(
|
|
13075
13076
|
* { databaseURL: '...' },
|
|
@@ -14366,11 +14367,14 @@ function getColumnInfo(query, column) {
|
|
|
14366
14367
|
};
|
|
14367
14368
|
return q;
|
|
14368
14369
|
}
|
|
14370
|
+
const columnsSql = (shape, columns) => {
|
|
14371
|
+
return columns.map((item) => `"${shape[item]?.data.name || item}"`).join(", ");
|
|
14372
|
+
};
|
|
14369
14373
|
const makeCopySql = (table, copy) => {
|
|
14370
14374
|
const ctx = newToSqlCtx(table);
|
|
14371
14375
|
const { q } = table;
|
|
14372
14376
|
const quotedAs = `"${q.as || table.table}"`;
|
|
14373
|
-
const columns = copy.columns ? `(${
|
|
14377
|
+
const columns = copy.columns ? `(${columnsSql(table.shape, copy.columns)})` : "";
|
|
14374
14378
|
const target = "from" in copy ? copy.from : copy.to;
|
|
14375
14379
|
const quotedTable = quoteTableWithSchema(table);
|
|
14376
14380
|
ctx.sql.push(`COPY ${quotedTable}${columns} ${"from" in copy ? "FROM" : "TO"} ${typeof target === "string" ? escapeString(target) : `PROGRAM ${escapeString(target.program)}`}`);
|
|
@@ -14383,9 +14387,9 @@ const makeCopySql = (table, copy) => {
|
|
|
14383
14387
|
if (copy.header) options.push(`HEADER ${copy.header}`);
|
|
14384
14388
|
if (copy.quote) options.push(`QUOTE ${escapeString(copy.quote)}`);
|
|
14385
14389
|
if (copy.escape) options.push(`ESCAPE ${escapeString(copy.escape)}`);
|
|
14386
|
-
if (copy.forceQuote) options.push(`FORCE_QUOTE ${copy.forceQuote === "*" ? "*" : `(${
|
|
14387
|
-
if (copy.forceNotNull) options.push(`FORCE_NOT_NULL (${
|
|
14388
|
-
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)})`);
|
|
14389
14393
|
if (copy.encoding) options.push(`ENCODING ${escapeString(copy.encoding)}`);
|
|
14390
14394
|
ctx.sql.push(`WITH (${options.join(", ")})`);
|
|
14391
14395
|
}
|
|
@@ -14502,6 +14506,6 @@ const testTransaction = {
|
|
|
14502
14506
|
if (db.internal[trxForTest]?.length === 0) return db.q.adapter.close();
|
|
14503
14507
|
}
|
|
14504
14508
|
};
|
|
14505
|
-
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 };
|
|
14506
14510
|
|
|
14507
14511
|
//# sourceMappingURL=index.mjs.map
|