@webiny/api-core-sql 0.0.0-unstable.d0f34a8194 → 0.0.0-unstable.e1999482d0

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.
Files changed (80) hide show
  1. package/TableManager.d.ts +30 -12
  2. package/TableManager.js +34 -30
  3. package/TableManager.js.map +1 -1
  4. package/adminUsers/index.js +58 -14
  5. package/adminUsers/index.js.map +1 -1
  6. package/connection/SqlConnectionFeature.d.ts +28 -0
  7. package/connection/SqlConnectionFeature.js +26 -0
  8. package/connection/SqlConnectionFeature.js.map +1 -0
  9. package/connection/index.d.ts +2 -0
  10. package/connection/index.js +1 -0
  11. package/connectionRetry/index.d.ts +3 -0
  12. package/connectionRetry/index.js +2 -0
  13. package/connectionRetry/isConnectionError.d.ts +1 -0
  14. package/connectionRetry/isConnectionError.js +28 -0
  15. package/connectionRetry/isConnectionError.js.map +1 -0
  16. package/connectionRetry/withPgConnectionRetry.d.ts +49 -0
  17. package/connectionRetry/withPgConnectionRetry.js +175 -0
  18. package/connectionRetry/withPgConnectionRetry.js.map +1 -0
  19. package/coreStorage/CoreSqlSchemaSetup.d.ts +18 -0
  20. package/coreStorage/CoreSqlSchemaSetup.js +35 -0
  21. package/coreStorage/CoreSqlSchemaSetup.js.map +1 -0
  22. package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +15 -0
  23. package/coreStorage/SqlApiCoreStorageOperationsFactory.js +32 -0
  24. package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -0
  25. package/coreStorage/feature.d.ts +13 -0
  26. package/coreStorage/feature.js +13 -0
  27. package/coreStorage/feature.js.map +1 -0
  28. package/coreStorage/index.d.ts +1 -0
  29. package/coreStorage/index.js +1 -0
  30. package/createApiCoreSql.d.ts +13 -1
  31. package/createApiCoreSql.js +8 -8
  32. package/createApiCoreSql.js.map +1 -1
  33. package/index.d.ts +16 -3
  34. package/index.js +10 -2
  35. package/index.js.map +1 -1
  36. package/keyValueStore/index.js +19 -17
  37. package/keyValueStore/index.js.map +1 -1
  38. package/package.json +9 -8
  39. package/schemaConfig/abstractions.d.ts +22 -0
  40. package/schemaConfig/abstractions.js +5 -0
  41. package/schemaConfig/abstractions.js.map +1 -0
  42. package/schemaConfig/index.d.ts +1 -0
  43. package/schemaConfig/index.js +1 -0
  44. package/schemaMemory/ensureTable.d.ts +35 -0
  45. package/schemaMemory/ensureTable.js +46 -0
  46. package/schemaMemory/ensureTable.js.map +1 -0
  47. package/schemaMemory/getConnectionKey.d.ts +8 -0
  48. package/schemaMemory/getConnectionKey.js +15 -0
  49. package/schemaMemory/getConnectionKey.js.map +1 -0
  50. package/schemaMemory/getSchemaMemory.d.ts +37 -0
  51. package/schemaMemory/getSchemaMemory.js +53 -0
  52. package/schemaMemory/getSchemaMemory.js.map +1 -0
  53. package/schemaSetup/abstractions.d.ts +67 -0
  54. package/schemaSetup/abstractions.js +6 -0
  55. package/schemaSetup/abstractions.js.map +1 -0
  56. package/schemaSetup/index.d.ts +4 -0
  57. package/schemaSetup/index.js +2 -0
  58. package/schemaSetup/runSchemaSetupSteps.d.ts +34 -0
  59. package/schemaSetup/runSchemaSetupSteps.js +35 -0
  60. package/schemaSetup/runSchemaSetupSteps.js.map +1 -0
  61. package/security/index.js +47 -47
  62. package/security/index.js.map +1 -1
  63. package/serviceDiscovery/SqlServiceManifestLoader.d.ts +1 -1
  64. package/serviceDiscovery/SqlServiceManifestLoader.js +3 -8
  65. package/serviceDiscovery/SqlServiceManifestLoader.js.map +1 -1
  66. package/serviceDiscovery/SqlServiceManifestWriter.d.ts +16 -0
  67. package/serviceDiscovery/SqlServiceManifestWriter.js +27 -0
  68. package/serviceDiscovery/SqlServiceManifestWriter.js.map +1 -0
  69. package/serviceDiscovery/index.d.ts +1 -0
  70. package/serviceDiscovery/index.js +1 -0
  71. package/serviceDiscovery/serviceManifestsTable.d.ts +13 -0
  72. package/serviceDiscovery/serviceManifestsTable.js +8 -0
  73. package/serviceDiscovery/serviceManifestsTable.js.map +1 -0
  74. package/storage/types.d.ts +22 -0
  75. package/storage/types.js +0 -0
  76. package/tenancy/index.js +9 -9
  77. package/tenancy/index.js.map +1 -1
  78. package/ApiCoreSqlFeature.d.ts +0 -18
  79. package/ApiCoreSqlFeature.js +0 -18
  80. package/ApiCoreSqlFeature.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"keyValueStore/index.js","sources":["../../src/keyValueStore/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { IKeyValueStorageOperations } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueStoreSetOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueDeleteOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { KeyValueComparable } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport { WebinyError } from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\n\nconst TABLE_NAME = \"webiny_core_key_value\";\n/*\n * Which collection each listable record belongs to. A table of its own because `ensure` only creates\n * tables, so an existing key-value table cannot gain a column, and because a record in no collection,\n * like most of them, then costs nothing here.\n */\nconst COLLECTION_TABLE_NAME = \"webiny_core_key_value_collection\";\n\ninterface IKeyValueRow {\n scopedKey: string;\n key: string;\n scope: string;\n value: string;\n expiresAt: Date | null;\n}\n\ninterface IKeyValueCollectionRow {\n scopedKey: string;\n scope: string;\n collection: string;\n key: string;\n}\n\n/*\n * An `exists: false` insert fails on the primary key when a live record holds the key. The code names\n * that violation per driver: Postgres, MySQL, and SQLite (better-sqlite3).\n */\nconst isPrimaryKeyViolation = (error: unknown): boolean => {\n const code = (error as { code?: unknown })?.code;\n return (\n code === \"23505\" ||\n code === \"ER_DUP_ENTRY\" ||\n code === \"SQLITE_CONSTRAINT_PRIMARYKEY\" ||\n code === \"SQLITE_CONSTRAINT_UNIQUE\"\n );\n};\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): IKeyValueStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureTable = async () => {\n await tableManager.ensure(TABLE_NAME, table => {\n table.text(\"scopedKey\").primary().notNullable();\n table.text(\"key\").notNullable();\n table.text(\"scope\").notNullable();\n table.text(\"value\").notNullable();\n table.datetime(\"expiresAt\");\n });\n await tableManager.ensure(COLLECTION_TABLE_NAME, table => {\n table.text(\"scopedKey\").primary().notNullable();\n table.text(\"scope\").notNullable();\n table.text(\"collection\").notNullable();\n table.text(\"key\").notNullable();\n table.index([\"scope\", \"collection\"]);\n });\n };\n\n const query = (trx: Knex = knex) => {\n return trx<IKeyValueRow>(tableManager.resolve(TABLE_NAME));\n };\n\n const collectionQuery = (trx: Knex = knex) => {\n return trx<IKeyValueCollectionRow>(tableManager.resolve(COLLECTION_TABLE_NAME));\n };\n\n /*\n * The key compared byte by byte, as DynamoDB compares sort keys, so both stores page in the same\n * order. SQLite compares text that way already. Postgres and MySQL use the column's collation,\n * which can be a locale that ignores case and punctuation, unless told otherwise. `??` leaves\n * quoting the column to the dialect.\n */\n const binaryKey = (column: string): { sql: string; bindings: string[] } => {\n switch (knex.client.dialect) {\n case \"postgresql\":\n return { sql: `?? COLLATE \"C\"`, bindings: [column] };\n case \"mysql\":\n case \"mysql2\":\n return { sql: \"BINARY ??\", bindings: [column] };\n default:\n return { sql: \"??\", bindings: [column] };\n }\n };\n\n const createScopedKey = (key: string, scope: string): string => {\n return `${scope}:${key}`;\n };\n\n /*\n * Narrows a query to the live record, and with `equals` to one holding that value. The value is\n * compared as stored, JSON text, byte for byte: a case-insensitive collation would let \"P1\"\n * match \"p1\".\n */\n const whereLive = (\n builder: Knex.QueryBuilder<IKeyValueRow>,\n scopedKey: string,\n equals: KeyValueComparable | undefined\n ) => {\n const now = new Date();\n builder\n .where(\"scopedKey\", scopedKey)\n .where(live => live.whereNull(\"expiresAt\").orWhere(\"expiresAt\", \">\", now));\n if (equals === undefined) {\n return builder;\n }\n const expectedValue = JSON.stringify(equals);\n const binaryValue = binaryKey(\"value\");\n return builder.whereRaw(`${binaryValue.sql} = ?`, [...binaryValue.bindings, expectedValue]);\n };\n\n return {\n async get(key: string, scope: string) {\n await ensureTable();\n\n try {\n const scopedKey = createScopedKey(key, scope);\n const row = await query().where(\"scopedKey\", scopedKey).first();\n\n if (!row) {\n return null;\n }\n\n if (row.expiresAt && new Date(row.expiresAt) <= new Date()) {\n await knex.transaction(async trx => {\n await query(trx).where(\"scopedKey\", scopedKey).delete();\n await collectionQuery(trx).where(\"scopedKey\", scopedKey).delete();\n });\n return null;\n }\n\n return {\n key,\n value: JSON.parse(row.value)\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not get key-value record.\",\n code: \"GET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n },\n\n async set(key: string, value: any, scope: string, options?: IKeyValueStoreSetOptions) {\n await ensureTable();\n\n const scopedKey = createScopedKey(key, scope);\n const row: IKeyValueRow = {\n scopedKey,\n key,\n scope,\n value: JSON.stringify(value),\n expiresAt: options?.expiresAt ?? null\n };\n const collection = options?.collection;\n const condition = options?.condition;\n\n /*\n * Like DynamoDB's put, a write without a collection takes the record out of the one it\n * was in, so both stores agree on what `list` returns.\n */\n const writeCollection = async (trx: Knex) => {\n if (collection) {\n await collectionQuery(trx)\n .insert({ scopedKey, scope, collection, key })\n .onConflict(\"scopedKey\")\n .merge();\n return;\n }\n await collectionQuery(trx).where(\"scopedKey\", scopedKey).delete();\n };\n\n try {\n if (condition?.exists === false) {\n /*\n * An expired record counts as absent, so it is cleared first. The insert then\n * fails on the primary key exactly when a live record holds the key, and the\n * transaction rolls back with it. Of two callers racing, the database lets one\n * insert through.\n *\n * The delete runs only when an expired record is there: on MySQL a delete that\n * matches nothing locks the gap, and two racing callers holding that lock would\n * deadlock on the insert instead of one losing on the primary key.\n */\n await knex.transaction(async trx => {\n const now = new Date();\n const expired = await query(trx)\n .where(\"scopedKey\", scopedKey)\n .whereNotNull(\"expiresAt\")\n .where(\"expiresAt\", \"<=\", now)\n .first(\"scopedKey\");\n if (expired) {\n await query(trx)\n .where(\"scopedKey\", scopedKey)\n .where(\"expiresAt\", \"<=\", now)\n .delete();\n }\n await query(trx).insert(row);\n await writeCollection(trx);\n });\n return true;\n }\n\n // `exists: true` or `equals`: only a live record, and the right one, is replaced.\n if (condition) {\n return await knex.transaction(async trx => {\n const records = query(trx);\n const updated = await whereLive(\n records,\n scopedKey,\n condition.equals\n ).update({\n value: row.value,\n expiresAt: row.expiresAt\n });\n if (updated === 0) {\n return false;\n }\n await writeCollection(trx);\n return true;\n });\n }\n\n await knex.transaction(async trx => {\n await query(trx).insert(row).onConflict(\"scopedKey\").merge();\n await writeCollection(trx);\n });\n return true;\n } catch (err) {\n if (condition?.exists === false && isPrimaryKeyViolation(err)) {\n return false;\n }\n throw WebinyError.from(err, {\n message: \"Could not set key-value record.\",\n code: \"SET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n },\n\n async list({ collection, scope, limit, reverse, after }) {\n await ensureTable();\n\n try {\n const builder = knex\n .from({ c: tableManager.resolve(COLLECTION_TABLE_NAME) })\n .join({ kv: tableManager.resolve(TABLE_NAME) }, \"kv.scopedKey\", \"c.scopedKey\")\n .where(\"c.scope\", scope)\n .where(\"c.collection\", collection)\n .select(\"kv.key\", \"kv.value\", \"kv.expiresAt\");\n\n const orderedKey = binaryKey(\"c.key\");\n if (after !== undefined) {\n builder.whereRaw(`${orderedKey.sql} ${reverse ? \"<\" : \">\"} ?`, [\n ...orderedKey.bindings,\n after\n ]);\n }\n\n // One extra row tells whether another page exists without a second, empty read.\n const rows: Pick<IKeyValueRow, \"key\" | \"value\" | \"expiresAt\">[] = await builder\n .orderByRaw(\n `${orderedKey.sql} ${reverse ? \"DESC\" : \"ASC\"}`,\n orderedKey.bindings\n )\n .limit(limit + 1);\n const page = rows.slice(0, limit);\n const now = new Date();\n\n return {\n items: page\n .filter(row => !row.expiresAt || new Date(row.expiresAt) > now)\n .map(row => ({ key: row.key, value: JSON.parse(row.value) })),\n lastKey: rows.length > limit ? page[page.length - 1].key : null\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list key-value records.\",\n code: \"LIST_KEY_VALUE_ERROR\",\n data: { collection, scope, after }\n });\n }\n },\n\n async delete(key: string, scope: string, options?: IKeyValueDeleteOptions) {\n await ensureTable();\n\n const scopedKey = createScopedKey(key, scope);\n\n try {\n return await knex.transaction(async trx => {\n const condition = options?.condition;\n if (condition) {\n const records = query(trx);\n const deleted = await whereLive(\n records,\n scopedKey,\n condition.equals\n ).delete();\n if (deleted === 0) {\n return false;\n }\n } else {\n await query(trx).where(\"scopedKey\", scopedKey).delete();\n }\n await collectionQuery(trx).where(\"scopedKey\", scopedKey).delete();\n return true;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete key-value record.\",\n code: \"DELETE_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n };\n};\n"],"names":["TABLE_NAME","COLLECTION_TABLE_NAME","isPrimaryKeyViolation","error","code","createStorageOperations","params","knex","tableManager","ensureTable","table","query","trx","collectionQuery","binaryKey","column","createScopedKey","key","scope","whereLive","builder","scopedKey","equals","now","Date","live","undefined","expectedValue","JSON","binaryValue","row","err","WebinyError","value","options","collection","condition","writeCollection","expired","records","updated","limit","reverse","after","orderedKey","rows","page","deleted"],"mappings":";AAQA,MAAMA,aAAa;AAMnB,MAAMC,wBAAwB;AAqB9B,MAAMC,wBAAwB,CAACC;IAC3B,MAAMC,OAAQD,OAA8B;IAC5C,OACIC,AAAS,YAATA,QACAA,AAAS,mBAATA,QACAA,AAAS,mCAATA,QACAA,AAAS,+BAATA;AAER;AAOO,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,cAAc;QAChB,MAAMD,aAAa,MAAM,CAACR,YAAYU,CAAAA;YAClCA,MAAM,I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I;wBAAYjB;wBAAOyB;oBAAM;gBACrC;YACJ;QACJ;QAEA,MAAM,QAAO1B,GAAW,EAAEC,KAAa,EAAEgB,OAAgC;YACrE,MAAMzB;YAEN,MAAMY,YAAYL,gBAAgBC,KAAKC;YAEvC,IAAI;gBACA,OAAO,MAAMX,KAAK,WAAW,CAAC,OAAMK;oBAChC,MAAMwB,YAAYF,SAAS;oBAC3B,IAAIE,WAAW;wBACX,MAAMG,UAAU5B,MAAMC;wBACtB,MAAMmC,UAAU,MAAM5B,UAClBoB,SACAlB,WACAe,UAAU,MAAM,EAClB,MAAM;wBACR,IAAIW,AAAY,MAAZA,SACA,OAAO;oBAEf,OACI,MAAMpC,MAAMC,KAAK,KAAK,CAAC,aAAaS,WAAW,MAAM;oBAEzD,MAAMR,gBAAgBD,KAAK,KAAK,CAAC,aAAaS,WAAW,MAAM;oBAC/D,OAAO;gBACX;YACJ,EAAE,OAAOU,KAAK;gBACV,MAAMC,YAAY,IAAI,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;wBAAKC;oBAAM;gBACvB;YACJ;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"keyValueStore/index.js","sources":["../../src/keyValueStore/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { IKeyValueStorageOperations } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueStoreSetOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { IKeyValueDeleteOptions } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport type { KeyValueComparable } from \"@webiny/api-core/features/keyValueStore/abstractions.js\";\nimport { WebinyError } from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\n\nconst TABLE_NAME = \"webiny_core_key_value\";\n/*\n * Which collection each listable record belongs to. A table of its own because `ensure` only creates\n * tables, so an existing key-value table cannot gain a column, and because a record in no collection,\n * like most of them, then costs nothing here.\n */\nconst COLLECTION_TABLE_NAME = \"webiny_core_key_value_collection\";\n\ninterface IKeyValueRow {\n scopedKey: string;\n key: string;\n scope: string;\n value: string;\n expiresAt: Date | null;\n}\n\ninterface IKeyValueCollectionRow {\n scopedKey: string;\n scope: string;\n collection: string;\n key: string;\n}\n\n/*\n * An `exists: false` insert fails on the primary key when a live record holds the key. The code names\n * that violation per driver: Postgres, MySQL, and SQLite (better-sqlite3).\n */\nconst isPrimaryKeyViolation = (error: unknown): boolean => {\n const code = (error as { code?: unknown })?.code;\n return (\n code === \"23505\" ||\n code === \"ER_DUP_ENTRY\" ||\n code === \"SQLITE_CONSTRAINT_PRIMARYKEY\" ||\n code === \"SQLITE_CONSTRAINT_UNIQUE\"\n );\n};\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): IKeyValueStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureValuesTable = tableManager.define(TABLE_NAME, table => {\n table.text(\"scopedKey\").primary().notNullable();\n table.text(\"key\").notNullable();\n table.text(\"scope\").notNullable();\n table.text(\"value\").notNullable();\n table.datetime(\"expiresAt\");\n });\n const ensureCollectionTable = tableManager.define(COLLECTION_TABLE_NAME, table => {\n table.text(\"scopedKey\").primary().notNullable();\n table.text(\"scope\").notNullable();\n table.text(\"collection\").notNullable();\n table.text(\"key\").notNullable();\n table.index([\"scope\", \"collection\"]);\n });\n const ensureTable = async () => {\n await ensureValuesTable();\n await ensureCollectionTable();\n };\n\n const query = (trx: Knex = knex) => {\n return trx<IKeyValueRow>(tableManager.resolve(TABLE_NAME));\n };\n\n const collectionQuery = (trx: Knex = knex) => {\n return trx<IKeyValueCollectionRow>(tableManager.resolve(COLLECTION_TABLE_NAME));\n };\n\n /*\n * The key compared byte by byte, as DynamoDB compares sort keys, so both stores page in the same\n * order. SQLite compares text that way already. Postgres and MySQL use the column's collation,\n * which can be a locale that ignores case and punctuation, unless told otherwise. `??` leaves\n * quoting the column to the dialect.\n */\n const binaryKey = (column: string): { sql: string; bindings: string[] } => {\n switch (knex.client.dialect) {\n case \"postgresql\":\n return { sql: `?? COLLATE \"C\"`, bindings: [column] };\n case \"mysql\":\n case \"mysql2\":\n return { sql: \"BINARY ??\", bindings: [column] };\n default:\n return { sql: \"??\", bindings: [column] };\n }\n };\n\n const createScopedKey = (key: string, scope: string): string => {\n return `${scope}:${key}`;\n };\n\n /*\n * Narrows a query to the live record, and with `equals` to one holding that value. The value is\n * compared as stored, JSON text, byte for byte: a case-insensitive collation would let \"P1\"\n * match \"p1\".\n */\n const whereLive = (\n builder: Knex.QueryBuilder<IKeyValueRow>,\n scopedKey: string,\n equals: KeyValueComparable | undefined\n ) => {\n const now = new Date();\n builder\n .where(\"scopedKey\", scopedKey)\n .where(live => live.whereNull(\"expiresAt\").orWhere(\"expiresAt\", \">\", now));\n if (equals === undefined) {\n return builder;\n }\n const expectedValue = JSON.stringify(equals);\n const binaryValue = binaryKey(\"value\");\n return builder.whereRaw(`${binaryValue.sql} = ?`, [...binaryValue.bindings, expectedValue]);\n };\n\n return {\n async get(key: string, scope: string) {\n await ensureTable();\n\n try {\n const scopedKey = createScopedKey(key, scope);\n const row = await query().where(\"scopedKey\", scopedKey).first();\n\n if (!row) {\n return null;\n }\n\n if (row.expiresAt && new Date(row.expiresAt) <= new Date()) {\n await knex.transaction(async trx => {\n await query(trx).where(\"scopedKey\", scopedKey).delete();\n await collectionQuery(trx).where(\"scopedKey\", scopedKey).delete();\n });\n return null;\n }\n\n return {\n key,\n value: JSON.parse(row.value)\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not get key-value record.\",\n code: \"GET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n },\n\n async set(key: string, value: any, scope: string, options?: IKeyValueStoreSetOptions) {\n await ensureTable();\n\n const scopedKey = createScopedKey(key, scope);\n const row: IKeyValueRow = {\n scopedKey,\n key,\n scope,\n value: JSON.stringify(value),\n expiresAt: options?.expiresAt ?? null\n };\n const collection = options?.collection;\n const condition = options?.condition;\n\n /*\n * Like DynamoDB's put, a write without a collection takes the record out of the one it\n * was in, so both stores agree on what `list` returns.\n */\n const writeCollection = async (trx: Knex) => {\n if (collection) {\n await collectionQuery(trx)\n .insert({ scopedKey, scope, collection, key })\n .onConflict(\"scopedKey\")\n .merge();\n return;\n }\n await collectionQuery(trx).where(\"scopedKey\", scopedKey).delete();\n };\n\n try {\n if (condition?.exists === false) {\n /*\n * An expired record counts as absent, so it is cleared first. The insert then\n * fails on the primary key exactly when a live record holds the key, and the\n * transaction rolls back with it. Of two callers racing, the database lets one\n * insert through.\n *\n * The delete runs only when an expired record is there: on MySQL a delete that\n * matches nothing locks the gap, and two racing callers holding that lock would\n * deadlock on the insert instead of one losing on the primary key.\n */\n await knex.transaction(async trx => {\n const now = new Date();\n const expired = await query(trx)\n .where(\"scopedKey\", scopedKey)\n .whereNotNull(\"expiresAt\")\n .where(\"expiresAt\", \"<=\", now)\n .first(\"scopedKey\");\n if (expired) {\n await query(trx)\n .where(\"scopedKey\", scopedKey)\n .where(\"expiresAt\", \"<=\", now)\n .delete();\n }\n await query(trx).insert(row);\n await writeCollection(trx);\n });\n return true;\n }\n\n // `exists: true` or `equals`: only a live record, and the right one, is replaced.\n if (condition) {\n return await knex.transaction(async trx => {\n const records = query(trx);\n const updated = await whereLive(\n records,\n scopedKey,\n condition.equals\n ).update({\n value: row.value,\n expiresAt: row.expiresAt\n });\n if (updated === 0) {\n return false;\n }\n await writeCollection(trx);\n return true;\n });\n }\n\n await knex.transaction(async trx => {\n await query(trx).insert(row).onConflict(\"scopedKey\").merge();\n await writeCollection(trx);\n });\n return true;\n } catch (err) {\n if (condition?.exists === false && isPrimaryKeyViolation(err)) {\n return false;\n }\n throw WebinyError.from(err, {\n message: \"Could not set key-value record.\",\n code: \"SET_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n },\n\n async list({ collection, scope, limit, reverse, after }) {\n await ensureTable();\n\n try {\n const builder = knex\n .from({ c: tableManager.resolve(COLLECTION_TABLE_NAME) })\n .join({ kv: tableManager.resolve(TABLE_NAME) }, \"kv.scopedKey\", \"c.scopedKey\")\n .where(\"c.scope\", scope)\n .where(\"c.collection\", collection)\n .select(\"kv.key\", \"kv.value\", \"kv.expiresAt\");\n\n const orderedKey = binaryKey(\"c.key\");\n if (after !== undefined) {\n builder.whereRaw(`${orderedKey.sql} ${reverse ? \"<\" : \">\"} ?`, [\n ...orderedKey.bindings,\n after\n ]);\n }\n\n // One extra row tells whether another page exists without a second, empty read.\n const rows: Pick<IKeyValueRow, \"key\" | \"value\" | \"expiresAt\">[] = await builder\n .orderByRaw(\n `${orderedKey.sql} ${reverse ? \"DESC\" : \"ASC\"}`,\n orderedKey.bindings\n )\n .limit(limit + 1);\n const page = rows.slice(0, limit);\n const now = new Date();\n\n return {\n items: page\n .filter(row => !row.expiresAt || new Date(row.expiresAt) > now)\n .map(row => ({ key: row.key, value: JSON.parse(row.value) })),\n lastKey: rows.length > limit ? page[page.length - 1].key : null\n };\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list key-value records.\",\n code: \"LIST_KEY_VALUE_ERROR\",\n data: { collection, scope, after }\n });\n }\n },\n\n async delete(key: string, scope: string, options?: IKeyValueDeleteOptions) {\n await ensureTable();\n\n const scopedKey = createScopedKey(key, scope);\n\n try {\n return await knex.transaction(async trx => {\n const condition = options?.condition;\n if (condition) {\n const records = query(trx);\n const deleted = await whereLive(\n records,\n scopedKey,\n condition.equals\n ).delete();\n if (deleted === 0) {\n return false;\n }\n } else {\n await query(trx).where(\"scopedKey\", scopedKey).delete();\n }\n await collectionQuery(trx).where(\"scopedKey\", scopedKey).delete();\n return true;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete key-value record.\",\n code: \"DELETE_KEY_VALUE_ERROR\",\n data: { key, scope }\n });\n }\n }\n };\n};\n"],"names":["TABLE_NAME","COLLECTION_TABLE_NAME","isPrimaryKeyViolation","error","code","createStorageOperations","params","knex","tableManager","ensureValuesTable","table","ensureCollectionTable","ensureTable","query","trx","collectionQuery","binaryKey","column","createScopedKey","key","scope","whereLive","builder","scopedKey","equals","now","Date","live","undefined","expectedValue","JSON","binaryValue","row","err","WebinyError","value","options","collection","condition","writeCollection","expired","records","updated","limit","reverse","after","orderedKey","rows","page","deleted"],"mappings":";AAQA,MAAMA,aAAa;AAMnB,MAAMC,wBAAwB;AAqB9B,MAAMC,wBAAwB,CAACC;IAC3B,MAAMC,OAAQD,OAA8B;IAC5C,OACIC,AAAS,YAATA,QACAA,AAAS,mBAATA,QACAA,AAAS,mCAATA,QACAA,AAAS,+BAATA;AAER;AAOO,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,oBAAoBD,aAAa,MAAM,CAACR,YAAYU,CAAAA;QACtDA,MAAM,IAAI,CAAC,aAAa,OAAO,GAAG,WAAW;QAC7CA,MAAM,IAAI,CAAC,OAAO,WAAW;QAC7BA,MAAM,IAAI,CAAC,SAAS,WAAW;QAC/BA,MAAM,IAAI,CAAC,SAAS,WAAW;QAC/BA,MAAM,QAAQ,CAAC;IACnB;IACA,MAAMC,wBAAwBH,aAAa,MAAM,CAACP,uBAAuBS,CAAAA;QACrEA,MAAM,IAAI,CAAC,aAAa,OAAO,GAAG,WAAW;QAC7CA,MAAM,IAAI,CAAC,SAAS,WAAW;QAC/BA,MAAM,IAAI,CAAC,cAAc,WAAW;QACpCA,MAAM,IAAI,CAAC,OAAO,WAAW;QAC7BA,MAAM,KAAK,CAAC;YAAC;YAAS;SAAa;IACvC;IACA,MAAME,cAAc;QAChB,MAAMH;QACN,MAAME;IACV;IAEA,MAAME,QAAQ,CAACC,MAAYP,IAAI,GACpBO,IAAkBN,aAAa,OAAO,CAACR;IAGlD,MAAMe,kBAAkB,CAACD,MAAYP,IAAI,GAC9BO,IAA4BN,aAAa,OAAO,CAACP;IAS5D,MAAMe,YAAY,CAACC;QACf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AM;oBACN,MAAM;wBAAEd;wBAAKC;oBAAM;gBACvB;YACJ;QACJ;IACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-core-sql",
