@webiny/api-core-sql 0.0.0-unstable.3fddf667ea → 0.0.0-unstable.4373247389

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/TableManager.d.ts +5 -4
  2. package/TableManager.js +11 -7
  3. package/TableManager.js.map +1 -1
  4. package/adminUsers/index.d.ts +3 -0
  5. package/adminUsers/index.js +55 -3
  6. package/adminUsers/index.js.map +1 -1
  7. package/connection/SqlConnectionFeature.d.ts +10 -6
  8. package/connection/SqlConnectionFeature.js +5 -1
  9. package/connection/SqlConnectionFeature.js.map +1 -1
  10. package/coreStorage/CoreSqlSchemaSetup.js +2 -1
  11. package/coreStorage/CoreSqlSchemaSetup.js.map +1 -1
  12. package/coreStorage/SqlApiCoreStorageOperationsFactory.d.ts +1 -1
  13. package/coreStorage/SqlApiCoreStorageOperationsFactory.js +2 -1
  14. package/coreStorage/SqlApiCoreStorageOperationsFactory.js.map +1 -1
  15. package/coreStorage/SqlTenancyStorageOperationsFactory.d.ts +18 -0
  16. package/coreStorage/SqlTenancyStorageOperationsFactory.js +36 -0
  17. package/coreStorage/SqlTenancyStorageOperationsFactory.js.map +1 -0
  18. package/coreStorage/SqlTenantStorageReadiness.d.ts +19 -0
  19. package/coreStorage/SqlTenantStorageReadiness.js +48 -0
  20. package/coreStorage/SqlTenantStorageReadiness.js.map +1 -0
  21. package/coreStorage/feature.d.ts +4 -3
  22. package/coreStorage/feature.js +4 -0
  23. package/coreStorage/feature.js.map +1 -1
  24. package/createApiCoreSql.d.ts +8 -2
  25. package/createApiCoreSql.js +7 -5
  26. package/createApiCoreSql.js.map +1 -1
  27. package/feature/SqlDialect/abstractions.d.ts +15 -0
  28. package/feature/SqlDialect/abstractions.js +5 -0
  29. package/feature/SqlDialect/abstractions.js.map +1 -0
  30. package/feature/SqlDialect/index.d.ts +2 -0
  31. package/feature/SqlDialect/index.js +1 -0
  32. package/index.d.ts +13 -4
  33. package/index.js +9 -3
  34. package/index.js.map +1 -1
  35. package/package.json +8 -8
  36. package/schemaMemory/ensureTable.d.ts +10 -3
  37. package/schemaMemory/ensureTable.js +7 -4
  38. package/schemaMemory/ensureTable.js.map +1 -1
  39. package/schemaSetup/abstractions.d.ts +14 -2
  40. package/schemaSetup/abstractions.js.map +1 -1
  41. package/schemaSetup/index.d.ts +3 -1
  42. package/schemaSetup/index.js +1 -0
  43. package/schemaSetup/runSchemaSetupSteps.d.ts +9 -0
  44. package/schemaSetup/runSchemaSetupSteps.js +6 -2
  45. package/schemaSetup/runSchemaSetupSteps.js.map +1 -1
  46. package/schemaSetup/runSqlSchemaSetups.d.ts +22 -0
  47. package/schemaSetup/runSqlSchemaSetups.js +24 -0
  48. package/schemaSetup/runSqlSchemaSetups.js.map +1 -0
  49. package/scopeStorage/abstractions.d.ts +19 -0
  50. package/scopeStorage/abstractions.js +5 -0
  51. package/scopeStorage/abstractions.js.map +1 -0
  52. package/scopeStorage/index.d.ts +3 -0
  53. package/scopeStorage/index.js +2 -0
  54. package/scopeStorage/isPostgresScope.d.ts +14 -0
  55. package/scopeStorage/isPostgresScope.js +8 -0
  56. package/scopeStorage/isPostgresScope.js.map +1 -0
  57. package/security/index.d.ts +3 -0
  58. package/security/index.js +22 -1
  59. package/security/index.js.map +1 -1
  60. package/storage/sqlTenantStorage.d.ts +44 -0
  61. package/storage/sqlTenantStorage.js +32 -0
  62. package/storage/sqlTenantStorage.js.map +1 -0
  63. package/storage/types.d.ts +14 -5
  64. package/tenancy/index.js +50 -8
  65. package/tenancy/index.js.map +1 -1
package/TableManager.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Knex } from "knex";
2
- import { type TableCreator } from "./schemaMemory/ensureTable.js";
2
+ import { type TableCreator, type TableUpgrade } from "./schemaMemory/ensureTable.js";
3
3
  export interface TableManagerOptions {
4
4
  /**
5
5
  * The schema was set up before the API took traffic (see `SqlSchemaConfig`): `ensure()` then
@@ -26,11 +26,12 @@ export declare class TableManager {
26
26
  reset(): void;
27
27
  /**
28
28
  * Declares a table and returns the function that ensures it on first use. Declared tables are
29
- * created together by `setup()` (schema setup).
29
+ * created together by `setup()` (schema setup). `upgrade` brings a table that already existed up
30
+ * to date, for example with an index added after it was created.
30
31
  */
31
- define(tableName: string, creator: TableCreator): () => Promise<void>;
32
+ define(tableName: string, creator: TableCreator, upgrade?: TableUpgrade): () => Promise<void>;
32
33
  setup(): Promise<void>;
33
34
  resolve(tableName: string): string;
34
- ensure(tableName: string, creator: TableCreator): Promise<void>;
35
+ ensure(tableName: string, creator: TableCreator, upgrade?: TableUpgrade): Promise<void>;
35
36
  private get memory();
36
37
  }
