@webiny/api-core-sql 0.0.0-unstable.5387e5f7c8 → 0.0.0-unstable.676006d08e
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 +74 -19
- 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 +160 -21
- 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
|
@@ -1,16 +1,73 @@
|
|
|
1
1
|
import { WebinyError } from "@webiny/error";
|
|
2
2
|
const TABLE_NAME = "webiny_core_key_value";
|
|
3
|
+
const COLLECTION_TABLE_NAME = "webiny_core_key_value_collection";
|
|
4
|
+
const isPrimaryKeyViolation = (error)=>{
|
|
5
|
+
const code = error?.code;
|
|
6
|
+
return "23505" === code || "ER_DUP_ENTRY" === code || "SQLITE_CONSTRAINT_PRIMARYKEY" === code || "SQLITE_CONSTRAINT_UNIQUE" === code;
|
|
7
|
+
};
|
|
3
8
|
const createStorageOperations = (params)=>{
|
|
4
9
|
const { knex, tableManager } = params;
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const
|
|
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
|
+
});
|
|
27
|
+
const ensureTable = async ()=>{
|
|
28
|
+
await ensureValuesTable();
|
|
29
|
+
await ensureCollectionTable();
|
|
30
|
+
};
|
|
31
|
+
const query = (trx = knex)=>trx(tableManager.resolve(TABLE_NAME));
|
|
32
|
+
const collectionQuery = (trx = knex)=>trx(tableManager.resolve(COLLECTION_TABLE_NAME));
|
|
33
|
+
const binaryKey = (column)=>{
|
|
34
|
+
switch(knex.client.dialect){
|
|
35
|
+
case "postgresql":
|
|
36
|
+
return {
|
|
37
|
+
sql: '?? COLLATE "C"',
|
|
38
|
+
bindings: [
|
|
39
|
+
column
|
|
40
|
+
]
|
|
41
|
+
};
|
|
42
|
+
case "mysql":
|
|
43
|
+
case "mysql2":
|
|
44
|
+
return {
|
|
45
|
+
sql: "BINARY ??",
|
|
46
|
+
bindings: [
|
|
47
|
+
column
|
|
48
|
+
]
|
|
49
|
+
};
|
|
50
|
+
default:
|
|
51
|
+
return {
|
|
52
|
+
sql: "??",
|
|
53
|
+
bindings: [
|
|
54
|
+
column
|
|
55
|
+
]
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
};
|
|
13
59
|
const createScopedKey = (key, scope)=>`${scope}:${key}`;
|
|
60
|
+
const whereLive = (builder, scopedKey, equals)=>{
|
|
61
|
+
const now = new Date();
|
|
62
|
+
builder.where("scopedKey", scopedKey).where((live)=>live.whereNull("expiresAt").orWhere("expiresAt", ">", now));
|
|
63
|
+
if (void 0 === equals) return builder;
|
|
64
|
+
const expectedValue = JSON.stringify(equals);
|
|
65
|
+
const binaryValue = binaryKey("value");
|
|
66
|
+
return builder.whereRaw(`${binaryValue.sql} = ?`, [
|
|
67
|
+
...binaryValue.bindings,
|
|
68
|
+
expectedValue
|
|
69
|
+
]);
|
|
70
|
+
};
|
|
14
71
|
return {
|
|
15
72
|
async get (key, scope) {
|
|
16
73
|
await ensureTable();
|
|
@@ -19,7 +76,10 @@ const createStorageOperations = (params)=>{
|
|
|
19
76
|
const row = await query().where("scopedKey", scopedKey).first();
|
|
20
77
|
if (!row) return null;
|
|
21
78
|
if (row.expiresAt && new Date(row.expiresAt) <= new Date()) {
|
|
22
|
-
await
|
|
79
|
+
await knex.transaction(async (trx)=>{
|
|
80
|
+
await query(trx).where("scopedKey", scopedKey).delete();
|
|
81
|
+
await collectionQuery(trx).where("scopedKey", scopedKey).delete();
|
|
82
|
+
});
|
|
23
83
|
return null;
|
|
24
84
|
}
|
|
25
85
|
return {
|
|
@@ -39,18 +99,53 @@ const createStorageOperations = (params)=>{
|
|
|
39
99
|
},
|
|
40
100
|
async set (key, value, scope, options) {
|
|
41
101
|
await ensureTable();
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
102
|
+
const scopedKey = createScopedKey(key, scope);
|
|
103
|
+
const row = {
|
|
104
|
+
scopedKey,
|
|
105
|
+
key,
|
|
106
|
+
scope,
|
|
107
|
+
value: JSON.stringify(value),
|
|
108
|
+
expiresAt: options?.expiresAt ?? null
|
|
109
|
+
};
|
|
110
|
+
const collection = options?.collection;
|
|
111
|
+
const condition = options?.condition;
|
|
112
|
+
const writeCollection = async (trx)=>{
|
|
113
|
+
if (collection) return void await collectionQuery(trx).insert({
|
|
46
114
|
scopedKey,
|
|
47
|
-
key,
|
|
48
115
|
scope,
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
};
|
|
52
|
-
await
|
|
116
|
+
collection,
|
|
117
|
+
key
|
|
118
|
+
}).onConflict("scopedKey").merge();
|
|
119
|
+
await collectionQuery(trx).where("scopedKey", scopedKey).delete();
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
if (condition?.exists === false) {
|
|
123
|
+
await knex.transaction(async (trx)=>{
|
|
124
|
+
const now = new Date();
|
|
125
|
+
const expired = await query(trx).where("scopedKey", scopedKey).whereNotNull("expiresAt").where("expiresAt", "<=", now).first("scopedKey");
|
|
126
|
+
if (expired) await query(trx).where("scopedKey", scopedKey).where("expiresAt", "<=", now).delete();
|
|
127
|
+
await query(trx).insert(row);
|
|
128
|
+
await writeCollection(trx);
|
|
129
|
+
});
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
if (condition) return await knex.transaction(async (trx)=>{
|
|
133
|
+
const records = query(trx);
|
|
134
|
+
const updated = await whereLive(records, scopedKey, condition.equals).update({
|
|
135
|
+
value: row.value,
|
|
136
|
+
expiresAt: row.expiresAt
|
|
137
|
+
});
|
|
138
|
+
if (0 === updated) return false;
|
|
139
|
+
await writeCollection(trx);
|
|
140
|
+
return true;
|
|
141
|
+
});
|
|
142
|
+
await knex.transaction(async (trx)=>{
|
|
143
|
+
await query(trx).insert(row).onConflict("scopedKey").merge();
|
|
144
|
+
await writeCollection(trx);
|
|
145
|
+
});
|
|
146
|
+
return true;
|
|
53
147
|
} catch (err) {
|
|
148
|
+
if (condition?.exists === false && isPrimaryKeyViolation(err)) return false;
|
|
54
149
|
throw WebinyError.from(err, {
|
|
55
150
|
message: "Could not set key-value record.",
|
|
56
151
|
code: "SET_KEY_VALUE_ERROR",
|
|
@@ -61,11 +156,55 @@ const createStorageOperations = (params)=>{
|
|
|
61
156
|
});
|
|
62
157
|
}
|
|
63
158
|
},
|
|
64
|
-
async
|
|
159
|
+
async list ({ collection, scope, limit, reverse, after }) {
|
|
65
160
|
await ensureTable();
|
|
66
161
|
try {
|
|
67
|
-
const
|
|
68
|
-
|
|
162
|
+
const builder = knex.from({
|
|
163
|
+
c: tableManager.resolve(COLLECTION_TABLE_NAME)
|
|
164
|
+
}).join({
|
|
165
|
+
kv: tableManager.resolve(TABLE_NAME)
|
|
166
|
+
}, "kv.scopedKey", "c.scopedKey").where("c.scope", scope).where("c.collection", collection).select("kv.key", "kv.value", "kv.expiresAt");
|
|
167
|
+
const orderedKey = binaryKey("c.key");
|
|
168
|
+
if (void 0 !== after) builder.whereRaw(`${orderedKey.sql} ${reverse ? "<" : ">"} ?`, [
|
|
169
|
+
...orderedKey.bindings,
|
|
170
|
+
after
|
|
171
|
+
]);
|
|
172
|
+
const rows = await builder.orderByRaw(`${orderedKey.sql} ${reverse ? "DESC" : "ASC"}`, orderedKey.bindings).limit(limit + 1);
|
|
173
|
+
const page = rows.slice(0, limit);
|
|
174
|
+
const now = new Date();
|
|
175
|
+
return {
|
|
176
|
+
items: page.filter((row)=>!row.expiresAt || new Date(row.expiresAt) > now).map((row)=>({
|
|
177
|
+
key: row.key,
|
|
178
|
+
value: JSON.parse(row.value)
|
|
179
|
+
})),
|
|
180
|
+
lastKey: rows.length > limit ? page[page.length - 1].key : null
|
|
181
|
+
};
|
|
182
|
+
} catch (err) {
|
|
183
|
+
throw WebinyError.from(err, {
|
|
184
|
+
message: "Could not list key-value records.",
|
|
185
|
+
code: "LIST_KEY_VALUE_ERROR",
|
|
186
|
+
data: {
|
|
187
|
+
collection,
|
|
188
|
+
scope,
|
|
189
|
+
after
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
async delete (key, scope, options) {
|
|
195
|
+
await ensureTable();
|
|
196
|
+
const scopedKey = createScopedKey(key, scope);
|
|
197
|
+
try {
|
|
198
|
+
return await knex.transaction(async (trx)=>{
|
|
199
|
+
const condition = options?.condition;
|
|
200
|
+
if (condition) {
|
|
201
|
+
const records = query(trx);
|
|
202
|
+
const deleted = await whereLive(records, scopedKey, condition.equals).delete();
|
|
203
|
+
if (0 === deleted) return false;
|
|
204
|
+
} else await query(trx).where("scopedKey", scopedKey).delete();
|
|
205
|
+
await collectionQuery(trx).where("scopedKey", scopedKey).delete();
|
|
206
|
+
return true;
|
|
207
|
+
});
|
|
69
208
|
} catch (err) {
|
|
70
209
|
throw WebinyError.from(err, {
|
|
71
210
|
message: "Could not delete key-value record.",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyValueStore/index.js","sources":["../../src/keyValueStore/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n IKeyValueStorageOperations,\n IKeyValueStoreSetOptions\n} 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\ninterface IKeyValueRow {\n scopedKey: string;\n key: string;\n scope: string;\n value: string;\n expiresAt: Date | null;\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 = () => {\n return 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 };\n\n const query = () => {\n return knex<IKeyValueRow>(tableManager.resolve(TABLE_NAME));\n };\n\n const createScopedKey = (key: string, scope: string): string => {\n return `${scope}:${key}`;\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 query().where(\"scopedKey\", scopedKey).delete();\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 try {\n const scopedKey = createScopedKey(key, scope);\n const expiresAt = options?.expiresAt ?? null;\n\n const row: IKeyValueRow = {\n scopedKey,\n key,\n scope,\n value: JSON.stringify(value),\n expiresAt\n };\n\n await query().insert(row).onConflict(\"scopedKey\").merge();\n } catch (err) {\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 delete(key: string, scope: string) {\n await ensureTable();\n\n try {\n const scopedKey = createScopedKey(key, scope);\n await query().where(\"scopedKey\", scopedKey).delete();\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","createStorageOperations","params","knex","tableManager","ensureTable","table","query","createScopedKey","key","scope","scopedKey","row","Date","JSON","err","WebinyError","value","options","expiresAt"],"mappings":";AAQA,MAAMA,aAAa;AAeZ,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,cAAc,IACTD,aAAa,MAAM,CAACJ,YAAYM,CAAAA;YACnCA,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;IAGJ,MAAMC,QAAQ,IACHJ,KAAmBC,aAAa,OAAO,CAACJ;IAGnD,MAAMQ,kBAAkB,CAACC,KAAaC,QAC3B,GAAGA,MAAM,CAAC,EAAED,KAAK;IAG5B,OAAO;QACH,MAAM,KAAIA,GAAW,EAAEC,KAAa;YAChC,MAAML;YAEN,IAAI;gBACA,MAAMM,YAAYH,gBAAgBC,KAAKC;gBACvC,MAAME,MAAM,MAAML,QAAQ,KAAK,CAAC,aAAaI,WAAW,KAAK;gBAE7D,IAAI,CAACC,KACD,OAAO;gBAGX,IAAIA,IAAI,SAAS,IAAI,IAAIC,KAAKD,IAAI,SAAS,KAAK,IAAIC,QAAQ;oBACxD,MAAMN,QAAQ,KAAK,CAAC,aAAaI,WAAW,MAAM;oBAClD,OAAO;gBACX;gBAEA,OAAO;oBACHF;oBACA,OAAOK,KAAK,KAAK,CAACF,IAAI,KAAK;gBAC/B;YACJ,EAAE,OAAOG,KAAK;gBACV,MAAMC,YAAY,IAAI,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEN;wBAAKC;oBAAM;gBACvB;YACJ;QACJ;QAEA,MAAM,KAAID,GAAW,EAAEQ,KAAU,EAAEP,KAAa,EAAEQ,OAAkC;YAChF,MAAMb;YAEN,IAAI;gBACA,MAAMM,YAAYH,gBAAgBC,KAAKC;gBACvC,MAAMS,YAAYD,SAAS,aAAa;gBAExC,MAAMN,MAAoB;oBACtBD;oBACAF;oBACAC;oBACA,OAAOI,KAAK,SAAS,CAACG;oBACtBE;gBACJ;gBAEA,MAAMZ,QAAQ,MAAM,CAACK,KAAK,UAAU,CAAC,aAAa,KAAK;YAC3D,EAAE,OAAOG,KAAK;gBACV,MAAMC,YAAY,IAAI,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEN;wBAAKC;oBAAM;gBACvB;YACJ;QACJ;QAEA,MAAM,QAAOD,GAAW,EAAEC,KAAa;YACnC,MAAML;YAEN,IAAI;gBACA,MAAMM,YAAYH,gBAAgBC,KAAKC;gBACvC,MAAMH,QAAQ,KAAK,CAAC,aAAaI,WAAW,MAAM;YACtD,EAAE,OAAOI,KAAK;gBACV,MAAMC,YAAY,IAAI,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEN;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,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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.676006d08e",
|
|
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.676006d08e",
|
|
25
|
+
"@webiny/error": "0.0.0-unstable.676006d08e",
|
|
26
|
+
"@webiny/feature": "0.0.0-unstable.676006d08e",
|
|
27
|
+
"@webiny/handler": "0.0.0-unstable.676006d08e",
|
|
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.676006d08e",
|
|
32
|
+
"better-sqlite3": "13.2.0",
|
|
33
|
+
"pg": "8.23.1",
|
|
33
34
|
"typescript": "7.0.2",
|
|
34
|
-
"vitest": "
|
|
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,IAAI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,MAAMM;QAExB;IACJ;IACA,IAAI;QACA,MAAMN,KAAK,MAAM,CAAC,WAAW,CAACM,WAAWC;IAC7C,EAAE,OAAOS,OAAO;QACZ,IAAI,MAAMhB,KAAK,MAAM,CAAC,QAAQ,CAACM,YAC3B;QAEJ,MAAMU;IACV;AACJ"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Knex } from "knex";
|
|
2
|
+
/**
|
|
3
|
+
* A short id for the database a Knex instance connects to, for keys of the process's schema memory
|
|
4
|
+
* (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:
|
|
5
|
+
* what setup learns in a transaction is what the connection knows afterwards. Two Knex instances
|
|
6
|
+
* built separately get different ids, even for the same database.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getConnectionKey(knex: Knex): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const keys = new WeakMap();
|
|
2
|
+
let next = 0;
|
|
3
|
+
function getConnectionKey(knex) {
|
|
4
|
+
const identity = knex.client?.config ?? knex;
|
|
5
|
+
let key = keys.get(identity);
|
|
6
|
+
if (!key) {
|
|
7
|
+
next += 1;
|
|
8
|
+
key = `db${next}`;
|
|
9
|
+
keys.set(identity, key);
|
|
10
|
+
}
|
|
11
|
+
return key;
|
|
12
|
+
}
|
|
13
|
+
export { getConnectionKey };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=getConnectionKey.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schemaMemory/getConnectionKey.js","sources":["../../src/schemaMemory/getConnectionKey.ts"],"sourcesContent":["import type { Knex } from \"knex\";\n\nconst keys = new WeakMap<object, string>();\nlet next = 0;\n\n/**\n * A short id for the database a Knex instance connects to, for keys of the process's schema memory\n * (`getSchemaMemory`). A transaction shares its connection's config, so it gets its connection's id:\n * what setup learns in a transaction is what the connection knows afterwards. Two Knex instances\n * built separately get different ids, even for the same database.\n */\nexport function getConnectionKey(knex: Knex): string {\n const identity: object = knex.client?.config ?? knex;\n let key = keys.get(identity);\n if (!key) {\n next += 1;\n key = `db${next}`;\n keys.set(identity, key);\n }\n return key;\n}\n"],"names":["keys","WeakMap","next","getConnectionKey","knex","identity","key"],"mappings":"AAEA,MAAMA,OAAO,IAAIC;AACjB,IAAIC,OAAO;AAQJ,SAASC,iBAAiBC,IAAU;IACvC,MAAMC,WAAmBD,KAAK,MAAM,EAAE,UAAUA;IAChD,IAAIE,MAAMN,KAAK,GAAG,CAACK;IACnB,IAAI,CAACC,KAAK;QACNJ,QAAQ;QACRI,MAAM,CAAC,EAAE,EAAEJ,MAAM;QACjBF,KAAK,GAAG,CAACK,UAAUC;IACvB;IACA,OAAOA;AACX"}
|