@guren/orm 2.16.2 → 2.17.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 CHANGED
@@ -1409,6 +1409,14 @@ interface D1DatabaseHandle {
1409
1409
  */
1410
1410
  declare function createD1Database(options: D1DatabaseOptions): D1DatabaseHandle;
1411
1411
  //#endregion
1412
+ //#region src/aws-data-api-resume.d.ts
1413
+ interface AwsDataApiResumeRetryOptions {
1414
+ /** No retry starts later than this many milliseconds after the first try. 0 retries nothing. Default 60000. */
1415
+ timeoutMs?: number;
1416
+ /** Longest wait between two tries, in milliseconds, above 0. Waits start at 1 s and double. Default 5000. */
1417
+ maxDelayMs?: number;
1418
+ }
1419
+ //#endregion
1412
1420
  //#region src/aws-data-api.d.ts
1413
1421
  type AwsDataApiPgDatabase$1 = import('drizzle-orm/aws-data-api/pg').AwsDataApiPgDatabase;
1414
1422
  interface AwsDataApiDatabaseOptions {
@@ -1427,6 +1435,14 @@ interface AwsDataApiDatabaseOptions {
1427
1435
  secretArn?: ConnectionResolver;
1428
1436
  /** Extra RDSDataClient configuration (region, credentials, ...). */
1429
1437
  clientOptions?: RDSDataClientConfig;
1438
+ /**
1439
+ * A cluster with minimum capacity 0 pauses when idle, and the Data API cancels
1440
+ * the call that wakes it with `DatabaseResumingException`. That call is retried
1441
+ * until the cluster answers, for up to 60 s by default. `false` rethrows it at
1442
+ * once; keep `timeoutMs` under the timeout of whatever is waiting on the call.
1443
+ * A `timeoutMs` or `maxDelayMs` that is not a usable number throws here.
1444
+ */
1445
+ resumeRetry?: false | AwsDataApiResumeRetryOptions;
1430
1446
  /**
1431
1447
  * Run pending migrations on the first `getDatabase()` call. Off by default:
1432
1448
  * on Lambda it costs several serialized Data API round trips on every cold
@@ -1471,4 +1487,4 @@ declare function serializeRecord(record: PlainObject, options: {
1471
1487
  /** Serialize an array of records. */
1472
1488
  declare function serializeRecords(records: PlainObject[], options: Parameters<typeof serializeRecord>[1]): PlainObject[];
1473
1489
  //#endregion
1474
- export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type IncrementAmount, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
1490
+ export { type AccessorDefinitions, type AccessorFn, type AggregateFunction, type AvgValue, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiResumeRetryOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConnectionContext, type D1DatabaseHandle, type D1DatabaseOptions, type DatabaseDescription, DestructiveMigrationError, type DestructiveMigrationMode, DrizzleAdapter, type DrizzleSelectQuery, type EagerLoadConstraint, type FindManyOptions, GlobalScopeRegistry, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HookCallback, type HookName, type IncrementAmount, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type ModelSetOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type OrmConnectionEnv, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type SumValue, type TransactionHandle, type TransactionModelScope, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, applyAccessors, applyMutators, buildDrizzleConditions, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, executeHook, executeObservers, loadSeeders, runSeeders, serializeRecord, serializeRecords };
package/dist/index.js CHANGED
@@ -4295,6 +4295,55 @@ function createD1Database(options) {
4295
4295
  };
4296
4296
  }
4297
4297
  //#endregion
4298
+ //#region src/aws-data-api-resume.ts
4299
+ const DEFAULT_TIMEOUT_MS = 6e4;
4300
+ const DEFAULT_MAX_DELAY_MS = 5e3;
4301
+ const FIRST_DELAY_MS = 1e3;
4302
+ function isDatabaseResuming(error) {
4303
+ return typeof error === "object" && error !== null && error.name === "DatabaseResumingException";
4304
+ }
4305
+ function milliseconds(name, value, allowZero) {
4306
+ if (!Number.isFinite(value) || value < 0 || value === 0 && !allowZero) throw new Error(`createAwsDataApiDatabase(): resumeRetry.${name} must be a finite number of milliseconds, ${allowZero ? "0 or more" : "above 0"} (received ${value}).`);
4307
+ return value;
4308
+ }
4309
+ /**
4310
+ * Returns a function that replaces a client's `send` with one retrying a call
4311
+ * the Data API cancelled because the cluster was paused. Every other error,
4312
+ * `StatementTimeoutException` included, is rethrown at once: only the resuming
4313
+ * error says nothing ran. Options are checked here, before any client exists.
4314
+ */
4315
+ function createResumeRetry(options = {}) {
4316
+ const timeoutMs = milliseconds("timeoutMs", options.timeoutMs ?? DEFAULT_TIMEOUT_MS, true);
4317
+ const maxDelayMs = milliseconds("maxDelayMs", options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS, false);
4318
+ let announced = false;
4319
+ async function sendWithRetry(client, send, args) {
4320
+ const startedAt = performance.now();
4321
+ let delay = Math.min(FIRST_DELAY_MS, maxDelayMs);
4322
+ for (;;) try {
4323
+ const result = await send.apply(client, args);
4324
+ announced = false;
4325
+ return result;
4326
+ } catch (error) {
4327
+ const remaining = timeoutMs - (performance.now() - startedAt);
4328
+ if (!isDatabaseResuming(error) || remaining <= 0) throw error;
4329
+ if (!announced) {
4330
+ announced = true;
4331
+ console.warn(`[guren/orm] The Aurora cluster is resuming from a pause. Retrying the Data API call for up to ${Math.ceil(timeoutMs / 1e3)}s.`);
4332
+ }
4333
+ await new Promise((done) => setTimeout(done, Math.min(delay, remaining)));
4334
+ delay = Math.min(delay * 2, maxDelayMs);
4335
+ }
4336
+ }
4337
+ return (client) => {
4338
+ const send = client.send;
4339
+ if (typeof send !== "function") return;
4340
+ client.send = (...args) => {
4341
+ if (typeof args[args.length - 1] === "function") return send.apply(client, args);
4342
+ return sendWithRetry(client, send, args);
4343
+ };
4344
+ };
4345
+ }
4346
+ //#endregion
4298
4347
  //#region src/aws-data-api.ts
4299
4348
  async function loadAwsDataApiModules() {
4300
4349
  try {
@@ -4309,7 +4358,7 @@ async function loadAwsDataApiModules() {
4309
4358
  }
4310
4359
  }
4311
4360
  function createAwsDataApiDatabase(options) {
4312
- const { migrationsFolder, destructiveMigrations, database, resourceArn, secretArn, clientOptions, migrateOnStart, seedersFolder, relations } = options;
4361
+ const { migrationsFolder, destructiveMigrations, database, resourceArn, secretArn, clientOptions, resumeRetry, migrateOnStart, seedersFolder, relations } = options;
4313
4362
  const resolvedMigrationsFolder = migrationsFolder instanceof URL ? fileURLToPath(migrationsFolder) : resolve(String(migrationsFolder));
4314
4363
  const resolvedSeedersFolder = seedersFolder == null ? void 0 : seedersFolder instanceof URL ? fileURLToPath(seedersFolder) : resolve(String(seedersFolder));
4315
4364
  let client;
@@ -4344,6 +4393,17 @@ function createAwsDataApiDatabase(options) {
4344
4393
  ...relations ? { relations } : {}
4345
4394
  };
4346
4395
  }
4396
+ const retryWhileResuming = resumeRetry === false ? void 0 : createResumeRetry(resumeRetry);
4397
+ async function connect() {
4398
+ const { drizzle } = await loadAwsDataApiModules();
4399
+ const connection = resolveConnection();
4400
+ const db = drizzle(buildDrizzleConfig(connection));
4401
+ if (db.$client) retryWhileResuming?.(db.$client);
4402
+ return {
4403
+ db,
4404
+ connection
4405
+ };
4406
+ }
4347
4407
  let reapplyingAfterReset = false;
4348
4408
  const migrations = singleFlight(async () => {
4349
4409
  const report = !reapplyingAfterReset;
@@ -4368,9 +4428,7 @@ function createAwsDataApiDatabase(options) {
4368
4428
  });
4369
4429
  const databaseHandle = singleFlight(async () => {
4370
4430
  if (migrateOnStart) await migrations.get();
4371
- const { drizzle } = await loadAwsDataApiModules();
4372
- const connection = resolveConnection();
4373
- const db = drizzle(buildDrizzleConfig(connection));
4431
+ const { db, connection } = await connect();
4374
4432
  client = db.$client;
4375
4433
  activeKey = hotReloadKey("aws-data-api", callSite, `${connection.resourceArn}/${connection.database}`);
4376
4434
  if (activeKey) await replaceActiveConnection(activeKey, closeDatabase);
@@ -4401,8 +4459,7 @@ function createAwsDataApiDatabase(options) {
4401
4459
  return runSeeders(await databaseHandle.get(), resolvedSeedersFolder);
4402
4460
  }
4403
4461
  async function withAdminDb(callback) {
4404
- const { drizzle } = await loadAwsDataApiModules();
4405
- const adminDb = drizzle(buildDrizzleConfig(resolveConnection()));
4462
+ const { db: adminDb } = await connect();
4406
4463
  try {
4407
4464
  return await callback(adminDb);
4408
4465
  } finally {
@@ -50,11 +50,66 @@ declare const ALLOW_DESTRUCTIVE_ENV = "GUREN_ALLOW_DESTRUCTIVE_MIGRATIONS";
50
50
  /**
51
51
  * Every destructive statement in one migration file, and its acknowledgement.
52
52
  * Every way the dialect's server may read the SQL (each dialect's, when none is
53
- * named) is taken and merged so that none can hide a statement: every finding
54
- * counts, while exemption evidence, a create and the marker count only when
55
- * every reading has them.
53
+ * named), on the whole text and on the pieces drizzle's migrator runs, is taken
54
+ * and merged so that none can hide a statement: every finding counts, while
55
+ * exemption evidence, a create and one same marker count only when every reading has them.
56
56
  */
57
57
  declare function scanMigrationSql(sql: string, { dialect }?: ScanOptions): MigrationScan;
58
+ /** A foreign key a creation statement states, names as the SQL spells them. */
59
+ interface CreationForeignKey {
60
+ columns: string[];
61
+ table: string;
62
+ columnsTo: string[];
63
+ /** Upper-cased; absent when the SQL states none. */
64
+ onDelete?: string;
65
+ onUpdate?: string;
66
+ }
67
+ /**
68
+ * A column a `CREATE TABLE` defines. `type` is spelled as a drizzle-kit snapshot spells it (`numeric(8,2)`), and
69
+ * `default` as the SQL writes it, words lower-cased and strings single-quoted (`'draft'`, `now()`, `(unixepoch())`).
70
+ */
71
+ interface CreationColumn {
72
+ name: string;
73
+ type: string;
74
+ notNull: boolean;
75
+ primaryKey: boolean;
76
+ unique: boolean;
77
+ autoIncrement: boolean;
78
+ default?: string;
79
+ }
80
+ /** One statement of a migration that only creates: a table, an index on one, or a foreign key added to one. */
81
+ type CreationStatement = {
82
+ kind: 'create-table';
83
+ table: string;
84
+ columns: CreationColumn[];
85
+ foreignKeys: CreationForeignKey[];
86
+ uniques: string[][];
87
+ primaryKey?: string[];
88
+ } | {
89
+ kind: 'create-index';
90
+ table: string;
91
+ columns: string[];
92
+ unique: boolean;
93
+ } | {
94
+ kind: 'add-foreign-key';
95
+ table: string;
96
+ foreignKey: CreationForeignKey;
97
+ };
98
+ /**
99
+ * The statements of a migration that does nothing but create tables, their indexes and their foreign
100
+ * keys, in the shapes drizzle-kit writes them; `undefined` for anything else. An allowlist: a name
101
+ * qualified by a schema, an unquoted name, a body, a trigger, `AS SELECT`, a column definition with
102
+ * another word or a name in it, and text MySQL executes inside a comment each give `undefined`, and so
103
+ * does SQL the dialect's readings lex differently.
104
+ */
105
+ declare function readCreationStatements(sql: string, dialect: MigrationDialect): CreationStatement[] | undefined;
106
+ /**
107
+ * Whether `current`, a drizzle-kit 1.x `snapshot.json`, is `previous` (the snapshot of the migration before it,
108
+ * `undefined` for the first) plus what `statements` create, as far as this guard reads a snapshot: every entry of
109
+ * another table unchanged, each created column with the type the SQL gives it, and each foreign key the SQL
110
+ * states. A later migration's widening and cascade evidence is read from these, so one that misstates them fails.
111
+ */
112
+ declare function snapshotRecordsCreation(previous: unknown, current: unknown, statements: readonly CreationStatement[]): boolean;
58
113
  /**
59
114
  * Column types from a drizzle-kit 1.x `snapshot.json`, keyed by schema, table and
60
115
  * column exactly as the snapshot names them (no case folding), so `archive.posts`
@@ -155,4 +210,4 @@ declare function guardPendingMigrations(migrationsFolder: string, pending: reado
155
210
  foreignKeysEnforced?: boolean;
156
211
  }): void;
157
212
  //#endregion
158
- export { ALLOW_DESTRUCTIVE_ENV, ALLOW_DESTRUCTIVE_MARKER, ColumnTypes, DestructiveFinding, DestructiveKind, DestructiveMigrationError, DestructiveMigrationMode, DestructiveStatement, ForeignKeyReference, JudgeOptions, MigrationAcknowledgement, MigrationDialect, MigrationGuardReport, MigrationScan, MigrationSource, ScanOptions, formatDestructiveFinding, guardPendingMigrations, isWideningTypeChange, judgeMigrations, readMigrationSources, readSnapshotColumnTypes, scanMigrationSql };
213
+ export { ALLOW_DESTRUCTIVE_ENV, ALLOW_DESTRUCTIVE_MARKER, ColumnTypes, CreationColumn, CreationForeignKey, CreationStatement, DestructiveFinding, DestructiveKind, DestructiveMigrationError, DestructiveMigrationMode, DestructiveStatement, ForeignKeyReference, JudgeOptions, MigrationAcknowledgement, MigrationDialect, MigrationGuardReport, MigrationScan, MigrationSource, ScanOptions, formatDestructiveFinding, guardPendingMigrations, isWideningTypeChange, judgeMigrations, readCreationStatements, readMigrationSources, readSnapshotColumnTypes, scanMigrationSql, snapshotRecordsCreation };
@@ -4,19 +4,23 @@ import { existsSync, readFileSync, readdirSync } from "node:fs";
4
4
  const ALLOW_DESTRUCTIVE_MARKER = "guren:allow-destructive";
5
5
  /** One-run override of `destructiveMigrations: 'refuse'`, which `guren db:migrate --allow-destructive` sets. */
6
6
  const ALLOW_DESTRUCTIVE_ENV = "GUREN_ALLOW_DESTRUCTIVE_MIGRATIONS";
7
+ const STATEMENT_SEPARATOR = "--> statement-breakpoint";
8
+ const STATEMENT_BREAKPOINT = STATEMENT_SEPARATOR.slice(2);
7
9
  const POSTGRES = {
8
10
  backslashEscapes: false,
9
11
  escapeStrings: true,
10
12
  mysqlComments: false,
11
13
  dollarQuotes: true,
12
- nestedComments: true
14
+ nestedComments: true,
15
+ carriageReturnEndsComment: true
13
16
  };
14
17
  const MYSQL = {
15
18
  backslashEscapes: true,
16
19
  escapeStrings: false,
17
20
  mysqlComments: true,
18
21
  dollarQuotes: false,
19
- nestedComments: false
22
+ nestedComments: false,
23
+ carriageReturnEndsComment: false
20
24
  };
21
25
  /**
22
26
  * Each way a dialect's server may read the SQL, all of which count: MySQL under
@@ -37,7 +41,8 @@ const LEX_READINGS = {
37
41
  escapeStrings: false,
38
42
  mysqlComments: false,
39
43
  dollarQuotes: false,
40
- nestedComments: false
44
+ nestedComments: false,
45
+ carriageReturnEndsComment: false
41
46
  }]
42
47
  };
43
48
  function lex(sql, rules, firstLine = 1) {
@@ -94,8 +99,8 @@ function lex(sql, rules, firstLine = 1) {
94
99
  continue;
95
100
  }
96
101
  if (char === "-" && sql[i + 1] === "-" || char === "#" && rules.mysqlComments) {
97
- const end = sql.indexOf("\n", i);
98
- const body = advanceTo(end === -1 ? sql.length : end).slice(char === "#" ? 1 : 2);
102
+ const ends = [sql.indexOf("\n", i), rules.carriageReturnEndsComment ? sql.indexOf("\r", i) : -1].filter((at) => at !== -1);
103
+ const body = advanceTo(ends.length === 0 ? sql.length : Math.min(...ends)).slice(char === "#" ? 1 : 2);
99
104
  comments.push({
100
105
  text: body,
101
106
  line: startLine
@@ -842,6 +847,31 @@ function scanWith(sql, rules) {
842
847
  acknowledged: readAcknowledgement(lexed.comments)
843
848
  };
844
849
  }
850
+ /** The file as drizzle's migrator runs it: each piece between separators lexed on its own, then read as one file. */
851
+ function scanPieces(sql, rules) {
852
+ const joined = {
853
+ tokens: [],
854
+ comments: [],
855
+ executable: []
856
+ };
857
+ let line = 1;
858
+ for (const piece of sql.split(STATEMENT_SEPARATOR)) {
859
+ const lexed = lex(piece, rules, line);
860
+ joined.tokens.push(...lexed.tokens, {
861
+ kind: "punct",
862
+ value: ";",
863
+ line
864
+ });
865
+ joined.comments.push(...lexed.comments);
866
+ joined.executable.push(...lexed.executable);
867
+ joined.unterminatedAt ??= lexed.unterminatedAt;
868
+ for (const char of piece) if (char === "\n") line += 1;
869
+ }
870
+ return {
871
+ ...scanTokens(joined, rules),
872
+ acknowledged: readAcknowledgement(joined.comments)
873
+ };
874
+ }
845
875
  const findingKey = (statement) => [
846
876
  statement.kind,
847
877
  statement.line,
@@ -856,9 +886,9 @@ const evidence = (statement) => JSON.stringify([
856
886
  /**
857
887
  * Every destructive statement in one migration file, and its acknowledgement.
858
888
  * Every way the dialect's server may read the SQL (each dialect's, when none is
859
- * named) is taken and merged so that none can hide a statement: every finding
860
- * counts, while exemption evidence, a create and the marker count only when
861
- * every reading has them.
889
+ * named), on the whole text and on the pieces drizzle's migrator runs, is taken
890
+ * and merged so that none can hide a statement: every finding counts, while
891
+ * exemption evidence, a create and one same marker count only when every reading has them.
862
892
  */
863
893
  function scanMigrationSql(sql, { dialect } = {}) {
864
894
  const candidates = dialect ? LEX_READINGS[dialect] : Object.values(LEX_READINGS).flat();
@@ -869,7 +899,9 @@ function scanMigrationSql(sql, { dialect } = {}) {
869
899
  ...b,
870
900
  backslashEscapes: false
871
901
  });
872
- const readings = (sql.includes("\\") ? candidates : candidates.filter((rules, at) => candidates.findIndex((other) => sameRules(other, rules)) === at)).map((rules) => scanWith(sql, rules));
902
+ const distinct = sql.includes("\\") ? candidates : candidates.filter((rules, at) => candidates.findIndex((other) => sameRules(other, rules)) === at);
903
+ const readings = distinct.map((rules) => scanWith(sql, rules));
904
+ if (sql.includes(STATEMENT_SEPARATOR)) readings.push(...distinct.map((rules) => scanPieces(sql, rules)));
873
905
  if (readings.length === 1) return readings[0];
874
906
  const merged = /* @__PURE__ */ new Map();
875
907
  for (const reading of readings) {
@@ -898,8 +930,337 @@ function scanMigrationSql(sql, { dialect } = {}) {
898
930
  statements: statements.sort((a, b) => a.line - b.line),
899
931
  creates: first.creates.filter((entry) => rest.every((reading) => reading.creates.some((other) => createKey(other) === createKey(entry)))),
900
932
  cascadeTargets: [...new Set(readings.flatMap((reading) => reading.cascadeTargets))],
901
- acknowledged: readings.every((reading) => reading.acknowledged) ? first.acknowledged : null
933
+ acknowledged: readings.every((reading) => JSON.stringify(reading.acknowledged) === JSON.stringify(first.acknowledged)) ? first.acknowledged : null
934
+ };
935
+ }
936
+ const COLUMN_TYPE_WORDS = /* @__PURE__ */ new Set([
937
+ "SERIAL",
938
+ "INTEGER",
939
+ "INT",
940
+ "TEXT",
941
+ "VARCHAR",
942
+ "NUMERIC",
943
+ "DECIMAL",
944
+ "DOUBLE",
945
+ "PRECISION",
946
+ "REAL",
947
+ "BOOLEAN",
948
+ "DATE",
949
+ "TIMESTAMP",
950
+ "WITH",
951
+ "WITHOUT",
952
+ "TIME",
953
+ "ZONE",
954
+ "JSONB",
955
+ "JSON",
956
+ "UUID"
957
+ ]);
958
+ const DEFAULT_FUNCTIONS = /* @__PURE__ */ new Set(["NOW", "UNIXEPOCH"]);
959
+ const DEFAULT_WORDS = /* @__PURE__ */ new Set([
960
+ "TRUE",
961
+ "FALSE",
962
+ "NULL",
963
+ "CURRENT_TIMESTAMP",
964
+ "CURRENT_DATE"
965
+ ]);
966
+ const COLUMN_TYPE_PUNCT = /^[0-9(),]$/;
967
+ /** `NUMERIC ( 8 , 2 )` as `numeric(8,2)`, `TIMESTAMP WITH TIME ZONE` as `timestamp with time zone`, `'a''b'` as written. */
968
+ function spellTokens(tokens) {
969
+ let text = "";
970
+ for (const [at, token] of tokens.entries()) {
971
+ const spelled = token.kind === "word" ? token.value.toLowerCase() : token.kind === "string" ? `'${token.value.replaceAll("'", "''")}'` : token.value;
972
+ text += `${at > 0 && token.kind === "word" && tokens[at - 1].kind === "word" ? " " : ""}${spelled}`;
973
+ }
974
+ return text;
975
+ }
976
+ /** The end of a default expression at `start`: a string, a number, a literal word, `now()`, or one of those in parentheses. */
977
+ function defaultEnd(tokens, start) {
978
+ const token = tokens[start];
979
+ if (token?.kind === "string" || token?.kind === "word" && DEFAULT_WORDS.has(token.value)) return start + 1;
980
+ if (token?.kind === "word" && DEFAULT_FUNCTIONS.has(token.value)) return isPunct(tokens[start + 1], "(") && isPunct(tokens[start + 2], ")") ? start + 3 : void 0;
981
+ if (isPunct(token, "(")) {
982
+ const end = defaultEnd(tokens, start + 1);
983
+ return end !== void 0 && isPunct(tokens[end], ")") ? end + 1 : void 0;
984
+ }
985
+ let at = isPunct(token, "-") ? start + 1 : start;
986
+ const digits = at;
987
+ while (tokens[at]?.kind === "punct" && /^[0-9.]$/.test(tokens[at].value)) at += 1;
988
+ return at > digits ? at : void 0;
989
+ }
990
+ /** A column definition after its name: the type, then each of drizzle-kit's modifiers at most once, and nothing else. */
991
+ function readColumnDefinition(name, definition) {
992
+ let at = 0;
993
+ while (at < definition.length && (definition[at].kind === "word" && COLUMN_TYPE_WORDS.has(definition[at].value) || definition[at].kind === "punct" && COLUMN_TYPE_PUNCT.test(definition[at].value))) at += 1;
994
+ if (at === 0) return void 0;
995
+ const column = {
996
+ name,
997
+ type: spellTokens(definition.slice(0, at)),
998
+ notNull: false,
999
+ primaryKey: false,
1000
+ unique: false,
1001
+ autoIncrement: false
902
1002
  };
1003
+ const seen = /* @__PURE__ */ new Set();
1004
+ const once = (modifier) => !seen.has(modifier) && Boolean(seen.add(modifier));
1005
+ while (at < definition.length) {
1006
+ const word = (value, offset = 0) => isWord(definition[at + offset], value);
1007
+ if (word("NOT") && word("NULL", 1) && once("null")) {
1008
+ column.notNull = true;
1009
+ at += 2;
1010
+ } else if (word("PRIMARY") && word("KEY", 1) && once("primary")) {
1011
+ column.primaryKey = true;
1012
+ at += 2;
1013
+ } else if (word("UNIQUE") && once("unique")) {
1014
+ column.unique = true;
1015
+ at += 1;
1016
+ } else if ((word("AUTO_INCREMENT") || word("AUTOINCREMENT")) && once("auto")) {
1017
+ column.autoIncrement = true;
1018
+ at += 1;
1019
+ } else if (word("DEFAULT") && once("default")) {
1020
+ const end = defaultEnd(definition, at + 1);
1021
+ if (end === void 0) return void 0;
1022
+ column.default = spellTokens(definition.slice(at + 1, end));
1023
+ at = end;
1024
+ } else return;
1025
+ }
1026
+ return column;
1027
+ }
1028
+ const REFERENTIAL_ACTIONS = [
1029
+ "CASCADE",
1030
+ "RESTRICT",
1031
+ "SET NULL",
1032
+ "SET DEFAULT",
1033
+ "NO ACTION"
1034
+ ];
1035
+ /** A cursor over one statement; every reader returns `undefined` at the first token it does not allow. */
1036
+ var CreationCursor = class {
1037
+ tokens;
1038
+ at = 0;
1039
+ constructor(tokens) {
1040
+ this.tokens = tokens;
1041
+ }
1042
+ done() {
1043
+ return this.at === this.tokens.length;
1044
+ }
1045
+ word(...values) {
1046
+ if (!isWord(this.tokens[this.at], ...values)) return false;
1047
+ this.at += 1;
1048
+ return true;
1049
+ }
1050
+ words(phrase) {
1051
+ const start = this.at;
1052
+ if (phrase.split(" ").every((value) => this.word(value))) return true;
1053
+ this.at = start;
1054
+ return false;
1055
+ }
1056
+ punct(value) {
1057
+ const token = this.tokens[this.at];
1058
+ if (token?.kind !== "punct" || token.value !== value) return false;
1059
+ this.at += 1;
1060
+ return true;
1061
+ }
1062
+ /** A quoted, unqualified name. */
1063
+ ident() {
1064
+ const token = this.tokens[this.at];
1065
+ const next = this.tokens[this.at + 1];
1066
+ if (token?.kind !== "ident" || next?.kind === "punct" && next.value === ".") return void 0;
1067
+ this.at += 1;
1068
+ return token.value;
1069
+ }
1070
+ identList() {
1071
+ if (!this.punct("(")) return void 0;
1072
+ const names = [];
1073
+ do {
1074
+ const name = this.ident();
1075
+ if (name === void 0) return void 0;
1076
+ names.push(name);
1077
+ } while (this.punct(","));
1078
+ return this.punct(")") ? names : void 0;
1079
+ }
1080
+ action() {
1081
+ return REFERENTIAL_ACTIONS.find((phrase) => this.words(phrase));
1082
+ }
1083
+ /** `FOREIGN KEY (a) REFERENCES t (b) [ON DELETE x] [ON UPDATE y]` */
1084
+ foreignKey() {
1085
+ if (!this.words("FOREIGN KEY")) return void 0;
1086
+ const columns = this.identList();
1087
+ const table = columns && this.word("REFERENCES") ? this.ident() : void 0;
1088
+ const columnsTo = table === void 0 ? void 0 : this.identList();
1089
+ if (!columns || table === void 0 || !columnsTo) return void 0;
1090
+ const key = {
1091
+ columns,
1092
+ table,
1093
+ columnsTo
1094
+ };
1095
+ for (const [clause, field] of [["ON DELETE", "onDelete"], ["ON UPDATE", "onUpdate"]]) {
1096
+ if (!this.words(clause)) continue;
1097
+ const action = this.action();
1098
+ if (action === void 0) return void 0;
1099
+ key[field] = action;
1100
+ }
1101
+ return key;
1102
+ }
1103
+ rest() {
1104
+ return this.tokens.slice(this.at);
1105
+ }
1106
+ };
1107
+ function readCreationStatement(tokens) {
1108
+ const cursor = new CreationCursor(tokens);
1109
+ if (cursor.words("CREATE TABLE")) {
1110
+ const table = cursor.ident();
1111
+ const rest = cursor.rest();
1112
+ if (table === void 0 || !isPunct(rest[0], "(") || !isPunct(rest.at(-1), ")") || depths(rest).slice(1, -1).some((depth) => depth < 1)) return void 0;
1113
+ const created = {
1114
+ kind: "create-table",
1115
+ table,
1116
+ columns: [],
1117
+ foreignKeys: [],
1118
+ uniques: []
1119
+ };
1120
+ for (const part of splitTopLevel(rest.slice(1, -1))) {
1121
+ const item = new CreationCursor(part);
1122
+ const column = item.ident();
1123
+ if (column !== void 0) {
1124
+ const read = readColumnDefinition(column, item.rest());
1125
+ if (!read) return void 0;
1126
+ created.columns.push(read);
1127
+ continue;
1128
+ }
1129
+ if (item.word("CONSTRAINT") && item.ident() === void 0 && !isWord(part[item.at], "PRIMARY")) return void 0;
1130
+ if (isWord(part[item.at], "FOREIGN")) {
1131
+ const key = item.foreignKey();
1132
+ if (!key) return void 0;
1133
+ created.foreignKeys.push(key);
1134
+ } else if (item.word("UNIQUE")) {
1135
+ item.word("INDEX", "KEY");
1136
+ const columns = item.identList();
1137
+ if (!columns) return void 0;
1138
+ created.uniques.push(columns);
1139
+ } else if (item.words("PRIMARY KEY") && created.primaryKey === void 0) {
1140
+ created.primaryKey = item.identList();
1141
+ if (!created.primaryKey) return void 0;
1142
+ } else return;
1143
+ if (!item.done()) return void 0;
1144
+ }
1145
+ return created;
1146
+ }
1147
+ if (cursor.word("CREATE")) {
1148
+ const unique = cursor.word("UNIQUE");
1149
+ const table = (cursor.word("INDEX") ? cursor.ident() : void 0) !== void 0 && cursor.word("ON") ? cursor.ident() : void 0;
1150
+ const columns = table === void 0 ? void 0 : cursor.identList();
1151
+ return table !== void 0 && columns && cursor.done() ? {
1152
+ kind: "create-index",
1153
+ table,
1154
+ columns,
1155
+ unique
1156
+ } : void 0;
1157
+ }
1158
+ if (cursor.words("ALTER TABLE")) {
1159
+ const table = cursor.ident();
1160
+ const foreignKey = table !== void 0 && cursor.words("ADD CONSTRAINT") && cursor.ident() !== void 0 ? cursor.foreignKey() : void 0;
1161
+ return table !== void 0 && foreignKey && cursor.done() ? {
1162
+ kind: "add-foreign-key",
1163
+ table,
1164
+ foreignKey
1165
+ } : void 0;
1166
+ }
1167
+ }
1168
+ const isPunct = (token, value) => token?.kind === "punct" && token.value === value;
1169
+ /**
1170
+ * The statements of a migration that does nothing but create tables, their indexes and their foreign
1171
+ * keys, in the shapes drizzle-kit writes them; `undefined` for anything else. An allowlist: a name
1172
+ * qualified by a schema, an unquoted name, a body, a trigger, `AS SELECT`, a column definition with
1173
+ * another word or a name in it, and text MySQL executes inside a comment each give `undefined`, and so
1174
+ * does SQL the dialect's readings lex differently.
1175
+ */
1176
+ function readCreationStatements(sql, dialect) {
1177
+ if (sql.includes("\r")) return void 0;
1178
+ const whole = readCreationText(sql, dialect);
1179
+ const pieces = sql.split(STATEMENT_SEPARATOR).map((piece) => readCreationText(piece, dialect));
1180
+ if (!whole || pieces.some((piece) => piece === void 0) || JSON.stringify(pieces.flat()) !== JSON.stringify(whole)) return void 0;
1181
+ return whole;
1182
+ }
1183
+ function readCreationText(sql, dialect) {
1184
+ if (LEX_READINGS.mysql.some((rules) => lex(sql, rules).executable.some((entry) => entry.text !== STATEMENT_BREAKPOINT))) return void 0;
1185
+ let agreed;
1186
+ let statements;
1187
+ for (const rules of LEX_READINGS[dialect]) {
1188
+ const lexed = lex(sql, rules);
1189
+ if (lexed.unterminatedAt !== void 0 || lexed.tokens.some((token) => token.kind === "body")) return void 0;
1190
+ const read = splitStatements(lexed.tokens).map(readCreationStatement);
1191
+ if (read.some((statement) => statement === void 0)) return void 0;
1192
+ const key = JSON.stringify(read);
1193
+ if (agreed !== void 0 && agreed !== key) return void 0;
1194
+ agreed = key;
1195
+ statements = read;
1196
+ }
1197
+ return statements;
1198
+ }
1199
+ const OWN_SNAPSHOT_ENTITIES = /* @__PURE__ */ new Set([
1200
+ "tables",
1201
+ "columns",
1202
+ "fks",
1203
+ "indexes",
1204
+ "pks",
1205
+ "uniques"
1206
+ ]);
1207
+ function canonicalJson(value) {
1208
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
1209
+ if (value !== null && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
1210
+ return JSON.stringify(value);
1211
+ }
1212
+ const sameMultiset = (a, b) => a.length === b.length && JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
1213
+ /**
1214
+ * Whether `current`, a drizzle-kit 1.x `snapshot.json`, is `previous` (the snapshot of the migration before it,
1215
+ * `undefined` for the first) plus what `statements` create, as far as this guard reads a snapshot: every entry of
1216
+ * another table unchanged, each created column with the type the SQL gives it, and each foreign key the SQL
1217
+ * states. A later migration's widening and cascade evidence is read from these, so one that misstates them fails.
1218
+ */
1219
+ function snapshotRecordsCreation(previous, current, statements) {
1220
+ const snapshot = current;
1221
+ const before = previous;
1222
+ if (!snapshot || !Array.isArray(snapshot.ddl) || !Array.isArray(snapshot.renames) || snapshot.renames.length > 0 || readSnapshotDialect(snapshot) === void 0) return false;
1223
+ if (before !== void 0 && (!before || !Array.isArray(before.ddl) || before.dialect !== snapshot.dialect || before.version !== snapshot.version || !Array.isArray(snapshot.prevIds) || !snapshot.prevIds.includes(before.id))) return false;
1224
+ const created = new Map(statements.flatMap((statement) => statement.kind === "create-table" ? [[statement.table, statement]] : []));
1225
+ const own = [];
1226
+ const rest = [];
1227
+ for (const entry of snapshot.ddl) {
1228
+ const table = entry?.entityType === "tables" ? entry.name : entry?.table;
1229
+ const inSchema = entry?.schema === void 0 || entry.schema === "public";
1230
+ if (typeof table === "string" && created.has(table) && inSchema) {
1231
+ if (!OWN_SNAPSHOT_ENTITIES.has(String(entry.entityType))) return false;
1232
+ own.push(entry);
1233
+ } else rest.push(canonicalJson(entry));
1234
+ }
1235
+ if (!sameMultiset(rest, (before?.ddl ?? []).map(canonicalJson))) return false;
1236
+ const columns = own.filter((entry) => entry.entityType === "columns").map((entry) => canonicalJson([
1237
+ entry.table,
1238
+ entry.name,
1239
+ entry.type
1240
+ ]));
1241
+ const expectedColumns = [...created.values()].flatMap((statement) => statement.columns.map((column) => canonicalJson([
1242
+ statement.table,
1243
+ column.name,
1244
+ column.type
1245
+ ])));
1246
+ const keys = own.filter((entry) => entry.entityType === "fks").map((entry) => canonicalJson([
1247
+ entry.table,
1248
+ entry.columns,
1249
+ entry.tableTo,
1250
+ entry.columnsTo,
1251
+ entry.onDelete
1252
+ ]));
1253
+ const stated = statements.flatMap((statement) => {
1254
+ return (statement.kind === "create-table" ? statement.foreignKeys : statement.kind === "add-foreign-key" ? [statement.foreignKey] : []).map((key) => canonicalJson([
1255
+ statement.table,
1256
+ key.columns,
1257
+ key.table,
1258
+ key.columnsTo,
1259
+ key.onDelete ?? "NO ACTION"
1260
+ ]));
1261
+ });
1262
+ const tables = own.filter((entry) => entry.entityType === "tables").map((entry) => String(entry.name));
1263
+ return sameMultiset(columns, expectedColumns) && sameMultiset(keys, stated) && sameMultiset(tables, [...created.keys()]);
903
1264
  }
904
1265
  const KEY_SEPARATOR = "\0";
905
1266
  function readSnapshotColumnTypes(snapshot) {
@@ -1226,4 +1587,4 @@ function guardPendingMigrations(migrationsFolder, pending, mode, { pendingKnown
1226
1587
  console.warn(`[guren/orm] Applying ${unacknowledged.length} destructive statement(s) that no migration acknowledges (${why}):\n` + (pendingKnown ? "" : `[guren/orm] (${describeTrackerError(trackerError)}, so every local migration was judged)\n`) + unacknowledged.map((finding) => `[guren/orm] ${formatDestructiveFinding(finding)}`).join("\n"));
1227
1588
  }
1228
1589
  //#endregion
1229
- export { ALLOW_DESTRUCTIVE_ENV, ALLOW_DESTRUCTIVE_MARKER, DestructiveMigrationError, formatDestructiveFinding, guardPendingMigrations, isWideningTypeChange, judgeMigrations, readMigrationSources, readSnapshotColumnTypes, scanMigrationSql };
1590
+ export { ALLOW_DESTRUCTIVE_ENV, ALLOW_DESTRUCTIVE_MARKER, DestructiveMigrationError, formatDestructiveFinding, guardPendingMigrations, isWideningTypeChange, judgeMigrations, readCreationStatements, readMigrationSources, readSnapshotColumnTypes, scanMigrationSql, snapshotRecordsCreation };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.16.2",
3
+ "version": "2.17.0",
4
4
  "description": "Eloquent-style models for the Guren framework, on Drizzle ORM: PostgreSQL, MySQL, SQLite and Cloudflare D1.",
5
5
  "keywords": [
6
6
  "guren",