package/TableManager.js CHANGED
@@ -12,28 +12,32 @@ class TableManager {
12
12
  reset() {
13
13
  this.memory.reset();
14
14
  }
15
- define(tableName, creator) {
16
- this.defined.set(tableName, creator);
17
- return ()=>this.ensure(tableName, creator);
15
+ define(tableName, creator, upgrade) {
16
+ this.defined.set(tableName, {
17
+ creator,
18
+ upgrade
19
+ });
20
+ return ()=>this.ensure(tableName, creator, upgrade);
18
21
  }
19
22
  async setup() {
20
- for (const [tableName, creator] of this.defined){
23
+ for (const [tableName, { creator, upgrade }] of this.defined){
21
24
  const resolved = this.resolve(tableName);
22
25
  const generation = this.memory.generation;
23
- await createTableIfMissing(this.knex, resolved, creator);
26
+ await createTableIfMissing(this.knex, resolved, creator, upgrade);
24
27
  if (this.memory.generation === generation) recordTable(this.knex, this.memory, resolved);
25
28
  }
26
29
  }
27
30
  resolve(tableName) {
28
31
  return `${this.prefix}${tableName}`;
29
32
  }
30
- async ensure(tableName, creator) {
33
+ async ensure(tableName, creator, upgrade) {
31
34
  if (this.schemaManaged()) return;
32
35
  await ensureTable({
33
36
  knex: this.knex,
34
37
  memory: this.memory,
35
38
  tableName: this.resolve(tableName),
36
- create: creator
39
+ create: creator,
40
+ upgrade
37
41
  });
38
42
  }
39
43
  get memory() {
@@ -1 +1 @@
1
- {"version":3,"file":"TableManager.js","sources":["../src/TableManager.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { getSchemaMemory, type ISchemaMemory } from \"./schemaMemory/getSchemaMemory.js\";\nimport { getConnectionKey } from \"./schemaMemory/getConnectionKey.js\";\nimport {\n createTableIfMissing,\n ensureTable,\n recordTable,\n type TableCreator\n} from \"./schemaMemory/ensureTable.js\";\n\nexport interface TableManagerOptions {\n /**\n * The schema was set up before the API took traffic (see `SqlSchemaConfig`): `ensure()` then\n * never checks for or creates a table. `setup()` still creates them. A function when it can\n * change (a server turns it on once its schema setup at start ran): read on every `ensure()`.\n */\n schemaManaged?: boolean | (() => boolean);\n}\n\n/**\n * The tables of one SQL storage part (core, audit logs, login) on one connection. Built wherever the\n * storage is built, which is once per request: it holds no state of its own. What it learns (which\n * tables exist) is kept for the process, in one memory per connection and table prefix, so a new\n * instance doesn't check a table again and a long-running server keeps one entry per connection, not\n * one per request.\n */\nexport class TableManager {\n private readonly knex: Knex;\n private readonly prefix: string;\n private readonly schemaManaged: () => boolean;\n /* Tables declared by the storage operations using this manager, for schema setup. */\n private readonly defined = new Map<string, TableCreator>();\n private memoryOfTables?: ISchemaMemory;\n\n constructor(knex: Knex, prefix: string = \"\", options: TableManagerOptions = {}) {\n this.knex = knex;\n this.prefix = prefix ? `${prefix}_` : \"\";\n const schemaManaged = options.schemaManaged;\n this.schemaManaged =\n typeof schemaManaged === \"function\" ? schemaManaged : () => schemaManaged === true;\n }\n\n /** Forgets which tables this connection has (test setups drop all tables between tests). */\n public reset(): void {\n this.memory.reset();\n }\n\n /**\n * Declares a table and returns the function that ensures it on first use. Declared tables are\n * created together by `setup()` (schema setup).\n */\n public define(tableName: string, creator: TableCreator): () => Promise<void> {\n this.defined.set(tableName, creator);\n return () => this.ensure(tableName, creator);\n }\n\n /* Creates every declared table that doesn't exist yet. Runs at schema setup. */\n public async setup(): Promise<void> {\n for (const [tableName, creator] of this.defined) {\n const resolved = this.resolve(tableName);\n // Nothing checked before a reset is recorded after it (as in `ensureTable`).\n const generation = this.memory.generation;\n await createTableIfMissing(this.knex, resolved, creator);\n if (this.memory.generation === generation) {\n recordTable(this.knex, this.memory, resolved);\n }\n }\n }\n\n public resolve(tableName: string): string {\n return `${this.prefix}${tableName}`;\n }\n\n public async ensure(tableName: string, creator: TableCreator): Promise<void> {\n if (this.schemaManaged()) {\n return;\n }\n await ensureTable({\n knex: this.knex,\n memory: this.memory,\n tableName: this.resolve(tableName),\n create: creator\n });\n }\n\n /* Made on first use: a schema-managed manager never needs it. */\n private get memory(): ISchemaMemory {\n this.memoryOfTables ??= getSchemaMemory(\n `core.sql.tables:${getConnectionKey(this.knex)}:${this.prefix}`\n );\n return this.memoryOfTables;\n }\n}\n"],"names":["TableManager","knex","prefix","options","Map","schemaManaged","tableName","creator","resolved","generation","createTableIfMissing","recordTable","ensureTable","getSchemaMemory","getConnectionKey"],"mappings":";;;AA0BO,MAAMA;IAQT,YAAYC,IAAU,EAAEC,SAAiB,EAAE,EAAEC,UAA+B,CAAC,CAAC,CAAE;QAJG,KAClE,OAAO,GAAG,IAAIC;QAI3B,IAAI,CAAC,IAAI,GAAGH;QACZ,IAAI,CAAC,MAAM,GAAGC,SAAS,GAAGA,OAAO,CAAC,CAAC,GAAG;QACtC,MAAMG,gBAAgBF,QAAQ,aAAa;QAC3C,IAAI,CAAC,aAAa,GACd,AAAyB,cAAzB,OAAOE,gBAA+BA,gBAAgB,IAAMA,AAAkB,SAAlBA;IACpE;IAGO,QAAc;QACjB,IAAI,CAAC,MAAM,CAAC,KAAK;IACrB;IAMO,OAAOC,SAAiB,EAAEC,OAAqB,EAAuB;QACzE,IAAI,CAAC,OAAO,CAAC,GAAG,CAACD,WAAWC;QAC5B,OAAO,IAAM,IAAI,CAAC,MAAM,CAACD,WAAWC;IACxC;IAGA,MAAa,QAAuB;QAChC,KAAK,MAAM,CAACD,WAAWC,QAAQ,IAAI,IAAI,CAAC,OAAO,CAAE;YAC7C,MAAMC,WAAW,IAAI,CAAC,OAAO,CAACF;YAE9B,MAAMG,aAAa,IAAI,CAAC,MAAM,CAAC,UAAU;YACzC,MAAMC,qBAAqB,IAAI,CAAC,IAAI,EAAEF,UAAUD;YAChD,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,KAAKE,YAC3BE,YAAY,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAEH;QAE5C;IACJ;IAEO,QAAQF,SAAiB,EAAU;QACtC,OAAO,GAAG,IAAI,CAAC,MAAM,GAAGA,WAAW;IACvC;IAEA,MAAa,OAAOA,SAAiB,EAAEC,OAAqB,EAAiB;QACzE,IAAI,IAAI,CAAC,aAAa,IAClB;QAEJ,MAAMK,YAAY;YACd,MAAM,IAAI,CAAC,IAAI;YACf,QAAQ,IAAI,CAAC,MAAM;YACnB,WAAW,IAAI,CAAC,OAAO,CAACN;YACxB,QAAQC;QACZ;IACJ;IAGA,IAAY,SAAwB;QAChC,IAAI,CAAC,cAAc,KAAKM,gBACpB,CAAC,gBAAgB,EAAEC,iBAAiB,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE;QAEnE,OAAO,IAAI,CAAC,cAAc;IAC9B;AACJ"}
1
+ {"version":3,"file":"TableManager.js","sources":["../src/TableManager.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { getSchemaMemory, type ISchemaMemory } from \"./schemaMemory/getSchemaMemory.js\";\nimport { getConnectionKey } from \"./schemaMemory/getConnectionKey.js\";\nimport {\n createTableIfMissing,\n ensureTable,\n recordTable,\n type TableCreator,\n type TableUpgrade\n} from \"./schemaMemory/ensureTable.js\";\n\ninterface DefinedTable {\n creator: TableCreator;\n upgrade?: TableUpgrade;\n}\n\nexport interface TableManagerOptions {\n /**\n * The schema was set up before the API took traffic (see `SqlSchemaConfig`): `ensure()` then\n * never checks for or creates a table. `setup()` still creates them. A function when it can\n * change (a server turns it on once its schema setup at start ran): read on every `ensure()`.\n */\n schemaManaged?: boolean | (() => boolean);\n}\n\n/**\n * The tables of one SQL storage part (core, audit logs, login) on one connection. Built wherever the\n * storage is built, which is once per request: it holds no state of its own. What it learns (which\n * tables exist) is kept for the process, in one memory per connection and table prefix, so a new\n * instance doesn't check a table again and a long-running server keeps one entry per connection, not\n * one per request.\n */\nexport class TableManager {\n private readonly knex: Knex;\n private readonly prefix: string;\n private readonly schemaManaged: () => boolean;\n /* Tables declared by the storage operations using this manager, for schema setup. */\n private readonly defined = new Map<string, DefinedTable>();\n private memoryOfTables?: ISchemaMemory;\n\n constructor(knex: Knex, prefix: string = \"\", options: TableManagerOptions = {}) {\n this.knex = knex;\n this.prefix = prefix ? `${prefix}_` : \"\";\n const schemaManaged = options.schemaManaged;\n this.schemaManaged =\n typeof schemaManaged === \"function\" ? schemaManaged : () => schemaManaged === true;\n }\n\n /** Forgets which tables this connection has (test setups drop all tables between tests). */\n public reset(): void {\n this.memory.reset();\n }\n\n /**\n * Declares a table and returns the function that ensures it on first use. Declared tables are\n * created together by `setup()` (schema setup). `upgrade` brings a table that already existed up\n * to date, for example with an index added after it was created.\n */\n public define(\n tableName: string,\n creator: TableCreator,\n upgrade?: TableUpgrade\n ): () => Promise<void> {\n this.defined.set(tableName, { creator, upgrade });\n return () => this.ensure(tableName, creator, upgrade);\n }\n\n /* Creates every declared table that doesn't exist yet. Runs at schema setup. */\n public async setup(): Promise<void> {\n for (const [tableName, { creator, upgrade }] of this.defined) {\n const resolved = this.resolve(tableName);\n // Nothing checked before a reset is recorded after it (as in `ensureTable`).\n const generation = this.memory.generation;\n await createTableIfMissing(this.knex, resolved, creator, upgrade);\n if (this.memory.generation === generation) {\n recordTable(this.knex, this.memory, resolved);\n }\n }\n }\n\n public resolve(tableName: string): string {\n return `${this.prefix}${tableName}`;\n }\n\n public async ensure(\n tableName: string,\n creator: TableCreator,\n upgrade?: TableUpgrade\n ): Promise<void> {\n if (this.schemaManaged()) {\n return;\n }\n await ensureTable({\n knex: this.knex,\n memory: this.memory,\n tableName: this.resolve(tableName),\n create: creator,\n upgrade\n });\n }\n\n /* Made on first use: a schema-managed manager never needs it. */\n private get memory(): ISchemaMemory {\n this.memoryOfTables ??= getSchemaMemory(\n `core.sql.tables:${getConnectionKey(this.knex)}:${this.prefix}`\n );\n return this.memoryOfTables;\n }\n}\n"],"names":["TableManager","knex","prefix","options","Map","schemaManaged","tableName","creator","upgrade","resolved","generation","createTableIfMissing","recordTable","ensureTable","getSchemaMemory","getConnectionKey"],"mappings":";;;AAgCO,MAAMA;IAQT,YAAYC,IAAU,EAAEC,SAAiB,EAAE,EAAEC,UAA+B,CAAC,CAAC,CAAE;QAJG,KAClE,OAAO,GAAG,IAAIC;QAI3B,IAAI,CAAC,IAAI,GAAGH;QACZ,IAAI,CAAC,MAAM,GAAGC,SAAS,GAAGA,OAAO,CAAC,CAAC,GAAG;QACtC,MAAMG,gBAAgBF,QAAQ,aAAa;QAC3C,IAAI,CAAC,aAAa,GACd,AAAyB,cAAzB,OAAOE,gBAA+BA,gBAAgB,IAAMA,AAAkB,SAAlBA;IACpE;IAGO,QAAc;QACjB,IAAI,CAAC,MAAM,CAAC,KAAK;IACrB;IAOO,OACHC,SAAiB,EACjBC,OAAqB,EACrBC,OAAsB,EACH;QACnB,IAAI,CAAC,OAAO,CAAC,GAAG,CAACF,WAAW;YAAEC;YAASC;QAAQ;QAC/C,OAAO,IAAM,IAAI,CAAC,MAAM,CAACF,WAAWC,SAASC;IACjD;IAGA,MAAa,QAAuB;QAChC,KAAK,MAAM,CAACF,WAAW,EAAEC,OAAO,EAAEC,OAAO,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAE;YAC1D,MAAMC,WAAW,IAAI,CAAC,OAAO,CAACH;YAE9B,MAAMI,aAAa,IAAI,CAAC,MAAM,CAAC,UAAU;YACzC,MAAMC,qBAAqB,IAAI,CAAC,IAAI,EAAEF,UAAUF,SAASC;YACzD,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,KAAKE,YAC3BE,YAAY,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,EAAEH;QAE5C;IACJ;IAEO,QAAQH,SAAiB,EAAU;QACtC,OAAO,GAAG,IAAI,CAAC,MAAM,GAAGA,WAAW;IACvC;IAEA,MAAa,OACTA,SAAiB,EACjBC,OAAqB,EACrBC,OAAsB,EACT;QACb,IAAI,IAAI,CAAC,aAAa,IAClB;QAEJ,MAAMK,YAAY;YACd,MAAM,IAAI,CAAC,IAAI;YACf,QAAQ,IAAI,CAAC,MAAM;YACnB,WAAW,IAAI,CAAC,OAAO,CAACP;YACxB,QAAQC;YACRC;QACJ;IACJ;IAGA,IAAY,SAAwB;QAChC,IAAI,CAAC,cAAc,KAAKM,gBACpB,CAAC,gBAAgB,EAAEC,iBAAiB,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE;QAEnE,OAAO,IAAI,CAAC,cAAc;IAC9B;AACJ"}
@@ -1,9 +1,12 @@
1
1
  import type { Knex } from "knex";
2
2
  import type { AdminUsersStorageOperations } from "@webiny/api-core/types/users.js";
3
+ import type { ScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
3
4
  import type { TableManager } from "../TableManager.js";
4
5
  interface CreateStorageOperationsParams {
5
6
  knex: Knex;
6
7
  tableManager: TableManager;
8
+ /** The tenant the storage acts on: its scope's. */
9
+ scopeTenant: ScopeTenant.Interface;
7
10
  }
8
11
  export declare const createStorageOperations: (params: CreateStorageOperationsParams) => AdminUsersStorageOperations;
9
12
  export {};
@@ -9,7 +9,12 @@ const userToRow = (user)=>({
9
9
  });
10
10
  const rowToUser = (row)=>JSON.parse(row.data);
11
11
  const createStorageOperations = (params)=>{
12
- const { knex, tableManager } = params;
12
+ const { knex, tableManager, scopeTenant } = params;
13
+ const inScope = (user)=>({
14
+ ...user,
15
+ tenant: scopeTenant.getId()
16
+ });
17
+ const idIndexName = `${tableManager.resolve(TABLE_NAME)}_id_index`;
13
18
  const ensureTable = tableManager.define(TABLE_NAME, (table)=>{
14
19
  table.text("id").notNullable();
15
20
  table.text("tenant").notNullable();
@@ -23,12 +28,22 @@ const createStorageOperations = (params)=>{
23
28
  "tenant",
24
29
  "email"
25
30
  ]);
31
+ table.index([
32
+ "id"
33
+ ], idIndexName);
34
+ }, async (knex, tableName)=>{
35
+ await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??)", [
36
+ idIndexName,
37
+ tableName,
38
+ "id"
39
+ ]);
26
40
  });
27
41
  const query = ()=>knex(tableManager.resolve(TABLE_NAME));
28
42
  return {
29
43
  async getUser (params) {
30
44
  await ensureTable();
31
- const { where: { tenant, id, email } } = params;
45
+ const { where: { id, email } } = params;
46
+ const tenant = scopeTenant.getId();
32
47
  try {
33
48
  if (id) {
34
49
  const row = await query().where("tenant", tenant).andWhere("id", id).first();
@@ -47,11 +62,45 @@ const createStorageOperations = (params)=>{
47
62
  });
48
63
  }
49
64
  },
65
+ async getUserAcrossTenants (params) {
66
+ const { id, tenants } = params;
67
+ if (0 === tenants.length) return [];
68
+ await ensureTable();
69
+ try {
70
+ const rows = await query().where("id", id).whereIn("tenant", tenants);
71
+ return rows.map((row)=>rowToUser(row));
72
+ } catch (err) {
73
+ throw error.from(err, {
74
+ message: "Could not load user across tenants.",
75
+ code: "GET_ADMIN_USER_ACROSS_TENANTS_ERROR",
76
+ data: {
77
+ id,
78
+ tenants
79
+ }
80
+ });
81
+ }
82
+ },
83
+ async listUserRecords (params) {
84
+ await ensureTable();
85
+ const { id } = params;
86
+ try {
87
+ const rows = await query().where("id", id);
88
+ return rows.map((row)=>rowToUser(row));
89
+ } catch (err) {
90
+ throw error.from(err, {
91
+ message: "Could not list user records.",
92
+ code: "LIST_ADMIN_USER_RECORDS_ERROR",
93
+ data: {
94
+ id
95
+ }
96
+ });
97
+ }
98
+ },
50
99
  async listUsers (params) {
51
100
  await ensureTable();
52
101
  const { where, sort } = params;
53
102
  try {
54
- const rows = await query().where("tenant", where.tenant);
103
+ const rows = await query().where("tenant", scopeTenant.getId());
55
104
  let items = rows.map((row)=>rowToUser(row));
56
105
  items = sortItems(items, sort);
57
106
  const { id_in, teams_in } = where;
@@ -68,6 +117,7 @@ const createStorageOperations = (params)=>{
68
117
  }
69
118
  },
70
119
  async createUser ({ user }) {
120
+ user = inScope(user);
71
121
  await ensureTable();
72
122
  try {
73
123
  const row = userToRow(user);
@@ -84,6 +134,7 @@ const createStorageOperations = (params)=>{
84
134
  }
85
135
  },
86
136
  async updateUser ({ user }) {
137
+ user = inScope(user);
87
138
  await ensureTable();
88
139
  try {
89
140
  const row = userToRow(user);
@@ -100,6 +151,7 @@ const createStorageOperations = (params)=>{
100
151
  }
101
152
  },
102
153
  async deleteUser ({ user }) {
154
+ user = inScope(user);
103
155
  await ensureTable();
104
156
  try {
105
157
  await query().where("tenant", user.tenant).andWhere("id", user.id).delete();
@@ -1 +1 @@
1
- {"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n AdminUser,\n AdminUsersStorageOperations,\n StorageOperationsGetUserParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport { sortItems } from \"~/sortItems.js\";\n\nconst TABLE_NAME = \"webiny_core_admin_users\";\n\ninterface IAdminUserRow {\n id: string;\n tenant: string;\n email: string;\n data: string;\n}\n\nconst userToRow = (user: AdminUser): IAdminUserRow => {\n return {\n id: user.id,\n tenant: user.tenant,\n email: user.email,\n data: JSON.stringify(user)\n };\n};\n\nconst rowToUser = <TUser extends AdminUser = AdminUser>(row: IAdminUserRow): TUser => {\n return JSON.parse(row.data) as TUser;\n};\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): AdminUsersStorageOperations => {\n const { knex, tableManager } = params;\n\n const ensureTable = tableManager.define(TABLE_NAME, table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"email\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"email\"]);\n });\n\n const query = () => {\n return knex<IAdminUserRow>(tableManager.resolve(TABLE_NAME));\n };\n\n return {\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n await ensureTable();\n\n const {\n where: { tenant, id, email }\n } = params;\n\n try {\n if (id) {\n const row = await query().where(\"tenant\", tenant).andWhere(\"id\", id).first();\n\n return row ? rowToUser<TUser>(row) : null;\n }\n\n const row = await query()\n .where(\"tenant\", tenant)\n .andWhere(\"email\", email as string)\n .first();\n\n return row ? rowToUser<TUser>(row) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n\n async listUsers<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUsersParams\n ): Promise<TUser[]> {\n await ensureTable();\n\n const { where, sort } = params;\n\n try {\n const rows = await query().where(\"tenant\", where.tenant);\n\n let items = rows.map(row => rowToUser<TUser>(row));\n\n items = sortItems(items, sort);\n\n const { id_in, teams_in } = where;\n\n return items.filter(item => {\n if (Array.isArray(id_in) && !id_in.includes(item.id)) {\n return false;\n }\n if (Array.isArray(teams_in)) {\n return (item.teams || []).some(team => teams_in.includes(team));\n }\n return true;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n },\n\n async createUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<TUser> {\n await ensureTable();\n\n try {\n const row = userToRow(user);\n await query().insert(row);\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n },\n\n async updateUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<TUser> {\n await ensureTable();\n\n try {\n const row = userToRow(user);\n await query().where(\"tenant\", user.tenant).andWhere(\"id\", user.id).update(row);\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n },\n\n async deleteUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<void> {\n await ensureTable();\n\n try {\n await query().where(\"tenant\", user.tenant).andWhere(\"id\", user.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete user.\",\n code: \"DELETE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n }\n };\n};\n"],"names":["TABLE_NAME","userToRow","user","JSON","rowToUser","row","createStorageOperations","params","knex","tableManager","ensureTable","table","query","tenant","id","email","err","WebinyError","where","sort","rows","items","sortItems","id_in","teams_in","item","Array","team"],"mappings":";;AAWA,MAAMA,aAAa;AASnB,MAAMC,YAAY,CAACC,OACR;QACH,IAAIA,KAAK,EAAE;QACX,QAAQA,KAAK,MAAM;QACnB,OAAOA,KAAK,KAAK;QACjB,MAAMC,KAAK,SAAS,CAACD;IACzB;AAGJ,MAAME,YAAY,CAAsCC,MAC7CF,KAAK,KAAK,CAACE,IAAI,IAAI;AAQvB,MAAMC,0BAA0B,CACnCC;IAEA,MAAM,EAAEC,IAAI,EAAEC,YAAY,EAAE,GAAGF;IAE/B,MAAMG,cAAcD,aAAa,MAAM,CAACT,YAAYW,CAAAA;QAChDA,MAAM,IAAI,CAAC,MAAM,WAAW;QAC5BA,MAAM,IAAI,CAAC,UAAU,WAAW;QAChCA,MAAM,IAAI,CAAC,SAAS,WAAW;QAC/BA,MAAM,IAAI,CAAC,QAAQ,WAAW;QAE9BA,MAAM,OAAO,CAAC;YAAC;YAAU;SAAK;QAC9BA,MAAM,MAAM,CAAC;YAAC;YAAU;SAAQ;IACpC;IAEA,MAAMC,QAAQ,IACHJ,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K;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;gBACV;YACJ;QACJ;QAEA,MAAM,YAAgD,EAClDd,IAAI,EAGP;YACG,MAAMQ;YAEN,IAAI;gBACA,MAAML,MAAMJ,UAAUC;gBACtB,MAAMU,QAAQ,MAAM,CAACP;gBAErB,OAAOH;YACX,EAAE,OAAOc,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;oBAAK;gBACjB;YACJ;QACJ;QAEA,MAAM,YAAgD,EAClDA,IAAI,EAGP;YACG,MAAMQ;YAEN,IAAI;gBACA,MAAML,MAAMJ,UAAUC;gBACtB,MAAMU,QAAQ,KAAK,CAAC,UAAUV,KAAK,MAAM,EAAE,QAAQ,CAAC,MAAMA,KAAK,EAAE,EAAE,MAAM,CAACG;gBAE1E,OAAOH;YACX,EAAE,OAAOc,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;oBAAK;gBACjB;YACJ;QACJ;QAEA,MAAM,YAAgD,EAClDA,IAAI,EAGP;YACG,MAAMQ;YAEN,IAAI;gBACA,MAAME,QAAQ,KAAK,CAAC,UAAUV,KAAK,MAAM,EAAE,QAAQ,CAAC,MAAMA,KAAK,EAAE,EAAE,MAAM;YAC7E,EAAE,OAAOc,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAEd;oBAAK;gBACjB;YACJ;QACJ;IACJ;AACJ"}
1
+ {"version":3,"file":"adminUsers/index.js","sources":["../../src/adminUsers/index.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport type {\n AdminUser,\n AdminUsersStorageOperations,\n StorageOperationsGetUserAcrossTenantsParams,\n StorageOperationsGetUserParams,\n StorageOperationsListUserRecordsParams,\n StorageOperationsListUsersParams\n} from \"@webiny/api-core/types/users.js\";\nimport WebinyError from \"@webiny/error\";\nimport type { ScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.js\";\nimport type { TableManager } from \"~/TableManager.js\";\nimport { sortItems } from \"~/sortItems.js\";\n\nconst TABLE_NAME = \"webiny_core_admin_users\";\n\ninterface IAdminUserRow {\n id: string;\n tenant: string;\n email: string;\n data: string;\n}\n\nconst userToRow = (user: AdminUser): IAdminUserRow => {\n return {\n id: user.id,\n tenant: user.tenant,\n email: user.email,\n data: JSON.stringify(user)\n };\n};\n\nconst rowToUser = <TUser extends AdminUser = AdminUser>(row: IAdminUserRow): TUser => {\n return JSON.parse(row.data) as TUser;\n};\n\ninterface CreateStorageOperationsParams {\n knex: Knex;\n tableManager: TableManager;\n /** The tenant the storage acts on: its scope's. */\n scopeTenant: ScopeTenant.Interface;\n}\n\nexport const createStorageOperations = (\n params: CreateStorageOperationsParams\n): AdminUsersStorageOperations => {\n const { knex, tableManager, scopeTenant } = params;\n\n /** The user with its scope's tenant, whatever tenant it carries. */\n const inScope = <T extends AdminUser>(user: T): T => {\n return { ...user, tenant: scopeTenant.getId() };\n };\n\n // The user→tenant index: finds every tenant's record of one user.\n const idIndexName = `${tableManager.resolve(TABLE_NAME)}_id_index`;\n\n const ensureTable = tableManager.define(\n TABLE_NAME,\n table => {\n table.text(\"id\").notNullable();\n table.text(\"tenant\").notNullable();\n table.text(\"email\").notNullable();\n table.text(\"data\").notNullable();\n\n table.primary([\"tenant\", \"id\"]);\n table.unique([\"tenant\", \"email\"]);\n table.index([\"id\"], idIndexName);\n },\n async (knex, tableName) => {\n // Tables created before the index existed.\n await knex.raw(\"CREATE INDEX IF NOT EXISTS ?? ON ?? (??)\", [\n idIndexName,\n tableName,\n \"id\"\n ]);\n }\n );\n\n const query = () => {\n return knex<IAdminUserRow>(tableManager.resolve(TABLE_NAME));\n };\n\n return {\n async getUser<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserParams\n ): Promise<TUser | null> {\n await ensureTable();\n\n const {\n where: { id, email }\n } = params;\n const tenant = scopeTenant.getId();\n\n try {\n if (id) {\n const row = await query().where(\"tenant\", tenant).andWhere(\"id\", id).first();\n\n return row ? rowToUser<TUser>(row) : null;\n }\n\n const row = await query()\n .where(\"tenant\", tenant)\n .andWhere(\"email\", email as string)\n .first();\n\n return row ? rowToUser<TUser>(row) : null;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user.\",\n code: \"GET_ADMIN_USERS_ERROR\",\n data: { id, email }\n });\n }\n },\n\n // Cross-tenant by design: one user's records in the given tenants, not the scope's tenant.\n async getUserAcrossTenants<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsGetUserAcrossTenantsParams\n ): Promise<TUser[]> {\n const { id, tenants } = params;\n if (tenants.length === 0) {\n return [];\n }\n\n await ensureTable();\n\n try {\n const rows = await query().where(\"id\", id).whereIn(\"tenant\", tenants);\n\n return rows.map(row => rowToUser<TUser>(row));\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not load user across tenants.\",\n code: \"GET_ADMIN_USER_ACROSS_TENANTS_ERROR\",\n data: { id, tenants }\n });\n }\n },\n\n // Cross-tenant by design: every tenant's record of one user.\n async listUserRecords<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUserRecordsParams\n ): Promise<TUser[]> {\n await ensureTable();\n\n const { id } = params;\n\n try {\n const rows = await query().where(\"id\", id);\n\n return rows.map(row => rowToUser<TUser>(row));\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list user records.\",\n code: \"LIST_ADMIN_USER_RECORDS_ERROR\",\n data: { id }\n });\n }\n },\n\n async listUsers<TUser extends AdminUser = AdminUser>(\n params: StorageOperationsListUsersParams\n ): Promise<TUser[]> {\n await ensureTable();\n\n const { where, sort } = params;\n\n try {\n const rows = await query().where(\"tenant\", scopeTenant.getId());\n\n let items = rows.map(row => rowToUser<TUser>(row));\n\n items = sortItems(items, sort);\n\n const { id_in, teams_in } = where;\n\n return items.filter(item => {\n if (Array.isArray(id_in) && !id_in.includes(item.id)) {\n return false;\n }\n if (Array.isArray(teams_in)) {\n return (item.teams || []).some(team => teams_in.includes(team));\n }\n return true;\n });\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not list users.\",\n code: \"LIST_ADMIN_USERS_ERROR\"\n });\n }\n },\n\n async createUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<TUser> {\n user = inScope(user);\n await ensureTable();\n\n try {\n const row = userToRow(user);\n await query().insert(row);\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not create admin user.\",\n code: \"CREATE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n },\n\n async updateUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<TUser> {\n user = inScope(user);\n await ensureTable();\n\n try {\n const row = userToRow(user);\n await query().where(\"tenant\", user.tenant).andWhere(\"id\", user.id).update(row);\n\n return user;\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not update user.\",\n code: \"UPDATE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n },\n\n async deleteUser<TUser extends AdminUser = AdminUser>({\n user\n }: {\n user: TUser;\n }): Promise<void> {\n user = inScope(user);\n await ensureTable();\n\n try {\n await query().where(\"tenant\", user.tenant).andWhere(\"id\", user.id).delete();\n } catch (err) {\n throw WebinyError.from(err, {\n message: \"Could not delete user.\",\n code: \"DELETE_ADMIN_USER_ERROR\",\n data: { user }\n });\n }\n }\n };\n};\n"],"names":["TABLE_NAME","userToRow","user","JSON","rowToUser","row","createStorageOperations","params","knex","tableManager","scopeTenant","inScope","idIndexName","ensureTable","table","tableName","query","id","email","tenant","err","WebinyError","tenants","rows","where","sort","items","sortItems","id_in","teams_in","item","Array","team"],"mappings":";;AAcA,MAAMA,aAAa;AASnB,MAAMC,YAAY,CAACC,OACR;QACH,IAAIA,KAAK,EAAE;QACX,QAAQA,KAAK,MAAM;QACnB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AAMW;YAEN,IAAI;gBACA,MAAMG,QAAQ,KAAK,CAAC,UAAUd,KAAK,MAAM,EAAE,QAAQ,CAAC,MAAMA,KAAK,EAAE,EAAE,MAAM;YAC7E,EAAE,OAAOkB,KAAK;gBACV,MAAMC,MAAAA,IAAgB,CAACD,KAAK;oBACxB,SAAS;oBACT,MAAM;oBACN,MAAM;wBAAElB;oBAAK;gBACjB;YACJ;QACJ;IACJ;AACJ"}
@@ -1,6 +1,9 @@
1
1
  import type { Knex } from "knex";
2
+ import { SqlDialect } from "../feature/SqlDialect/index.js";
2
3
  export interface SqlConnectionConfig {
3
4
  knex: Knex;
5
+ /** The connection's database family, registered as `SqlDialect`. */
6
+ dialect: SqlDialect.Name;
4
7
  tableNamePrefix?: string;
5
8
  /**
6
9
  * The schema was set up before the API took traffic (the storage's schema setup ran), so no
@@ -10,12 +13,13 @@ export interface SqlConnectionConfig {
10
13
  schemaManaged?: boolean | (() => boolean);
11
14
  }
12
15
  /**
13
- * What a SQL storage puts in the root container, once per process: the connection (`KnexClient`)
14
- * and its settings, the table prefix and the schema-managed setting (`SqlSchemaConfig`). Every
15
- * storage part registered per request, and every module on the storage (the Postgres CMS, the folder
16
- * catalog), runs on these.
16
+ * A SQL storage's connection (`KnexClient`), its database family (`SqlDialect`) and its settings,
17
+ * the table prefix and the schema-managed setting (`SqlSchemaConfig`). Every storage part registered
18
+ * in a tenant scope, and every module on the storage (the Postgres CMS, the folder catalog), runs on
19
+ * these.
17
20
  *
18
- * It holds no feature's storage: those register per request (`RequestStorage`).
21
+ * The default storage registers it in the root container, once per process. It holds no feature's
22
+ * storage, not even the tenant registry's: those register in each tenant scope (`RequestStorage`).
19
23
  */
20
24
  export declare const SqlConnectionFeature: {
21
25
  name: string;
@@ -25,4 +29,4 @@ export declare const SqlConnectionFeature: {
25
29
  * Points service discovery at the manifests table of a connection. The loader is a static global of
26
30
  * the process, not a DI registration, so a storage sets it once, when it registers in the root.
27
31
  */
28
- export declare const setSqlServiceManifestLoader: (config: SqlConnectionConfig) => void;
32
+ export declare const setSqlServiceManifestLoader: (config: Omit<SqlConnectionConfig, "dialect">) => void;
@@ -1,14 +1,18 @@
1
1
  import { createFeature } from "@webiny/feature/api";
2
2
  import { ServiceDiscovery } from "@webiny/api-core/features/serviceDiscovery/index.js";
3
3
  import { KnexClientFeature } from "../feature/KnexClient/index.js";
4
+ import { SqlDialect } from "../feature/SqlDialect/index.js";
4
5
  import { SqlSchemaConfig } from "../schemaConfig/index.js";
5
6
  import { SqlServiceManifestLoader } from "../serviceDiscovery/index.js";
6
7
  import { TableManager } from "../TableManager.js";
7
8
  const isManaged = (schemaManaged)=>"function" == typeof schemaManaged ? schemaManaged() : true === schemaManaged;
8
9
  const SqlConnectionFeature = createFeature({
9
10
  name: "SqlConnection",
10
- register (container, { knex, tableNamePrefix, schemaManaged = false }) {
11
+ register (container, { knex, dialect, tableNamePrefix, schemaManaged = false }) {
11
12
  KnexClientFeature.register(container, knex);
13
+ container.registerInstance(SqlDialect, {
14
+ name: dialect
15
+ });
12
16
  container.registerInstance(SqlSchemaConfig, {
13
17
  isManaged: ()=>isManaged(schemaManaged),
14
18
  tableNamePrefix
@@ -1 +1 @@
1
- {"version":3,"file":"connection/SqlConnectionFeature.js","sources":["../../src/connection/SqlConnectionFeature.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { createFeature } from \"@webiny/feature/api\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { KnexClientFeature } from \"~/feature/KnexClient/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\nimport { SqlServiceManifestLoader } from \"~/serviceDiscovery/index.js\";\nimport { TableManager } from \"~/TableManager.js\";\n\nexport interface SqlConnectionConfig {\n knex: Knex;\n tableNamePrefix?: string;\n /**\n * The schema was set up before the API took traffic (the storage's schema setup ran), so no\n * storage code checks for or creates tables at runtime. Off by default: tables are created on\n * first use. A function when it can change: a server turns it on once its setup at start ran.\n */\n schemaManaged?: boolean | (() => boolean);\n}\n\nconst isManaged = (schemaManaged: SqlConnectionConfig[\"schemaManaged\"]): boolean => {\n return typeof schemaManaged === \"function\" ? schemaManaged() : schemaManaged === true;\n};\n\n/**\n * What a SQL storage puts in the root container, once per process: the connection (`KnexClient`)\n * and its settings, the table prefix and the schema-managed setting (`SqlSchemaConfig`). Every\n * storage part registered per request, and every module on the storage (the Postgres CMS, the folder\n * catalog), runs on these.\n *\n * It holds no feature's storage: those register per request (`RequestStorage`).\n */\nexport const SqlConnectionFeature = createFeature<SqlConnectionConfig>({\n name: \"SqlConnection\",\n register(container, { knex, tableNamePrefix, schemaManaged = false }) {\n KnexClientFeature.register(container, knex);\n container.registerInstance(SqlSchemaConfig, {\n isManaged: () => isManaged(schemaManaged),\n tableNamePrefix\n });\n }\n});\n\n/**\n * Points service discovery at the manifests table of a connection. The loader is a static global of\n * the process, not a DI registration, so a storage sets it once, when it registers in the root.\n */\nexport const setSqlServiceManifestLoader = (config: SqlConnectionConfig): void => {\n const tableManager = new TableManager(config.knex, config.tableNamePrefix, {\n schemaManaged: () => isManaged(config.schemaManaged)\n });\n ServiceDiscovery.setLoader(new SqlServiceManifestLoader(config.knex, tableManager));\n};\n"],"names":["isManaged","schemaManaged","SqlConnectionFeature","createFeature","container","knex","tableNamePrefix","KnexClientFeature","SqlSchemaConfig","setSqlServiceManifestLoader","config","tableManager","TableManager","ServiceDiscovery","SqlServiceManifestLoader"],"mappings":";;;;;;AAmBA,MAAMA,YAAY,CAACC,gBACR,AAAyB,cAAzB,OAAOA,gBAA+BA,kBAAkBA,AAAkB,SAAlBA;AAW5D,MAAMC,uBAAuBC,cAAmC;IACnE,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,IAAI,EAAEC,eAAe,EAAEL,gBAAgB,KAAK,EAAE;QAChEM,kBAAkB,QAAQ,CAACH,WAAWC;QACtCD,UAAU,gBAAgB,CAACI,iBAAiB;YACxC,WAAW,IAAMR,UAAUC;YAC3BK;QACJ;IACJ;AACJ;AAMO,MAAMG,8BAA8B,CAACC;IACxC,MAAMC,eAAe,IAAIC,aAAaF,OAAO,IAAI,EAAEA,OAAO,eAAe,EAAE;QACvE,eAAe,IAAMV,UAAUU,OAAO,aAAa;IACvD;IACAG,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBJ,OAAO,IAAI,EAAEC;AACzE"}
1
+ {"version":3,"file":"connection/SqlConnectionFeature.js","sources":["../../src/connection/SqlConnectionFeature.ts"],"sourcesContent":["import type { Knex } from \"knex\";\nimport { createFeature } from \"@webiny/feature/api\";\nimport { ServiceDiscovery } from \"@webiny/api-core/features/serviceDiscovery/index.js\";\nimport { KnexClientFeature } from \"~/feature/KnexClient/index.js\";\nimport { SqlDialect } from \"~/feature/SqlDialect/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\nimport { SqlServiceManifestLoader } from \"~/serviceDiscovery/index.js\";\nimport { TableManager } from \"~/TableManager.js\";\n\nexport interface SqlConnectionConfig {\n knex: Knex;\n /** The connection's database family, registered as `SqlDialect`. */\n dialect: SqlDialect.Name;\n tableNamePrefix?: string;\n /**\n * The schema was set up before the API took traffic (the storage's schema setup ran), so no\n * storage code checks for or creates tables at runtime. Off by default: tables are created on\n * first use. A function when it can change: a server turns it on once its setup at start ran.\n */\n schemaManaged?: boolean | (() => boolean);\n}\n\nconst isManaged = (schemaManaged: SqlConnectionConfig[\"schemaManaged\"]): boolean => {\n return typeof schemaManaged === \"function\" ? schemaManaged() : schemaManaged === true;\n};\n\n/**\n * A SQL storage's connection (`KnexClient`), its database family (`SqlDialect`) and its settings,\n * the table prefix and the schema-managed setting (`SqlSchemaConfig`). Every storage part registered\n * in a tenant scope, and every module on the storage (the Postgres CMS, the folder catalog), runs on\n * these.\n *\n * The default storage registers it in the root container, once per process. It holds no feature's\n * storage, not even the tenant registry's: those register in each tenant scope (`RequestStorage`).\n */\nexport const SqlConnectionFeature = createFeature<SqlConnectionConfig>({\n name: \"SqlConnection\",\n register(container, { knex, dialect, tableNamePrefix, schemaManaged = false }) {\n KnexClientFeature.register(container, knex);\n container.registerInstance(SqlDialect, { name: dialect });\n container.registerInstance(SqlSchemaConfig, {\n isManaged: () => isManaged(schemaManaged),\n tableNamePrefix\n });\n }\n});\n\n/**\n * Points service discovery at the manifests table of a connection. The loader is a static global of\n * the process, not a DI registration, so a storage sets it once, when it registers in the root.\n */\nexport const setSqlServiceManifestLoader = (config: Omit<SqlConnectionConfig, \"dialect\">): void => {\n const tableManager = new TableManager(config.knex, config.tableNamePrefix, {\n schemaManaged: () => isManaged(config.schemaManaged)\n });\n ServiceDiscovery.setLoader(new SqlServiceManifestLoader(config.knex, tableManager));\n};\n"],"names":["isManaged","schemaManaged","SqlConnectionFeature","createFeature","container","knex","dialect","tableNamePrefix","KnexClientFeature","SqlDialect","SqlSchemaConfig","setSqlServiceManifestLoader","config","tableManager","TableManager","ServiceDiscovery","SqlServiceManifestLoader"],"mappings":";;;;;;;AAsBA,MAAMA,YAAY,CAACC,gBACR,AAAyB,cAAzB,OAAOA,gBAA+BA,kBAAkBA,AAAkB,SAAlBA;AAY5D,MAAMC,uBAAuBC,cAAmC;IACnE,MAAM;IACN,UAASC,SAAS,EAAE,EAAEC,IAAI,EAAEC,OAAO,EAAEC,eAAe,EAAEN,gBAAgB,KAAK,EAAE;QACzEO,kBAAkB,QAAQ,CAACJ,WAAWC;QACtCD,UAAU,gBAAgB,CAACK,YAAY;YAAE,MAAMH;QAAQ;QACvDF,UAAU,gBAAgB,CAACM,iBAAiB;YACxC,WAAW,IAAMV,UAAUC;YAC3BM;QACJ;IACJ;AACJ;AAMO,MAAMI,8BAA8B,CAACC;IACxC,MAAMC,eAAe,IAAIC,aAAaF,OAAO,IAAI,EAAEA,OAAO,eAAe,EAAE;QACvE,eAAe,IAAMZ,UAAUY,OAAO,aAAa;IACvD;IACAG,iBAAiB,SAAS,CAAC,IAAIC,yBAAyBJ,OAAO,IAAI,EAAEC;AACzE"}
@@ -4,6 +4,7 @@ import { SqlSchemaConfig } from "../schemaConfig/index.js";
4
4
  import { SqlSchemaSetup } from "../schemaSetup/index.js";
5
5
  import { TableManager } from "../TableManager.js";
6
6
  import { defineServiceManifestsTable } from "../serviceDiscovery/serviceManifestsTable.js";
7
+ import { tenantNeutralScopeTenant } from "@webiny/api-core/features/tenancy/ScopeTenant/index.js";
7
8
  class CoreSqlSchemaSetupImpl {
8
9
  constructor(knex, schemaConfig){
9
10
  this.knex = knex;
@@ -13,7 +14,7 @@ class CoreSqlSchemaSetupImpl {
13
14
  async setup() {
14
15
  const knex = this.knex.client;
15
16
  const tableManager = new TableManager(knex, this.schemaConfig?.tableNamePrefix);
16
- createApiCoreSqlOperations(knex, tableManager);
17
+ createApiCoreSqlOperations(knex, tableManager, tenantNeutralScopeTenant);
17
18
  defineServiceManifestsTable(tableManager);
18
19
  await tableManager.setup();
19
20
  }
@@ -1 +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"}
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\";\nimport { tenantNeutralScopeTenant } from \"@webiny/api-core/features/tenancy/ScopeTenant/index.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. The setup runs in no tenant.\n createApiCoreSqlOperations(knex, tableManager, tenantNeutralScopeTenant);\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","tenantNeutralScopeTenant","defineServiceManifestsTable","CoreSqlSchemaSetup","SqlSchemaSetup","KnexClient","SqlSchemaConfig"],"mappings":";;;;;;;AAYA,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,cAAcG;QAC/CC,4BAA4BJ;QAC5B,MAAMA,aAAa,KAAK;IAC5B;AACJ;AAEO,MAAMK,qBAAqBC,eAAe,oBAAoB,CAAC;IAClE,gBAAgBT;IAChB,cAAc;QAACU;QAAY;YAACC;YAAiB;gBAAE,UAAU;YAAK;SAAE;KAAC;AACrE"}
@@ -7,7 +7,7 @@ declare class SqlApiCoreStorageOperationsFactoryImpl implements ApiCoreStorageOp
7
7
  private readonly knex;
8
8
  private readonly schemaConfig?;
9
9
  constructor(knex: KnexClient.Interface, schemaConfig?: SqlSchemaConfig.Interface | undefined);
10
- create(): ApiCoreStorageOperations;
10
+ create({ scopeTenant }: ApiCoreStorageOperationsFactory.Params): ApiCoreStorageOperations;
11
11
  }
12
12
  export declare const SqlApiCoreStorageOperationsFactory: typeof SqlApiCoreStorageOperationsFactoryImpl & {
13
13
  __abstraction: import("@webiny/di").Abstraction<import("@webiny/api-core/features/storageOperations/abstractions").IApiCoreStorageOperationsFactory>;
@@ -7,8 +7,9 @@ class SqlApiCoreStorageOperationsFactoryImpl {
7
7
  this.knex = knex;
8
8
  this.schemaConfig = schemaConfig;
9
9
  }
10
- create() {
10
+ create({ scopeTenant }) {
11
11
  return createApiCoreSql({
12
+ scopeTenant,
12
13
  knex: this.knex.client,
13
14
  tableNamePrefix: this.schemaConfig?.tableNamePrefix,
14
15
  schemaManaged: this.schemaConfig?.isManaged() === true
@@ -1 +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"}
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({\n scopeTenant\n }: ApiCoreStorageOperationsFactory.Params): ApiCoreStorageOperations {\n return createApiCoreSql({\n scopeTenant,\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","scopeTenant","createApiCoreSql","SqlApiCoreStorageOperationsFactory","ApiCoreStorageOperationsFactory","KnexClient","SqlSchemaConfig"],"mappings":";;;;AAOA,MAAMA;IACF,YACqBC,IAA0B,EAC1BC,YAAwC,CAC3D;aAFmBD,IAAI,GAAJA;aACAC,YAAY,GAAZA;IAClB;IAEI,OAAO,EACVC,WAAW,EAC0B,EAA4B;QACjE,OAAOC,iBAAiB;YACpBD;YACA,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM;YACtB,iBAAiB,IAAI,CAAC,YAAY,EAAE;YACpC,eAAe,IAAI,CAAC,YAAY,EAAE,gBAAgB;QACtD;IACJ;AACJ;AAEO,MAAME,qCACTC,gCAAgC,oBAAoB,CAAC;IACjD,gBAAgBN;IAChB,cAAc;QAACO;QAAY;YAACC;YAAiB;gBAAE,UAAU;YAAK;SAAE;KAAC;AACrE"}
@@ -0,0 +1,18 @@
1
+ import { TenancyStorageOperationsFactory } from "@webiny/api-core/features/storageOperations/abstractions.js";
2
+ import type { TenancyStorageOperations } from "@webiny/api-core/types/tenancy.js";
3
+ import { KnexClient } from "../feature/KnexClient/index.js";
4
+ import { SqlSchemaConfig } from "../schemaConfig/index.js";
5
+ /**
6
+ * The tenant registry's storage on the container's connection: the tenants table only. Root's scope
7
+ * reads every tenant's record from it, the request's tenant's included.
8
+ */
9
+ declare class SqlTenancyStorageOperationsFactoryImpl implements TenancyStorageOperationsFactory.Interface {
10
+ private readonly knex;
11
+ private readonly schemaConfig?;
12
+ constructor(knex: KnexClient.Interface, schemaConfig?: SqlSchemaConfig.Interface | undefined);
13
+ create(): TenancyStorageOperations;
14
+ }
15
+ export declare const SqlTenancyStorageOperationsFactory: typeof SqlTenancyStorageOperationsFactoryImpl & {
16
+ __abstraction: import("@webiny/di").Abstraction<import("@webiny/api-core/features/storageOperations/abstractions.js").ITenancyStorageOperationsFactory>;
17
+ };
18
+ export {};
@@ -0,0 +1,36 @@
1
+ import { TenancyStorageOperationsFactory } from "@webiny/api-core/features/storageOperations/abstractions.js";
2
+ import { KnexClient } from "../feature/KnexClient/index.js";
3
+ import { SqlSchemaConfig } from "../schemaConfig/index.js";
4
+ import { TableManager } from "../TableManager.js";
5
+ import { createStorageOperations } from "../tenancy/index.js";
6
+ class SqlTenancyStorageOperationsFactoryImpl {
7
+ constructor(knex, schemaConfig){
8
+ this.knex = knex;
9
+ this.schemaConfig = schemaConfig;
10
+ }
11
+ create() {
12
+ const knex = this.knex.client;
13
+ const tableManager = new TableManager(knex, this.schemaConfig?.tableNamePrefix, {
14
+ schemaManaged: this.schemaConfig?.isManaged() === true
15
+ });
16
+ return createStorageOperations({
17
+ knex,
18
+ tableManager
19
+ });
20
+ }
21
+ }
22
+ const SqlTenancyStorageOperationsFactory = TenancyStorageOperationsFactory.createImplementation({
23
+ implementation: SqlTenancyStorageOperationsFactoryImpl,
24
+ dependencies: [
25
+ KnexClient,
26
+ [
27
+ SqlSchemaConfig,
28
+ {
29
+ optional: true
30
+ }
31
+ ]
32
+ ]
33
+ });
34
+ export { SqlTenancyStorageOperationsFactory };
35
+
36
+ //# sourceMappingURL=SqlTenancyStorageOperationsFactory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coreStorage/SqlTenancyStorageOperationsFactory.js","sources":["../../src/coreStorage/SqlTenancyStorageOperationsFactory.ts"],"sourcesContent":["// A deep import: the package root pulls in all of api-core.\nimport { TenancyStorageOperationsFactory } from \"@webiny/api-core/features/storageOperations/abstractions.js\";\nimport type { TenancyStorageOperations } from \"@webiny/api-core/types/tenancy.js\";\nimport { KnexClient } from \"~/feature/KnexClient/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\nimport { TableManager } from \"~/TableManager.js\";\nimport { createStorageOperations as createTenancyStorageOperations } from \"~/tenancy/index.js\";\n\n/**\n * The tenant registry's storage on the container's connection: the tenants table only. Root's scope\n * reads every tenant's record from it, the request's tenant's included.\n */\nclass SqlTenancyStorageOperationsFactoryImpl implements TenancyStorageOperationsFactory.Interface {\n public constructor(\n private readonly knex: KnexClient.Interface,\n private readonly schemaConfig?: SqlSchemaConfig.Interface\n ) {}\n\n public create(): TenancyStorageOperations {\n const knex = this.knex.client;\n const tableManager = new TableManager(knex, this.schemaConfig?.tableNamePrefix, {\n schemaManaged: this.schemaConfig?.isManaged() === true\n });\n return createTenancyStorageOperations({ knex, tableManager });\n }\n}\n\nexport const SqlTenancyStorageOperationsFactory =\n TenancyStorageOperationsFactory.createImplementation({\n implementation: SqlTenancyStorageOperationsFactoryImpl,\n dependencies: [KnexClient, [SqlSchemaConfig, { optional: true }]]\n });\n"],"names":["SqlTenancyStorageOperationsFactoryImpl","knex","schemaConfig","tableManager","TableManager","createTenancyStorageOperations","SqlTenancyStorageOperationsFactory","TenancyStorageOperationsFactory","KnexClient","SqlSchemaConfig"],"mappings":";;;;;AAYA,MAAMA;IACF,YACqBC,IAA0B,EAC1BC,YAAwC,CAC3D;aAFmBD,IAAI,GAAJA;aACAC,YAAY,GAAZA;IAClB;IAEI,SAAmC;QACtC,MAAMD,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM;QAC7B,MAAME,eAAe,IAAIC,aAAaH,MAAM,IAAI,CAAC,YAAY,EAAE,iBAAiB;YAC5E,eAAe,IAAI,CAAC,YAAY,EAAE,gBAAgB;QACtD;QACA,OAAOI,wBAA+B;YAAEJ;YAAME;QAAa;IAC/D;AACJ;AAEO,MAAMG,qCACTC,gCAAgC,oBAAoB,CAAC;IACjD,gBAAgBP;IAChB,cAAc;QAACQ;QAAY;YAACC;YAAiB;gBAAE,UAAU;YAAK;SAAE;KAAC;AACrE"}
@@ -0,0 +1,19 @@
1
+ import { TenantStorageNotReadyError, TenantStorageReadiness } from "@webiny/api-core/features/tenancy/TenantStorageReadiness/index.js";
2
+ import { Result } from "@webiny/feature/api";
3
+ import { KnexClient } from "../feature/KnexClient/index.js";
4
+ import { SqlSchemaConfig } from "../schemaConfig/index.js";
5
+ /**
6
+ * A SQL storage can take a new tenant when its database answers and, when its schema is managed (set
7
+ * up before the API took traffic, so nothing creates tables at runtime), the schema setup ran on it.
8
+ * An unmanaged schema creates its tables on first use, so there's nothing more to check.
9
+ */
10
+ declare class SqlTenantStorageReadinessImpl implements TenantStorageReadiness.Interface {
11
+ private knexClient;
12
+ private schemaConfig;
13
+ constructor(knexClient: KnexClient.Interface, schemaConfig: SqlSchemaConfig.Interface | undefined);
14
+ check(): Promise<Result<void, TenantStorageNotReadyError>>;
15
+ }
16
+ export declare const SqlTenantStorageReadiness: typeof SqlTenantStorageReadinessImpl & {
17
+ __abstraction: import("@webiny/di").Abstraction<import("@webiny/api-core/features/tenancy/TenantStorageReadiness/abstractions").ITenantStorageReadiness>;
18
+ };
19
+ export {};
@@ -0,0 +1,48 @@
1
+ import { TenantStorageNotReadyError, TenantStorageReadiness } from "@webiny/api-core/features/tenancy/TenantStorageReadiness/index.js";
2
+ import { Result } from "@webiny/feature/api";
3
+ import { KnexClient } from "../feature/KnexClient/index.js";
4
+ import { SqlSchemaConfig } from "../schemaConfig/index.js";
5
+ const ROLES_TABLE = "webiny_core_roles";
6
+ class SqlTenantStorageReadinessImpl {
7
+ constructor(knexClient, schemaConfig){
8
+ this.knexClient = knexClient;
9
+ this.schemaConfig = schemaConfig;
10
+ }
11
+ async check() {
12
+ const knex = this.knexClient.client;
13
+ try {
14
+ await knex.raw("SELECT 1");
15
+ } catch (error) {
16
+ return Result.fail(TenantStorageNotReadyError.unreachable(`the database is not reachable (${messageOf(error)}).`));
17
+ }
18
+ if (!this.schemaConfig?.isManaged()) return Result.ok();
19
+ const prefix = this.schemaConfig.tableNamePrefix;
20
+ const table = prefix ? `${prefix}_${ROLES_TABLE}` : ROLES_TABLE;
21
+ let hasTable;
22
+ try {
23
+ hasTable = await knex.schema.hasTable(table);
24
+ } catch (error) {
25
+ return Result.fail(TenantStorageNotReadyError.unreachable(`the database is not reachable (${messageOf(error)}).`));
26
+ }
27
+ if (!hasTable) return Result.fail(TenantStorageNotReadyError.notSetUp(`its schema is not set up (table "${table}" is missing).`));
28
+ return Result.ok();
29
+ }
30
+ }
31
+ function messageOf(error) {
32
+ return error instanceof Error ? error.message : String(error);
33
+ }
34
+ const SqlTenantStorageReadiness = TenantStorageReadiness.createImplementation({
35
+ implementation: SqlTenantStorageReadinessImpl,
36
+ dependencies: [
37
+ KnexClient,
38
+ [
39
+ SqlSchemaConfig,
40
+ {
41
+ optional: true
42
+ }
43
+ ]
44
+ ]
45
+ });
46
+ export { SqlTenantStorageReadiness };
47
+
48
+ //# sourceMappingURL=SqlTenantStorageReadiness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coreStorage/SqlTenantStorageReadiness.js","sources":["../../src/coreStorage/SqlTenantStorageReadiness.ts"],"sourcesContent":["// A deep import: the package root pulls in all of api-core.\nimport {\n TenantStorageNotReadyError,\n TenantStorageReadiness\n} from \"@webiny/api-core/features/tenancy/TenantStorageReadiness/index.js\";\nimport { Result } from \"@webiny/feature/api\";\nimport { KnexClient } from \"~/feature/KnexClient/index.js\";\nimport { SqlSchemaConfig } from \"~/schemaConfig/index.js\";\n\n/** A table every installation writes to (the security installer's roles). */\nconst ROLES_TABLE = \"webiny_core_roles\";\n\n/**\n * A SQL storage can take a new tenant when its database answers and, when its schema is managed (set\n * up before the API took traffic, so nothing creates tables at runtime), the schema setup ran on it.\n * An unmanaged schema creates its tables on first use, so there's nothing more to check.\n */\nclass SqlTenantStorageReadinessImpl implements TenantStorageReadiness.Interface {\n constructor(\n private knexClient: KnexClient.Interface,\n private schemaConfig: SqlSchemaConfig.Interface | undefined\n ) {}\n\n async check(): Promise<Result<void, TenantStorageNotReadyError>> {\n const knex = this.knexClient.client;\n try {\n await knex.raw(\"SELECT 1\");\n } catch (error) {\n return Result.fail(\n TenantStorageNotReadyError.unreachable(\n `the database is not reachable (${messageOf(error)}).`\n )\n );\n }\n\n if (!this.schemaConfig?.isManaged()) {\n return Result.ok();\n }\n const prefix = this.schemaConfig.tableNamePrefix;\n const table = prefix ? `${prefix}_${ROLES_TABLE}` : ROLES_TABLE;\n let hasTable: boolean;\n try {\n hasTable = await knex.schema.hasTable(table);\n } catch (error) {\n return Result.fail(\n TenantStorageNotReadyError.unreachable(\n `the database is not reachable (${messageOf(error)}).`\n )\n );\n }\n if (!hasTable) {\n return Result.fail(\n TenantStorageNotReadyError.notSetUp(\n `its schema is not set up (table \"${table}\" is missing).`\n )\n );\n }\n return Result.ok();\n }\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport const SqlTenantStorageReadiness = TenantStorageReadiness.createImplementation({\n implementation: SqlTenantStorageReadinessImpl,\n dependencies: [KnexClient, [SqlSchemaConfig, { optional: true }]]\n});\n"],"names":["ROLES_TABLE","SqlTenantStorageReadinessImpl","knexClient","schemaConfig","knex","error","Result","TenantStorageNotReadyError","messageOf","prefix","table","hasTable","Error","String","SqlTenantStorageReadiness","TenantStorageReadiness","KnexClient","SqlSchemaConfig"],"mappings":";;;;AAUA,MAAMA,cAAc;AAOpB,MAAMC;IACF,YACYC,UAAgC,EAChCC,YAAmD,CAC7D;aAFUD,UAAU,GAAVA;aACAC,YAAY,GAAZA;IACT;IAEH,MAAM,QAA2D;QAC7D,MAAMC,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM;QACnC,IAAI;YACA,MAAMA,KAAK,GAAG,CAAC;QACnB,EAAE,OAAOC,OAAO;YACZ,OAAOC,OAAO,IAAI,CACdC,2BAA2B,WAAW,CAClC,CAAC,+BAA+B,EAAEC,UAAUH,OAAO,EAAE,CAAC;QAGlE;QAEA,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,aACpB,OAAOC,OAAO,EAAE;QAEpB,MAAMG,SAAS,IAAI,CAAC,YAAY,CAAC,eAAe;QAChD,MAAMC,QAAQD,SAAS,GAAGA,OAAO,CAAC,EAAET,aAAa,GAAGA;QACpD,IAAIW;QACJ,IAAI;YACAA,WAAW,MAAMP,KAAK,MAAM,CAAC,QAAQ,CAACM;QAC1C,EAAE,OAAOL,OAAO;YACZ,OAAOC,OAAO,IAAI,CACdC,2BAA2B,WAAW,CAClC,CAAC,+BAA+B,EAAEC,UAAUH,OAAO,EAAE,CAAC;QAGlE;QACA,IAAI,CAACM,UACD,OAAOL,OAAO,IAAI,CACdC,2BAA2B,QAAQ,CAC/B,CAAC,iCAAiC,EAAEG,MAAM,cAAc,CAAC;QAIrE,OAAOJ,OAAO,EAAE;IACpB;AACJ;AAEA,SAASE,UAAUH,KAAc;IAC7B,OAAOA,iBAAiBO,QAAQP,MAAM,OAAO,GAAGQ,OAAOR;AAC3D;AAEO,MAAMS,4BAA4BC,uBAAuB,oBAAoB,CAAC;IACjF,gBAAgBd;IAChB,cAAc;QAACe;QAAY;YAACC;YAAiB;gBAAE,UAAU;YAAK;SAAE;KAAC;AACrE"}
@@ -1,7 +1,8 @@
1
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`.
2
+ * The SQL core storage of a tenant scope: the implementation of `ApiCoreStorageOperationsFactory`,
3
+ * which `ApiCoreFeature.register` resolves and builds, the tenant registry's
4
+ * (`TenancyStorageOperationsFactory`, used in root's scope and the default storage's), and the `core`
5
+ * schema setup step. Mirrors `ApiCoreDdbFeature`.
5
6
  *
6
7
  * Registered per request (by the SQL storage's `RequestStorage`). It runs on what the root holds:
7
8
  * the connection (`KnexClient`) and the table prefix and schema-managed setting (`SqlSchemaConfig`),
@@ -1,11 +1,15 @@
1
1
  import { createFeature } from "@webiny/feature/api";
2
2
  import { SqlApiCoreStorageOperationsFactory } from "./SqlApiCoreStorageOperationsFactory.js";
3
3
  import { CoreSqlSchemaSetup } from "./CoreSqlSchemaSetup.js";
4
+ import { SqlTenancyStorageOperationsFactory } from "./SqlTenancyStorageOperationsFactory.js";
5
+ import { SqlTenantStorageReadiness } from "./SqlTenantStorageReadiness.js";
4
6
  const ApiCoreSqlFeature = createFeature({
5
7
  name: "ApiCoreSql",
6
8
  register (container) {
7
9
  container.register(SqlApiCoreStorageOperationsFactory);
10
+ container.register(SqlTenancyStorageOperationsFactory);
8
11
  container.register(CoreSqlSchemaSetup);
12
+ container.register(SqlTenantStorageReadiness);
9
13
  }
10
14
  });
11
15
  export { ApiCoreSqlFeature };
@@ -1 +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"}
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\";\nimport { SqlTenancyStorageOperationsFactory } from \"./SqlTenancyStorageOperationsFactory.js\";\nimport { SqlTenantStorageReadiness } from \"./SqlTenantStorageReadiness.js\";\n\n/**\n * The SQL core storage of a tenant scope: the implementation of `ApiCoreStorageOperationsFactory`,\n * which `ApiCoreFeature.register` resolves and builds, the tenant registry's\n * (`TenancyStorageOperationsFactory`, used in root's scope and the default storage's), and the `core`\n * schema setup step. Mirrors `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(SqlTenancyStorageOperationsFactory);\n container.register(CoreSqlSchemaSetup);\n container.register(SqlTenantStorageReadiness);\n }\n});\n"],"names":["ApiCoreSqlFeature","createFeature","container","SqlApiCoreStorageOperationsFactory","SqlTenancyStorageOperationsFactory","CoreSqlSchemaSetup","SqlTenantStorageReadiness"],"mappings":";;;;;AAgBO,MAAMA,oBAAoBC,cAAc;IAC3C,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;QACnBD,UAAU,QAAQ,CAACE;QACnBF,UAAU,QAAQ,CAACG;QACnBH,UAAU,QAAQ,CAACI;IACvB;AACJ"}