relq 1.0.100 → 1.0.102

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.
@@ -35,7 +35,6 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.runPush = runPush;
37
37
  const citty_1 = require("citty");
38
- const fs = __importStar(require("node:fs"));
39
38
  const path = __importStar(require("node:path"));
40
39
  const p = __importStar(require("@clack/prompts"));
41
40
  const context_1 = require("../utils/context.cjs");
@@ -58,8 +57,6 @@ const schema_hash_1 = require("../utils/schema-hash.cjs");
58
57
  const migration_generator_1 = require("../utils/migration-generator.cjs");
59
58
  const migration_helpers_1 = require("../utils/migration-helpers.cjs");
60
59
  const ast_transformer_1 = require("../utils/ast-transformer.cjs");
61
- const ast_codegen_1 = require("../utils/ast-codegen.cjs");
62
- const schema_to_ast_1 = require("../utils/schema-to-ast.cjs");
63
60
  function formatColumnProps(col) {
64
61
  if (!col)
65
62
  return '';
@@ -470,38 +467,6 @@ async function runPush(config, projectRoot, opts = {}) {
470
467
  mergeTrackingIds(updatedSchema, desiredSchema);
471
468
  (0, snapshot_manager_1.saveSnapshot)(updatedSchema, snapshotPath, connection.database);
472
469
  spin.stop('Snapshot updated');
473
- spin.start('Syncing schema from database...');
474
- try {
475
- const liveSchema = await (0, dialect_introspect_1.dialectIntrospect)(config, {
476
- includeFunctions,
477
- includeTriggers,
478
- });
479
- const parsedSchema = await (0, ast_transformer_1.introspectedToParsedSchema)(liveSchema);
480
- try {
481
- const { createJiti } = await Promise.resolve().then(() => __importStar(require('jiti')));
482
- const jiti = createJiti(projectRoot, { interopDefault: true });
483
- const existingModule = await jiti.import(schemaPath);
484
- const existingAst = (0, schema_to_ast_1.schemaToAST)(existingModule);
485
- (0, ast_codegen_1.mergeTrackingIdsFromParsed)(parsedSchema, existingAst);
486
- }
487
- catch { }
488
- (0, ast_codegen_1.assignTrackingIds)(parsedSchema);
489
- const builderImportPath = `relq/${(0, dialect_router_1.detectDialect)(config)}-builder`;
490
- const typescript = (0, ast_codegen_1.generateTypeScriptFromAST)(parsedSchema, {
491
- camelCase: config.generate?.camelCase ?? true,
492
- importPath: builderImportPath,
493
- includeFunctions: false,
494
- includeTriggers: false,
495
- includeEnums: parsedSchema.enums.length > 0,
496
- includeDomains: parsedSchema.domains.length > 0,
497
- });
498
- fs.writeFileSync(schemaPath, typescript, 'utf-8');
499
- spin.stop('Schema synced');
500
- }
501
- catch (syncErr) {
502
- spin.stop('');
503
- (0, ui_1.warning)(`Could not sync schema: ${syncErr instanceof Error ? syncErr.message : String(syncErr)}`);
504
- }
505
470
  const duration = Date.now() - startTime;
506
471
  console.log('');
507
472
  console.log(`Push completed in ${(0, format_1.formatDuration)(duration)}`);
@@ -65,7 +65,7 @@ class ConnectedInsertBuilder {
65
65
  }
66
66
  doNothing(...args) {
67
67
  const columns = [...new Set(args.flat())];
68
- this.builder._onConflict(columns, q => q.doNothing());
68
+ this.builder._onConflict(columns.length > 0 ? columns : null, q => q.doNothing());
69
69
  return this;
70
70
  }
71
71
  doUpdate(columns, values, where) {
@@ -113,8 +113,17 @@ class ConnectedQueryBuilder {
113
113
  update: options.update,
114
114
  });
115
115
  }
116
- async insertMany(rows) {
117
- return (0, query_convenience_1.executeInsertMany)(this.ctx, rows);
116
+ insertMany(rows) {
117
+ if (rows.length === 0) {
118
+ const builder = new insert_builder_1.InsertBuilder(this.tableName, {});
119
+ builder.clear();
120
+ return new ConnectedInsertBuilder_1.ConnectedInsertBuilder(builder, this.relq, this.tableName, this.schemaKey);
121
+ }
122
+ const builder = new insert_builder_1.InsertBuilder(this.tableName, rows[0]);
123
+ for (let i = 1; i < rows.length; i++) {
124
+ builder.addRow(rows[i]);
125
+ }
126
+ return new ConnectedInsertBuilder_1.ConnectedInsertBuilder(builder, this.relq, this.tableName, this.schemaKey);
118
127
  }
119
128
  async insertFrom(columns, selectCallback) {
120
129
  const tables = (0, table_accessor_1.createTableAccessor)(this.relq, this.relq.schema);
@@ -38,7 +38,6 @@ exports.executeFindOne = executeFindOne;
38
38
  exports.executeFindMany = executeFindMany;
39
39
  exports.executeExists = executeExists;
40
40
  exports.executeUpsert = executeUpsert;
41
- exports.executeInsertMany = executeInsertMany;
42
41
  exports.executeSoftDelete = executeSoftDelete;
43
42
  exports.executeRestore = executeRestore;
44
43
  exports.executeInsertFrom = executeInsertFrom;
@@ -114,20 +113,6 @@ async function executeUpsert(ctx, options) {
114
113
  const transformed = ctx.relq[methods_1.INTERNAL].transformResultsFromDb(ctx.tableName, result.result.rows);
115
114
  return transformed[0];
116
115
  }
117
- async function executeInsertMany(ctx, rows) {
118
- if (rows.length === 0)
119
- return [];
120
- const firstDbRow = ctx.relq[methods_1.INTERNAL].transformToDbColumns(ctx.tableName, rows[0]);
121
- const builder = new insert_builder_1.InsertBuilder(ctx.tableName, firstDbRow);
122
- for (let i = 1; i < rows.length; i++) {
123
- const dbRow = ctx.relq[methods_1.INTERNAL].transformToDbColumns(ctx.tableName, rows[i]);
124
- builder.addRow(dbRow);
125
- }
126
- builder.returning(['*']);
127
- const sql = builder.toString();
128
- const result = await ctx.relq[methods_1.INTERNAL].executeQuery(sql);
129
- return ctx.relq[methods_1.INTERNAL].transformResultsFromDb(ctx.tableName, result.result.rows);
130
- }
131
116
  async function executeSoftDelete(ctx, filter) {
132
117
  const dbFilter = ctx.relq[methods_1.INTERNAL].transformToDbColumns(ctx.tableName, filter);
133
118
  const builder = new update_builder_1.UpdateBuilder(ctx.tableName, { deleted_at: new Date() });
@@ -97,7 +97,7 @@ class InsertBuilder {
97
97
  return this.insertData.length;
98
98
  }
99
99
  _onConflict(columns, callback) {
100
- this.conflictColumns = Array.isArray(columns) ? columns : [columns];
100
+ this.conflictColumns = columns === null ? [] : Array.isArray(columns) ? columns : [columns];
101
101
  this.conflictBuilder = new conflict_builder_1.ConflictBuilder(this.tableName);
102
102
  if (callback) {
103
103
  callback(this.conflictBuilder);
@@ -215,12 +215,11 @@ class InsertBuilder {
215
215
  return { values: processedValues, placeholders: placeholderTypes.join(', ') };
216
216
  }
217
217
  buildConflictClause() {
218
- if (!this.conflictColumns || !this.conflictBuilder)
218
+ if (!this.conflictBuilder)
219
219
  return '';
220
- if (this.insertData.length > 1) {
221
- throw new relq_errors_1.RelqBuilderError('ON CONFLICT (upsert) is not supported with multiple row inserts', { builder: 'InsertBuilder', hint: 'Use single row insert for upsert operations' });
222
- }
223
- let clause = (0, pg_format_1.default)(' ON CONFLICT (%I)', this.conflictColumns);
220
+ let clause = this.conflictColumns && this.conflictColumns.length > 0
221
+ ? (0, pg_format_1.default)(' ON CONFLICT (%I)', this.conflictColumns)
222
+ : ' ON CONFLICT';
224
223
  if (this.conflictBuilder.action === 'update') {
225
224
  const updateSql = (0, conflict_builder_1.buildConflictUpdateSql)(this.conflictBuilder.updateData, this.tableName);
226
225
  clause += ` DO UPDATE SET ${updateSql}`;
@@ -1,5 +1,4 @@
1
1
  import { defineCommand } from 'citty';
2
- import * as fs from 'node:fs';
3
2
  import * as path from 'node:path';
4
3
  import * as p from '@clack/prompts';
5
4
  import { buildContext } from "../utils/context.js";
@@ -22,8 +21,6 @@ import { normalizeSchema } from "../utils/schema-hash.js";
22
21
  import { generateTimestampedName, generateMigrationFromComparison, generateMigrationNameFromComparison } from "../utils/migration-generator.js";
23
22
  import { getMigrationTableDDL } from "../utils/migration-helpers.js";
24
23
  import { introspectedToParsedSchema } from "../utils/ast-transformer.js";
25
- import { generateTypeScriptFromAST, assignTrackingIds, mergeTrackingIdsFromParsed } from "../utils/ast-codegen.js";
26
- import { schemaToAST } from "../utils/schema-to-ast.js";
27
24
  function formatColumnProps(col) {
28
25
  if (!col)
29
26
  return '';
@@ -434,38 +431,6 @@ export async function runPush(config, projectRoot, opts = {}) {
434
431
  mergeTrackingIds(updatedSchema, desiredSchema);
435
432
  saveSnapshot(updatedSchema, snapshotPath, connection.database);
436
433
  spin.stop('Snapshot updated');
437
- spin.start('Syncing schema from database...');
438
- try {
439
- const liveSchema = await dialectIntrospect(config, {
440
- includeFunctions,
441
- includeTriggers,
442
- });
443
- const parsedSchema = await introspectedToParsedSchema(liveSchema);
444
- try {
445
- const { createJiti } = await import('jiti');
446
- const jiti = createJiti(projectRoot, { interopDefault: true });
447
- const existingModule = await jiti.import(schemaPath);
448
- const existingAst = schemaToAST(existingModule);
449
- mergeTrackingIdsFromParsed(parsedSchema, existingAst);
450
- }
451
- catch { }
452
- assignTrackingIds(parsedSchema);
453
- const builderImportPath = `relq/${detectDialect(config)}-builder`;
454
- const typescript = generateTypeScriptFromAST(parsedSchema, {
455
- camelCase: config.generate?.camelCase ?? true,
456
- importPath: builderImportPath,
457
- includeFunctions: false,
458
- includeTriggers: false,
459
- includeEnums: parsedSchema.enums.length > 0,
460
- includeDomains: parsedSchema.domains.length > 0,
461
- });
462
- fs.writeFileSync(schemaPath, typescript, 'utf-8');
463
- spin.stop('Schema synced');
464
- }
465
- catch (syncErr) {
466
- spin.stop('');
467
- warning(`Could not sync schema: ${syncErr instanceof Error ? syncErr.message : String(syncErr)}`);
468
- }
469
434
  const duration = Date.now() - startTime;
470
435
  console.log('');
471
436
  console.log(`Push completed in ${formatDuration(duration)}`);
@@ -62,7 +62,7 @@ export class ConnectedInsertBuilder {
62
62
  }
63
63
  doNothing(...args) {
64
64
  const columns = [...new Set(args.flat())];
65
- this.builder._onConflict(columns, q => q.doNothing());
65
+ this.builder._onConflict(columns.length > 0 ? columns : null, q => q.doNothing());
66
66
  return this;
67
67
  }
68
68
  doUpdate(columns, values, where) {
@@ -13,7 +13,7 @@ import { ConnectedUpdateBuilder } from "./ConnectedUpdateBuilder.js";
13
13
  import { INTERNAL } from "./methods.js";
14
14
  import { PaginateBuilder } from "./PaginateBuilder.js";
15
15
  import { createTableAccessor } from "../shared/table-accessor.js";
16
- import { executeFindById, executeFindOne, executeFindMany, executeExists, executeUpsert, executeInsertMany, executeInsertFrom, executeCreateWith, executeSoftDelete, executeRestore, getPrimaryKeyColumn } from "./query-convenience.js";
16
+ import { executeFindById, executeFindOne, executeFindMany, executeExists, executeUpsert, executeInsertFrom, executeCreateWith, executeSoftDelete, executeRestore, getPrimaryKeyColumn } from "./query-convenience.js";
17
17
  export class ConnectedQueryBuilder {
18
18
  tableName;
19
19
  relq;
@@ -110,8 +110,17 @@ export class ConnectedQueryBuilder {
110
110
  update: options.update,
111
111
  });
112
112
  }
113
- async insertMany(rows) {
114
- return executeInsertMany(this.ctx, rows);
113
+ insertMany(rows) {
114
+ if (rows.length === 0) {
115
+ const builder = new InsertBuilder(this.tableName, {});
116
+ builder.clear();
117
+ return new ConnectedInsertBuilder(builder, this.relq, this.tableName, this.schemaKey);
118
+ }
119
+ const builder = new InsertBuilder(this.tableName, rows[0]);
120
+ for (let i = 1; i < rows.length; i++) {
121
+ builder.addRow(rows[i]);
122
+ }
123
+ return new ConnectedInsertBuilder(builder, this.relq, this.tableName, this.schemaKey);
115
124
  }
116
125
  async insertFrom(columns, selectCallback) {
117
126
  const tables = createTableAccessor(this.relq, this.relq.schema);
@@ -68,20 +68,6 @@ export async function executeUpsert(ctx, options) {
68
68
  const transformed = ctx.relq[INTERNAL].transformResultsFromDb(ctx.tableName, result.result.rows);
69
69
  return transformed[0];
70
70
  }
71
- export async function executeInsertMany(ctx, rows) {
72
- if (rows.length === 0)
73
- return [];
74
- const firstDbRow = ctx.relq[INTERNAL].transformToDbColumns(ctx.tableName, rows[0]);
75
- const builder = new InsertBuilder(ctx.tableName, firstDbRow);
76
- for (let i = 1; i < rows.length; i++) {
77
- const dbRow = ctx.relq[INTERNAL].transformToDbColumns(ctx.tableName, rows[i]);
78
- builder.addRow(dbRow);
79
- }
80
- builder.returning(['*']);
81
- const sql = builder.toString();
82
- const result = await ctx.relq[INTERNAL].executeQuery(sql);
83
- return ctx.relq[INTERNAL].transformResultsFromDb(ctx.tableName, result.result.rows);
84
- }
85
71
  export async function executeSoftDelete(ctx, filter) {
86
72
  const dbFilter = ctx.relq[INTERNAL].transformToDbColumns(ctx.tableName, filter);
87
73
  const builder = new UpdateBuilder(ctx.tableName, { deleted_at: new Date() });
@@ -91,7 +91,7 @@ export class InsertBuilder {
91
91
  return this.insertData.length;
92
92
  }
93
93
  _onConflict(columns, callback) {
94
- this.conflictColumns = Array.isArray(columns) ? columns : [columns];
94
+ this.conflictColumns = columns === null ? [] : Array.isArray(columns) ? columns : [columns];
95
95
  this.conflictBuilder = new ConflictBuilder(this.tableName);
96
96
  if (callback) {
97
97
  callback(this.conflictBuilder);
@@ -209,12 +209,11 @@ export class InsertBuilder {
209
209
  return { values: processedValues, placeholders: placeholderTypes.join(', ') };
210
210
  }
211
211
  buildConflictClause() {
212
- if (!this.conflictColumns || !this.conflictBuilder)
212
+ if (!this.conflictBuilder)
213
213
  return '';
214
- if (this.insertData.length > 1) {
215
- throw new RelqBuilderError('ON CONFLICT (upsert) is not supported with multiple row inserts', { builder: 'InsertBuilder', hint: 'Use single row insert for upsert operations' });
216
- }
217
- let clause = format(' ON CONFLICT (%I)', this.conflictColumns);
214
+ let clause = this.conflictColumns && this.conflictColumns.length > 0
215
+ ? format(' ON CONFLICT (%I)', this.conflictColumns)
216
+ : ' ON CONFLICT';
218
217
  if (this.conflictBuilder.action === 'update') {
219
218
  const updateSql = buildConflictUpdateSql(this.conflictBuilder.updateData, this.tableName);
220
219
  clause += ` DO UPDATE SET ${updateSql}`;
package/dist/index.d.ts CHANGED
@@ -2997,7 +2997,7 @@ export declare class InsertBuilder {
2997
2997
  * @internal Handle ON CONFLICT - used by ConnectedInsertBuilder
2998
2998
  * Use .doNothing() or .doUpdate() for type-safe conflict handling
2999
2999
  */
3000
- _onConflict(columns: string | string[], callback?: (builder: ConflictBuilder) => void): InsertBuilder;
3000
+ _onConflict(columns: string | string[] | null, callback?: (builder: ConflictBuilder) => void): InsertBuilder;
3001
3001
  /**
3002
3002
  * RETURNING clause with simple column list
3003
3003
  *
@@ -8162,21 +8162,28 @@ declare class ConnectedInsertBuilder<TTable = any> {
8162
8162
  * | MySQL | ⚠️ | Uses INSERT IGNORE (different semantics) |
8163
8163
  * | SQLite | ✅ | Native ON CONFLICT support |
8164
8164
  *
8165
- * @param columns - Column(s) for conflict detection (array or multiple args)
8165
+ * @param columns - Optional column(s) for conflict detection.
8166
+ * Omit to match any constraint (`ON CONFLICT DO NOTHING`).
8166
8167
  *
8167
8168
  * @example
8168
8169
  * ```typescript
8170
+ * // Any constraint conflict
8171
+ * await db.table.users.insert({ email: 'test@example.com' })
8172
+ * .doNothing()
8173
+ * .run()
8174
+ *
8169
8175
  * // Single column conflict
8170
8176
  * await db.table.users.insert({ email: 'test@example.com' })
8171
8177
  * .doNothing('email')
8172
- * .execute()
8178
+ * .run()
8173
8179
  *
8174
8180
  * // Multiple columns (composite unique constraint)
8175
8181
  * await db.table.userRoles.insert({ userId, roleId })
8176
8182
  * .doNothing('userId', 'roleId')
8177
- * .execute()
8183
+ * .run()
8178
8184
  * ```
8179
8185
  */
8186
+ doNothing(): this;
8180
8187
  doNothing(columns: ColumnName<TTable>[]): this;
8181
8188
  doNothing(...columns: ColumnName<TTable>[]): this;
8182
8189
  /**
@@ -8470,12 +8477,26 @@ declare class ConnectedQueryBuilder<TSchema = any, TTable = any> {
8470
8477
  $inferInsert: infer I;
8471
8478
  } ? I : Record<string, any>>;
8472
8479
  }): Promise<T>;
8473
- /** Insert multiple records at once */
8474
- insertMany<T = TTable extends {
8475
- $inferSelect: infer S;
8476
- } ? S : any>(rows: Array<TTable extends {
8480
+ /**
8481
+ * Insert multiple records at once.
8482
+ * Returns a ConnectedInsertBuilder so you can chain
8483
+ * `.doNothing()`, `.doUpdate()`, `.returning()`, and `.run()`.
8484
+ *
8485
+ * @example
8486
+ * ```typescript
8487
+ * // Standard insert (returns row count)
8488
+ * await db.table.users.insertMany([...]).run()
8489
+ *
8490
+ * // With conflict resolution
8491
+ * await db.table.users.insertMany([...]).doNothing('email').run()
8492
+ *
8493
+ * // With RETURNING
8494
+ * const users = await db.table.users.insertMany([...]).returning('*').run()
8495
+ * ```
8496
+ */
8497
+ insertMany(rows: Array<TTable extends {
8477
8498
  $inferInsert: infer I;
8478
- } ? I : Record<string, any>>): Promise<T[]>;
8499
+ } ? I : Record<string, any>>): Omit<ConnectedInsertBuilder<TTable>, "addRow" | "addRows" | "clear" | "total">;
8479
8500
  /**
8480
8501
  * INSERT INTO ... SELECT — insert rows from a SELECT query.
8481
8502
  * The callback receives all schema tables so you can build
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "relq",
3
- "version": "1.0.100",
3
+ "version": "1.0.102",
4
4
  "description": "The Fully-Typed PostgreSQL ORM for TypeScript",
5
5
  "author": "Olajide Mathew O. <olajide.mathew@yuniq.solutions>",
6
6
  "license": "MIT",