3
- "version": "0.0.0-unstable.d0f34a8194",
3
+ "version": "0.0.0-unstable.e1999482d0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./index.js",
@@ -21,17 +21,18 @@
21
21
  "author": "Webiny Ltd.",
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "@webiny/api-core": "0.0.0-unstable.d0f34a8194",
25
- "@webiny/error": "0.0.0-unstable.d0f34a8194",
26
- "@webiny/feature": "0.0.0-unstable.d0f34a8194",
27
- "@webiny/handler": "0.0.0-unstable.d0f34a8194",
24
+ "@webiny/api-core": "0.0.0-unstable.e1999482d0",
25
+ "@webiny/error": "0.0.0-unstable.e1999482d0",
26
+ "@webiny/feature": "0.0.0-unstable.e1999482d0",
27
+ "@webiny/handler": "0.0.0-unstable.e1999482d0",
28
28
  "knex": "3.3.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@webiny/build-tools": "0.0.0-unstable.d0f34a8194",
32
- "better-sqlite3": "13.0.3",
31
+ "@webiny/build-tools": "0.0.0-unstable.e1999482d0",
32
+ "better-sqlite3": "13.2.0",
33
+ "pg": "8.23.1",
33
34
  "typescript": "7.0.2",
34
- "vitest": "4.1.11"
35
+ "vitest": "5.1.1"
35
36
  },
