@venizia/ignis-connectors 0.4.7-1 → 0.4.7-2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../../../../src/relational/core/migrations/runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAY,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,WAAW,UAAU;IACzB,4GAA4G;IAC5G,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;CACb;AAUD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,yBAA0B,SAAQ,UAAU;IACvD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA6B;IACpD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IAErC,2FAA2F;IAC3F,OAAO,CAAC,iBAAiB,CAAS;gBAEtB,IAAI,EAAE;QAChB,MAAM,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACnC,uEAAuE;QACvE,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB;IAUD;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,cAAc;IAY7B,gIAAgI;IAChI,MAAM,CAAC,eAAe,CAAC,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,KAAK,CAAC,MAAM,CAAC;IAOtD,GAAG,CAAC,IAAI,EAAE;QAAE,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAoCzE,iMAAiM;YACnL,QAAQ;CAsCvB"}
1
+ {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../../../../src/relational/core/migrations/runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAY,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,WAAW,UAAU;IACzB,4GAA4G;IAC5G,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;CACb;AAUD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,yBAA0B,SAAQ,UAAU;IACvD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA6B;IACpD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IAErC,2FAA2F;IAC3F,OAAO,CAAC,iBAAiB,CAAS;gBAEtB,IAAI,EAAE;QAChB,MAAM,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACnC,uEAAuE;QACvE,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB;IAUD;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,cAAc;IAY7B,gIAAgI;IAChI,MAAM,CAAC,eAAe,CAAC,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,KAAK,CAAC,MAAM,CAAC;IAOtD,GAAG,CAAC,IAAI,EAAE;QAAE,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAoCzE,iMAAiM;YACnL,QAAQ;CAwCvB"}
@@ -114,12 +114,15 @@ export class RelationalMigrationRunner extends BaseHelper {
114
114
  // A FAILED rollback leaves the session inside a transaction. Returning that connection to
115
115
  // the pool hands the next borrower an aborted session - the driver contract says such a
116
116
  // connection must be destroyed, and the datasource teardown already does exactly that.
117
- await connection.execute({ statement: 'ROLLBACK' }).catch((rollbackError) => {
117
+ try {
118
+ await connection.execute({ statement: 'ROLLBACK' });
119
+ }
120
+ catch (rollbackError) {
118
121
  this.isSessionPoisoned = true;
119
122
  this.logger
120
123
  .for(this.applyOne.name)
121
124
  .error('Rollback failed | name: %s | error: %s', migration.name, rollbackError);
122
- });
125
+ }
123
126
  throw error;
124
127
  }
125
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../../../src/relational/core/migrations/runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AASnE,iIAAiI;AACjI,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAEhD,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AAEhD,qFAAqF;AACrF,MAAM,oBAAoB,GAAG,0BAA0B,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,OAAO,yBAA0B,SAAQ,UAAU;IAOvD,YAAY,IAKX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,yBAAyB,CAAC,IAAI,EAAE,CAAC,CAAC;QATjE,2FAA2F;QACnF,sBAAiB,GAAG,KAAK,CAAC;QAUhC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,WAAW,GAAG,yBAAyB,CAAC,cAAc,CAAC;YAC1D,KAAK,EAAE,IAAI,CAAC,WAAW,IAAI,oBAAoB;YAC/C,KAAK,EAAE,aAAa;SACrB,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACK,MAAM,CAAC,cAAc,CAAC,IAAsC;QAClE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAE9B,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACrC,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,sCAAsC,KAAK,aAAa,KAAK,4CAA4C;aACnH,CAAC,CAAC;QACL,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED,gIAAgI;IAChI,MAAM,CAAC,eAAe,CAAC,IAAqB;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B,KAAK,CAAC,uDAAuD,EAAE,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAEzF,0FAA0F;YAC1F,wFAAwF;YACxF,uFAAuF;YACvF,MAAM,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,aAAsB,EAAE,EAAE;gBACnF,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;gBAC9B,IAAI,CAAC,MAAM;qBACR,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;qBACvB,KAAK,CAAC,wCAAwC,EAAE,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YACpF,CAAC,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { IRelationalDriver } from '../drivers';\n\nexport interface IMigration {\n /** Ledger key. Never rewrite an applied one - see the hashing note on {@link RelationalMigrationRunner}. */\n name: string;\n sql: string;\n}\n\n/** A name safe to embed as a SQL literal, checked rather than escaped - see {@link RelationalMigrationRunner.assertSafeName}. */\nconst SAFE_MIGRATION_NAME = /^[A-Za-z0-9._-]+$/;\n\nconst DEFAULT_LEDGER_TABLE = 'ignis_migrations';\n\n/** What `drizzle-kit generate` writes between statements in a single `.sql` file. */\nconst STATEMENT_BREAKPOINT = '--> statement-breakpoint';\n\n/**\n * Applies every migration not already in the ledger, each with its ledger row, in ONE transaction.\n *\n * Exists because Drizzle's own migrator cannot run everywhere: `drizzle-orm/*\\/migrator` reads the\n * migration folder through `node:fs`, so it resolves to nothing in a browser. This runs off a driver\n * connection instead, which every engine already implements.\n *\n * The property that matters is that the DDL and its ledger row commit together. Run as two\n * statements they would not: a bare `exec` commits when it returns, so a process killed between\n * them leaves the table present and the ledger empty, and the next boot re-runs a bare\n * `CREATE TABLE` and dies with `already exists` from then on. In a browser that window lands on the\n * FIRST visit, while the page is still fetching WASM - the likeliest moment for a user to close the\n * tab. A storage-quota failure on the INSERT does the same.\n *\n * TWO LIMITS THE TRANSACTION AND THE MINIMAL LEDGER IMPOSE, both deliberate:\n *\n * 1. Postgres refuses some DDL inside a transaction block, so a migration may not contain\n * `CREATE INDEX CONCURRENTLY` - which Drizzle emits for any `.concurrently()` index. Measured: it\n * fails with `CREATE INDEX CONCURRENTLY cannot run inside a transaction block`, while a bare\n * `exec` accepts it. Atomicity is worth more than a concurrent index build.\n * 2. The ledger keys on the NAME and stores no content hash, so editing an already-applied migration\n * is silently skipped rather than reported. Drizzle's own migrator hashes for this reason. Add a\n * migration; never rewrite one.\n */\nexport class RelationalMigrationRunner extends BaseHelper {\n private readonly driver: IRelationalDriver<unknown>;\n private readonly ledgerTable: string;\n\n /** Set when a ROLLBACK itself fails, so the connection is destroyed rather than pooled. */\n private isSessionPoisoned = false;\n\n constructor(opts: {\n driver: IRelationalDriver<unknown>;\n /** Defaults to `ignis_migrations`. Validated like a migration name. */\n ledgerTable?: string;\n scope?: string;\n }) {\n super({ scope: opts.scope ?? RelationalMigrationRunner.name });\n\n this.driver = opts.driver;\n this.ledgerTable = RelationalMigrationRunner.assertSafeName({\n value: opts.ledgerTable ?? DEFAULT_LEDGER_TABLE,\n field: 'ledgerTable',\n });\n }\n\n /**\n * Placeholder syntax is not portable (`$1` on Postgres, `?` on SQLite), so the ledger name is\n * embedded as a literal rather than bound. That is only safe because it is checked first: these\n * names are authored in code, never taken from a request, and anything outside the character set\n * is refused rather than escaped. Escaping is what gets this wrong; refusing cannot.\n */\n private static assertSafeName(opts: { value: string; field: string }): string {\n const { value, field } = opts;\n\n if (!SAFE_MIGRATION_NAME.test(value)) {\n throw getError({\n message: `[RelationalMigrationRunner] Unsafe ${field} | value: ${value} | allowed: letters, digits, '.', '_', '-'`,\n });\n }\n\n return value;\n }\n\n /** Splits on `drizzle-kit`'s own breakpoint marker; a hand-written single-statement migration has none and comes back whole. */\n static splitStatements(opts: { sql: string }): Array<string> {\n return opts.sql\n .split(STATEMENT_BREAKPOINT)\n .map((statement) => statement.trim())\n .filter((statement) => statement.length > 0);\n }\n\n async run(opts: { migrations: ReadonlyArray<IMigration> }): Promise<void> {\n const { migrations } = opts;\n const logger = this.logger.for(this.run.name);\n\n for (const migration of migrations) {\n RelationalMigrationRunner.assertSafeName({ value: migration.name, field: 'migration name' });\n }\n\n const connection = await this.driver.acquire({ schema: {} });\n\n try {\n // Idempotent and outside any transaction on purpose: it carries no data, so re-running it\n // after an interrupted boot is a no-op rather than a conflict.\n await connection.execute({\n statement: `CREATE TABLE IF NOT EXISTS \"${this.ledgerTable}\" (\"name\" text PRIMARY KEY NOT NULL)`,\n });\n\n const applied = await connection.query<{ name: string }>({\n statement: `SELECT \"name\" FROM \"${this.ledgerTable}\"`,\n });\n const appliedNames = new Set(applied.map((row) => row.name));\n\n for (const migration of migrations) {\n if (appliedNames.has(migration.name)) {\n logger.info('Migration already applied, skipping | name: %s', migration.name);\n continue;\n }\n\n await this.applyOne({ connection, migration });\n logger.info('Applied migration | name: %s', migration.name);\n }\n } finally {\n connection.release({ destroy: this.isSessionPoisoned });\n }\n }\n\n /** BEGIN/COMMIT written here rather than through `beginTransaction()`: that acquires its OWN connection, and the ledger read above has to see the same session on a single-connection engine. */\n private async applyOne(opts: {\n connection: Awaited<ReturnType<IRelationalDriver<unknown>['acquire']>>;\n migration: IMigration;\n }): Promise<void> {\n const { connection, migration } = opts;\n\n await connection.execute({ statement: 'BEGIN' });\n\n try {\n // One statement per call: only some clients accept a multi-statement string (PGlite's `exec`\n // does, its `query` does not), and `drizzle-kit` already marks the boundaries for us.\n const statements = RelationalMigrationRunner.splitStatements({ sql: migration.sql });\n for (const statement of statements) {\n await connection.execute({ statement });\n }\n\n await connection.execute({\n statement: `INSERT INTO \"${this.ledgerTable}\" (\"name\") VALUES ('${migration.name}')`,\n });\n await connection.execute({ statement: 'COMMIT' });\n } catch (error) {\n this.logger\n .for(this.applyOne.name)\n .error('Migration failed, rolling back | name: %s | error: %s', migration.name, error);\n\n // A FAILED rollback leaves the session inside a transaction. Returning that connection to\n // the pool hands the next borrower an aborted session - the driver contract says such a\n // connection must be destroyed, and the datasource teardown already does exactly that.\n await connection.execute({ statement: 'ROLLBACK' }).catch((rollbackError: unknown) => {\n this.isSessionPoisoned = true;\n this.logger\n .for(this.applyOne.name)\n .error('Rollback failed | name: %s | error: %s', migration.name, rollbackError);\n });\n\n throw error;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../../../src/relational/core/migrations/runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AASnE,iIAAiI;AACjI,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAEhD,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AAEhD,qFAAqF;AACrF,MAAM,oBAAoB,GAAG,0BAA0B,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,OAAO,yBAA0B,SAAQ,UAAU;IAOvD,YAAY,IAKX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,yBAAyB,CAAC,IAAI,EAAE,CAAC,CAAC;QATjE,2FAA2F;QACnF,sBAAiB,GAAG,KAAK,CAAC;QAUhC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,WAAW,GAAG,yBAAyB,CAAC,cAAc,CAAC;YAC1D,KAAK,EAAE,IAAI,CAAC,WAAW,IAAI,oBAAoB;YAC/C,KAAK,EAAE,aAAa;SACrB,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACK,MAAM,CAAC,cAAc,CAAC,IAAsC;QAClE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAE9B,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE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MAAM,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC;QACpD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;iBACvB,KAAK,CAAC,uDAAuD,EAAE,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAEzF,0FAA0F;YAC1F,wFAAwF;YACxF,uFAAuF;YACvF,IAAI,CAAC;gBACH,MAAM,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC,CAAC;YACtD,CAAC;YAAC,OAAO,aAAa,EAAE,CAAC;gBACvB,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;gBAC9B,IAAI,CAAC,MAAM;qBACR,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;qBACvB,KAAK,CAAC,wCAAwC,EAAE,SAAS,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YACpF,CAAC;YAED,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { IRelationalDriver } from '../drivers';\n\nexport interface IMigration {\n /** Ledger key. Never rewrite an applied one - see the hashing note on {@link RelationalMigrationRunner}. */\n name: string;\n sql: string;\n}\n\n/** A name safe to embed as a SQL literal, checked rather than escaped - see {@link RelationalMigrationRunner.assertSafeName}. */\nconst SAFE_MIGRATION_NAME = /^[A-Za-z0-9._-]+$/;\n\nconst DEFAULT_LEDGER_TABLE = 'ignis_migrations';\n\n/** What `drizzle-kit generate` writes between statements in a single `.sql` file. */\nconst STATEMENT_BREAKPOINT = '--> statement-breakpoint';\n\n/**\n * Applies every migration not already in the ledger, each with its ledger row, in ONE transaction.\n *\n * Exists because Drizzle's own migrator cannot run everywhere: `drizzle-orm/*\\/migrator` reads the\n * migration folder through `node:fs`, so it resolves to nothing in a browser. This runs off a driver\n * connection instead, which every engine already implements.\n *\n * The property that matters is that the DDL and its ledger row commit together. Run as two\n * statements they would not: a bare `exec` commits when it returns, so a process killed between\n * them leaves the table present and the ledger empty, and the next boot re-runs a bare\n * `CREATE TABLE` and dies with `already exists` from then on. In a browser that window lands on the\n * FIRST visit, while the page is still fetching WASM - the likeliest moment for a user to close the\n * tab. A storage-quota failure on the INSERT does the same.\n *\n * TWO LIMITS THE TRANSACTION AND THE MINIMAL LEDGER IMPOSE, both deliberate:\n *\n * 1. Postgres refuses some DDL inside a transaction block, so a migration may not contain\n * `CREATE INDEX CONCURRENTLY` - which Drizzle emits for any `.concurrently()` index. Measured: it\n * fails with `CREATE INDEX CONCURRENTLY cannot run inside a transaction block`, while a bare\n * `exec` accepts it. Atomicity is worth more than a concurrent index build.\n * 2. The ledger keys on the NAME and stores no content hash, so editing an already-applied migration\n * is silently skipped rather than reported. Drizzle's own migrator hashes for this reason. Add a\n * migration; never rewrite one.\n */\nexport class RelationalMigrationRunner extends BaseHelper {\n private readonly driver: IRelationalDriver<unknown>;\n private readonly ledgerTable: string;\n\n /** Set when a ROLLBACK itself fails, so the connection is destroyed rather than pooled. */\n private isSessionPoisoned = false;\n\n constructor(opts: {\n driver: IRelationalDriver<unknown>;\n /** Defaults to `ignis_migrations`. Validated like a migration name. */\n ledgerTable?: string;\n scope?: string;\n }) {\n super({ scope: opts.scope ?? RelationalMigrationRunner.name });\n\n this.driver = opts.driver;\n this.ledgerTable = RelationalMigrationRunner.assertSafeName({\n value: opts.ledgerTable ?? DEFAULT_LEDGER_TABLE,\n field: 'ledgerTable',\n });\n }\n\n /**\n * Placeholder syntax is not portable (`$1` on Postgres, `?` on SQLite), so the ledger name is\n * embedded as a literal rather than bound. That is only safe because it is checked first: these\n * names are authored in code, never taken from a request, and anything outside the character set\n * is refused rather than escaped. Escaping is what gets this wrong; refusing cannot.\n */\n private static assertSafeName(opts: { value: string; field: string }): string {\n const { value, field } = opts;\n\n if (!SAFE_MIGRATION_NAME.test(value)) {\n throw getError({\n message: `[RelationalMigrationRunner] Unsafe ${field} | value: ${value} | allowed: letters, digits, '.', '_', '-'`,\n });\n }\n\n return value;\n }\n\n /** Splits on `drizzle-kit`'s own breakpoint marker; a hand-written single-statement migration has none and comes back whole. */\n static splitStatements(opts: { sql: string }): Array<string> {\n return opts.sql\n .split(STATEMENT_BREAKPOINT)\n .map((statement) => statement.trim())\n .filter((statement) => statement.length > 0);\n }\n\n async run(opts: { migrations: ReadonlyArray<IMigration> }): Promise<void> {\n const { migrations } = opts;\n const logger = this.logger.for(this.run.name);\n\n for (const migration of migrations) {\n RelationalMigrationRunner.assertSafeName({ value: migration.name, field: 'migration name' });\n }\n\n const connection = await this.driver.acquire({ schema: {} });\n\n try {\n // Idempotent and outside any transaction on purpose: it carries no data, so re-running it\n // after an interrupted boot is a no-op rather than a conflict.\n await connection.execute({\n statement: `CREATE TABLE IF NOT EXISTS \"${this.ledgerTable}\" (\"name\" text PRIMARY KEY NOT NULL)`,\n });\n\n const applied = await connection.query<{ name: string }>({\n statement: `SELECT \"name\" FROM \"${this.ledgerTable}\"`,\n });\n const appliedNames = new Set(applied.map((row) => row.name));\n\n for (const migration of migrations) {\n if (appliedNames.has(migration.name)) {\n logger.info('Migration already applied, skipping | name: %s', migration.name);\n continue;\n }\n\n await this.applyOne({ connection, migration });\n logger.info('Applied migration | name: %s', migration.name);\n }\n } finally {\n connection.release({ destroy: this.isSessionPoisoned });\n }\n }\n\n /** BEGIN/COMMIT written here rather than through `beginTransaction()`: that acquires its OWN connection, and the ledger read above has to see the same session on a single-connection engine. */\n private async applyOne(opts: {\n connection: Awaited<ReturnType<IRelationalDriver<unknown>['acquire']>>;\n migration: IMigration;\n }): Promise<void> {\n const { connection, migration } = opts;\n\n await connection.execute({ statement: 'BEGIN' });\n\n try {\n // One statement per call: only some clients accept a multi-statement string (PGlite's `exec`\n // does, its `query` does not), and `drizzle-kit` already marks the boundaries for us.\n const statements = RelationalMigrationRunner.splitStatements({ sql: migration.sql });\n for (const statement of statements) {\n await connection.execute({ statement });\n }\n\n await connection.execute({\n statement: `INSERT INTO \"${this.ledgerTable}\" (\"name\") VALUES ('${migration.name}')`,\n });\n await connection.execute({ statement: 'COMMIT' });\n } catch (error) {\n this.logger\n .for(this.applyOne.name)\n .error('Migration failed, rolling back | name: %s | error: %s', migration.name, error);\n\n // A FAILED rollback leaves the session inside a transaction. Returning that connection to\n // the pool hands the next borrower an aborted session - the driver contract says such a\n // connection must be destroyed, and the datasource teardown already does exactly that.\n try {\n await connection.execute({ statement: 'ROLLBACK' });\n } catch (rollbackError) {\n this.isSessionPoisoned = true;\n this.logger\n .for(this.applyOne.name)\n .error('Rollback failed | name: %s | error: %s', migration.name, rollbackError);\n }\n\n throw error;\n }\n }\n}\n"]}
@@ -13,7 +13,12 @@ export interface IRecursiveTreeOptions {
13
13
  name: string;
14
14
  /** Runtime-checked with `is(table, Table)`; also the sole dialect selector (Postgres vs SQLite) - see {@link RecursiveTreeSql}. */
15
15
  table: unknown;
16
- rootId: string;
16
+ /**
17
+ * Where the walk starts: one id, several ids (each is a root of the walk), or none. With no root a DOWN walk
18
+ * starts from every row whose parent column is NULL; an UP walk needs a root (the ancestors of every row is never
19
+ * what is meant) and an empty list is refused, because it would silently return nothing.
20
+ */
21
+ rootId?: string | ReadonlyArray<string>;
17
22
  direction: TRecursiveTreeDirection;
18
23
  /**
19
24
  * Counts EDGES, not rows: the root is at depth 0, so `N` returns up to `N+1` rows.
@@ -26,7 +31,15 @@ export interface IRecursiveTreeOptions {
26
31
  /** Extra columns, beyond `idColumn`/`parentColumn`, carried into every row of the walk. */
27
32
  columns?: string[];
28
33
  /**
29
- * ANDed into the anchor term's WHERE clause, next to the `idColumn = rootId` match - build it with
34
+ * ANDed into BOTH terms (the anchor and the recursive one): a row it rejects is not in the walk and its subtree is
35
+ * cut off. Build it with Drizzle's own `sql` tag and name the table by its alias `t`, which both terms use for it when this option is set:
36
+ * `sql\`t.deleted_at IS NULL\``. An unqualified column is ambiguous in the recursive term when the walk carries it too
37
+ * (`id`, `parent_id`, anything in `columns`). It is the same as passing the fragment as {@link anchorFilter} and as
38
+ * {@link recursiveFilter}, written once.
39
+ */
40
+ filter?: SQL;
41
+ /**
42
+ * ANDed into the anchor term's WHERE clause, next to the root match - build it with
30
43
  * Drizzle's own `sql` tag, columns unqualified. Together with {@link recursiveFilter} it keeps a
31
44
  * row out of the walk at both ends, e.g. `sql\`deleted_at IS NULL\`` on each term.
32
45
  *
@@ -55,6 +68,8 @@ export interface IRecursiveTreeOptions {
55
68
  export declare class RecursiveTreeSql {
56
69
  private static assertValidIdentifier;
57
70
  static walk(opts: IRecursiveTreeOptions): SQL;
71
+ /** The anchor's root match: one id keeps the SQL it always had; several ids are an IN list; none is every row without a parent. */
72
+ private static compileRootCondition;
58
73
  /** See {@link RecursiveTreeSql} for why there is no separate `engine` option. */
59
74
  private static detectEngine;
60
75
  /** Postgres needs an explicit cast so the base and recursive terms agree on the `depth` column's type; SQLite's looser typing does not, but casts anyway for parity and to fail loudly on a non-numeric `startDepth`. */
@@ -1 +1 @@
1
- {"version":3,"file":"recursive-tree.d.ts","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/sqls/recursive-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAEjE,OAAO,KAAK,EAAQ,GAAG,EAAE,MAAM,aAAa,CAAC;AAK7C,sIAAsI;AACtI,qBAAa,uBAAuB;IAClC,MAAM,CAAC,QAAQ,CAAC,EAAE,QAAQ;IAC1B,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAC9B,MAAM,CAAC,QAAQ,CAAC,UAAU,cAAiC;IAE3D,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;CAG3C;AAED,MAAM,MAAM,uBAAuB,GAAG,WAAW,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAoBlF,MAAM,WAAW,qBAAqB;IACpC,mFAAmF;IACnF,IAAI,EAAE,MAAM,CAAC;IAEb,mIAAmI;IACnI,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,uBAAuB,CAAC;IAEnC;;;;OAIG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,2FAA2F;IAC3F,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAEnB;;;;;;;OAOG;IACH,YAAY,CAAC,EAAE,GAAG,CAAC;IAEnB,4FAA4F;IAC5F,eAAe,CAAC,EAAE,GAAG,CAAC;IAEtB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;GAMG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAC,qBAAqB;IAUpC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,GAAG,GAAG;IAkG7C,iFAAiF;IACjF,OAAO,CAAC,MAAM,CAAC,YAAY;IAc3B,yNAAyN;IACzN,OAAO,CAAC,MAAM,CAAC,gBAAgB;IAkB/B,wGAAwG;IACxG,OAAO,CAAC,MAAM,CAAC,0BAA0B;CA0B1C"}
1
+ {"version":3,"file":"recursive-tree.d.ts","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/sqls/recursive-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAEjE,OAAO,KAAK,EAAQ,GAAG,EAAE,MAAM,aAAa,CAAC;AAK7C,sIAAsI;AACtI,qBAAa,uBAAuB;IAClC,MAAM,CAAC,QAAQ,CAAC,EAAE,QAAQ;IAC1B,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAC9B,MAAM,CAAC,QAAQ,CAA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}
42
42
  }
43
43
  static walk(opts) {
44
- const { name, table, rootId, direction, maxDepth, idColumn = 'id', parentColumn = 'parent_id', columns = [], anchorFilter, recursiveFilter, trackPath = false, startDepth = 0, } = opts;
44
+ const { name, table, rootId, direction, maxDepth, idColumn = 'id', parentColumn = 'parent_id', columns = [], filter, anchorFilter, recursiveFilter, trackPath = false, startDepth = 0, } = opts;
45
45
  RecursiveTreeSql.assertValidIdentifier({ field: 'name', value: name });
46
46
  RecursiveTreeSql.assertValidIdentifier({ field: 'idColumn', value: idColumn });
47
47
  RecursiveTreeSql.assertValidIdentifier({ field: 'parentColumn', value: parentColumn });
@@ -85,8 +85,17 @@ export class RecursiveTreeSql {
85
85
  const { basePathColumns, recursivePathColumns } = trackPath
86
86
  ? RecursiveTreeSql.compileCycleGuardFragments({ engine, idIdentifier })
87
87
  : { basePathColumns: sql ``, recursivePathColumns: sql `` };
88
+ const rootCondition = RecursiveTreeSql.compileRootCondition({
89
+ rootId,
90
+ direction,
91
+ idIdentifier,
92
+ parentIdentifier,
93
+ });
94
+ const bothTerms = filter ? sql ` AND (${filter})` : sql ``;
95
+ // The anchor names the table by the alias `t` only when `filter` is given, so a fragment written once with `t.` is valid in both terms; without it the anchor's text is what it always was.
96
+ const anchorTable = filter ? sql `${tableIdentifier} t` : tableIdentifier;
88
97
  const anchorExtraFilter = anchorFilter ? sql ` AND (${anchorFilter})` : sql ``;
89
- const baseCase = sql `SELECT ${baseColumnList}, ${depthCast} AS depth${basePathColumns} FROM ${tableIdentifier} WHERE ${idIdentifier} = ${rootId}${anchorExtraFilter}`;
98
+ const baseCase = sql `SELECT ${baseColumnList}, ${depthCast} AS depth${basePathColumns} FROM ${anchorTable} WHERE ${rootCondition}${bothTerms}${anchorExtraFilter}`;
90
99
  // DOWN walks parent -> children (t.parentColumn = r.idColumn); UP walks child -> parent (t.idColumn = r.parentColumn).
91
100
  const joinCondition = direction === RecursiveTreeDirections.DOWN
92
101
  ? sql `t.${parentIdentifier} = r.${idIdentifier}`
@@ -95,9 +104,30 @@ export class RecursiveTreeSql {
95
104
  // result set with is_cycle = true, only its own children are cut off.
96
105
  const cycleGuard = trackPath ? sql ` AND NOT r.is_cycle` : sql ``;
97
106
  const extraFilter = recursiveFilter ? sql ` AND (${recursiveFilter})` : sql ``;
98
- const recursiveCase = sql `SELECT ${recursiveColumnList}, r.depth + 1${recursivePathColumns} FROM ${tableIdentifier} t JOIN ${cteIdentifier} r ON ${joinCondition} WHERE r.depth + 1 <= ${maxDepth}${cycleGuard}${extraFilter}`;
107
+ const recursiveCase = sql `SELECT ${recursiveColumnList}, r.depth + 1${recursivePathColumns} FROM ${tableIdentifier} t JOIN ${cteIdentifier} r ON ${joinCondition} WHERE r.depth + 1 <= ${maxDepth}${cycleGuard}${bothTerms}${extraFilter}`;
99
108
  return sql `WITH RECURSIVE ${cteIdentifier} AS (${baseCase} UNION ALL ${recursiveCase})`;
100
109
  }
110
+ /** The anchor's root match: one id keeps the SQL it always had; several ids are an IN list; none is every row without a parent. */
111
+ static compileRootCondition(opts) {
112
+ const { rootId, direction, idIdentifier, parentIdentifier } = opts;
113
+ if (rootId === undefined) {
114
+ if (direction === RecursiveTreeDirections.UP) {
115
+ throw getError({
116
+ message: `[RecursiveTreeSql.walk] Invalid 'rootId' | An ${RecursiveTreeDirections.UP} walk needs at least one root | Got: undefined`,
117
+ });
118
+ }
119
+ return sql `${parentIdentifier} IS NULL`;
120
+ }
121
+ if (typeof rootId === 'string') {
122
+ return sql `${idIdentifier} = ${rootId}`;
123
+ }
124
+ if (rootId.length === 0) {
125
+ throw getError({
126
+ message: "[RecursiveTreeSql.walk] Invalid 'rootId' | An empty list of roots would return nothing | Got: []",
127
+ });
128
+ }
129
+ return sql `${idIdentifier} IN (${sql.join(rootId.map((id) => sql `${id}`), sql `, `)})`;
130
+ }
101
131
  /** See {@link RecursiveTreeSql} for why there is no separate `engine` option. */
102
132
  static detectEngine(table) {
103
133
  if (is(table, PgTable)) {
@@ -1 +1 @@
1
- {"version":3,"file":"recursive-tree.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/sqls/recursive-tree.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD,sIAAsI;AACtI,MAAM,OAAO,uBAAuB;aAClB,OAAE,GAAG,IAAI,CAAC;aACV,SAAI,GAAG,MAAM,CAAC;aACd,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAE3D,MAAM,CAAC,OAAO,CAAC,SAAiB;QAC9B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,CAAC;;AAKH,oHAAoH;AACpH,MAAM,oBAAoB;aACR,aAAQ,GAAG,UAAU,CAAC;aACtB,WAAM,GAAG,QAAQ,CAAC;aAClB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;;AAKrE,oIAAoI;AACpI,MAAM,kBAAkB,GAAG,0BAA0B,CAAC;AAEtD;;;GAGG;AACH,MAAM,qBAAqB,GAAG,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AA8ClD;;;;;;GAMG;AACH,MAAM,OAAO,gBAAgB;IACnB,MAAM,CAAC,qBAAqB,CAAC,IAAsC;QACzE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAE9B,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACpC,MAAM,QAA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AK,cAAc,CAAC;YACxC,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,mDAAmD,MAAM,EAAE;iBACrE,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;IAED,wGAAwG;IAChG,MAAM,CAAC,0BAA0B,CAAC,IAGzC;QACC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;QAEtC,QAAQ,MAAM,EAAE,CAAC;YACf,KAAK,oBAAoB,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACnC,OAAO;oBACL,eAAe,EAAE,GAAG,CAAA,WAAW,YAAY,8BAA8B;oBACzE,oBAAoB,EAAE,GAAG,CAAA,iBAAiB,YAAY,eAAe,YAAY,4BAA4B;iBAC9G,CAAC;YACJ,CAAC;YACD,KAAK,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAAC;gBACjC,OAAO;oBACL,eAAe,EAAE,GAAG,CAAA,KAAK,qBAAqB,OAAO,YAAY,OAAO,qBAAqB,yBAAyB;oBACtH,oBAAoB,EAAE,GAAG,CAAA,iBAAiB,YAAY,OAAO,qBAAqB,2BAA2B,qBAAqB,SAAS,YAAY,OAAO,qBAAqB,mBAAmB;iBACvM,CAAC;YACJ,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,mDAAmD,MAAM,EAAE;iBACrE,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { Name, SQL } from 'drizzle-orm';\nimport { getTableName, is, sql, Table } from 'drizzle-orm';\nimport { getTableConfig, PgTable } from 'drizzle-orm/pg-core';\nimport { SQLiteTable } from 'drizzle-orm/sqlite-core';\n\n/** Walk direction relative to `rootId`: DOWN follows `parentColumn -> idColumn` (descendants), UP follows the reverse (ancestors). */\nexport class RecursiveTreeDirections {\n static readonly UP = 'UP';\n static readonly DOWN = 'DOWN';\n static readonly SCHEME_SET = new Set([this.UP, this.DOWN]);\n\n static isValid(direction: string): boolean {\n return this.SCHEME_SET.has(direction);\n }\n}\n\nexport type TRecursiveTreeDirection = TConstValue<typeof RecursiveTreeDirections>;\n\n/** Internal only - not part of {@link IRecursiveTreeOptions}. Derived from `table`, never accepted as an option. */\nclass RecursiveTreeEngines {\n static readonly POSTGRES = 'POSTGRES';\n static readonly SQLITE = 'SQLITE';\n static readonly SCHEME_SET = new Set([this.POSTGRES, this.SQLITE]);\n}\n\ntype TRecursiveTreeEngine = TConstValue<typeof RecursiveTreeEngines>;\n\n/** A SQL identifier is safe to splice only after it matches this allowlist - see {@link RecursiveTreeSql.assertValidIdentifier}. */\nconst IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * ASCII Unit Separator (0x1F) - chosen because it does not occur in real ids, unlike `/` or `,`.\n * See {@link RecursiveTreeSql} for the exactness limitation this relies on.\n */\nconst SQLITE_PATH_DELIMITER = sql.raw('char(31)');\n\nexport interface IRecursiveTreeOptions {\n /** CTE name the caller references in the SELECT it writes around this fragment. */\n name: string;\n\n /** Runtime-checked with `is(table, Table)`; also the sole dialect selector (Postgres vs SQLite) - see {@link RecursiveTreeSql}. */\n table: unknown;\n rootId: string;\n direction: TRecursiveTreeDirection;\n\n /**\n * Counts EDGES, not rows: the root is at depth 0, so `N` returns up to `N+1` rows.\n * No default - `0` type-checks but silently produces an empty result, so `walk` throws at\n * runtime for `maxDepth <= 0`.\n */\n maxDepth: number;\n idColumn?: string;\n parentColumn?: string;\n\n /** Extra columns, beyond `idColumn`/`parentColumn`, carried into every row of the walk. */\n columns?: string[];\n\n /**\n * ANDed into the anchor term's WHERE clause, next to the `idColumn = rootId` match - build it with\n * Drizzle's own `sql` tag, columns unqualified. Together with {@link recursiveFilter} it keeps a\n * row out of the walk at both ends, e.g. `sql\\`deleted_at IS NULL\\`` on each term.\n *\n * `walk` takes a table, not a model, so it never applies a model's soft delete or `access` scope by\n * itself: both terms are filtered only by what the caller passes here and in `recursiveFilter`.\n */\n anchorFilter?: SQL;\n\n /** ANDed into the recursive term's WHERE clause - build it with Drizzle's own `sql` tag. */\n recursiveFilter?: SQL;\n\n /**\n * Emits `path`/`is_cycle` and stops expanding once a row re-visits an id in its own path. Row\n * shape differs per engine and nothing in this signature shows it: Postgres returns a real array\n * and boolean; SQLite returns delimited text and `1`/`0` - so `row.path.length` throws on SQLite\n * and `row.is_cycle === true` is always false there.\n */\n trackPath?: boolean;\n startDepth?: number;\n}\n\n/**\n * Returns the CTE definition only - the caller writes its own `SELECT ... FROM <name>` around it.\n * Engine is read off `table`, never asked of the caller, so no option can disagree with the schema.\n * SQLite's `path` is `char(31)`-delimited text, not an array: exact unless an id contains that byte,\n * which this class does not reject. Identifiers cannot be parameterized, so `name`/`idColumn`/\n * `parentColumn`/`columns` are allowlist-checked before reaching a template.\n */\nexport class RecursiveTreeSql {\n private static assertValidIdentifier(opts: { field: string; value: string }): void {\n const { field, value } = opts;\n\n if (!IDENTIFIER_PATTERN.test(value)) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid '${field}' | Expected letters, digits and underscores only, not starting with a digit | Got: ${value}`,\n });\n }\n }\n\n static walk(opts: IRecursiveTreeOptions): SQL {\n const {\n name,\n table,\n rootId,\n direction,\n maxDepth,\n idColumn = 'id',\n parentColumn = 'parent_id',\n columns = [],\n anchorFilter,\n recursiveFilter,\n trackPath = false,\n startDepth = 0,\n } = opts;\n\n RecursiveTreeSql.assertValidIdentifier({ field: 'name', value: name });\n RecursiveTreeSql.assertValidIdentifier({ field: 'idColumn', value: idColumn });\n RecursiveTreeSql.assertValidIdentifier({ field: 'parentColumn', value: parentColumn });\n columns.forEach((column) =>\n RecursiveTreeSql.assertValidIdentifier({ field: 'columns', value: column }),\n );\n\n if (!RecursiveTreeDirections.isValid(direction)) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'direction' | Expected ${RecursiveTreeDirections.UP} or ${RecursiveTreeDirections.DOWN} | Got: ${direction}`,\n });\n }\n\n if (!Number.isInteger(maxDepth) || maxDepth <= 0) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'maxDepth' | Expected a positive integer | Got: ${maxDepth}`,\n });\n }\n\n if (!is(table, Table)) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'table' | Expected a Drizzle table | Got: ${typeof table}`,\n });\n }\n\n const engine = RecursiveTreeSql.detectEngine(table);\n\n const tableName = getTableName(table);\n RecursiveTreeSql.assertValidIdentifier({ field: 'table', value: tableName });\n\n // A Postgres table declared with `pgSchema('commerce').table(...)` lives outside the search path,\n // so the unqualified name would read the wrong relation or none. SQLite has no schemas.\n const schemaName =\n engine === RecursiveTreeEngines.POSTGRES\n ? getTableConfig(table as PgTable).schema\n : undefined;\n\n if (schemaName !== undefined) {\n RecursiveTreeSql.assertValidIdentifier({ field: 'schema', value: schemaName });\n }\n\n const tableIdentifier =\n schemaName === undefined\n ? sql.identifier(tableName)\n : sql`${sql.identifier(schemaName)}.${sql.identifier(tableName)}`;\n const cteIdentifier = sql.identifier(name);\n const idIdentifier = sql.identifier(idColumn);\n const parentIdentifier = sql.identifier(parentColumn);\n const extraIdentifiers = columns.map((column) => sql.identifier(column));\n\n const baseColumnList = sql.join([idIdentifier, parentIdentifier, ...extraIdentifiers], sql`, `);\n const recursiveColumnList = sql.join(\n [idIdentifier, parentIdentifier, ...extraIdentifiers].map(\n (identifier) => sql`t.${identifier}`,\n ),\n sql`, `,\n );\n\n const depthCast = RecursiveTreeSql.compileDepthCast({ engine, depth: startDepth });\n const { basePathColumns, recursivePathColumns } = trackPath\n ? RecursiveTreeSql.compileCycleGuardFragments({ engine, idIdentifier })\n : { basePathColumns: sql``, recursivePathColumns: sql`` };\n\n const anchorExtraFilter = anchorFilter ? sql` AND (${anchorFilter})` : sql``;\n const baseCase = sql`SELECT ${baseColumnList}, ${depthCast} AS depth${basePathColumns} FROM ${tableIdentifier} WHERE ${idIdentifier} = ${rootId}${anchorExtraFilter}`;\n\n // DOWN walks parent -> children (t.parentColumn = r.idColumn); UP walks child -> parent (t.idColumn = r.parentColumn).\n const joinCondition =\n direction === RecursiveTreeDirections.DOWN\n ? sql`t.${parentIdentifier} = r.${idIdentifier}`\n : sql`t.${idIdentifier} = r.${parentIdentifier}`;\n\n // `NOT r.is_cycle` stops expanding a row already flagged cyclic - the row itself stays in the\n // result set with is_cycle = true, only its own children are cut off.\n const cycleGuard = trackPath ? sql` AND NOT r.is_cycle` : sql``;\n const extraFilter = recursiveFilter ? sql` AND (${recursiveFilter})` : sql``;\n\n const recursiveCase = sql`SELECT ${recursiveColumnList}, r.depth + 1${recursivePathColumns} FROM ${tableIdentifier} t JOIN ${cteIdentifier} r ON ${joinCondition} WHERE r.depth + 1 <= ${maxDepth}${cycleGuard}${extraFilter}`;\n\n return sql`WITH RECURSIVE ${cteIdentifier} AS (${baseCase} UNION ALL ${recursiveCase})`;\n }\n\n /** See {@link RecursiveTreeSql} for why there is no separate `engine` option. */\n private static detectEngine(table: Table): TRecursiveTreeEngine {\n if (is(table, PgTable)) {\n return RecursiveTreeEngines.POSTGRES;\n }\n\n if (is(table, SQLiteTable)) {\n return RecursiveTreeEngines.SQLITE;\n }\n\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'table' | Expected a Postgres or SQLite Drizzle table | Got: ${getTableName(table)}`,\n });\n }\n\n /** Postgres needs an explicit cast so the base and recursive terms agree on the `depth` column's type; SQLite's looser typing does not, but casts anyway for parity and to fail loudly on a non-numeric `startDepth`. */\n private static compileDepthCast(opts: { engine: TRecursiveTreeEngine; depth: number }): SQL {\n const { engine, depth } = opts;\n\n switch (engine) {\n case RecursiveTreeEngines.POSTGRES: {\n return sql`${depth}::int`;\n }\n case RecursiveTreeEngines.SQLITE: {\n return sql`CAST(${depth} AS INTEGER)`;\n }\n default: {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'engine' | Got: ${engine}`,\n });\n }\n }\n }\n\n /** See {@link RecursiveTreeSql} for why Postgres and SQLite need different `path`/`is_cycle` shapes. */\n private static compileCycleGuardFragments(opts: {\n engine: TRecursiveTreeEngine;\n idIdentifier: Name;\n }): { basePathColumns: SQL; recursivePathColumns: SQL } {\n const { engine, idIdentifier } = opts;\n\n switch (engine) {\n case RecursiveTreeEngines.POSTGRES: {\n return {\n basePathColumns: sql`, ARRAY[${idIdentifier}] AS path, false AS is_cycle`,\n recursivePathColumns: sql`, r.path || t.${idIdentifier} AS path, t.${idIdentifier} = ANY(r.path) AS is_cycle`,\n };\n }\n case RecursiveTreeEngines.SQLITE: {\n return {\n basePathColumns: sql`, ${SQLITE_PATH_DELIMITER} || ${idIdentifier} || ${SQLITE_PATH_DELIMITER} AS path, 0 AS is_cycle`,\n recursivePathColumns: sql`, r.path || t.${idIdentifier} || ${SQLITE_PATH_DELIMITER} AS path, instr(r.path, ${SQLITE_PATH_DELIMITER} || t.${idIdentifier} || ${SQLITE_PATH_DELIMITER}) > 0 AS is_cycle`,\n };\n }\n default: {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'engine' | Got: ${engine}`,\n });\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"recursive-tree.js","sourceRoot":"","sources":["../../../../../../src/relational/core/repositories/sqls/recursive-tree.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAE,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD,sIAAsI;AACtI,MAAM,OAAO,uBAAuB;aAClB,OAAE,GAAG,IAAI,CAAC;aACV,SAAI,GAAG,MAAM,CAAC;aACd,e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AW,YAAY,8BAA8B;oBACzE,oBAAoB,EAAE,GAAG,CAAA,iBAAiB,YAAY,eAAe,YAAY,4BAA4B;iBAC9G,CAAC;YACJ,CAAC;YACD,KAAK,oBAAoB,CAAC,MAAM,CAAC,CAAC,CAAC;gBACjC,OAAO;oBACL,eAAe,EAAE,GAAG,CAAA,KAAK,qBAAqB,OAAO,YAAY,OAAO,qBAAqB,yBAAyB;oBACtH,oBAAoB,EAAE,GAAG,CAAA,iBAAiB,YAAY,OAAO,qBAAqB,2BAA2B,qBAAqB,SAAS,YAAY,OAAO,qBAAqB,mBAAmB;iBACvM,CAAC;YACJ,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,mDAAmD,MAAM,EAAE;iBACrE,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { Name, SQL } from 'drizzle-orm';\nimport { getTableName, is, sql, Table } from 'drizzle-orm';\nimport { getTableConfig, PgTable } from 'drizzle-orm/pg-core';\nimport { SQLiteTable } from 'drizzle-orm/sqlite-core';\n\n/** Walk direction relative to `rootId`: DOWN follows `parentColumn -> idColumn` (descendants), UP follows the reverse (ancestors). */\nexport class RecursiveTreeDirections {\n static readonly UP = 'UP';\n static readonly DOWN = 'DOWN';\n static readonly SCHEME_SET = new Set([this.UP, this.DOWN]);\n\n static isValid(direction: string): boolean {\n return this.SCHEME_SET.has(direction);\n }\n}\n\nexport type TRecursiveTreeDirection = TConstValue<typeof RecursiveTreeDirections>;\n\n/** Internal only - not part of {@link IRecursiveTreeOptions}. Derived from `table`, never accepted as an option. */\nclass RecursiveTreeEngines {\n static readonly POSTGRES = 'POSTGRES';\n static readonly SQLITE = 'SQLITE';\n static readonly SCHEME_SET = new Set([this.POSTGRES, this.SQLITE]);\n}\n\ntype TRecursiveTreeEngine = TConstValue<typeof RecursiveTreeEngines>;\n\n/** A SQL identifier is safe to splice only after it matches this allowlist - see {@link RecursiveTreeSql.assertValidIdentifier}. */\nconst IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * ASCII Unit Separator (0x1F) - chosen because it does not occur in real ids, unlike `/` or `,`.\n * See {@link RecursiveTreeSql} for the exactness limitation this relies on.\n */\nconst SQLITE_PATH_DELIMITER = sql.raw('char(31)');\n\nexport interface IRecursiveTreeOptions {\n /** CTE name the caller references in the SELECT it writes around this fragment. */\n name: string;\n\n /** Runtime-checked with `is(table, Table)`; also the sole dialect selector (Postgres vs SQLite) - see {@link RecursiveTreeSql}. */\n table: unknown;\n\n /**\n * Where the walk starts: one id, several ids (each is a root of the walk), or none. With no root a DOWN walk\n * starts from every row whose parent column is NULL; an UP walk needs a root (the ancestors of every row is never\n * what is meant) and an empty list is refused, because it would silently return nothing.\n */\n rootId?: string | ReadonlyArray<string>;\n direction: TRecursiveTreeDirection;\n\n /**\n * Counts EDGES, not rows: the root is at depth 0, so `N` returns up to `N+1` rows.\n * No default - `0` type-checks but silently produces an empty result, so `walk` throws at\n * runtime for `maxDepth <= 0`.\n */\n maxDepth: number;\n idColumn?: string;\n parentColumn?: string;\n\n /** Extra columns, beyond `idColumn`/`parentColumn`, carried into every row of the walk. */\n columns?: string[];\n\n /**\n * ANDed into BOTH terms (the anchor and the recursive one): a row it rejects is not in the walk and its subtree is\n * cut off. Build it with Drizzle's own `sql` tag and name the table by its alias `t`, which both terms use for it when this option is set:\n * `sql\\`t.deleted_at IS NULL\\``. An unqualified column is ambiguous in the recursive term when the walk carries it too\n * (`id`, `parent_id`, anything in `columns`). It is the same as passing the fragment as {@link anchorFilter} and as\n * {@link recursiveFilter}, written once.\n */\n filter?: SQL;\n\n /**\n * ANDed into the anchor term's WHERE clause, next to the root match - build it with\n * Drizzle's own `sql` tag, columns unqualified. Together with {@link recursiveFilter} it keeps a\n * row out of the walk at both ends, e.g. `sql\\`deleted_at IS NULL\\`` on each term.\n *\n * `walk` takes a table, not a model, so it never applies a model's soft delete or `access` scope by\n * itself: both terms are filtered only by what the caller passes here and in `recursiveFilter`.\n */\n anchorFilter?: SQL;\n\n /** ANDed into the recursive term's WHERE clause - build it with Drizzle's own `sql` tag. */\n recursiveFilter?: SQL;\n\n /**\n * Emits `path`/`is_cycle` and stops expanding once a row re-visits an id in its own path. Row\n * shape differs per engine and nothing in this signature shows it: Postgres returns a real array\n * and boolean; SQLite returns delimited text and `1`/`0` - so `row.path.length` throws on SQLite\n * and `row.is_cycle === true` is always false there.\n */\n trackPath?: boolean;\n startDepth?: number;\n}\n\n/**\n * Returns the CTE definition only - the caller writes its own `SELECT ... FROM <name>` around it.\n * Engine is read off `table`, never asked of the caller, so no option can disagree with the schema.\n * SQLite's `path` is `char(31)`-delimited text, not an array: exact unless an id contains that byte,\n * which this class does not reject. Identifiers cannot be parameterized, so `name`/`idColumn`/\n * `parentColumn`/`columns` are allowlist-checked before reaching a template.\n */\nexport class RecursiveTreeSql {\n private static assertValidIdentifier(opts: { field: string; value: string }): void {\n const { field, value } = opts;\n\n if (!IDENTIFIER_PATTERN.test(value)) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid '${field}' | Expected letters, digits and underscores only, not starting with a digit | Got: ${value}`,\n });\n }\n }\n\n static walk(opts: IRecursiveTreeOptions): SQL {\n const {\n name,\n table,\n rootId,\n direction,\n maxDepth,\n idColumn = 'id',\n parentColumn = 'parent_id',\n columns = [],\n filter,\n anchorFilter,\n recursiveFilter,\n trackPath = false,\n startDepth = 0,\n } = opts;\n\n RecursiveTreeSql.assertValidIdentifier({ field: 'name', value: name });\n RecursiveTreeSql.assertValidIdentifier({ field: 'idColumn', value: idColumn });\n RecursiveTreeSql.assertValidIdentifier({ field: 'parentColumn', value: parentColumn });\n columns.forEach((column) =>\n RecursiveTreeSql.assertValidIdentifier({ field: 'columns', value: column }),\n );\n\n if (!RecursiveTreeDirections.isValid(direction)) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'direction' | Expected ${RecursiveTreeDirections.UP} or ${RecursiveTreeDirections.DOWN} | Got: ${direction}`,\n });\n }\n\n if (!Number.isInteger(maxDepth) || maxDepth <= 0) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'maxDepth' | Expected a positive integer | Got: ${maxDepth}`,\n });\n }\n\n if (!is(table, Table)) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'table' | Expected a Drizzle table | Got: ${typeof table}`,\n });\n }\n\n const engine = RecursiveTreeSql.detectEngine(table);\n\n const tableName = getTableName(table);\n RecursiveTreeSql.assertValidIdentifier({ field: 'table', value: tableName });\n\n // A Postgres table declared with `pgSchema('commerce').table(...)` lives outside the search path,\n // so the unqualified name would read the wrong relation or none. SQLite has no schemas.\n const schemaName =\n engine === RecursiveTreeEngines.POSTGRES\n ? getTableConfig(table as PgTable).schema\n : undefined;\n\n if (schemaName !== undefined) {\n RecursiveTreeSql.assertValidIdentifier({ field: 'schema', value: schemaName });\n }\n\n const tableIdentifier =\n schemaName === undefined\n ? sql.identifier(tableName)\n : sql`${sql.identifier(schemaName)}.${sql.identifier(tableName)}`;\n const cteIdentifier = sql.identifier(name);\n const idIdentifier = sql.identifier(idColumn);\n const parentIdentifier = sql.identifier(parentColumn);\n const extraIdentifiers = columns.map((column) => sql.identifier(column));\n\n const baseColumnList = sql.join([idIdentifier, parentIdentifier, ...extraIdentifiers], sql`, `);\n const recursiveColumnList = sql.join(\n [idIdentifier, parentIdentifier, ...extraIdentifiers].map(\n (identifier) => sql`t.${identifier}`,\n ),\n sql`, `,\n );\n\n const depthCast = RecursiveTreeSql.compileDepthCast({ engine, depth: startDepth });\n const { basePathColumns, recursivePathColumns } = trackPath\n ? RecursiveTreeSql.compileCycleGuardFragments({ engine, idIdentifier })\n : { basePathColumns: sql``, recursivePathColumns: sql`` };\n\n const rootCondition = RecursiveTreeSql.compileRootCondition({\n rootId,\n direction,\n idIdentifier,\n parentIdentifier,\n });\n const bothTerms = filter ? sql` AND (${filter})` : sql``;\n // The anchor names the table by the alias `t` only when `filter` is given, so a fragment written once with `t.` is valid in both terms; without it the anchor's text is what it always was.\n const anchorTable = filter ? sql`${tableIdentifier} t` : tableIdentifier;\n const anchorExtraFilter = anchorFilter ? sql` AND (${anchorFilter})` : sql``;\n const baseCase = sql`SELECT ${baseColumnList}, ${depthCast} AS depth${basePathColumns} FROM ${anchorTable} WHERE ${rootCondition}${bothTerms}${anchorExtraFilter}`;\n\n // DOWN walks parent -> children (t.parentColumn = r.idColumn); UP walks child -> parent (t.idColumn = r.parentColumn).\n const joinCondition =\n direction === RecursiveTreeDirections.DOWN\n ? sql`t.${parentIdentifier} = r.${idIdentifier}`\n : sql`t.${idIdentifier} = r.${parentIdentifier}`;\n\n // `NOT r.is_cycle` stops expanding a row already flagged cyclic - the row itself stays in the\n // result set with is_cycle = true, only its own children are cut off.\n const cycleGuard = trackPath ? sql` AND NOT r.is_cycle` : sql``;\n const extraFilter = recursiveFilter ? sql` AND (${recursiveFilter})` : sql``;\n\n const recursiveCase = sql`SELECT ${recursiveColumnList}, r.depth + 1${recursivePathColumns} FROM ${tableIdentifier} t JOIN ${cteIdentifier} r ON ${joinCondition} WHERE r.depth + 1 <= ${maxDepth}${cycleGuard}${bothTerms}${extraFilter}`;\n\n return sql`WITH RECURSIVE ${cteIdentifier} AS (${baseCase} UNION ALL ${recursiveCase})`;\n }\n\n /** The anchor's root match: one id keeps the SQL it always had; several ids are an IN list; none is every row without a parent. */\n private static compileRootCondition(opts: {\n rootId?: string | ReadonlyArray<string>;\n direction: TRecursiveTreeDirection;\n idIdentifier: Name;\n parentIdentifier: Name;\n }): SQL {\n const { rootId, direction, idIdentifier, parentIdentifier } = opts;\n\n if (rootId === undefined) {\n if (direction === RecursiveTreeDirections.UP) {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'rootId' | An ${RecursiveTreeDirections.UP} walk needs at least one root | Got: undefined`,\n });\n }\n\n return sql`${parentIdentifier} IS NULL`;\n }\n\n if (typeof rootId === 'string') {\n return sql`${idIdentifier} = ${rootId}`;\n }\n\n if (rootId.length === 0) {\n throw getError({\n message:\n \"[RecursiveTreeSql.walk] Invalid 'rootId' | An empty list of roots would return nothing | Got: []\",\n });\n }\n\n return sql`${idIdentifier} IN (${sql.join(\n rootId.map((id) => sql`${id}`),\n sql`, `,\n )})`;\n }\n\n /** See {@link RecursiveTreeSql} for why there is no separate `engine` option. */\n private static detectEngine(table: Table): TRecursiveTreeEngine {\n if (is(table, PgTable)) {\n return RecursiveTreeEngines.POSTGRES;\n }\n\n if (is(table, SQLiteTable)) {\n return RecursiveTreeEngines.SQLITE;\n }\n\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'table' | Expected a Postgres or SQLite Drizzle table | Got: ${getTableName(table)}`,\n });\n }\n\n /** Postgres needs an explicit cast so the base and recursive terms agree on the `depth` column's type; SQLite's looser typing does not, but casts anyway for parity and to fail loudly on a non-numeric `startDepth`. */\n private static compileDepthCast(opts: { engine: TRecursiveTreeEngine; depth: number }): SQL {\n const { engine, depth } = opts;\n\n switch (engine) {\n case RecursiveTreeEngines.POSTGRES: {\n return sql`${depth}::int`;\n }\n case RecursiveTreeEngines.SQLITE: {\n return sql`CAST(${depth} AS INTEGER)`;\n }\n default: {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'engine' | Got: ${engine}`,\n });\n }\n }\n }\n\n /** See {@link RecursiveTreeSql} for why Postgres and SQLite need different `path`/`is_cycle` shapes. */\n private static compileCycleGuardFragments(opts: {\n engine: TRecursiveTreeEngine;\n idIdentifier: Name;\n }): { basePathColumns: SQL; recursivePathColumns: SQL } {\n const { engine, idIdentifier } = opts;\n\n switch (engine) {\n case RecursiveTreeEngines.POSTGRES: {\n return {\n basePathColumns: sql`, ARRAY[${idIdentifier}] AS path, false AS is_cycle`,\n recursivePathColumns: sql`, r.path || t.${idIdentifier} AS path, t.${idIdentifier} = ANY(r.path) AS is_cycle`,\n };\n }\n case RecursiveTreeEngines.SQLITE: {\n return {\n basePathColumns: sql`, ${SQLITE_PATH_DELIMITER} || ${idIdentifier} || ${SQLITE_PATH_DELIMITER} AS path, 0 AS is_cycle`,\n recursivePathColumns: sql`, r.path || t.${idIdentifier} || ${SQLITE_PATH_DELIMITER} AS path, instr(r.path, ${SQLITE_PATH_DELIMITER} || t.${idIdentifier} || ${SQLITE_PATH_DELIMITER}) > 0 AS is_cycle`,\n };\n }\n default: {\n throw getError({\n message: `[RecursiveTreeSql.walk] Invalid 'engine' | Got: ${engine}`,\n });\n }\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-connectors",
3
- "version": "0.4.7-1",
3
+ "version": "0.4.7-2",
4
4
  "description": "Datasource and repository connectors for the IGNIS framework: the engine-neutral relational and search tiers, plus Postgres, SQLite, PGlite, Typesense and Meilisearch behind sub-paths.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -97,15 +97,15 @@
97
97
  },
98
98
  "dependencies": {
99
99
  "@venizia/ignis-filter": "0.4.6-1",
100
- "@venizia/ignis-helpers": "0.4.7-1",
100
+ "@venizia/ignis-helpers": "0.4.7-2",
101
101
  "@venizia/ignis-inversion": "0.4.6-1",
102
- "@venizia/ignis-kernel": "0.4.7-1",
102
+ "@venizia/ignis-kernel": "0.4.7-2",
103
103
  "zod": "^4.6.7"
104
104
  },
105
105
  "devDependencies": {
106
106
  "@types/bun": "^1.4.3",
107
107
  "@types/pg": "^8.23.1",
108
- "@venizia/dev-configs": "0.4.7-1",
108
+ "@venizia/dev-configs": "0.4.7-2",
109
109
  "eslint": "^10.13.0",
110
110
  "oxlint": "1.89.0",
111
111
  "oxlint-tsgolint": "7.0.2004",