@webiny/api-core-sql 0.0.0-unstable.33e4fd9647 → 0.0.0-unstable.3fddf667ea
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 +29 -12
- package/TableManager.js +29 -29
- package/TableManager.js.map +1 -1
- package/adminUsers/index.js +20 -17
- package/adminUsers/index.js.map +1 -1
- package/connection/SqlConnectionFeature.d.ts +28 -0
- package/connection/SqlConnectionFeature.js +26 -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 +35 -0
- package/coreStorage/CoreSqlSchemaSetup.js.map +1 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +15 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.js +32 -0
- package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -0
- package/coreStorage/feature.d.ts +13 -0
- package/coreStorage/feature.js +13 -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 +13 -1
- package/createApiCoreSql.js +8 -8
- package/createApiCoreSql.js.map +1 -1
- package/index.d.ts +16 -3
- package/index.js +10 -2
- package/index.js.map +1 -1
- package/keyValueStore/index.js +19 -17
- package/keyValueStore/index.js.map +1 -1
- package/package.json +8 -7
- 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 +28 -0
- package/schemaMemory/ensureTable.js +43 -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 +67 -0
- package/schemaSetup/abstractions.js +6 -0
- package/schemaSetup/abstractions.js.map +1 -0
- package/schemaSetup/index.d.ts +4 -0
- package/schemaSetup/index.js +2 -0
- package/schemaSetup/runSchemaSetupSteps.d.ts +34 -0
- package/schemaSetup/runSchemaSetupSteps.js +35 -0
- package/schemaSetup/runSchemaSetupSteps.js.map +1 -0
- package/security/index.js +47 -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/types.d.ts +22 -0
- package/storage/types.js +0 -0
- package/tenancy/index.js +9 -9
- 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 @@
|
|
|
1
|
+
{"version":3,"file":"connectionRetry/withPgConnectionRetry.js","sources":["../../src/connectionRetry/withPgConnectionRetry.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { isConnectionError } from \"./isConnectionError.js\";\n\n/**\n * Makes a Postgres knex instance survive a lost connection (a database failover, a dropped proxy\n * connection, a server restart) without failing the API request, where that is safe:\n *\n * - A transaction (`knex.transaction(async trx => …)`) that loses its connection before COMMIT is sent\n * is run again: the server rolled it back, so nothing of it was kept.\n * - A transaction that loses its connection during COMMIT may or may not have committed. Before\n * COMMIT, the transaction reads its own ID; after the failure, the wrapper asks the server for that\n * transaction's outcome (`pg_xact_status`) on a new connection. Committed: the result is returned\n * as is, and the work is not repeated. Rolled back: the transaction is run again. Unknown: the\n * error is thrown.\n * - A read-only transaction that fails at COMMIT returns its result: there was nothing to commit.\n * - A read outside a transaction (a SELECT) is run again.\n *\n * Retries wait 100 ms, 250 ms, 500 ms, 1 s, then every 2 s, until `maxRetryMs` has passed since the\n * first failure; then the last error is thrown. Errors that aren't about the connection (a constraint\n * violation, a syntax error, a timeout of the statement itself) are never retried.\n *\n * A transaction's callback is run again on a retry, so it must only change the database: a call to\n * another service inside it would be repeated.\n *\n * Writes outside a transaction are not retried: their outcome can't be checked.\n */\n\nexport type PgConnectionRetryEventType =\n /** A connection error; the operation runs again after `delayMs`. */\n | \"retry\"\n /** COMMIT failed, but the server confirmed that the transaction committed: no retry needed. */\n | \"commitConfirmed\"\n /** COMMIT failed, and the server confirmed that the transaction was rolled back: it runs again. */\n | \"commitRolledBack\"\n /** COMMIT failed for a transaction that changed nothing: its result is returned. */\n | \"readOnlyCommitIgnored\"\n /** Retries ran out (time or an unknown transaction outcome): the error is thrown. */\n | \"gaveUp\";\n\nexport interface IPgConnectionRetryEvent {\n type: PgConnectionRetryEventType;\n operation: \"transaction\" | \"query\";\n /** Retries so far for this operation. */\n attempt: number;\n delayMs?: number;\n error: unknown;\n}\n\nexport interface IPgConnectionRetryOptions {\n /** How long to keep retrying after an operation's first connection error. Default: 15,000 ms. */\n maxRetryMs?: number;\n onEvent?: (event: IPgConnectionRetryEvent) => void;\n}\n\nconst DELAYS_MS = [100, 250, 500, 1000, 2000];\n/** How often to ask again while the server still reports the transaction as in progress. */\nconst IN_PROGRESS_CHECKS = 5;\n\nconst RETRY_INSTALLED = Symbol.for(\"webiny.pgConnectionRetry\");\n\n/* Statements that can't change data, so a transaction made only of them has nothing to lose. */\nconst READ_STATEMENT = /^\\s*(select|show|explain|set|with)\\b/i;\n/* Anything in a statement that changes data or takes a session lock. */\nconst WRITE_KEYWORDS =\n /\\b(insert\\s+into|update\\s+\\S+\\s+set|delete\\s+from|merge\\s+into|truncate|create|alter|drop|grant|revoke|copy|nextval|setval|pg_advisory_lock|pg_try_advisory_lock)\\b/i;\n\nconst mayWrite = (sql: string): boolean => {\n return !READ_STATEMENT.test(sql) || WRITE_KEYWORDS.test(sql);\n};\n\nconst READ_METHODS = new Set([\"select\", \"first\", \"pluck\"]);\n\n/* A query builder or raw statement that only reads. */\nconst isReadOnlyBuilder = (builder: { _method?: unknown; sql?: unknown }): boolean => {\n if (typeof builder._method === \"string\") {\n return READ_METHODS.has(builder._method);\n }\n if (typeof builder.sql === \"string\") {\n return /^\\s*(select|show|explain)\\b/i.test(builder.sql) && !mayWrite(builder.sql);\n }\n return false;\n};\n\n/* Thrown inside an attempt to stop retrying; carries the error to throw. */\nclass StopRetrying {\n public constructor(public readonly error: unknown) {}\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\ntype TransactionCallback = (trx: Knex.Transaction) => Promise<unknown> | unknown;\n\ninterface IRunner {\n run(): Promise<unknown>;\n}\n\ninterface IClientWithRunner {\n runner(builder: unknown): IRunner;\n}\n\ninterface ITransactionState {\n /* COMMIT has been sent (or is about to be). */\n committing: boolean;\n /* A statement that may have changed data ran. */\n wrote: boolean;\n xid: string | null;\n pid: number | null;\n result: unknown;\n}\n\nexport const withPgConnectionRetry = (\n knex: Knex,\n options: IPgConnectionRetryOptions = {}\n): Knex => {\n const target = knex as Knex & { [RETRY_INSTALLED]?: boolean };\n const clientName = String((knex.client as { config?: { client?: unknown } }).config?.client);\n if (target[RETRY_INSTALLED] || ![\"pg\", \"postgres\", \"postgresql\"].includes(clientName)) {\n return knex;\n }\n target[RETRY_INSTALLED] = true;\n\n const maxRetryMs = options.maxRetryMs ?? 15_000;\n const emit = (event: IPgConnectionRetryEvent) => {\n try {\n options.onEvent?.(event);\n } catch {\n // A failing listener must not change the outcome of the query.\n }\n };\n\n /* Runs `attempt` until it succeeds, throws a non-connection error, or time runs out. */\n const retrying = async <T>(\n operation: IPgConnectionRetryEvent[\"operation\"],\n attempt: (attemptNumber: number) => Promise<T>\n ): Promise<T> => {\n let firstFailureAt: number | undefined;\n for (let attemptNumber = 0; ; attemptNumber++) {\n try {\n return await attempt(attemptNumber);\n } catch (error) {\n if (error instanceof StopRetrying) {\n throw error.error;\n }\n if (!isConnectionError(error)) {\n throw error;\n }\n firstFailureAt ??= Date.now();\n const delayMs = DELAYS_MS[Math.min(attemptNumber, DELAYS_MS.length - 1)];\n if (Date.now() - firstFailureAt + delayMs > maxRetryMs) {\n emit({ type: \"gaveUp\", operation, attempt: attemptNumber, error });\n throw error;\n }\n emit({ type: \"retry\", operation, attempt: attemptNumber, delayMs, error });\n await sleep(delayMs);\n }\n }\n };\n\n // Reads outside a transaction. Transactions run their queries on their own client object (knex\n // creates it from the client's prototype), so this only sees statements outside transactions.\n const client = knex.client as unknown as IClientWithRunner;\n const originalRunner = client.runner;\n client.runner = function (this: IClientWithRunner, builder: unknown): IRunner {\n const runner = originalRunner.call(this, builder);\n if (!isReadOnlyBuilder(builder as Parameters<typeof isReadOnlyBuilder>[0])) {\n return runner;\n }\n const firstRun = runner.run.bind(runner);\n runner.run = () => {\n return retrying(\"query\", attemptNumber => {\n return attemptNumber === 0\n ? firstRun()\n : originalRunner.call(client, builder).run();\n });\n };\n return runner;\n };\n\n const originalTransaction = knex.transaction;\n\n /* The outcome of a transaction whose COMMIT failed: \"committed\", \"aborted\" or null (unknown). */\n const transactionOutcome = async (xid: string, pid: number | null): Promise<string | null> => {\n for (let check = 0; check < IN_PROGRESS_CHECKS; check++) {\n // A read outside a transaction: retried on connection errors by the runner above.\n const result = await knex.raw<{ rows: { status: string | null }[] }>(\n \"SELECT pg_xact_status(?::xid8)::text AS status\",\n [xid]\n );\n const status = result.rows[0]?.status ?? null;\n if (status !== \"in progress\") {\n return status;\n }\n // The server still has the transaction open. If its session is idle (the COMMIT never\n // arrived), end the session: the transaction is rolled back, and the next check says so.\n if (pid !== null) {\n await knex.raw(\n `SELECT pg_terminate_backend(pid) FROM pg_stat_activity\n WHERE pid = ? AND backend_xid = (?::xid8)::xid AND state LIKE 'idle in transaction%'`,\n [pid, xid]\n );\n }\n await sleep(DELAYS_MS[Math.min(check, DELAYS_MS.length - 1)]);\n }\n return null;\n };\n\n const runTransactionOnce = async (\n callback: TransactionCallback,\n config: Knex.TransactionConfig | undefined,\n attemptNumber: number\n ): Promise<unknown> => {\n const state: ITransactionState = {\n committing: false,\n wrote: false,\n xid: null,\n pid: null,\n result: undefined\n };\n try {\n return await originalTransaction.call(\n knex,\n async (trx: Knex.Transaction) => {\n trx.on(\"query\", (query: { sql?: string }) => {\n if (!state.wrote && typeof query.sql === \"string\" && mayWrite(query.sql)) {\n state.wrote = true;\n }\n });\n const result = await callback(trx);\n state.result = result;\n if (state.wrote) {\n // The transaction's ID, if it has one (it gets one when it changes data), so\n // its outcome can be checked if COMMIT fails.\n const ids = await trx.raw<{ rows: { xid: string | null; pid: number }[] }>(\n \"SELECT pg_current_xact_id_if_assigned()::text AS xid, pg_backend_pid() AS pid\"\n );\n state.xid = ids.rows[0]?.xid ?? null;\n state.pid = ids.rows[0]?.pid ?? null;\n }\n state.committing = true;\n return result;\n },\n config\n );\n } catch (error) {\n if (!state.committing || !isConnectionError(error)) {\n // Before COMMIT, a connection error is retried by the caller: the server rolled the\n // transaction back. Other errors are thrown.\n throw error;\n }\n if (!state.xid) {\n emit({\n type: \"readOnlyCommitIgnored\",\n operation: \"transaction\",\n attempt: attemptNumber,\n error\n });\n return state.result;\n }\n const outcome = await transactionOutcome(state.xid, state.pid);\n if (outcome === \"committed\") {\n emit({\n type: \"commitConfirmed\",\n operation: \"transaction\",\n attempt: attemptNumber,\n error\n });\n return state.result;\n }\n if (outcome === \"aborted\") {\n emit({\n type: \"commitRolledBack\",\n operation: \"transaction\",\n attempt: attemptNumber,\n error\n });\n throw error;\n }\n emit({ type: \"gaveUp\", operation: \"transaction\", attempt: attemptNumber, error });\n throw new StopRetrying(error);\n }\n };\n\n Object.defineProperty(knex, \"transaction\", {\n configurable: true,\n enumerable: true,\n writable: false,\n value: function transaction(this: Knex, ...args: unknown[]) {\n const [callback, config] = args;\n if (typeof callback !== \"function\") {\n // No callback: the caller commits and rolls back by hand; nothing to retry.\n return (originalTransaction as (...a: unknown[]) => unknown).apply(knex, args);\n }\n return retrying(\"transaction\", attemptNumber => {\n return runTransactionOnce(\n callback as TransactionCallback,\n config as Knex.TransactionConfig | undefined,\n attemptNumber\n );\n });\n }\n });\n\n return knex;\n};\n"],"names":["DELAYS_MS","IN_PROGRESS_CHECKS","RETRY_INSTALLED","Symbol","READ_STATEMENT","WRITE_KEYWORDS","mayWrite","sql","READ_METHODS","Set","isReadOnlyBuilder","builder","StopRetrying","error","sleep","ms","Promise","resolve","setTimeout","withPgConnectionRetry","knex","options","target","clientName","String","maxRetryMs","emit","event","retrying","operation","attempt","firstFailureAt","attemptNumber","isConnectionError","Date","delayMs","Math","client","originalRunner","runner","firstRun","originalTransaction","transactionOutcome","xid","pid","check","result","status","runTransactionOnce","callback","config","state","undefined","trx","query","ids","outcome","Object","args"],"mappings":";AAsDA,MAAMA,YAAY;IAAC;IAAK;IAAK;IAAK;IAAM;CAAK;AAE7C,MAAMC,qBAAqB;AAE3B,MAAMC,kBAAkBC,OAAO,GAAG,CAAC;AAGnC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AW;oBACX,SAASM;oBACTnB;gBACJ;gBACA,MAAMA;YACV;YACAa,KAAK;gBAAE,MAAM;gBAAU,WAAW;gBAAe,SAASM;gBAAenB;YAAM;YAC/E,MAAM,IAAID,aAAaC;QAC3B;IACJ;IAEA4C,OAAO,cAAc,CAACrC,MAAM,eAAe;QACvC,cAAc;QACd,YAAY;QACZ,UAAU;QACV,OAAO,SAAiC,GAAGsC,IAAe;YACtD,MAAM,CAACT,UAAUC,OAAO,GAAGQ;YAC3B,IAAI,AAAoB,cAApB,OAAOT,UAEP,OAAQR,oBAAqD,KAAK,CAACrB,MAAMsC;YAE7E,OAAO9B,SAAS,eAAeI,CAAAA,gBACpBgB,mBACHC,UACAC,QACAlB;QAGZ;IACJ;IAEA,OAAOZ;AACX"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { KnexClient } from "../feature/KnexClient/index.js";
|
|
2
|
+
import { SqlSchemaConfig } from "../schemaConfig/index.js";
|
|
3
|
+
import { SqlSchemaSetup } from "../schemaSetup/index.js";
|
|
4
|
+
/**
|
|
5
|
+
* The `core` schema setup step: the tables of users, tenancy, security, the key-value store and the
|
|
6
|
+
* service manifests, on the container's connection.
|
|
7
|
+
*/
|
|
8
|
+
declare class CoreSqlSchemaSetupImpl implements SqlSchemaSetup.Interface {
|
|
9
|
+
private readonly knex;
|
|
10
|
+
private readonly schemaConfig?;
|
|
11
|
+
readonly name = "core";
|
|
12
|
+
constructor(knex: KnexClient.Interface, schemaConfig?: SqlSchemaConfig.Interface | undefined);
|
|
13
|
+
setup(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export declare const CoreSqlSchemaSetup: typeof CoreSqlSchemaSetupImpl & {
|
|
16
|
+
__abstraction: import("@webiny/di").Abstraction<import("../schemaSetup/abstractions").ISqlSchemaSetup>;
|
|
17
|
+
};
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createApiCoreSqlOperations } from "../createApiCoreSql.js";
|
|
2
|
+
import { KnexClient } from "../feature/KnexClient/index.js";
|
|
3
|
+
import { SqlSchemaConfig } from "../schemaConfig/index.js";
|
|
4
|
+
import { SqlSchemaSetup } from "../schemaSetup/index.js";
|
|
5
|
+
import { TableManager } from "../TableManager.js";
|
|
6
|
+
import { defineServiceManifestsTable } from "../serviceDiscovery/serviceManifestsTable.js";
|
|
7
|
+
class CoreSqlSchemaSetupImpl {
|
|
8
|
+
constructor(knex, schemaConfig){
|
|
9
|
+
this.knex = knex;
|
|
10
|
+
this.schemaConfig = schemaConfig;
|
|
11
|
+
this.name = "core";
|
|
12
|
+
}
|
|
13
|
+
async setup() {
|
|
14
|
+
const knex = this.knex.client;
|
|
15
|
+
const tableManager = new TableManager(knex, this.schemaConfig?.tableNamePrefix);
|
|
16
|
+
createApiCoreSqlOperations(knex, tableManager);
|
|
17
|
+
defineServiceManifestsTable(tableManager);
|
|
18
|
+
await tableManager.setup();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const CoreSqlSchemaSetup = SqlSchemaSetup.createImplementation({
|
|
22
|
+
implementation: CoreSqlSchemaSetupImpl,
|
|
23
|
+
dependencies: [
|
|
24
|
+
KnexClient,
|
|
25
|
+
[
|
|
26
|
+
SqlSchemaConfig,
|
|
27
|
+
{
|
|
28
|
+
optional: true
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
]
|
|
32
|
+
});
|
|
33
|
+
export { CoreSqlSchemaSetup };
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=CoreSqlSchemaSetup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coreStorage/CoreSqlSchemaSetup.js","sources":["../../src/coreStorage/CoreSqlSchemaSetup.ts"],"sourcesContent":["import { createApiCoreSqlOperations } from \"~/createApiCoreSql.js\";\nimport { KnexClient } from \"~/feature/KnexClient/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\nimport { SqlSchemaSetup } from \"~/schemaSetup/index.js\";\nimport { TableManager } from \"~/TableManager.js\";\nimport { defineServiceManifestsTable } from \"~/serviceDiscovery/serviceManifestsTable.js\";\n\n/**\n * The `core` schema setup step: the tables of users, tenancy, security, the key-value store and the\n * service manifests, on the container's connection.\n */\nclass CoreSqlSchemaSetupImpl implements SqlSchemaSetup.Interface {\n public readonly name = \"core\";\n\n public constructor(\n private readonly knex: KnexClient.Interface,\n private readonly schemaConfig?: SqlSchemaConfig.Interface\n ) {}\n\n public async setup(): Promise<void> {\n const knex = this.knex.client;\n const tableManager = new TableManager(knex, this.schemaConfig?.tableNamePrefix);\n // Building them declares their tables on the manager.\n createApiCoreSqlOperations(knex, tableManager);\n defineServiceManifestsTable(tableManager);\n await tableManager.setup();\n }\n}\n\nexport const CoreSqlSchemaSetup = SqlSchemaSetup.createImplementation({\n implementation: CoreSqlSchemaSetupImpl,\n dependencies: [KnexClient, [SqlSchemaConfig, { optional: true }]]\n});\n"],"names":["CoreSqlSchemaSetupImpl","knex","schemaConfig","tableManager","TableManager","createApiCoreSqlOperations","defineServiceManifestsTable","CoreSqlSchemaSetup","SqlSchemaSetup","KnexClient","SqlSchemaConfig"],"mappings":";;;;;;AAWA,MAAMA;IAGF,YACqBC,IAA0B,EAC1BC,YAAwC,CAC3D;aAFmBD,IAAI,GAAJA;aACAC,YAAY,GAAZA;aAJL,IAAI,GAAG;IAKpB;IAEH,MAAa,QAAuB;QAChC,MAAMD,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM;QAC7B,MAAME,eAAe,IAAIC,aAAaH,MAAM,IAAI,CAAC,YAAY,EAAE;QAE/DI,2BAA2BJ,MAAME;QACjCG,4BAA4BH;QAC5B,MAAMA,aAAa,KAAK;IAC5B;AACJ;AAEO,MAAMI,qBAAqBC,eAAe,oBAAoB,CAAC;IAClE,gBAAgBR;IAChB,cAAc;QAACS;QAAY;YAACC;YAAiB;gBAAE,UAAU;YAAK;SAAE;KAAC;AACrE"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ApiCoreStorageOperationsFactory } from "@webiny/api-core";
|
|
2
|
+
import type { ApiCoreStorageOperations } from "@webiny/api-core/types/core.js";
|
|
3
|
+
import { KnexClient } from "../feature/KnexClient/index.js";
|
|
4
|
+
import { SqlSchemaConfig } from "../schemaConfig/index.js";
|
|
5
|
+
/** Builds the core storage operations on the container's connection and table prefix. */
|
|
6
|
+
declare class SqlApiCoreStorageOperationsFactoryImpl implements ApiCoreStorageOperationsFactory.Interface {
|
|
7
|
+
private readonly knex;
|
|
8
|
+
private readonly schemaConfig?;
|
|
9
|
+
constructor(knex: KnexClient.Interface, schemaConfig?: SqlSchemaConfig.Interface | undefined);
|
|
10
|
+
create(): ApiCoreStorageOperations;
|
|
11
|
+
}
|
|
12
|
+
export declare const SqlApiCoreStorageOperationsFactory: typeof SqlApiCoreStorageOperationsFactoryImpl & {
|
|
13
|
+
__abstraction: import("@webiny/di").Abstraction<import("@webiny/api-core/features/storageOperations/abstractions").IApiCoreStorageOperationsFactory>;
|
|
14
|
+
};
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ApiCoreStorageOperationsFactory } from "@webiny/api-core";
|
|
2
|
+
import { createApiCoreSql } from "../createApiCoreSql.js";
|
|
3
|
+
import { KnexClient } from "../feature/KnexClient/index.js";
|
|
4
|
+
import { SqlSchemaConfig } from "../schemaConfig/index.js";
|
|
5
|
+
class SqlApiCoreStorageOperationsFactoryImpl {
|
|
6
|
+
constructor(knex, schemaConfig){
|
|
7
|
+
this.knex = knex;
|
|
8
|
+
this.schemaConfig = schemaConfig;
|
|
9
|
+
}
|
|
10
|
+
create() {
|
|
11
|
+
return createApiCoreSql({
|
|
12
|
+
knex: this.knex.client,
|
|
13
|
+
tableNamePrefix: this.schemaConfig?.tableNamePrefix,
|
|
14
|
+
schemaManaged: this.schemaConfig?.isManaged() === true
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const SqlApiCoreStorageOperationsFactory = ApiCoreStorageOperationsFactory.createImplementation({
|
|
19
|
+
implementation: SqlApiCoreStorageOperationsFactoryImpl,
|
|
20
|
+
dependencies: [
|
|
21
|
+
KnexClient,
|
|
22
|
+
[
|
|
23
|
+
SqlSchemaConfig,
|
|
24
|
+
{
|
|
25
|
+
optional: true
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
]
|
|
29
|
+
});
|
|
30
|
+
export { SqlApiCoreStorageOperationsFactory };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=SqlApiCoreStorageOperationsFactory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coreStorage/SqlApiCoreStorageOperationsFactory.js","sources":["../../src/coreStorage/SqlApiCoreStorageOperationsFactory.ts"],"sourcesContent":["import { ApiCoreStorageOperationsFactory } from \"@webiny/api-core\";\nimport type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport { createApiCoreSql } from \"~/createApiCoreSql.js\";\nimport { KnexClient } from \"~/feature/KnexClient/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\n\n/** Builds the core storage operations on the container's connection and table prefix. */\nclass SqlApiCoreStorageOperationsFactoryImpl implements ApiCoreStorageOperationsFactory.Interface {\n public constructor(\n private readonly knex: KnexClient.Interface,\n private readonly schemaConfig?: SqlSchemaConfig.Interface\n ) {}\n\n public create(): ApiCoreStorageOperations {\n return createApiCoreSql({\n knex: this.knex.client,\n tableNamePrefix: this.schemaConfig?.tableNamePrefix,\n schemaManaged: this.schemaConfig?.isManaged() === true\n });\n }\n}\n\nexport const SqlApiCoreStorageOperationsFactory =\n ApiCoreStorageOperationsFactory.createImplementation({\n implementation: SqlApiCoreStorageOperationsFactoryImpl,\n dependencies: [KnexClient, [SqlSchemaConfig, { optional: true }]]\n });\n"],"names":["SqlApiCoreStorageOperationsFactoryImpl","knex","schemaConfig","createApiCoreSql","SqlApiCoreStorageOperationsFactory","ApiCoreStorageOperationsFactory","KnexClient","SqlSchemaConfig"],"mappings":";;;;AAOA,MAAMA;IACF,YACqBC,IAA0B,EAC1BC,YAAwC,CAC3D;aAFmBD,IAAI,GAAJA;aACAC,YAAY,GAAZA;IAClB;IAEI,SAAmC;QACtC,OAAOC,iBAAiB;YACpB,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM;YACtB,iBAAiB,IAAI,CAAC,YAAY,EAAE;YACpC,eAAe,IAAI,CAAC,YAAY,EAAE,gBAAgB;QACtD;IACJ;AACJ;AAEO,MAAMC,qCACTC,gCAAgC,oBAAoB,CAAC;IACjD,gBAAgBL;IAChB,cAAc;QAACM;QAAY;YAACC;YAAiB;gBAAE,UAAU;YAAK;SAAE;KAAC;AACrE"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SQL core storage of a request: the implementation of `ApiCoreStorageOperationsFactory`, which
|
|
3
|
+
* `ApiCoreFeature.register` resolves and builds, and the `core` schema setup step. Mirrors
|
|
4
|
+
* `ApiCoreDdbFeature`.
|
|
5
|
+
*
|
|
6
|
+
* Registered per request (by the SQL storage's `RequestStorage`). It runs on what the root holds:
|
|
7
|
+
* the connection (`KnexClient`) and the table prefix and schema-managed setting (`SqlSchemaConfig`),
|
|
8
|
+
* both registered by `SqlConnectionFeature`.
|
|
9
|
+
*/
|
|
10
|
+
export declare const ApiCoreSqlFeature: {
|
|
11
|
+
name: string;
|
|
12
|
+
register(container: import("@webiny/di").Container): void;
|
|
13
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createFeature } from "@webiny/feature/api";
|
|
2
|
+
import { SqlApiCoreStorageOperationsFactory } from "./SqlApiCoreStorageOperationsFactory.js";
|
|
3
|
+
import { CoreSqlSchemaSetup } from "./CoreSqlSchemaSetup.js";
|
|
4
|
+
const ApiCoreSqlFeature = createFeature({
|
|
5
|
+
name: "ApiCoreSql",
|
|
6
|
+
register (container) {
|
|
7
|
+
container.register(SqlApiCoreStorageOperationsFactory);
|
|
8
|
+
container.register(CoreSqlSchemaSetup);
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
export { ApiCoreSqlFeature };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=feature.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coreStorage/feature.js","sources":["../../src/coreStorage/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { SqlApiCoreStorageOperationsFactory } from \"./SqlApiCoreStorageOperationsFactory.js\";\nimport { CoreSqlSchemaSetup } from \"./CoreSqlSchemaSetup.js\";\n\n/**\n * The SQL core storage of a request: the implementation of `ApiCoreStorageOperationsFactory`, which\n * `ApiCoreFeature.register` resolves and builds, and the `core` schema setup step. Mirrors\n * `ApiCoreDdbFeature`.\n *\n * Registered per request (by the SQL storage's `RequestStorage`). It runs on what the root holds:\n * the connection (`KnexClient`) and the table prefix and schema-managed setting (`SqlSchemaConfig`),\n * both registered by `SqlConnectionFeature`.\n */\nexport const ApiCoreSqlFeature = createFeature({\n name: \"ApiCoreSql\",\n register(container) {\n container.register(SqlApiCoreStorageOperationsFactory);\n container.register(CoreSqlSchemaSetup);\n }\n});\n"],"names":["ApiCoreSqlFeature","createFeature","container","SqlApiCoreStorageOperationsFactory","CoreSqlSchemaSetup"],"mappings":";;;AAaO,MAAMA,oBAAoBC,cAAc;IAC3C,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;QACnBD,UAAU,QAAQ,CAACE;IACvB;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { ApiCoreSqlFeature } from "./feature.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { ApiCoreSqlFeature } from "./feature.js";
|
package/createApiCoreSql.d.ts
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
2
|
import type { ApiCoreStorageOperations } from "@webiny/api-core/types/core.js";
|
|
3
|
+
import { TableManager } from "./TableManager.js";
|
|
3
4
|
interface CreateApiCoreSqlParams {
|
|
4
5
|
knex: Knex;
|
|
5
6
|
tableNamePrefix?: string;
|
|
7
|
+
/** The schema was set up before the API took traffic: no table checks at runtime. */
|
|
8
|
+
schemaManaged?: boolean;
|
|
6
9
|
}
|
|
7
|
-
|
|
10
|
+
/**
|
|
11
|
+
* The core storage operations (users, tenancy, security, key-value store) on `tableManager`, which
|
|
12
|
+
* they declare their tables on.
|
|
13
|
+
*/
|
|
14
|
+
export declare const createApiCoreSqlOperations: (knex: Knex, tableManager: TableManager) => ApiCoreStorageOperations;
|
|
15
|
+
/**
|
|
16
|
+
* The core storage operations on a connection. Cheap to build: what the table checks learn is kept
|
|
17
|
+
* for the process (see `TableManager`), so they are built per request.
|
|
18
|
+
*/
|
|
19
|
+
export declare const createApiCoreSql: ({ knex, tableNamePrefix, schemaManaged }: CreateApiCoreSqlParams) => ApiCoreStorageOperations;
|
|
8
20
|
export {};
|
package/createApiCoreSql.js
CHANGED
|
@@ -1,14 +1,9 @@
|
|
|
1
|
-
import { ServiceDiscovery } from "@webiny/api-core/features/serviceDiscovery/index.js";
|
|
2
1
|
import { createStorageOperations } from "./adminUsers/index.js";
|
|
3
2
|
import { createStorageOperations as index_js_createStorageOperations } from "./tenancy/index.js";
|
|
4
3
|
import { createStorageOperations as external_security_index_js_createStorageOperations } from "./security/index.js";
|
|
5
4
|
import { createStorageOperations as external_keyValueStore_index_js_createStorageOperations } from "./keyValueStore/index.js";
|
|
6
5
|
import { TableManager } from "./TableManager.js";
|
|
7
|
-
|
|
8
|
-
const createApiCoreSql = ({ knex, tableNamePrefix })=>{
|
|
9
|
-
const tableManager = new TableManager(knex, tableNamePrefix);
|
|
10
|
-
ServiceDiscovery.setLoader(new SqlServiceManifestLoader(knex, tableManager));
|
|
11
|
-
return {
|
|
6
|
+
const createApiCoreSqlOperations = (knex, tableManager)=>({
|
|
12
7
|
usersStorageOperations: createStorageOperations({
|
|
13
8
|
knex,
|
|
14
9
|
tableManager
|
|
@@ -25,8 +20,13 @@ const createApiCoreSql = ({ knex, tableNamePrefix })=>{
|
|
|
25
20
|
knex,
|
|
26
21
|
tableManager
|
|
27
22
|
})
|
|
28
|
-
};
|
|
23
|
+
});
|
|
24
|
+
const createApiCoreSql = ({ knex, tableNamePrefix, schemaManaged })=>{
|
|
25
|
+
const tableManager = new TableManager(knex, tableNamePrefix, {
|
|
26
|
+
schemaManaged
|
|
27
|
+
});
|
|
28
|
+
return createApiCoreSqlOperations(knex, tableManager);
|
|
29
29
|
};
|
|
30
|
-
export { createApiCoreSql };
|
|
30
|
+
export { createApiCoreSql, createApiCoreSqlOperations };
|
|
31
31
|
|
|
32
32
|
//# sourceMappingURL=createApiCoreSql.js.map
|
package/createApiCoreSql.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createApiCoreSql.js","sources":["../src/createApiCoreSql.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"createApiCoreSql.js","sources":["../src/createApiCoreSql.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type { ApiCoreStorageOperations } from \"@webiny/api-core/types/core.js\";\nimport { createStorageOperations as createUsersStorageOperations } from \"./adminUsers/index.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"./tenancy/index.js\";\nimport { createStorageOperations as createSecurityStorageOperations } from \"./security/index.js\";\nimport { createStorageOperations as createKeyValueStorageOperations } from \"./keyValueStore/index.js\";\nimport { TableManager } from \"./TableManager.js\";\n\ninterface CreateApiCoreSqlParams {\n knex: Knex;\n tableNamePrefix?: string;\n /** The schema was set up before the API took traffic: no table checks at runtime. */\n schemaManaged?: boolean;\n}\n\n/**\n * The core storage operations (users, tenancy, security, key-value store) on `tableManager`, which\n * they declare their tables on.\n */\nexport const createApiCoreSqlOperations = (\n knex: Knex,\n tableManager: TableManager\n): ApiCoreStorageOperations => {\n return {\n usersStorageOperations: createUsersStorageOperations({ knex, tableManager }),\n tenancyStorageOperations: createTenancyStorageOperations({ knex, tableManager }),\n securityStorageOperations: createSecurityStorageOperations({ knex, tableManager }),\n keyValueStorageOperations: createKeyValueStorageOperations({ knex, tableManager })\n };\n};\n\n/**\n * The core storage operations on a connection. Cheap to build: what the table checks learn is kept\n * for the process (see `TableManager`), so they are built per request.\n */\nexport const createApiCoreSql = ({\n knex,\n tableNamePrefix,\n schemaManaged\n}: CreateApiCoreSqlParams): ApiCoreStorageOperations => {\n const tableManager = new TableManager(knex, tableNamePrefix, { schemaManaged });\n return createApiCoreSqlOperations(knex, tableManager);\n};\n"],"names":["createApiCoreSqlOperations","knex","tableManager","createUsersStorageOperations","createTenancyStorageOperations","createSecurityStorageOperations","createKeyValueStorageOperations","createApiCoreSql","tableNamePrefix","schemaManaged","TableManager"],"mappings":";;;;;AAmBO,MAAMA,6BAA6B,CACtCC,MACAC,eAEO;QACH,wBAAwBC,wBAA6B;YAAEF;YAAMC;QAAa;QAC1E,0BAA0BE,iCAA+B;YAAEH;YAAMC;QAAa;QAC9E,2BAA2BG,mDAAgC;YAAEJ;YAAMC;QAAa;QAChF,2BAA2BI,wDAAgC;YAAEL;YAAMC;QAAa;IACpF;AAOG,MAAMK,mBAAmB,CAAC,EAC7BN,IAAI,EACJO,eAAe,EACfC,aAAa,EACQ;IACrB,MAAMP,eAAe,IAAIQ,aAAaT,MAAMO,iBAAiB;QAAEC;IAAc;IAC7E,OAAOT,2BAA2BC,MAAMC;AAC5C"}
|
package/index.d.ts
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
import type { Knex } from "knex";
|
|
2
2
|
export { createApiCoreSql } from "./createApiCoreSql.js";
|
|
3
|
-
export { ApiCoreSqlFeature } from "./
|
|
4
|
-
export
|
|
3
|
+
export { ApiCoreSqlFeature } from "./coreStorage/index.js";
|
|
4
|
+
export { SqlConnectionFeature, setSqlServiceManifestLoader } from "./connection/index.js";
|
|
5
|
+
export type { SqlConnectionConfig } from "./connection/index.js";
|
|
5
6
|
export { getSqlTablePrefix } from "./getSqlTablePrefix.js";
|
|
6
|
-
export {
|
|
7
|
+
export { TableManager } from "./TableManager.js";
|
|
8
|
+
export type { TableManagerOptions } from "./TableManager.js";
|
|
9
|
+
export { SqlSchemaConfig } from "./schemaConfig/index.js";
|
|
10
|
+
export { SqlSchemaSetup, SqlSchemaSetupRunner, runSchemaSetupSteps } from "./schemaSetup/index.js";
|
|
11
|
+
export type { ISqlSchemaSetupRequest, RequiredSqlSchemaSetup, RunSchemaSetupStepsParams, SqlSchemaSetupRunParams } from "./schemaSetup/index.js";
|
|
12
|
+
export { getSchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
13
|
+
export { getConnectionKey } from "./schemaMemory/getConnectionKey.js";
|
|
14
|
+
export { ensureTable, createTableIfMissing, recordTable } from "./schemaMemory/ensureTable.js";
|
|
15
|
+
export type { EnsureTableParams, TableCreator } from "./schemaMemory/ensureTable.js";
|
|
16
|
+
export type { ISchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
17
|
+
export type { SqlStorage } from "./storage/types.js";
|
|
18
|
+
export * from "./connectionRetry/index.js";
|
|
19
|
+
export { SqlServiceManifestLoader, SqlServiceManifestWriter } from "./serviceDiscovery/index.js";
|
|
7
20
|
export { KnexClient } from "./feature/KnexClient/index.js";
|
|
8
21
|
interface IRegisterApiCoreSqlExtension {
|
|
9
22
|
knex: Knex;
|
package/index.js
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import { createRegisterExtensionPlugin } from "@webiny/handler";
|
|
2
2
|
import { KnexClient, KnexClientFeature } from "./feature/KnexClient/index.js";
|
|
3
|
+
export * from "./connectionRetry/index.js";
|
|
3
4
|
const registerSQLCore = ({ knex })=>createRegisterExtensionPlugin(async (context)=>{
|
|
4
5
|
KnexClientFeature.register(context.container, knex);
|
|
5
6
|
});
|
|
6
7
|
export { createApiCoreSql } from "./createApiCoreSql.js";
|
|
7
|
-
export { ApiCoreSqlFeature } from "./
|
|
8
|
+
export { ApiCoreSqlFeature } from "./coreStorage/index.js";
|
|
9
|
+
export { SqlConnectionFeature, setSqlServiceManifestLoader } from "./connection/index.js";
|
|
8
10
|
export { getSqlTablePrefix } from "./getSqlTablePrefix.js";
|
|
9
|
-
export {
|
|
11
|
+
export { TableManager } from "./TableManager.js";
|
|
12
|
+
export { SqlSchemaConfig } from "./schemaConfig/index.js";
|
|
13
|
+
export { SqlSchemaSetup, SqlSchemaSetupRunner, runSchemaSetupSteps } from "./schemaSetup/index.js";
|
|
14
|
+
export { getSchemaMemory } from "./schemaMemory/getSchemaMemory.js";
|
|
15
|
+
export { getConnectionKey } from "./schemaMemory/getConnectionKey.js";
|
|
16
|
+
export { createTableIfMissing, ensureTable, recordTable } from "./schemaMemory/ensureTable.js";
|
|
17
|
+
export { SqlServiceManifestLoader, SqlServiceManifestWriter } from "./serviceDiscovery/index.js";
|
|
10
18
|
export { KnexClient, registerSQLCore };
|
|
11
19
|
|
|
12
20
|
//# 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\";\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 { SqlSchemaSetup, SqlSchemaSetupRunner, runSchemaSetupSteps } from \"./schemaSetup/index.js\";\nexport type {\n ISqlSchemaSetupRequest,\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 } from \"./schemaMemory/ensureTable.js\";\nexport type { ISchemaMemory } from \"./schemaMemory/getSchemaMemory.js\";\nexport type { SqlStorage } from \"./storage/types.js\";\nexport * from \"./connectionRetry/index.js\";\nexport { SqlServiceManifestLoader, SqlServiceManifestWriter } from \"./serviceDiscovery/index.js\";\n\nexport { KnexClient } from \"./feature/KnexClient/index.js\";\n\ninterface IRegisterApiCoreSqlExtension {\n knex: Knex;\n}\n\nexport const registerSQLCore = ({ knex }: IRegisterApiCoreSqlExtension) => {\n return createRegisterExtensionPlugin(async context => {\n KnexClientFeature.register(context.container, knex);\n });\n};\n"],"names":["registerSQLCore","knex","createRegisterExtensionPlugin","context","KnexClientFeature"],"mappings":";;;AAkCO,MAAMA,kBAAkB,CAAC,EAAEC,IAAI,EAAgC,GAC3DC,8BAA8B,OAAMC;QACvCC,kBAAkB,QAAQ,CAACD,QAAQ,SAAS,EAAEF;IAClD"}
|
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,aAAa,OAAO,GAAG,WAAW;YAC7CA,MAAM,IAAI,CAAC,OAAO,WAAW;YAC7BA,MAAM,IAAI,CAAC,SAAS,WAAW;YAC/BA,MAAM,IAAI,CAAC,SAAS,WAAW;YAC/BA,MAAM,QAAQ,CAAC;QACnB;QACA,MAAMF,aAAa,MAAM,CAACP,uBAAuBS,CAAAA;YAC7CA,MAAM,IAAI,CAAC,aAAa,OAAO,GAAG,WAAW;YAC7CA,MAAM,IAAI,CAAC,SAAS,WAAW;YAC/BA,MAAM,IAAI,CAAC,cAAc,WAAW;YACpCA,MAAM,IA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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,AAA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AI,KAAK;wBAAE;oBAC9D,SAASe,KAAK,MAAM,GAAGJ,QAAQK,IAAI,CAACA,KAAK,MAAM,GAAG,EAAE,CAAC,GAAG,GAAG;gBAC/D;YACJ,EAAE,OAAOf,KAAK;gBACV,MAAMC,YAAY,IAAI,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEI;wBAAYjB;wBAAOyB;oBAAM;gBACrC;YACJ;QACJ;QAEA,MAAM,QAAO1B,GAAW,EAAEC,KAAa,EAAEgB,OAAgC;YACrE,MAAMxB;YAEN,MAAMW,YAAYL,gBAAgBC,KAAKC;YAEvC,IAAI;gBACA,OAAO,MAAMb,KAAK,WAAW,CAAC,OAAMO;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"}
|
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.3fddf667ea",
|
|
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.3fddf667ea",
|
|
25
|
+
"@webiny/error": "0.0.0-unstable.3fddf667ea",
|
|
26
|
+
"@webiny/feature": "0.0.0-unstable.3fddf667ea",
|
|
27
|
+
"@webiny/handler": "0.0.0-unstable.3fddf667ea",
|
|
28
28
|
"knex": "3.3.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
|
-
"@webiny/build-tools": "0.0.0-unstable.
|
|
31
|
+
"@webiny/build-tools": "0.0.0-unstable.3fddf667ea",
|
|
32
32
|
"better-sqlite3": "13.0.3",
|
|
33
|
+
"pg": "8.23.1",
|
|
33
34
|
"typescript": "7.0.2",
|
|
34
|
-
"vitest": "
|
|
35
|
+
"vitest": "5.0.5"
|
|
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,28 @@
|
|
|
1
|
+
import type { Knex } from "knex";
|
|
2
|
+
import type { ISchemaMemory } from "./getSchemaMemory.js";
|
|
3
|
+
export type TableCreator = (table: Knex.CreateTableBuilder) => void;
|
|
4
|
+
export interface EnsureTableParams {
|
|
5
|
+
/** The connection or transaction to check and create the table on. */
|
|
6
|
+
knex: Knex;
|
|
7
|
+
/** What the process knows about the tables this one belongs to. */
|
|
8
|
+
memory: ISchemaMemory;
|
|
9
|
+
tableName: string;
|
|
10
|
+
create: TableCreator;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Creates the table if it doesn't exist yet, once per process: a table the memory knows is skipped,
|
|
14
|
+
* and concurrent callers on the same handle wait for one check. What a transaction creates is
|
|
15
|
+
* remembered only by `recordTable` after it commits, never here, and nothing started before the
|
|
16
|
+
* memory was reset is recorded after it.
|
|
17
|
+
*/
|
|
18
|
+
export declare function ensureTable(params: EnsureTableParams): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* Records that the table exists, unless `knex` is a transaction: it can still roll back, and the
|
|
21
|
+
* table with it, so only a committed table is known.
|
|
22
|
+
*/
|
|
23
|
+
export declare function recordTable(knex: Knex, memory: ISchemaMemory, tableName: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* Creates the table if it doesn't exist. Another process (or connection) may create it between the
|
|
26
|
+
* check and the create: if it exists after a failed create, that's success.
|
|
27
|
+
*/
|
|
28
|
+
export declare function createTableIfMissing(knex: Knex, tableName: string, create: TableCreator): Promise<void>;
|