36
37
  "publishConfig": {
37
38
  "access": "public"
@@ -0,0 +1,22 @@
1
+ export interface ISqlSchemaConfig {
2
+ /**
3
+ * Whether the schema was set up before the API took traffic (the storage's schema setup ran).
4
+ * When it is, storage code never checks for or creates tables at runtime: no catalog queries
5
+ * and no DDL on a cold start. When it isn't, each table is checked and created on first use.
6
+ */
7
+ isManaged(): boolean;
8
+ /**
9
+ * The prefix of every table the storage uses. Modules registered after the storage (the
10
+ * Postgres CMS and folder catalog) name their tables with it.
11
+ */
12
+ readonly tableNamePrefix?: string;
13
+ }
14
+ /**
15
+ * How the SQL storage finds its tables, set by the storage that registers it. Optional for the
16
+ * code that only reads `isManaged()`: when it isn't registered, tables are checked and created on
17
+ * first use.
18
+ */
19
+ export declare const SqlSchemaConfig: import("@webiny/di").Abstraction<ISqlSchemaConfig>;
20
+ export declare namespace SqlSchemaConfig {
21
+ type Interface = ISqlSchemaConfig;
22
+ }
@@ -0,0 +1,5 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ const SqlSchemaConfig = createAbstraction("Db/Sql/SchemaConfig");
3
+ export { SqlSchemaConfig };
4
+
5
+ //# sourceMappingURL=abstractions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaConfig/abstractions.js","sources":["../../src/schemaConfig/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\n\nexport interface ISqlSchemaConfig {\n /**\n * Whether the schema was set up before the API took traffic (the storage's schema setup ran).\n * When it is, storage code never checks for or creates tables at runtime: no catalog queries\n * and no DDL on a cold start. When it isn't, each table is checked and created on first use.\n */\n isManaged(): boolean;\n /**\n * The prefix of every table the storage uses. Modules registered after the storage (the\n * Postgres CMS and folder catalog) name their tables with it.\n */\n readonly tableNamePrefix?: string;\n}\n\n/**\n * How the SQL storage finds its tables, set by the storage that registers it. Optional for the\n * code that only reads `isManaged()`: when it isn't registered, tables are checked and created on\n * first use.\n */\nexport const SqlSchemaConfig = createAbstraction<ISqlSchemaConfig>(\"Db/Sql/SchemaConfig\");\n\nexport namespace SqlSchemaConfig {\n export type Interface = ISqlSchemaConfig;\n}\n"],"names":["SqlSchemaConfig","createAbstraction"],"mappings":";AAqBO,MAAMA,kBAAkBC,kBAAoC"}
@@ -0,0 +1 @@
1
+ export { SqlSchemaConfig } from "./abstractions.js";
@@ -0,0 +1 @@
1
+ export { SqlSchemaConfig } from "./abstractions.js";
@@ -0,0 +1,35 @@
1
+ import type { Knex } from "knex";
2
+ import type { ISchemaMemory } from "./getSchemaMemory.js";
3
+ export type TableCreator = (table: Knex.CreateTableBuilder) => void;
4
+ /**
5
+ * Brings a table that already existed up to date (the creator only runs for new tables).
6
+ * Must be idempotent: it runs once per process for every existing table.
7
+ */
8
+ export type TableUpgrade = (knex: Knex, tableName: string) => Promise<void>;
9
+ export interface EnsureTableParams {
10
+ /** The connection or transaction to check and create the table on. */
11
+ knex: Knex;
12
+ /** What the process knows about the tables this one belongs to. */
13
+ memory: ISchemaMemory;
14
+ tableName: string;
15
+ create: TableCreator;
16
+ upgrade?: TableUpgrade;
17
+ }
18
+ /**
19
+ * Creates the table if it doesn't exist yet, once per process: a table the memory knows is skipped,
20
+ * and concurrent callers on the same handle wait for one check. What a transaction creates is
21
+ * remembered only by `recordTable` after it commits, never here, and nothing started before the
22
+ * memory was reset is recorded after it.
23
+ */
24
+ export declare function ensureTable(params: EnsureTableParams): Promise<void>;
25
+ /**
26
+ * Records that the table exists, unless `knex` is a transaction: it can still roll back, and the
27
+ * table with it, so only a committed table is known.
28
+ */
29
+ export declare function recordTable(knex: Knex, memory: ISchemaMemory, tableName: string): void;
30
+ /**
31
+ * Creates the table if it doesn't exist, or runs `upgrade` on it if it does. Another process (or
32
+ * connection) may create it between the check and the create: if it exists after a failed create,
33
+ * that's success, and that process created it with the current creator.
34
+ */
35
+ export declare function createTableIfMissing(knex: Knex, tableName: string, create: TableCreator, upgrade?: TableUpgrade): Promise<void>;
@@ -0,0 +1,46 @@
1
+ const inFlight = new Map();
2
+ const transactionIds = new WeakMap();
3
+ let lastTransactionId = 0;
4
+ const handleOf = (knex)=>{
5
+ if (!knex.isTransaction) return "connection";
6
+ let id = transactionIds.get(knex);
7
+ if (void 0 === id) {
8
+ lastTransactionId += 1;
9
+ id = lastTransactionId;
10
+ transactionIds.set(knex, id);
11
+ }
12
+ return `trx${id}`;
13
+ };
14
+ function ensureTable(params) {
15
+ const { knex, memory, tableName, create, upgrade } = params;
16
+ if (memory.known.has(tableName)) return Promise.resolve();
17
+ const generation = memory.generation;
18
+ const key = `${memory.key}#${generation}:${tableName}:${handleOf(knex)}`;
19
+ const pending = inFlight.get(key);
20
+ if (pending) return pending;
21
+ const check = createTableIfMissing(knex, tableName, create, upgrade).then(()=>{
22
+ if (memory.generation === generation) recordTable(knex, memory, tableName);
23
+ }).finally(()=>{
24
+ if (inFlight.get(key) === check) inFlight.delete(key);
25
+ });
26
+ inFlight.set(key, check);
27
+ return check;
28
+ }
29
+ function recordTable(knex, memory, tableName) {
30
+ if (!knex.isTransaction) memory.known.add(tableName);
31
+ }
32
+ async function createTableIfMissing(knex, tableName, create, upgrade) {
33
+ if (await knex.schema.hasTable(tableName)) {
34
+ if (upgrade) await upgrade(knex, tableName);
35
+ return;
36
+ }
37
+ try {
38
+ await knex.schema.createTable(tableName, create);
39
+ } catch (error) {
40
+ if (await knex.schema.hasTable(tableName)) return;
41
+ throw error;
42
+ }
43
+ }
44
+ export { createTableIfMissing, ensureTable, recordTable };
45
+
46
+ //# sourceMappingURL=ensureTable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/ensureTable.js","sources":["../../src/schemaMemory/ensureTable.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { ISchemaMemory } from \"./getSchemaMemory.js\";\n\nexport type TableCreator = (table: Knex.CreateTableBuilder) => void;\n\n/**\n * Brings a table that already existed up to date (the creator only runs for new tables).\n * Must be idempotent: it runs once per process for every existing table.\n */\nexport type TableUpgrade = (knex: Knex, tableName: string) => Promise<void>;\n\nexport interface EnsureTableParams {\n /** The connection or transaction to check and create the table on. */\n knex: Knex;\n /** What the process knows about the tables this one belongs to. */\n memory: ISchemaMemory;\n tableName: string;\n create: TableCreator;\n upgrade?: TableUpgrade;\n}\n\n/*\n * Checks in flight, per memory, table and handle, so concurrent first uses share one\n * hasTable+createTable instead of racing into \"table already exists\".\n */\nconst inFlight = new Map<string, Promise<void>>();\n\nconst transactionIds = new WeakMap<object, number>();\nlet lastTransactionId = 0;\n\n/*\n * Which handle a check runs on. A transaction shares its connection's key (`getConnectionKey`), but\n * a table it creates is visible to others only once it commits, and is gone if it rolls back. So a\n * check in a transaction is shared only with checks in that same transaction.\n */\nconst handleOf = (knex: Knex): string => {\n if (!knex.isTransaction) {\n return \"connection\";\n }\n let id = transactionIds.get(knex);\n if (id === undefined) {\n lastTransactionId += 1;\n id = lastTransactionId;\n transactionIds.set(knex, id);\n }\n return `trx${id}`;\n};\n\n/**\n * Creates the table if it doesn't exist yet, once per process: a table the memory knows is skipped,\n * and concurrent callers on the same handle wait for one check. What a transaction creates is\n * remembered only by `recordTable` after it commits, never here, and nothing started before the\n * memory was reset is recorded after it.\n */\nexport function ensureTable(params: EnsureTableParams): Promise<void> {\n const { knex, memory, tableName, create, upgrade } = params;\n if (memory.known.has(tableName)) {\n return Promise.resolve();\n }\n\n const generation = memory.generation;\n const key = `${memory.key}#${generation}:${tableName}:${handleOf(knex)}`;\n const pending = inFlight.get(key);\n if (pending) {\n return pending;\n }\n\n const check: Promise<void> = createTableIfMissing(knex, tableName, create, upgrade)\n .then(() => {\n if (memory.generation === generation) {\n recordTable(knex, memory, tableName);\n }\n })\n .finally(() => {\n if (inFlight.get(key) === check) {\n inFlight.delete(key);\n }\n });\n inFlight.set(key, check);\n return check;\n}\n\n/**\n * Records that the table exists, unless `knex` is a transaction: it can still roll back, and the\n * table with it, so only a committed table is known.\n */\nexport function recordTable(knex: Knex, memory: ISchemaMemory, tableName: string): void {\n if (!knex.isTransaction) {\n memory.known.add(tableName);\n }\n}\n\n/**\n * Creates the table if it doesn't exist, or runs `upgrade` on it if it does. Another process (or\n * connection) may create it between the check and the create: if it exists after a failed create,\n * that's success, and that process created it with the current creator.\n */\nexport async function createTableIfMissing(\n knex: Knex,\n tableName: string,\n create: TableCreator,\n upgrade?: TableUpgrade\n): Promise<void> {\n if (await knex.schema.hasTable(tableName)) {\n if (upgrade) {\n await upgrade(knex, tableName);\n }\n return;\n }\n try {\n await knex.schema.createTable(tableName, create);\n } catch (error) {\n if (await knex.schema.hasTable(tableName)) {\n return;\n }\n throw error;\n }\n}\n"],"names":["inFlight","Map","transactionIds","WeakMap","lastTransactionId","handleOf","knex","id","undefined","ensureTable","params","memory","tableName","create","upgrade","Promise","generation","key","pending","check","createTableIfMissing","recordTable","error"],"mappings":"AAyBA,MAAMA,WAAW,IAAIC;AAErB,MAAMC,iBAAiB,IAAIC;AAC3B,IAAIC,oBAAoB;AAOxB,MAAMC,WAAW,CAACC;IACd,IAAI,CAACA,KAAK,aAAa,EACnB,OAAO;IAEX,IAAIC,KAAKL,eAAe,GAAG,CAACI;IAC5B,IAAIC,AAAOC,WAAPD,IAAkB;QAClBH,qBAAqB;QACrBG,KAAKH;QACLF,eAAe,GAAG,CAACI,MAAMC;IAC7B;IACA,OAAO,CAAC,GAAG,EAAEA,IAAI;AACrB;AAQO,SAASE,YAAYC,MAAyB;IACjD,MAAM,EAAEJ,IAAI,EAAEK,MAAM,EAAEC,SAAS,EAAEC,MAAM,EAAEC,OAAO,EAAE,GAAGJ;IACrD,IAAIC,OAAO,KAAK,CAAC,GAAG,CAACC,YACjB,OAAOG,QAAQ,OAAO;IAG1B,MAAMC,aAAaL,OAAO,UAAU;IACpC,MAAMM,MAAM,GAAGN,OAAO,GAAG,CAAC,CAAC,EAAEK,WAAW,CAAC,EAAEJ,UAAU,CAAC,EAAEP,SAASC,OAAO;IACxE,MAAMY,UAAUlB,SAAS,GAAG,CAACiB;IAC7B,IAAIC,SACA,OAAOA;IAGX,MAAMC,QAAuBC,qBAAqBd,MAAMM,WAAWC,QAAQC,SACtE,IAAI,CAAC;QACF,IAAIH,OAAO,UAAU,KAAKK,YACtBK,YAAYf,MAAMK,QAAQC;IAElC,GACC,OAAO,CAAC;QACL,IAAIZ,SAAS,GAAG,CAACiB,SAASE,OACtBnB,SAAS,MAAM,CAACiB;IAExB;IACJjB,SAAS,GAAG,CAACiB,KAAKE;IAClB,OAAOA;AACX;AAMO,SAASE,YAAYf,IAAU,EAAEK,MAAqB,EAAEC,SAAiB;IAC5E,IAAI,CAACN,KAAK,aAAa,EACnBK,OAAO,KAAK,CAAC,GAAG,CAACC;AAEzB;AAOO,eAAeQ,qBAClBd,IAAU,EACVM,SAAiB,EACjBC,MAAoB,EACpBC,OAAsB;IAEtB,IAAI,MAAMR,KAAK,MAAM,CAAC,QAAQ,CAACM,YAAY;QACvC,IAAIE,SACA,MAAMA,QAAQR,MAAMM;QAExB;IACJ;IACA,IAAI;QACA,MAAMN,KAAK,MAAM,CAAC,WAAW,CAACM,WAAWC;IAC7C,EAAE,OAAOS,OAAO;QACZ,IAAI,MAAMhB,KAAK,MAAM,CAAC,QAAQ,CAACM,YAC3B;QAEJ,MAAMU;IACV;AACJ"}
@@ -0,0 +1,8 @@
1
+ import type { Knex } from "knex";
2
+ /**
3
+ * A short id for the database a Knex instance connects to, for keys of the process's schema memory
4
+ * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:
5
+ * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances
6
+ * built separately get different ids, even for the same database.
7
+ */
8
+ export declare function getConnectionKey(knex: Knex): string;
@@ -0,0 +1,15 @@
1
+ const keys = new WeakMap();
2
+ let next = 0;
3
+ function getConnectionKey(knex) {
4
+ const identity = knex.client?.config ?? knex;
5
+ let key = keys.get(identity);
6
+ if (!key) {
7
+ next += 1;
8
+ key = `db${next}`;
9
+ keys.set(identity, key);
10
+ }
11
+ return key;
12
+ }
13
+ export { getConnectionKey };
14
+
15
+ //# sourceMappingURL=getConnectionKey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/getConnectionKey.js","sources":["../../src/schemaMemory/getConnectionKey.ts"],"sourcesContent":["import type { Knex } from \"knex\";\n\nconst keys = new WeakMap<object, string>();\nlet next = 0;\n\n/**\n * A short id for the database a Knex instance connects to, for keys of the process's schema memory\n * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:\n * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances\n * built separately get different ids, even for the same database.\n */\nexport function getConnectionKey(knex: Knex): string {\n const identity: object = knex.client?.config ?? knex;\n let key = keys.get(identity);\n if (!key) {\n next += 1;\n key = `db${next}`;\n keys.set(identity, key);\n }\n return key;\n}\n"],"names":["keys","WeakMap","next","getConnectionKey","knex","identity","key"],"mappings":"AAEA,MAAMA,OAAO,IAAIC;AACjB,IAAIC,OAAO;AAQJ,SAASC,iBAAiBC,IAAU;IACvC,MAAMC,WAAmBD,KAAK,MAAM,EAAE,UAAUA;IAChD,IAAIE,MAAMN,KAAK,GAAG,CAACK;IACnB,IAAI,CAACC,KAAK;QACNJ,QAAQ;QACRI,MAAM,CAAC,EAAE,EAAEJ,MAAM;QACjBF,KAAK,GAAG,CAACK,UAAUC;IACvB;IACA,OAAOA;AACX"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What this process knows about some tables: whether they were created, and a set of names it has
3
+ * checked (tables, tenants). Shared by every caller that asks for the same key, so it outlives the
4
+ * instance that learned it. The Postgres CMS and folder catalog are registered per request (they
5
+ * come with the project's extensions), so each request builds new instances: what they learn about
6
+ * the tables must live here, for the process.
7
+ */
8
+ export interface ISchemaMemory {
9
+ /** What the memory is of: the key it was asked for with. */
10
+ readonly key: string;
11
+ /**
12
+ * Runs `create` once per process; callers at the same time wait for the same run. A failed run is
13
+ * forgotten, so the next call tries again.
14
+ */
15
+ once(create: () => Promise<void>): Promise<void>;
16
+ /** Whether the tables are known to exist (`once` succeeded, or `markReady` was called). */
17
+ isReady(): boolean;
18
+ /** Records that the tables exist (created in a caller's transaction that has committed). */
19
+ markReady(): void;
20
+ /** Names this process has checked (tables, tenants). */
21
+ readonly known: Set<string>;
22
+ /**
23
+ * Goes up on every `reset()`. Work that started before a reset must not record what it learned
24
+ * after it: compare the value taken at the start with the current one.
25
+ */
26
+ readonly generation: number;
27
+ /** Forgets everything (test setups drop all tables between tests). */
28
+ reset(): void;
29
+ }
30
+ /**
31
+ * The process's memory for `key` (a table name, or a name that stands for a set of tables). Made on
32
+ * first use, with `onReset` run whenever it is reset; later callers get the same one.
33
+ *
34
+ * Each memory joins `globalThis.__sqlTableManagers` once, so test setups that drop all tables and
35
+ * call `reset()` on every entry reset it too.
36
+ */
37
+ export declare function getSchemaMemory(key: string, onReset?: () => void): ISchemaMemory;
@@ -0,0 +1,53 @@
1
+ class SchemaMemory {
2
+ constructor(key, onReset){
3
+ this.key = key;
4
+ this.onReset = onReset;
5
+ this.known = new Set();
6
+ this.ready = false;
7
+ this.currentGeneration = 0;
8
+ }
9
+ once(create) {
10
+ if (this.ready) return Promise.resolve();
11
+ if (this.pending) return this.pending;
12
+ const generation = this.currentGeneration;
13
+ const run = create().then(()=>{
14
+ if (this.currentGeneration === generation) this.ready = true;
15
+ }, (error)=>{
16
+ if (this.pending === run) this.pending = void 0;
17
+ throw error;
18
+ });
19
+ this.pending = run;
20
+ return run;
21
+ }
22
+ get generation() {
23
+ return this.currentGeneration;
24
+ }
25
+ isReady() {
26
+ return this.ready;
27
+ }
28
+ markReady() {
29
+ this.ready = true;
30
+ }
31
+ reset() {
32
+ this.currentGeneration += 1;
33
+ this.pending = void 0;
34
+ this.ready = false;
35
+ this.known.clear();
36
+ this.onReset?.();
37
+ }
38
+ }
39
+ const memories = new Map();
40
+ function getSchemaMemory(key, onReset) {
41
+ let memory = memories.get(key);
42
+ if (!memory) {
43
+ memory = new SchemaMemory(key, onReset);
44
+ memories.set(key, memory);
45
+ const g = globalThis;
46
+ const managers = g.__sqlTableManagers ??= [];
47
+ managers.push(memory);
48
+ }
49
+ return memory;
50
+ }
51
+ export { getSchemaMemory };
52
+
53
+ //# sourceMappingURL=getSchemaMemory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaMemory/getSchemaMemory.js","sources":["../../src/schemaMemory/getSchemaMemory.ts"],"sourcesContent":["/**\n * What this process knows about some tables: whether they were created, and a set of names it has\n * checked (tables, tenants). Shared by every caller that asks for the same key, so it outlives the\n * instance that learned it. The Postgres CMS and folder catalog are registered per request (they\n * come with the project's extensions), so each request builds new instances: what they learn about\n * the tables must live here, for the process.\n */\nexport interface ISchemaMemory {\n /** What the memory is of: the key it was asked for with. */\n readonly key: string;\n /**\n * Runs `create` once per process; callers at the same time wait for the same run. A failed run is\n * forgotten, so the next call tries again.\n */\n once(create: () => Promise<void>): Promise<void>;\n /** Whether the tables are known to exist (`once` succeeded, or `markReady` was called). */\n isReady(): boolean;\n /** Records that the tables exist (created in a caller's transaction that has committed). */\n markReady(): void;\n /** Names this process has checked (tables, tenants). */\n readonly known: Set<string>;\n /**\n * Goes up on every `reset()`. Work that started before a reset must not record what it learned\n * after it: compare the value taken at the start with the current one.\n */\n readonly generation: number;\n /** Forgets everything (test setups drop all tables between tests). */\n reset(): void;\n}\n\nclass SchemaMemory implements ISchemaMemory {\n public readonly known = new Set<string>();\n private pending?: Promise<void>;\n private ready = false;\n private currentGeneration = 0;\n\n public constructor(\n public readonly key: string,\n private readonly onReset?: () => void\n ) {}\n\n public once(create: () => Promise<void>): Promise<void> {\n if (this.ready) {\n return Promise.resolve();\n }\n if (this.pending) {\n return this.pending;\n }\n // A run that ends after a reset() must neither mark the tables ready nor clear a newer run.\n const generation = this.currentGeneration;\n const run: Promise<void> = create().then(\n () => {\n if (this.currentGeneration === generation) {\n this.ready = true;\n }\n },\n error => {\n if (this.pending === run) {\n this.pending = undefined;\n }\n throw error;\n }\n );\n this.pending = run;\n return run;\n }\n\n public get generation(): number {\n return this.currentGeneration;\n }\n\n public isReady(): boolean {\n return this.ready;\n }\n\n public markReady(): void {\n this.ready = true;\n }\n\n public reset(): void {\n this.currentGeneration += 1;\n this.pending = undefined;\n this.ready = false;\n this.known.clear();\n this.onReset?.();\n }\n}\n\nconst memories = new Map<string, SchemaMemory>();\n\n/**\n * The process's memory for `key` (a table name, or a name that stands for a set of tables). Made on\n * first use, with `onReset` run whenever it is reset; later callers get the same one.\n *\n * Each memory joins `globalThis.__sqlTableManagers` once, so test setups that drop all tables and\n * call `reset()` on every entry reset it too.\n */\nexport function getSchemaMemory(key: string, onReset?: () => void): ISchemaMemory {\n let memory = memories.get(key);\n if (!memory) {\n memory = new SchemaMemory(key, onReset);\n memories.set(key, memory);\n const g = globalThis as Record<string, unknown>;\n const managers = (g.__sqlTableManagers ??= []) as ISchemaMemory[];\n managers.push(memory);\n }\n return memory;\n}\n"],"names":["SchemaMemory","key","onReset","Set","create","Promise","generation","run","error","undefined","memories","Map","getSchemaMemory","memory","g","globalThis","managers"],"mappings":"AA8BA,MAAMA;IAMF,YACoBC,GAAW,EACVC,OAAoB,CACvC;aAFkBD,GAAG,GAAHA;aACCC,OAAO,GAAPA;aAPL,KAAK,GAAG,IAAIC;aAEpB,KAAK,GAAG;aACR,iBAAiB,GAAG;IAKzB;IAEI,KAAKC,MAA2B,EAAiB;QACpD,IAAI,IAAI,CAAC,KAAK,EACV,OAAOC,QAAQ,OAAO;QAE1B,IAAI,IAAI,CAAC,OAAO,EACZ,OAAO,IAAI,CAAC,OAAO;QAGvB,MAAMC,aAAa,IAAI,CAAC,iBAAiB;QACzC,MAAMC,MAAqBH,SAAS,IAAI,CACpC;YACI,IAAI,IAAI,CAAC,iBAAiB,KAAKE,YAC3B,IAAI,CAAC,KAAK,GAAG;QAErB,GACAE,CAAAA;YACI,IAAI,IAAI,CAAC,OAAO,KAAKD,KACjB,IAAI,CAAC,OAAO,GAAGE;YAEnB,MAAMD;QACV;QAEJ,IAAI,CAAC,OAAO,GAAGD;QACf,OAAOA;IACX;IAEA,IAAW,aAAqB;QAC5B,OAAO,IAAI,CAAC,iBAAiB;IACjC;IAEO,UAAmB;QACtB,OAAO,IAAI,CAAC,KAAK;IACrB;IAEO,YAAkB;QACrB,IAAI,CAAC,KAAK,GAAG;IACjB;IAEO,QAAc;QACjB,IAAI,CAAC,iBAAiB,IAAI;QAC1B,IAAI,CAAC,OAAO,GAAGE;QACf,IAAI,CAAC,KAAK,GAAG;QACb,IAAI,CAAC,KAAK,CAAC,KAAK;QAChB,IAAI,CAAC,OAAO;IAChB;AACJ;AAEA,MAAMC,WAAW,IAAIC;AASd,SAASC,gBAAgBX,GAAW,EAAEC,OAAoB;IAC7D,IAAIW,SAASH,SAAS,GAAG,CAACT;IAC1B,IAAI,CAACY,QAAQ;QACTA,SAAS,IAAIb,aAAaC,KAAKC;QAC/BQ,SAAS,GAAG,CAACT,KAAKY;QAClB,MAAMC,IAAIC;QACV,MAAMC,WAAYF,EAAE,kBAAkB,KAAK,EAAE;QAC7CE,SAAS,IAAI,CAACH;IAClB;IACA,OAAOA;AACX"}
@@ -0,0 +1,67 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ export interface ISqlSchemaSetup {
4
+ /**
5
+ * What the step sets up, as a short id (`core`, `websockets`, `cms`, `aco`). The runner reports
6
+ * the steps it ran by these names, and can check that a module it needs registered its step.
7
+ */
8
+ readonly name: string;
9
+ /**
10
+ * Brings the step's tables, indexes and functions up to date, whatever the schema-managed
11
+ * setting. Safe to run again: what already exists is kept. It never drops a table or a column,
12
+ * but a step may migrate in place. The Postgres CMS, for one, adds columns
13
+ * (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), changes column statistics, replaces its trigger
14
+ * functions, replaces the old count triggers and rebuilds the count rows from the search table
15
+ * once. The database user that runs setup needs the rights for that.
16
+ */
17
+ setup(): Promise<void>;
18
+ }
19
+ /**
20
+ * One step of the schema setup. Every part that owns tables registers its own step in a request's
21
+ * container: the storage's parts (core, audit logs, websockets), the transport's login storage, and
22
+ * the modules registered through the project's extensions (the Postgres CMS, the folder catalog).
23
+ * The setup runner runs every step it finds, so it doesn't need to know which modules exist.
24
+ */
25
+ export declare const SqlSchemaSetup: import("@webiny/di").Abstraction<ISqlSchemaSetup>;
26
+ export declare namespace SqlSchemaSetup {
27
+ type Interface = ISqlSchemaSetup;
28
+ }
29
+ /**
30
+ * What a request registers, as the transport builds every request's container: its storages (every
31
+ * `RequestStorage`), the API's features and the project's extensions. The schema setup builds its
32
+ * container with it, so it sets up exactly the tables the API uses, with their settings.
33
+ */
34
+ export interface ISqlSchemaSetupRequest {
35
+ register(container: Container): Promise<void>;
36
+ }
37
+ export interface SqlSchemaSetupRunParams {
38
+ /** Registers a request's parts in the setup's container. */
39
+ request: ISqlSchemaSetupRequest;
40
+ /**
41
+ * The connection to set the schema up on. Defaults to the storage's. The caller closes it.
42
+ * On Lambda, setup goes to the database's writer, not through the proxy the API uses.
43
+ */
44
+ knex?: Knex;
45
+ }
46
+ export interface ISqlSchemaSetupRunner {
47
+ /**
48
+ * Creates every table, index and function the API uses: opens the setup's transaction (on
49
+ * Postgres, behind an advisory lock), builds a container on it the way a request's is built,
50
+ * and runs every `SqlSchemaSetup` step in it. Keeps what exists, and is safe to run on every
51
+ * start or deploy (see `ISqlSchemaSetup.setup` for what a step may migrate). Afterwards the storage is schema-managed. Returns the names of the steps it
52
+ * ran.
53
+ */
54
+ run(params: SqlSchemaSetupRunParams): Promise<string[]>;
55
+ }
56
+ /**
57
+ * Runs the schema setup of the SQL storage. Each storage registers its implementation in the root:
58
+ * it knows how its engine runs DDL safely (a transaction behind an advisory lock on Postgres, a plain
59
+ * transaction on SQLite) and which modules it can't run without. The transport runs it before the
60
+ * API takes traffic: the standalone server at start, the Lambda API on its schema-setup event.
61
+ */
62
+ export declare const SqlSchemaSetupRunner: import("@webiny/di").Abstraction<ISqlSchemaSetupRunner>;
63
+ export declare namespace SqlSchemaSetupRunner {
64
+ type Interface = ISqlSchemaSetupRunner;
65
+ type Request = ISqlSchemaSetupRequest;
66
+ type RunParams = SqlSchemaSetupRunParams;
67
+ }
@@ -0,0 +1,6 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ const SqlSchemaSetup = createAbstraction("Db/Sql/SchemaSetup");
3
+ const SqlSchemaSetupRunner = createAbstraction("Db/Sql/SchemaSetupRunner");
4
+ export { SqlSchemaSetup, SqlSchemaSetupRunner };
5
+
6
+ //# sourceMappingURL=abstractions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaSetup/abstractions.js","sources":["../../src/schemaSetup/abstractions.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/feature/api\";\nimport { createAbstraction } from \"@webiny/feature/api\";\n\nexport interface ISqlSchemaSetup {\n /**\n * What the step sets up, as a short id (`core`, `websockets`, `cms`, `aco`). The runner reports\n * the steps it ran by these names, and can check that a module it needs registered its step.\n */\n readonly name: string;\n /**\n * Brings the step's tables, indexes and functions up to date, whatever the schema-managed\n * setting. Safe to run again: what already exists is kept. It never drops a table or a column,\n * but a step may migrate in place. The Postgres CMS, for one, adds columns\n * (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), changes column statistics, replaces its trigger\n * functions, replaces the old count triggers and rebuilds the count rows from the search table\n * once. The database user that runs setup needs the rights for that.\n */\n setup(): Promise<void>;\n}\n\n/**\n * One step of the schema setup. Every part that owns tables registers its own step in a request's\n * container: the storage's parts (core, audit logs, websockets), the transport's login storage, and\n * the modules registered through the project's extensions (the Postgres CMS, the folder catalog).\n * The setup runner runs every step it finds, so it doesn't need to know which modules exist.\n */\nexport const SqlSchemaSetup = createAbstraction<ISqlSchemaSetup>(\"Db/Sql/SchemaSetup\");\n\nexport namespace SqlSchemaSetup {\n export type Interface = ISqlSchemaSetup;\n}\n\n/**\n * What a request registers, as the transport builds every request's container: its storages (every\n * `RequestStorage`), the API's features and the project's extensions. The schema setup builds its\n * container with it, so it sets up exactly the tables the API uses, with their settings.\n */\nexport interface ISqlSchemaSetupRequest {\n register(container: Container): Promise<void>;\n}\n\nexport interface SqlSchemaSetupRunParams {\n /** Registers a request's parts in the setup's container. */\n request: ISqlSchemaSetupRequest;\n /**\n * The connection to set the schema up on. Defaults to the storage's. The caller closes it.\n * On Lambda, setup goes to the database's writer, not through the proxy the API uses.\n */\n knex?: Knex;\n}\n\nexport interface ISqlSchemaSetupRunner {\n /**\n * Creates every table, index and function the API uses: opens the setup's transaction (on\n * Postgres, behind an advisory lock), builds a container on it the way a request's is built,\n * and runs every `SqlSchemaSetup` step in it. Keeps what exists, and is safe to run on every\n * start or deploy (see `ISqlSchemaSetup.setup` for what a step may migrate). Afterwards the storage is schema-managed. Returns the names of the steps it\n * ran.\n */\n run(params: SqlSchemaSetupRunParams): Promise<string[]>;\n}\n\n/**\n * Runs the schema setup of the SQL storage. Each storage registers its implementation in the root:\n * it knows how its engine runs DDL safely (a transaction behind an advisory lock on Postgres, a plain\n * transaction on SQLite) and which modules it can't run without. The transport runs it before the\n * API takes traffic: the standalone server at start, the Lambda API on its schema-setup event.\n */\nexport const SqlSchemaSetupRunner = createAbstraction<ISqlSchemaSetupRunner>(\n \"Db/Sql/SchemaSetupRunner\"\n);\n\nexport namespace SqlSchemaSetupRunner {\n export type Interface = ISqlSchemaSetupRunner;\n export type Request = ISqlSchemaSetupRequest;\n export type RunParams = SqlSchemaSetupRunParams;\n}\n"],"names":["SqlSchemaSetup","createAbstraction","SqlSchemaSetupRunner"],"mappings":";AA2BO,MAAMA,iBAAiBC,kBAAmC;AA0C1D,MAAMC,uBAAuBD,kBAChC"}
@@ -0,0 +1,4 @@
1
+ export { SqlSchemaSetup, SqlSchemaSetupRunner } from "./abstractions.js";
2
+ export type { ISqlSchemaSetupRequest, SqlSchemaSetupRunParams } from "./abstractions.js";
3
+ export { runSchemaSetupSteps } from "./runSchemaSetupSteps.js";
4
+ export type { RequiredSqlSchemaSetup, RunSchemaSetupStepsParams } from "./runSchemaSetupSteps.js";
@@ -0,0 +1,2 @@
1
+ export { SqlSchemaSetup, SqlSchemaSetupRunner } from "./abstractions.js";
2
+ export { runSchemaSetupSteps } from "./runSchemaSetupSteps.js";
@@ -0,0 +1,34 @@
1
+ import type { Knex } from "knex";
2
+ import type { Container } from "@webiny/feature/api";
3
+ import { type ISqlSchemaSetupRequest } from "./abstractions.js";
4
+ export interface RequiredSqlSchemaSetup {
5
+ /** The step's name (`SqlSchemaSetup.name`). */
6
+ name: string;
7
+ /** The error when no step of that name is registered: what to add to the project. */
8
+ message: string;
9
+ }
10
+ export interface RunSchemaSetupStepsParams {
11
+ /** The root container the storage is registered in. The setup's container is its child. */
12
+ root: Container;
13
+ /** The setup's connection: a transaction the runner opened. */
14
+ knex: Knex;
15
+ tableNamePrefix?: string;
16
+ /** Registers a request's parts in the setup's container. */
17
+ request: ISqlSchemaSetupRequest;
18
+ /** Steps the storage can't run without (a module the project must add). */
19
+ required?: RequiredSqlSchemaSetup[];
20
+ }
21
+ /**
22
+ * The part of schema setup every SQL storage shares, run inside the runner's transaction. It builds
23
+ * a container on the setup's connection the way a request's is built, and runs every schema setup
24
+ * step in it.
25
+ *
26
+ * The container is a child of the root, so it has what a request has (the logger, the storages'
27
+ * `RequestStorage`). The setup's connection is registered in it first, with schema-managed off:
28
+ * every storage the request registers runs on it, including the ones built while the request
29
+ * registers and the modules' singletons, which are built in the container that registers them.
30
+ *
31
+ * Checks `required` before running anything, so a missing module fails before any DDL. Returns the
32
+ * names of the steps it ran, in order.
33
+ */
34
+ export declare function runSchemaSetupSteps(params: RunSchemaSetupStepsParams): Promise<string[]>;
@@ -0,0 +1,35 @@
1
+ import { SqlConnectionFeature } from "../connection/SqlConnectionFeature.js";
2
+ import { SqlSchemaSetup } from "./abstractions.js";
3
+ async function runSchemaSetupSteps(params) {
4
+ const { root, knex, tableNamePrefix, request, required = [] } = params;
5
+ const container = root.createChildContainer();
6
+ SqlConnectionFeature.register(container, {
7
+ knex,
8
+ tableNamePrefix,
9
+ schemaManaged: false
10
+ });
11
+ await request.register(container);
12
+ const steps = resolveSteps(container, required);
13
+ for (const step of required)if (!steps.some((item)=>item.name === step.name)) throw new Error(step.message);
14
+ const done = [];
15
+ for (const step of steps){
16
+ await step.setup();
17
+ done.push(step.name);
18
+ }
19
+ return done;
20
+ }
21
+ function resolveSteps(container, required) {
22
+ try {
23
+ return container.resolveAll(SqlSchemaSetup);
24
+ } catch (error) {
25
+ if (!required.length) throw error;
26
+ const cause = error instanceof Error ? error.message : String(error);
27
+ const needs = required.map((step)=>step.message).join(" ");
28
+ throw new Error(`Schema setup could not build its steps (${cause}). ${needs}`, {
29
+ cause: error
30
+ });
31
+ }
32
+ }
33
+ export { runSchemaSetupSteps };
34
+
35
+ //# sourceMappingURL=runSchemaSetupSteps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemaSetup/runSchemaSetupSteps.js","sources":["../../src/schemaSetup/runSchemaSetupSteps.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { Container } from \"@webiny/feature/api\";\nimport { SqlConnectionFeature } from \"~/connection/SqlConnectionFeature.js\";\nimport { SqlSchemaSetup, type ISqlSchemaSetupRequest } from \"./abstractions.js\";\n\nexport interface RequiredSqlSchemaSetup {\n /** The step's name (`SqlSchemaSetup.name`). */\n name: string;\n /** The error when no step of that name is registered: what to add to the project. */\n message: string;\n}\n\nexport interface RunSchemaSetupStepsParams {\n /** The root container the storage is registered in. The setup's container is its child. */\n root: Container;\n /** The setup's connection: a transaction the runner opened. */\n knex: Knex;\n tableNamePrefix?: string;\n /** Registers a request's parts in the setup's container. */\n request: ISqlSchemaSetupRequest;\n /** Steps the storage can't run without (a module the project must add). */\n required?: RequiredSqlSchemaSetup[];\n}\n\n/**\n * The part of schema setup every SQL storage shares, run inside the runner's transaction. It builds\n * a container on the setup's connection the way a request's is built, and runs every schema setup\n * step in it.\n *\n * The container is a child of the root, so it has what a request has (the logger, the storages'\n * `RequestStorage`). The setup's connection is registered in it first, with schema-managed off:\n * every storage the request registers runs on it, including the ones built while the request\n * registers and the modules' singletons, which are built in the container that registers them.\n *\n * Checks `required` before running anything, so a missing module fails before any DDL. Returns the\n * names of the steps it ran, in order.\n */\nexport async function runSchemaSetupSteps(params: RunSchemaSetupStepsParams): Promise<string[]> {\n const { root, knex, tableNamePrefix, request, required = [] } = params;\n\n const container = root.createChildContainer();\n SqlConnectionFeature.register(container, { knex, tableNamePrefix, schemaManaged: false });\n await request.register(container);\n\n const steps = resolveSteps(container, required);\n for (const step of required) {\n if (!steps.some(item => item.name === step.name)) {\n throw new Error(step.message);\n }\n }\n\n const done: string[] = [];\n for (const step of steps) {\n await step.setup();\n done.push(step.name);\n }\n return done;\n}\n\n/**\n * Builds the steps. A step whose module needs another one that is missing (the folder catalog needs\n * the CMS's table names) can't be built, and that fails before any step has a name to check. So\n * the failure says which modules the storage needs, with the cause.\n */\nfunction resolveSteps(container: Container, required: RequiredSqlSchemaSetup[]) {\n try {\n return container.resolveAll(SqlSchemaSetup);\n } catch (error) {\n if (!required.length) {\n throw error;\n }\n const cause = error instanceof Error ? error.message : String(error);\n const needs = required.map(step => step.message).join(\" \");\n throw new Error(`Schema setup could not build its steps (${cause}). ${needs}`, {\n cause: error\n });\n }\n}\n"],"names":["runSchemaSetupSteps","params","root","knex","tableNamePrefix","request","required","container","SqlConnectionFeature","steps","resolveSteps","step","item","Error","done","SqlSchemaSetup","error","cause","String","needs"],"mappings":";;AAqCO,eAAeA,oBAAoBC,MAAiC;IACvE,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAEC,eAAe,EAAEC,OAAO,EAAEC,WAAW,EAAE,EAAE,GAAGL;IAEhE,MAAMM,YAAYL,KAAK,oBAAoB;IAC3CM,qBAAqB,QAAQ,CAACD,WAAW;QAAEJ;QAAMC;QAAiB,eAAe;IAAM;IACvF,MAAMC,QAAQ,QAAQ,CAACE;IAEvB,MAAME,QAAQC,aAAaH,WAAWD;IACtC,KAAK,MAAMK,QAAQL,SACf,IAAI,CAACG,MAAM,IAAI,CAACG,CAAAA,OAAQA,KAAK,IAAI,KAAKD,KAAK,IAAI,GAC3C,MAAM,IAAIE,MAAMF,KAAK,OAAO;IAIpC,MAAMG,OAAiB,EAAE;IACzB,KAAK,MAAMH,QAAQF,MAAO;QACtB,MAAME,KAAK,KAAK;QAChBG,KAAK,IAAI,CAACH,KAAK,IAAI;IACvB;IACA,OAAOG;AACX;AAOA,SAASJ,aAAaH,SAAoB,EAAED,QAAkC;IAC1E,IAAI;QACA,OAAOC,UAAU,UAAU,CAACQ;IAChC,EAAE,OAAOC,OAAO;QACZ,IAAI,CAACV,SAAS,MAAM,EAChB,MAAMU;QAEV,MAAMC,QAAQD,iBAAiBH,QAAQG,MAAM,OAAO,GAAGE,OAAOF;QAC9D,MAAMG,QAAQb,SAAS,GAAG,CAACK,CAAAA,OAAQA,KAAK,OAAO,EAAE,IAAI,CAAC;QACtD,MAAM,IAAIE,MAAM,CAAC,wCAAwC,EAAEI,MAAM,GAAG,EAAEE,OAAO,EAAE;YAC3E,OAAOH;QACX;IACJ;AACJ"}