@webiny/api-core-sql 0.0.0-unstable.0156a4c312 → 0.0.0-unstable.292eb6dc15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/TableManager.d.ts +30 -12
- package/TableManager.js +34 -30
- package/TableManager.js.map +1 -1
- package/adminUsers/index.d.ts +3 -0
- package/adminUsers/index.js +68 -16
- package/adminUsers/index.js.map +1 -1
- package/connection/SqlConnectionFeature.d.ts +32 -0
- package/connection/SqlConnectionFeature.js +30 -0
- package/connection/SqlConnectionFeature.js.map +1 -0
- package/connection/index.d.ts +2 -0
- package/connection/index.js +1 -0
- package/connectionRetry/index.d.ts +3 -0
- package/connectionRetry/index.js +2 -0
- package/connectionRetry/isConnectionError.d.ts +1 -0
- package/connectionRetry/isConnectionError.js +28 -0
- package/connectionRetry/isConnectionError.js.map +1 -0
- package/connectionRetry/withPgConnectionRetry.d.ts +49 -0
- package/connectionRetry/withPgConnectionRetry.js +175 -0
- package/connectionRetry/withPgConnectionRetry.js.map +1 -0
- package/coreStorage/CoreSqlSchemaSetup.d.ts +18 -0
- package/coreStorage/CoreSqlSchemaSetup.js +36 -0
- package/coreStorage/CoreSqlSchemaSetup.js.map +1 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +15 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.js +33 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -0
- package/coreStorage/SqlTenancyStorageOperationsFactory.d.ts +18 -0
- package/coreStorage/SqlTenancyStorageOperationsFactory.js +36 -0
- package/coreStorage/SqlTenancyStorageOperationsFactory.js.map +1 -0
- package/coreStorage/SqlTenantStorageReadiness.d.ts +19 -0
- package/coreStorage/SqlTenantStorageReadiness.js +48 -0
- package/coreStorage/SqlTenantStorageReadiness.js.map +1 -0
- package/coreStorage/feature.d.ts +14 -0
- package/coreStorage/feature.js +17 -0
- package/coreStorage/feature.js.map +1 -0
- package/coreStorage/index.d.ts +1 -0
- package/coreStorage/index.js +1 -0
- package/createApiCoreSql.d.ts +19 -1
- package/createApiCoreSql.js +12 -10
- package/createApiCoreSql.js.map +1 -1
- package/feature/SqlDialect/abstractions.d.ts +15 -0
- package/feature/SqlDialect/abstractions.js +5 -0
- package/feature/SqlDialect/abstractions.js.map +1 -0
- package/feature/SqlDialect/index.d.ts +2 -0
- package/feature/SqlDialect/index.js +1 -0
- package/index.d.ts +26 -4
- package/index.js +18 -4
- package/index.js.map +1 -1
- package/keyValueStore/index.js +19 -17
- package/keyValueStore/index.js.map +1 -1
- package/package.json +9 -8
- package/schemaConfig/abstractions.d.ts +22 -0
- package/schemaConfig/abstractions.js +5 -0
- package/schemaConfig/abstractions.js.map +1 -0
- package/schemaConfig/index.d.ts +1 -0
- package/schemaConfig/index.js +1 -0
- package/schemaMemory/ensureTable.d.ts +35 -0
- package/schemaMemory/ensureTable.js +46 -0
- package/schemaMemory/ensureTable.js.map +1 -0
- package/schemaMemory/getConnectionKey.d.ts +8 -0
- package/schemaMemory/getConnectionKey.js +15 -0
- package/schemaMemory/getConnectionKey.js.map +1 -0
- package/schemaMemory/getSchemaMemory.d.ts +37 -0
- package/schemaMemory/getSchemaMemory.js +53 -0
- package/schemaMemory/getSchemaMemory.js.map +1 -0
- package/schemaSetup/abstractions.d.ts +79 -0
- package/schemaSetup/abstractions.js +6 -0
- package/schemaSetup/abstractions.js.map +1 -0
- package/schemaSetup/index.d.ts +6 -0
- package/schemaSetup/index.js +3 -0
- package/schemaSetup/runSchemaSetupSteps.d.ts +43 -0
- package/schemaSetup/runSchemaSetupSteps.js +39 -0
- package/schemaSetup/runSchemaSetupSteps.js.map +1 -0
- package/schemaSetup/runSqlSchemaSetups.d.ts +22 -0
- package/schemaSetup/runSqlSchemaSetups.js +24 -0
- package/schemaSetup/runSqlSchemaSetups.js.map +1 -0
- package/scopeStorage/abstractions.d.ts +19 -0
- package/scopeStorage/abstractions.js +5 -0
- package/scopeStorage/abstractions.js.map +1 -0
- package/scopeStorage/index.d.ts +3 -0
- package/scopeStorage/index.js +2 -0
- package/scopeStorage/isPostgresScope.d.ts +14 -0
- package/scopeStorage/isPostgresScope.js +8 -0
- package/scopeStorage/isPostgresScope.js.map +1 -0
- package/security/index.d.ts +3 -0
- package/security/index.js +68 -47
- package/security/index.js.map +1 -1
- package/serviceDiscovery/SqlServiceManifestLoader.d.ts +1 -1
- package/serviceDiscovery/SqlServiceManifestLoader.js +3 -8
- package/serviceDiscovery/SqlServiceManifestLoader.js.map +1 -1
- package/serviceDiscovery/SqlServiceManifestWriter.d.ts +16 -0
- package/serviceDiscovery/SqlServiceManifestWriter.js +27 -0
- package/serviceDiscovery/SqlServiceManifestWriter.js.map +1 -0
- package/serviceDiscovery/index.d.ts +1 -0
- package/serviceDiscovery/index.js +1 -0
- package/serviceDiscovery/serviceManifestsTable.d.ts +13 -0
- package/serviceDiscovery/serviceManifestsTable.js +8 -0
- package/serviceDiscovery/serviceManifestsTable.js.map +1 -0
- package/storage/sqlTenantStorage.d.ts +44 -0
- package/storage/sqlTenantStorage.js +32 -0
- package/storage/sqlTenantStorage.js.map +1 -0
- package/storage/types.d.ts +31 -0
- package/storage/types.js +0 -0
- package/tenancy/index.js +59 -17
- package/tenancy/index.js.map +1 -1
- package/ApiCoreSqlFeature.d.ts +0 -18
- package/ApiCoreSqlFeature.js +0 -18
- package/ApiCoreSqlFeature.js.map +0 -1
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** The SQL database families the API runs on. */
|
|
2
|
+
export type SqlDialectName = "postgres" | "sqlite";
|
|
3
|
+
export interface ISqlDialect {
|
|
4
|
+
/** The database family of the connection (`KnexClient`) registered next to it. */
|
|
5
|
+
readonly name: SqlDialectName;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Which database the SQL connection talks to. Registered with the connection (`SqlConnectionFeature`),
|
|
9
|
+
* by the storage that knows it, so code that branches on the database never asks the driver.
|
|
10
|
+
*/
|
|
11
|
+
export declare const SqlDialect: import("@webiny/di").Abstraction<ISqlDialect>;
|
|
12
|
+
export declare namespace SqlDialect {
|
|
13
|
+
type Interface = ISqlDialect;
|
|
14
|
+
type Name = SqlDialectName;
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"feature/SqlDialect/abstractions.js","sources":["../../../src/feature/SqlDialect/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\n\n/** The SQL database families the API runs on. */\nexport type SqlDialectName = \"postgres\" | \"sqlite\";\n\nexport interface ISqlDialect {\n /** The database family of the connection (`KnexClient`) registered next to it. */\n readonly name: SqlDialectName;\n}\n\n/**\n * Which database the SQL connection talks to. Registered with the connection (`SqlConnectionFeature`),\n * by the storage that knows it, so code that branches on the database never asks the driver.\n */\nexport const SqlDialect = createAbstraction<ISqlDialect>(\"Db/Sql/SqlDialect\");\n\nexport namespace SqlDialect {\n export type Interface = ISqlDialect;\n export type Name = SqlDialectName;\n}\n"],"names":["SqlDialect","createAbstraction"],"mappings":";AAcO,MAAMA,aAAaC,kBAA+B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { SqlDialect } from "./abstractions.js";
|
package/index.d.ts
CHANGED
|
@@ -1,11 +1,33 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
|
+
import { SqlDialect } from "./feature/SqlDialect/index.js";
|
|
2
3
|
export { createApiCoreSql } from "./createApiCoreSql.js";
|
|
3
|
-
export { ApiCoreSqlFeature } from "./
|
|
4
|
-
export
|
|
4
|
+
export { ApiCoreSqlFeature } from "./coreStorage/index.js";
|
|
5
|
+
export { SqlConnectionFeature, setSqlServiceManifestLoader } from "./connection/index.js";
|
|
6
|
+
export type { SqlConnectionConfig } from "./connection/index.js";
|
|
5
7
|
export { getSqlTablePrefix } from "./getSqlTablePrefix.js";
|
|
6
|
-
export {
|
|
8
|
+
export { TableManager } from "./TableManager.js";
|
|
9
|
+
export type { TableManagerOptions } from "./TableManager.js";
|
|
10
|
+
export { SqlSchemaConfig } from "./schemaConfig/index.js";
|
|
11
|
+
export { SqlSchemaSetup, SqlSchemaSetupRunner, runSchemaSetupSteps, runSqlSchemaSetups } from "./schemaSetup/index.js";
|
|
12
|
+
export type { ISqlSchemaSetupRequest, ISqlSchemaSetupRequestOptions, RunSqlSchemaSetupsParams, SqlSchemaSetupResult, RequiredSqlSchemaSetup, RunSchemaSetupStepsParams, SqlSchemaSetupRunParams } from "./schemaSetup/index.js";
|
|
13
|
+
export { getSchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
14
|
+
export { getConnectionKey } from "./schemaMemory/getConnectionKey.js";
|
|
15
|
+
export { ensureTable, createTableIfMissing, recordTable } from "./schemaMemory/ensureTable.js";
|
|
16
|
+
export type { EnsureTableParams, TableCreator, TableUpgrade } from "./schemaMemory/ensureTable.js";
|
|
17
|
+
export type { ISchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
18
|
+
export type { SqlStorage } from "./storage/types.js";
|
|
19
|
+
export { createSqlRequestStorage, createSqlTenantStorageBackend, registerSqlScopeStorages, registerTenantStorageBackend } from "./storage/sqlTenantStorage.js";
|
|
20
|
+
export type { CreateSqlTenantStorageBackendParams, RegisterSqlStorageParts, SqlStorageIdentityParams } from "./storage/sqlTenantStorage.js";
|
|
21
|
+
export { SqlScopeStorage, isPostgresScope } from "./scopeStorage/index.js";
|
|
22
|
+
export type { ISqlScopeStorage } from "./scopeStorage/index.js";
|
|
23
|
+
export * from "./connectionRetry/index.js";
|
|
24
|
+
export { SqlServiceManifestLoader, SqlServiceManifestWriter } from "./serviceDiscovery/index.js";
|
|
7
25
|
export { KnexClient } from "./feature/KnexClient/index.js";
|
|
26
|
+
export { SqlDialect };
|
|
27
|
+
export type { ISqlDialect, SqlDialectName } from "./feature/SqlDialect/index.js";
|
|
8
28
|
interface IRegisterApiCoreSqlExtension {
|
|
9
29
|
knex: Knex;
|
|
30
|
+
/** The connection's database family, registered as `SqlDialect` (`isPostgresScope` reads it). */
|
|
31
|
+
dialect: SqlDialect.Name;
|
|
10
32
|
}
|
|
11
|
-
export declare const registerSQLCore: ({ knex }: IRegisterApiCoreSqlExtension) => import("@webiny/handler").RegisterExtensionPlugin<import("@webiny/handler/types.js").Context>;
|
|
33
|
+
export declare const registerSQLCore: ({ knex, dialect }: IRegisterApiCoreSqlExtension) => import("@webiny/handler").RegisterExtensionPlugin<import("@webiny/handler/types.js").Context>;
|
package/index.js
CHANGED
|
@@ -1,12 +1,26 @@
|
|
|
1
1
|
import { createRegisterExtensionPlugin } from "@webiny/handler";
|
|
2
2
|
import { KnexClient, KnexClientFeature } from "./feature/KnexClient/index.js";
|
|
3
|
-
|
|
3
|
+
import { SqlDialect } from "./feature/SqlDialect/index.js";
|
|
4
|
+
export * from "./connectionRetry/index.js";
|
|
5
|
+
const registerSQLCore = ({ knex, dialect })=>createRegisterExtensionPlugin(async (context)=>{
|
|
4
6
|
KnexClientFeature.register(context.container, knex);
|
|
7
|
+
context.container.registerInstance(SqlDialect, {
|
|
8
|
+
name: dialect
|
|
9
|
+
});
|
|
5
10
|
});
|
|
6
11
|
export { createApiCoreSql } from "./createApiCoreSql.js";
|
|
7
|
-
export { ApiCoreSqlFeature } from "./
|
|
12
|
+
export { ApiCoreSqlFeature } from "./coreStorage/index.js";
|
|
13
|
+
export { SqlConnectionFeature, setSqlServiceManifestLoader } from "./connection/index.js";
|
|
8
14
|
export { getSqlTablePrefix } from "./getSqlTablePrefix.js";
|
|
9
|
-
export {
|
|
10
|
-
export {
|
|
15
|
+
export { TableManager } from "./TableManager.js";
|
|
16
|
+
export { SqlSchemaConfig } from "./schemaConfig/index.js";
|
|
17
|
+
export { SqlSchemaSetup, SqlSchemaSetupRunner, runSchemaSetupSteps, runSqlSchemaSetups } from "./schemaSetup/index.js";
|
|
18
|
+
export { getSchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
19
|
+
export { getConnectionKey } from "./schemaMemory/getConnectionKey.js";
|
|
20
|
+
export { createTableIfMissing, ensureTable, recordTable } from "./schemaMemory/ensureTable.js";
|
|
21
|
+
export { createSqlRequestStorage, createSqlTenantStorageBackend, registerSqlScopeStorages, registerTenantStorageBackend } from "./storage/sqlTenantStorage.js";
|
|
22
|
+
export { SqlScopeStorage, isPostgresScope } from "./scopeStorage/index.js";
|
|
23
|
+
export { SqlServiceManifestLoader, SqlServiceManifestWriter } from "./serviceDiscovery/index.js";
|
|
24
|
+
export { KnexClient, SqlDialect, registerSQLCore };
|
|
11
25
|
|
|
12
26
|
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { createRegisterExtensionPlugin } from \"@webiny/handler\";\nimport type { Knex } from \"knex\";\nimport { KnexClientFeature } from \"./feature/KnexClient/index.js\";\n\nexport { createApiCoreSql } from \"./createApiCoreSql.js\";\nexport { ApiCoreSqlFeature } from \"./
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { createRegisterExtensionPlugin } from \"@webiny/handler\";\nimport type { Knex } from \"knex\";\nimport { KnexClientFeature } from \"./feature/KnexClient/index.js\";\nimport { SqlDialect } from \"./feature/SqlDialect/index.js\";\n\nexport { createApiCoreSql } from \"./createApiCoreSql.js\";\nexport { ApiCoreSqlFeature } from \"./coreStorage/index.js\";\nexport { SqlConnectionFeature, setSqlServiceManifestLoader } from \"./connection/index.js\";\nexport type { SqlConnectionConfig } from \"./connection/index.js\";\nexport { getSqlTablePrefix } from \"./getSqlTablePrefix.js\";\nexport { TableManager } from \"./TableManager.js\";\nexport type { TableManagerOptions } from \"./TableManager.js\";\nexport { SqlSchemaConfig } from \"./schemaConfig/index.js\";\nexport {\n SqlSchemaSetup,\n SqlSchemaSetupRunner,\n runSchemaSetupSteps,\n runSqlSchemaSetups\n} from \"./schemaSetup/index.js\";\nexport type {\n ISqlSchemaSetupRequest,\n ISqlSchemaSetupRequestOptions,\n RunSqlSchemaSetupsParams,\n SqlSchemaSetupResult,\n RequiredSqlSchemaSetup,\n RunSchemaSetupStepsParams,\n SqlSchemaSetupRunParams\n} from \"./schemaSetup/index.js\";\nexport { getSchemaMemory } from \"./schemaMemory/getSchemaMemory.js\";\nexport { getConnectionKey } from \"./schemaMemory/getConnectionKey.js\";\nexport { ensureTable, createTableIfMissing, recordTable } from \"./schemaMemory/ensureTable.js\";\nexport type { EnsureTableParams, TableCreator, TableUpgrade } from \"./schemaMemory/ensureTable.js\";\nexport type { ISchemaMemory } from \"./schemaMemory/getSchemaMemory.js\";\nexport type { SqlStorage } from \"./storage/types.js\";\nexport {\n createSqlRequestStorage,\n createSqlTenantStorageBackend,\n registerSqlScopeStorages,\n registerTenantStorageBackend\n} from \"./storage/sqlTenantStorage.js\";\nexport type {\n CreateSqlTenantStorageBackendParams,\n RegisterSqlStorageParts,\n SqlStorageIdentityParams\n} from \"./storage/sqlTenantStorage.js\";\nexport { SqlScopeStorage, isPostgresScope } from \"./scopeStorage/index.js\";\nexport type { ISqlScopeStorage } from \"./scopeStorage/index.js\";\nexport * from \"./connectionRetry/index.js\";\nexport { SqlServiceManifestLoader, SqlServiceManifestWriter } from \"./serviceDiscovery/index.js\";\n\nexport { KnexClient } from \"./feature/KnexClient/index.js\";\nexport { SqlDialect };\nexport type { ISqlDialect, SqlDialectName } from \"./feature/SqlDialect/index.js\";\n\ninterface IRegisterApiCoreSqlExtension {\n knex: Knex;\n /** The connection's database family, registered as `SqlDialect` (`isPostgresScope` reads it). */\n dialect: SqlDialect.Name;\n}\n\nexport const registerSQLCore = ({ knex, dialect }: IRegisterApiCoreSqlExtension) => {\n return createRegisterExtensionPlugin(async context => {\n KnexClientFeature.register(context.container, knex);\n context.container.registerInstance(SqlDialect, { name: dialect });\n });\n};\n"],"names":["registerSQLCore","knex","dialect","createRegisterExtensionPlugin","context","KnexClientFeature","SqlDialect"],"mappings":";;;;AA4DO,MAAMA,kBAAkB,CAAC,EAAEC,IAAI,EAAEC,OAAO,EAAgC,GACpEC,8BAA8B,OAAMC;QACvCC,kBAAkB,QAAQ,CAACD,QAAQ,SAAS,EAAEH;QAC9CG,QAAQ,SAAS,CAAC,gBAAgB,CAACE,YAAY;YAAE,MAAMJ;QAAQ;IACnE"}
|
package/keyValueStore/index.js
CHANGED
|
@@ -7,24 +7,26 @@ const isPrimaryKeyViolation = (error)=>{
|
|
|
7
7
|
};
|
|
8
8
|
const createStorageOperations = (params)=>{
|
|
9
9
|
const { knex, tableManager } = params;
|
|
10
|
+
const ensureValuesTable = tableManager.define(TABLE_NAME, (table)=>{
|
|
11
|
+
table.text("scopedKey").primary().notNullable();
|
|
12
|
+
table.text("key").notNullable();
|
|
13
|
+
table.text("scope").notNullable();
|
|
14
|
+
table.text("value").notNullable();
|
|
15
|
+
table.datetime("expiresAt");
|
|
16
|
+
});
|
|
17
|
+
const ensureCollectionTable = tableManager.define(COLLECTION_TABLE_NAME, (table)=>{
|
|
18
|
+
table.text("scopedKey").primary().notNullable();
|
|
19
|
+
table.text("scope").notNullable();
|
|
20
|
+
table.text("collection").notNullable();
|
|
21
|
+
table.text("key").notNullable();
|
|
22
|
+
table.index([
|
|
23
|
+
"scope",
|
|
24
|
+
"collection"
|
|
25
|
+
]);
|
|
26
|
+
});
|
|
10
27
|
const ensureTable = async ()=>{
|
|
11
|
-
await
|
|
12
|
-
|
|
13
|
-
table.text("key").notNullable();
|
|
14
|
-
table.text("scope").notNullable();
|
|
15
|
-
table.text("value").notNullable();
|
|
16
|
-
table.datetime("expiresAt");
|
|
17
|
-
});
|
|
18
|
-
await tableManager.ensure(COLLECTION_TABLE_NAME, (table)=>{
|
|
19
|
-
table.text("scopedKey").primary().notNullable();
|
|
20
|
-
table.text("scope").notNullable();
|
|
21
|
-
table.text("collection").notNullable();
|
|
22
|
-
table.text("key").notNullable();
|
|
23
|
-
table.index([
|
|
24
|
-
"scope",
|
|
25
|
-
"collection"
|
|
26
|
-
]);
|
|
27
|
-
});
|
|
28
|
+
await ensureValuesTable();
|
|
29
|
+
await ensureCollectionTable();
|
|
28
30
|
};
|
|
29
31
|
const query = (trx = knex)=>trx(tableManager.resolve(TABLE_NAME));
|
|
30
32
|
const collectionQuery = (trx = knex)=>trx(tableManager.resolve(COLLECTION_TABLE_NAME));
|
|
@@ -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,IAAI,CAAC,a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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,OAA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BACN,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.
|
|
3
|
+
"version": "0.0.0-unstable.292eb6dc15",
|
|
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.
|
|
25
|
-
"@webiny/error": "0.0.0-unstable.
|
|
26
|
-
"@webiny/feature": "0.0.0-unstable.
|
|
27
|
-
"@webiny/handler": "0.0.0-unstable.
|
|
24
|
+
"@webiny/api-core": "0.0.0-unstable.292eb6dc15",
|
|
25
|
+
"@webiny/error": "0.0.0-unstable.292eb6dc15",
|
|
26
|
+
"@webiny/feature": "0.0.0-unstable.292eb6dc15",
|
|
27
|
+
"@webiny/handler": "0.0.0-unstable.292eb6dc15",
|
|
28
28
|
"knex": "3.3.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
|
-
"@webiny/build-tools": "0.0.0-unstable.
|
|
32
|
-
"better-sqlite3": "13.0
|
|
31
|
+
"@webiny/build-tools": "0.0.0-unstable.292eb6dc15",
|
|
32
|
+
"better-sqlite3": "13.2.0",
|
|
33
|
+
"pg": "8.23.1",
|
|
33
34
|
"typescript": "7.0.2",
|
|
34
|
-
"vitest": "5.
|
|
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 @@
|
|
|
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;QA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ACM,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,GAC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