@protobase/server 0.130.0 → 0.130.1

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.
@@ -1,4 +1,4 @@
1
- import "kysely";
1
+ import { RawBuilder } from "kysely";
2
2
  import { createAuthMiddleware } from "better-auth/api";
3
3
  //#region src/better-auth/organizations/store.d.ts
4
4
  export type AuthContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0]['context'];
@@ -0,0 +1,11 @@
1
+ import { ModuleId } from "../../names/modules/index.js";
2
+ import { StoreNames } from "../store-names.js";
3
+ //#region src/better-auth/store/offline/archive-revival.d.ts
4
+ /**
5
+ * The statements that give back to each column `module` left in use on the tables of `existing` the foreign key to its
6
+ * table, once that table is made again, where the column has none: not checked against the rows there, whose values
7
+ * may name a row the archive holds, such as a token's organization, which then no longer works. As SQL text after a
8
+ * comment; `undefined` when it leaves none.
9
+ */
10
+ export declare const restoredKeysSql: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[]) => string | undefined;
11
+ //#endregion
@@ -0,0 +1,25 @@
1
+ import { generatedName } from "../../names/identifier-length.js";
2
+ import { ddl } from "../ddl.js";
3
+ import { statementsSql } from "../migration-sql.js";
4
+ import { stillWrittenColumns } from "./module-switches.js";
5
+ import { sql } from "kysely";
6
+ //#region src/better-auth/store/offline/archive-revival.ts
7
+ /**
8
+ * The statements that give back to each column `module` left in use on the tables of `existing` the foreign key to its
9
+ * table, once that table is made again, where the column has none: not checked against the rows there, whose values
10
+ * may name a row the archive holds, such as a token's organization, which then no longer works. As SQL text after a
11
+ * comment; `undefined` when it leaves none.
12
+ */
13
+ const restoredKeysSql = (names, module, existing) => {
14
+ const statements = stillWrittenColumns(names, module, existing).map(({ table, column, references }) => ddl`do $restore$
15
+ begin
16
+ if not exists (select from pg_constraint where conrelid = ${sql.lit(String(table))}::regclass and contype = 'f' and confrelid = ${sql.lit(String(references))}::regclass) then
17
+ alter table ${table} add constraint ${sql.id(generatedName(`${table.name}_${column.name}_fkey`))} foreign key (${column}) references ${references} (id) on delete cascade not valid;
18
+ end if;
19
+ end
20
+ $restore$`);
21
+ if (statements.length === 0) return;
22
+ return `-- ${module} on: the columns it left in use while off point at its tables again where an archive took their foreign key; a value the archive holds no longer names a row.\n${statementsSql(statements)}`;
23
+ };
24
+ //#endregion
25
+ export { restoredKeysSql };
@@ -0,0 +1,18 @@
1
+ import { RawBuilder } from "kysely";
2
+ //#region src/better-auth/store/offline/contract-gate.d.ts
3
+ /** The line that marks the statement under it as taking what the migration `id` stopped older code from using. */
4
+ export declare const contractMark: (id: string) => string;
5
+ /** `statements` as SQL text, each under the mark naming the migration `id`. */
6
+ export declare const markedSql: (id: string, statements: readonly RawBuilder<unknown>[]) => string;
7
+ /** A migration a sign-off waits on: its id and file name, as `migrations.history` records them. */
8
+ export type SignedOff = {
9
+ id: string;
10
+ name: string;
11
+ };
12
+ /**
13
+ * The block that refuses, unless `migrations.history` has `after`'s row, `hours` have passed since it was applied,
14
+ * and, when `followed`, a row applied after it: what `step` says it does waits for the update to have served that long,
15
+ * and for the next one to have followed it.
16
+ */
17
+ export declare const signOffGate: (after: SignedOff, hours: number, step: string, followed: boolean) => RawBuilder<unknown>;
18
+ //#endregion
@@ -0,0 +1,35 @@
1
+ import { ddl, ddlText } from "../ddl.js";
2
+ import { recordTable } from "../../../migration-record/record-table.js";
3
+ import { sql } from "kysely";
4
+ //#region src/better-auth/store/offline/contract-gate.ts
5
+ /** The line that marks the statement under it as taking what the migration `id` stopped older code from using. */
6
+ const contractMark = (id) => `-- protobase:contract ${id}`;
7
+ /** `statements` as SQL text, each under the mark naming the migration `id`. */
8
+ const markedSql = (id, statements) => statements.map((statement) => `${contractMark(id)}\n${ddlText(statement)};`).join("\n\n");
9
+ /**
10
+ * The block that refuses, unless `migrations.history` has `after`'s row, `hours` have passed since it was applied,
11
+ * and, when `followed`, a row applied after it: what `step` says it does waits for the update to have served that long,
12
+ * and for the next one to have followed it.
13
+ */
14
+ const signOffGate = (after, hours, step, followed) => {
15
+ const waits = `${step} waits until ${after.name}`;
16
+ const next = ddl`
17
+ if not exists (select from ${sql.raw(recordTable)} where applied_at > applied) then
18
+ raise exception '%', ${sql.lit(`${waits} is followed by a migration applied after it, as the next update applies one`)};
19
+ end if;`;
20
+ return ddl`do $gate$
21
+ declare
22
+ applied timestamptz;
23
+ begin
24
+ select applied_at into applied from ${sql.raw(recordTable)} where id = ${sql.lit(after.id)};
25
+ if applied is null then
26
+ raise exception '%', ${sql.lit(`${waits} is applied`)};
27
+ end if;${followed ? next : sql``}
28
+ if now() - applied < ${sql.lit(`${hours} hours`)}::interval then
29
+ raise exception '%', format(${sql.lit(`${waits} was applied ${hours} hours ago; it was applied at %s`)}, applied);
30
+ end if;
31
+ end
32
+ $gate$`;
33
+ };
34
+ //#endregion
35
+ export { contractMark, markedSql, signOffGate };
@@ -0,0 +1,41 @@
1
+ import { ModuleId } from "../../names/modules/index.js";
2
+ import { DeferredOff, KeptModule, RetiredName } from "./store-model.js";
3
+ //#region src/better-auth/store/offline/module-archive.d.ts
4
+ /** A module archived: where its tables went, the columns it retired, the choice made, and the migration that archived it. */
5
+ export type ArchivedModule = {
6
+ module: ModuleId;
7
+ step: number;
8
+ /** The store's schema, which the retired columns' tables are in; `null` when the search path decides. */
9
+ store: string | null;
10
+ /** The schema its tables moved to (`archiveSchema`), and their names there. */
11
+ schema: string;
12
+ tables: string[];
13
+ columns: RetiredName[];
14
+ choice: DeferredOff['choice'];
15
+ /** The id of the migration that archived it, which the one that deletes it names. */
16
+ file: string;
17
+ };
18
+ /** The schema the migration numbered `number` archives tables to. */
19
+ export declare const archiveSchema: (number: number) => string;
20
+ /** The name a retired column takes once archived; one past 63 bytes is shortened as Postgres would not. */
21
+ export declare const archivedColumn: (column: string) => string;
22
+ /**
23
+ * The statements that archive `kept` from the store's schema `store` to `schema`: the watch's schema, table and
24
+ * function where missing, the foreign keys between its tables and the others dropped, its tables moved, each watched
25
+ * as a whole, and each column it retired renamed to its archive and watched under it, counted as the column.
26
+ */
27
+ export declare const archiveStatements: (store: string | null, schema: string, kept: KeptModule & {
28
+ off: DeferredOff;
29
+ }) => import("kysely").RawBuilder<unknown>[];
30
+ /**
31
+ * The statements that take from every role that owns or holds a privilege on a table of `schema`, one of its columns
32
+ * or the schema itself, and from everyone, the use of its tables and sequences, then of the schema, the role applying
33
+ * the migration included, each with the grants made from them: written once the file has moved every table there,
34
+ * which needs the schema. The schema goes last, as revoking on its tables looks it up.
35
+ */
36
+ export declare const revokeStatements: (schema: string) => import("kysely").RawBuilder<unknown>[];
37
+ /** The snapshot's record of `kept` once archived to `schema` by the migration `file`. */
38
+ export declare const archivedModule: (store: string | null, schema: string, kept: KeptModule & {
39
+ off: DeferredOff;
40
+ }, file: string) => ArchivedModule;
41
+ //#endregion
@@ -0,0 +1,95 @@
1
+ import { generatedName } from "../../names/identifier-length.js";
2
+ import { columnId, tableId } from "../../names/identifiers.js";
3
+ import { ddl } from "../ddl.js";
4
+ import { retiredSchema, watchBaseStatements, watchTrigger, watchTriggerName } from "./retired-watch.js";
5
+ import { sql } from "kysely";
6
+ //#region src/better-auth/store/offline/module-archive.ts
7
+ /** The schema the migration numbered `number` archives tables to. */
8
+ const archiveSchema = (number) => `protobase_archive_${number}`;
9
+ /** The name a retired column takes once archived; one past 63 bytes is shortened as Postgres would not. */
10
+ const archivedColumn = (column) => generatedName(`${column}_archive`);
11
+ /** The trigger that counts the writes of an archived table. */
12
+ const tableWatchTrigger = "retired_writes";
13
+ const qualified = (store, table) => tableId(store ?? void 0, table);
14
+ /** `tables` as an array of `regclass`, for a block to compare with the catalogue. */
15
+ const regclasses = (tables) => ddl`array[${sql.join(tables.map((table) => sql.lit(String(table))))}]::regclass[]`;
16
+ const dropCrossingKeys = (tables) => ddl`do $archive$
17
+ declare
18
+ found record;
19
+ begin
20
+ for found in select conrelid::regclass as relation, conname from pg_constraint where contype = 'f' and (conrelid = any(${tables})) <> (confrelid = any(${tables})) loop
21
+ execute format('alter table %s drop constraint %I', found.relation, found.conname);
22
+ end loop;
23
+ end
24
+ $archive$`;
25
+ /**
26
+ * The statements that archive `kept` from the store's schema `store` to `schema`: the watch's schema, table and
27
+ * function where missing, the foreign keys between its tables and the others dropped, its tables moved, each watched
28
+ * as a whole, and each column it retired renamed to its archive and watched under it, counted as the column.
29
+ */
30
+ const archiveStatements = (store, schema, kept) => {
31
+ const tables = Object.values(kept.tables).map(({ name }) => name);
32
+ return [
33
+ ...watchBaseStatements(),
34
+ ddl`create schema if not exists ${schema}`,
35
+ dropCrossingKeys(regclasses(tables.map((table) => qualified(store, table)))),
36
+ ...tables.map((table) => ddl`alter table ${qualified(store, table)} set schema ${schema}`),
37
+ ...tables.map((table) => ddl`create trigger ${tableWatchTrigger} after insert or update or delete on ${tableId(schema, table)} for each row execute function ${retiredSchema}.${"count_write"}(${sql.lit("*")})`),
38
+ ...kept.off.columns.flatMap(({ table, column }) => {
39
+ const at = qualified(store, table);
40
+ const archived = columnId(at, archivedColumn(column));
41
+ return [
42
+ ddl`drop trigger if exists ${watchTriggerName(column)} on ${at}`,
43
+ ddl`alter table ${at} rename column ${column} to ${archived}`,
44
+ watchTrigger(at, columnId(at, column), archived)
45
+ ];
46
+ })
47
+ ];
48
+ };
49
+ /**
50
+ * The statements that take from every role that owns or holds a privilege on a table of `schema`, one of its columns
51
+ * or the schema itself, and from everyone, the use of its tables and sequences, then of the schema, the role applying
52
+ * the migration included, each with the grants made from them: written once the file has moved every table there,
53
+ * which needs the schema. The schema goes last, as revoking on its tables looks it up.
54
+ */
55
+ const revokeStatements = (schema) => {
56
+ const at = sql.lit(schema);
57
+ return [ddl`do $revoke$
58
+ declare
59
+ holders text[];
60
+ holder text;
61
+ begin
62
+ select array_agg(distinct found.role::regrole::text) into holders from (
63
+ select relowner as role from pg_class where relnamespace = ${at}::regnamespace
64
+ union all
65
+ select privilege.grantee from pg_class, aclexplode(relacl) as privilege where relnamespace = ${at}::regnamespace and privilege.grantee <> 0
66
+ union all
67
+ select privilege.grantee from pg_class join pg_attribute on attrelid = pg_class.oid, aclexplode(attacl) as privilege where relnamespace = ${at}::regnamespace and privilege.grantee <> 0
68
+ union all
69
+ select privilege.grantee from pg_namespace, aclexplode(nspacl) as privilege where pg_namespace.oid = ${at}::regnamespace and privilege.grantee <> 0
70
+ ) as found;
71
+ foreach holder in array coalesce(holders, '{}') loop
72
+ execute format('revoke all on all tables in schema %I from %s cascade', ${at}, holder);
73
+ execute format('revoke all on all sequences in schema %I from %s cascade', ${at}, holder);
74
+ end loop;
75
+ execute format('revoke all on all tables in schema %I from public cascade', ${at});
76
+ execute format('revoke all on all sequences in schema %I from public cascade', ${at});
77
+ foreach holder in array coalesce(holders, '{}') loop
78
+ execute format('revoke all on schema %I from %s cascade', ${at}, holder);
79
+ end loop;
80
+ end
81
+ $revoke$`, ddl`revoke all on schema ${schema} from public, current_user cascade`];
82
+ };
83
+ /** The snapshot's record of `kept` once archived to `schema` by the migration `file`. */
84
+ const archivedModule = (store, schema, kept, file) => ({
85
+ module: kept.module,
86
+ step: kept.step,
87
+ store,
88
+ schema,
89
+ tables: Object.values(kept.tables).map(({ name }) => name),
90
+ columns: kept.off.columns,
91
+ choice: kept.off.choice,
92
+ file
93
+ });
94
+ //#endregion
95
+ export { archiveSchema, archiveStatements, archivedColumn, archivedModule, regclasses, revokeStatements, tableWatchTrigger };
@@ -0,0 +1,22 @@
1
+ import { TableId } from "../../names/identifiers.js";
2
+ import { ModuleId } from "../../names/modules/index.js";
3
+ import { StoreModel } from "./store-model.js";
4
+ import { ArchivedModule } from "./module-archive.js";
5
+ //#region src/better-auth/store/offline/module-delete.d.ts
6
+ /** The table that records the store's steps, with its module and target columns, by their names. */
7
+ export type StepRecord = {
8
+ table: TableId;
9
+ module: string;
10
+ target: string;
11
+ };
12
+ /** The step record of the store `model` describes; `undefined` for one without it. */
13
+ export declare const stepRecordOf: (model: StoreModel) => StepRecord | undefined;
14
+ /** `forgetSteps` as SQL text. */
15
+ export declare const forgetStepsSql: (steps: StepRecord, id: ModuleId) => string;
16
+ /**
17
+ * The statements that delete `entry` for good once nothing wrote it for `hours` (`unwrittenCheck`): the use of its
18
+ * schema taken back for the role applying it, its tables dropped, and the schema once nothing else is in it, then each
19
+ * column archive with its watch; and with `steps`, while the module is still off, its rows in `auth_steps`.
20
+ */
21
+ export declare const deleteStatements: (entry: ArchivedModule, hours: number, steps: StepRecord | undefined) => import("kysely").RawBuilder<unknown>[];
22
+ //#endregion
@@ -0,0 +1,99 @@
1
+ import { columnId, tableId } from "../../names/identifiers.js";
2
+ import { ddl } from "../ddl.js";
3
+ import { statementsSql } from "../migration-sql.js";
4
+ import { retiredSchema, watchTriggerName } from "./retired-watch.js";
5
+ import { stillWrittenTargets } from "./module-switches.js";
6
+ import { archivedColumn, tableWatchTrigger } from "./module-archive.js";
7
+ import { sql } from "kysely";
8
+ //#region src/better-auth/store/offline/module-delete.ts
9
+ const watched = (entry) => [...entry.tables.map((table) => ({
10
+ table: tableId(entry.schema, table),
11
+ schema: sql.lit(entry.schema),
12
+ name: table,
13
+ column: "*",
14
+ trigger: tableWatchTrigger
15
+ })), ...entry.columns.map(({ table, column }) => ({
16
+ table: tableId(entry.store ?? void 0, table),
17
+ schema: entry.store === null ? sql.raw("current_schema()") : sql.lit(entry.store),
18
+ name: table,
19
+ column,
20
+ trigger: watchTriggerName(archivedColumn(column))
21
+ }))];
22
+ /** The message a delete refuses with while the watch counts a write of `entry` within the last `hours`. */
23
+ const stillWritten = (entry, hours) => `${entry.module} was written within the last ${hours} hours, which retired.writes counts: %s. Find what still writes it, and delete it once nothing has for that long`;
24
+ /**
25
+ * The block that refuses unless every table and column archive of `entry` is watched, by a trigger that fires for the
26
+ * app's writes (enabled, or always), and the watch counts no write of any within the last `hours`: a write names each
27
+ * one written and its count.
28
+ */
29
+ const unwrittenCheck = (entry, hours) => {
30
+ const parts = watched(entry);
31
+ const triggers = parts.map(({ table, trigger }) => ddl`exists (select from pg_trigger where tgrelid = ${sql.lit(String(table))}::regclass and tgname = ${sql.lit(trigger)} and tgenabled in ('O', 'A'))`);
32
+ const keys = parts.map(({ schema, name, column }) => ddl`(format('%I.%I', ${schema}, ${sql.lit(name)}), ${sql.lit(column)})`);
33
+ return ddl`do $unwritten$
34
+ declare
35
+ found text;
36
+ begin
37
+ if to_regclass(${sql.lit(`${retiredSchema}.writes`)}) is null or not (${sql.join(triggers, sql` and `)}) then
38
+ raise exception '%', ${sql.lit(`${entry.module} has a table or column archive that retired.writes does not watch, so whether something still writes it is unknown: it is not deleted`)};
39
+ end if;
40
+ select string_agg(counted.table_name || '.' || counted.column_name || ' ' || counted.writes, ', ' order by counted.table_name, counted.column_name) into found
41
+ from (
42
+ select table_name, column_name, sum(writes) as writes from ${sql.raw(retiredSchema)}.writes
43
+ where hour >= date_trunc('hour', now() - ${sql.lit(`${hours} hours`)}::interval) and (table_name, column_name) in (${sql.join(keys)})
44
+ group by table_name, column_name
45
+ ) as counted;
46
+ if found is not null then
47
+ raise exception '%', format(${sql.lit(stillWritten(entry, hours))}, found);
48
+ end if;
49
+ end
50
+ $unwritten$`;
51
+ };
52
+ /** The step record of the store `model` describes; `undefined` for one without it. */
53
+ const stepRecordOf = (model) => {
54
+ const table = model.modules.auth?.tables.auth_steps;
55
+ if (!table) return;
56
+ return {
57
+ table: tableId(model.schema ?? void 0, table.name),
58
+ module: table.columns.module,
59
+ target: table.columns.target
60
+ };
61
+ };
62
+ /**
63
+ * The statement that forgets the steps of the module `id` and those applied to its tables, so it starts again from its
64
+ * first, but its parts on the tables of the modules whose columns it leaves in use while off (`stillWrittenTargets`),
65
+ * which stay as they are and are not applied again.
66
+ */
67
+ const forgetSteps = ({ table, module, target }, id) => {
68
+ const kept = stillWrittenTargets(id);
69
+ const own = ddl`${columnId(table, module)} = ${sql.lit(id)}`;
70
+ const parts = kept.length === 0 ? own : ddl`(${own} and ${columnId(table, target)} not in (${sql.join(kept.map((other) => sql.lit(other)))}))`;
71
+ return ddl`delete from ${table} where ${parts} or ${columnId(table, target)} = ${sql.lit(id)}`;
72
+ };
73
+ /** `forgetSteps` as SQL text. */
74
+ const forgetStepsSql = (steps, id) => statementsSql([forgetSteps(steps, id)]);
75
+ /**
76
+ * The statements that delete `entry` for good once nothing wrote it for `hours` (`unwrittenCheck`): the use of its
77
+ * schema taken back for the role applying it, its tables dropped, and the schema once nothing else is in it, then each
78
+ * column archive with its watch; and with `steps`, while the module is still off, its rows in `auth_steps`.
79
+ */
80
+ const deleteStatements = (entry, hours, steps) => [
81
+ ddl`grant usage on schema ${entry.schema} to current_user`,
82
+ unwrittenCheck(entry, hours),
83
+ ddl`drop table ${sql.join(entry.tables.map((table) => tableId(entry.schema, table)))}`,
84
+ ddl`do $empty$
85
+ begin
86
+ if not exists (select from pg_class where relnamespace = ${sql.lit(entry.schema)}::regnamespace) then
87
+ execute format('drop schema %I', ${sql.lit(entry.schema)});
88
+ end if;
89
+ end
90
+ $empty$`,
91
+ ...entry.columns.flatMap(({ table, column }) => {
92
+ const at = tableId(entry.store ?? void 0, table);
93
+ const archived = archivedColumn(column);
94
+ return [ddl`drop trigger if exists ${watchTriggerName(archived)} on ${at}`, ddl`alter table ${at} drop column ${columnId(at, archived)}`];
95
+ }),
96
+ ...steps ? [forgetSteps(steps, entry.module)] : []
97
+ ];
98
+ //#endregion
99
+ export { deleteStatements, forgetSteps, forgetStepsSql, stepRecordOf, stillWritten, unwrittenCheck };
@@ -8,6 +8,11 @@ export declare const offChoices: readonly ["keep", "archive", "delete"];
8
8
  export type OffChoice = (typeof offChoices)[number];
9
9
  /** The setting `protobase migrate --force` sets in its transactions, which lets a module whose kept tables hold rows on again. */
10
10
  export declare const forceSetting = "protobase.force";
11
+ /** The columns `module` retires (`retiredColumns`) by the names of their tables and themselves, as a snapshot records them. */
12
+ export declare const retiredNames: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[], externalUser?: boolean) => {
13
+ table: string;
14
+ column: string;
15
+ }[];
11
16
  /** The tables of `module` its steps up to `step` made, under the store's names. */
12
17
  export declare const keptTables: (names: StoreNames, module: ModuleId, step: number) => ResolvedTable<string>[];
13
18
  /** The message that refuses turning `module` on again while its kept tables hold rows: `found` lists each table with its count. */
@@ -19,7 +19,21 @@ const everyTable = (names) => resolveNames({
19
19
  ...names.names.input,
20
20
  modules: allModules
21
21
  }).tables;
22
- const writtenWhileOff = { organizations: { personal_access_token: ["organization_id"] } };
22
+ const writtenWhileOff = { organizations: { personal_access_token: { organization_id: "organization" } } };
23
+ /** The modules on whose tables `module` adds columns that stay written while it is off (`writtenWhileOff`), which its archive leaves as they are. */
24
+ const stillWrittenTargets = (module) => Object.keys(writtenWhileOff[module] ?? {}).map((table) => builtInModules.find((declaration) => table in declaration.tables).id);
25
+ /**
26
+ * The columns `module` adds that stay written while it is off, on the tables of `existing`, the modules the store has
27
+ * before the migration, each with the table its foreign key points at, under the store's names.
28
+ */
29
+ const stillWrittenColumns = (names, module, existing) => {
30
+ const every = everyTable(names);
31
+ return Object.entries(writtenWhileOff[module] ?? {}).filter(([table]) => existing.includes(every[table].module)).flatMap(([table, columns]) => Object.entries(columns).map(([column, references]) => ({
32
+ table: every[table],
33
+ column: every[table].columns[column],
34
+ references: every[references]
35
+ })));
36
+ };
23
37
  /**
24
38
  * The columns `module` adds to the tables of the modules that stay on, which retire once it is off: each table one of
25
39
  * `existing`, whose tables the store has before the migration; a column the server still writes while it is off stays
@@ -32,7 +46,7 @@ const retiredColumns = (names, module, existing, externalUser = names.users.keyT
32
46
  return Object.entries(declaration.columns ?? {}).filter(([table]) => {
33
47
  const kept = names.names.tables[table];
34
48
  return kept !== void 0 && existing.includes(kept.module) && !(table === "user" && externalUser);
35
- }).flatMap(([table, columns]) => Object.keys(columns).filter((column) => !writtenWhileOff[module]?.[table]?.includes(column)).map((column) => ({
49
+ }).flatMap(([table, columns]) => Object.keys(columns).filter((column) => !(column in (writtenWhileOff[module]?.[table] ?? {}))).map((column) => ({
36
50
  table: every[table],
37
51
  column: every[table].columns[column]
38
52
  })));
@@ -46,6 +60,11 @@ const keepStatements = (names, module, existing, externalUser) => {
46
60
  const columns = retiredColumns(names, module, existing, externalUser);
47
61
  return [...columns.map(({ table, column }) => ddl`alter table ${table} alter column ${column} drop not null`), ...watchStatements(columns)];
48
62
  };
63
+ /** The columns `module` retires (`retiredColumns`) by the names of their tables and themselves, as a snapshot records them. */
64
+ const retiredNames = (names, module, existing, externalUser) => retiredColumns(names, module, existing, externalUser).map(({ table, column }) => ({
65
+ table: table.name,
66
+ column: column.name
67
+ }));
49
68
  /** The tables of `module` its steps up to `step` made, under the store's names. */
50
69
  const keptTables = (names, module, step) => {
51
70
  const every = everyTable(names);
@@ -91,4 +110,4 @@ const unwatchSql = (names, module, existing, externalUser) => {
91
110
  return `-- ${module} on again: the columns it adds are in use again, with the values they kept, and no longer watched.\n${statementsSql(statements)}`;
92
111
  };
93
112
  //#endregion
94
- export { forceSetting, keepSql, keepStatements, keptTables, offChoices, retiredColumns, revivalCheckSql, revivalRefusal, unwatchSql };
113
+ export { forceSetting, keepSql, keepStatements, keptTables, offChoices, retiredColumns, retiredNames, revivalCheckSql, revivalRefusal, stillWrittenColumns, stillWrittenTargets, unwatchSql };
@@ -4,7 +4,8 @@ import { sql } from "kysely";
4
4
  //#region src/better-auth/store/offline/retired-watch.ts
5
5
  /** The schema of the watch, made by the first migration that retires a column. */
6
6
  const retiredSchema = "retired";
7
- const triggerName = (column) => generatedName(`${column.name}_retired_writes`);
7
+ /** The trigger on a column's table that counts its writes; a name past 63 bytes is shortened as Postgres would not. */
8
+ const watchTriggerName = (column) => generatedName(`${column}_retired_writes`);
8
9
  const watchTable = ddl`create table if not exists ${retiredSchema}.${"writes"} (
9
10
  table_name text not null,
10
11
  column_name text not null,
@@ -20,17 +21,23 @@ begin
20
21
  return null;
21
22
  end
22
23
  $retired$`;
24
+ /** The statements that make the watch's schema, table and function, each only when missing. */
25
+ const watchBaseStatements = () => [
26
+ ddl`create schema if not exists ${retiredSchema}`,
27
+ watchTable,
28
+ countFunction
29
+ ];
30
+ /**
31
+ * The trigger that counts the writes of `column` of `table` that set it, under `name`: the column itself, or one that
32
+ * holds its values since, such as its archive, which then counts as `column`.
33
+ */
34
+ const watchTrigger = (table, column, name = column) => ddl`create trigger ${watchTriggerName(name.name)} after insert or update of ${name} on ${table} for each row when (new.${name} is not null) execute function ${retiredSchema}.${"count_write"}(${sql.lit(column.name)})`;
23
35
  /** The statements that start the watch on `columns`: its schema, table and function, then a trigger on each column. */
24
36
  const watchStatements = (columns) => {
25
37
  if (columns.length === 0) return [];
26
- return [
27
- ddl`create schema if not exists ${retiredSchema}`,
28
- watchTable,
29
- countFunction,
30
- ...columns.map(({ table, column }) => ddl`create trigger ${triggerName(column)} after insert or update of ${column} on ${table} for each row when (new.${column} is not null) execute function ${retiredSchema}.${"count_write"}(${sql.lit(column.name)})`)
31
- ];
38
+ return [...watchBaseStatements(), ...columns.map(({ table, column }) => watchTrigger(table, column))];
32
39
  };
33
40
  /** The statements that stop the watch on `columns`, once their module is on again; a column retired before the watch existed has none. */
34
- const unwatchStatements = (columns) => columns.map(({ table, column }) => ddl`drop trigger if exists ${triggerName(column)} on ${table}`);
41
+ const unwatchStatements = (columns) => columns.map(({ table, column }) => ddl`drop trigger if exists ${watchTriggerName(column.name)} on ${table}`);
35
42
  //#endregion
36
- export { retiredSchema, unwatchStatements, watchStatements };
43
+ export { retiredSchema, unwatchStatements, watchBaseStatements, watchStatements, watchTrigger, watchTriggerName };
@@ -33,11 +33,29 @@ export declare const latestSteps: (modules: readonly ModuleId[]) => LastSteps;
33
33
  export declare const storeModel: ({ schema, names, users, uuidIds }: StoreNames, lastSteps: LastSteps) => StoreModel;
34
34
  /** Every name the store has in the database: its schema, each table, `table.column` and index, sorted. */
35
35
  export declare const storeNamesList: (model: StoreModel) => string[];
36
- /** A module turned off whose tables and rows the store keeps: the last step it had, and its tables' names then. */
36
+ /** A column a module turned off retired from a table still on, by their names. */
37
+ export type RetiredName = {
38
+ table: string;
39
+ column: string;
40
+ };
41
+ /**
42
+ * What awaits the sign-off of a module turned off with `--off archive` or `--off delete`: the choice, the id of the
43
+ * migration that turned it off, and the columns it retired then.
44
+ */
45
+ export type DeferredOff = {
46
+ choice: 'archive' | 'delete';
47
+ file: string;
48
+ columns: RetiredName[];
49
+ };
50
+ /**
51
+ * A module turned off whose tables and rows the store keeps: the last step it had, and its tables' names then; `off`
52
+ * once it awaits the sign-off that archives it.
53
+ */
37
54
  export type KeptModule = {
38
55
  module: ModuleId;
39
56
  step: number;
40
57
  tables: Record<string, ModelTable>;
58
+ off?: DeferredOff;
41
59
  };
42
60
  /** `module` kept at `step`, its tables named as `names` would name them with it on. */
43
61
  export declare const keptModule: ({ schema, names, users, uuidIds }: StoreNames, module: ModuleId, step: number) => KeptModule;
@@ -1,3 +1,3 @@
1
1
  import "../../names/modules/index.js";
2
2
  import "./step.js";
3
- import "kysely";
3
+ import { RawBuilder } from "kysely";
@@ -3,7 +3,7 @@ import "../../names/modules/index.js";
3
3
  import "../../names/resolve-names.js";
4
4
  import { DefaultOrganization } from "../../organizations/options.js";
5
5
  import "../store-names.js";
6
- import "kysely";
6
+ import { RawBuilder } from "kysely";
7
7
  //#region src/better-auth/store/steps/step.d.ts
8
8
  /** The organizations' settings a step writes rows from: the default organization, and the app role of the users there already. */
9
9
  export type OrganizationsInput = {
@@ -1,3 +1,3 @@
1
1
  import "../names/resolve-names.js";
2
2
  import "../organizations/store.js";
3
- import { Kysely } from "kysely";
3
+ import { Kysely, RawBuilder } from "kysely";
@@ -27,11 +27,15 @@ import { workflowPlugins } from "./workflows/default-plugins.js";
27
27
  import { StoreNames, storeNames } from "./better-auth/store/store-names.js";
28
28
  import { settingsStoreNames } from "./better-auth/store/offline/settings-names.js";
29
29
  import { OrganizationsInput, organizationsInput } from "./better-auth/store/steps/step.js";
30
- import { KeptModule, LastSteps, StoreModel, keptModule, latestSteps, storeModel, storeNamesList } from "./better-auth/store/offline/store-model.js";
30
+ import { DeferredOff, KeptModule, LastSteps, RetiredName, StoreModel, keptModule, latestSteps, storeModel, storeNamesList } from "./better-auth/store/offline/store-model.js";
31
31
  import { nameChanges } from "./better-auth/store/offline/name-changes.js";
32
32
  import { SnapshotStore, offlineStepsMigration } from "./better-auth/store/offline/offline-steps.js";
33
33
  import { retiredSchema } from "./better-auth/store/offline/retired-watch.js";
34
- import { OffChoice, forceSetting, keepSql, keptTables, offChoices, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
34
+ import { OffChoice, forceSetting, keepSql, keptTables, offChoices, retiredNames, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
35
+ import { SignedOff, contractMark, markedSql, signOffGate } from "./better-auth/store/offline/contract-gate.js";
36
+ import { ArchivedModule, archiveSchema, archiveStatements, archivedColumn, archivedModule, revokeStatements } from "./better-auth/store/offline/module-archive.js";
37
+ import { StepRecord, deleteStatements, forgetStepsSql, stepRecordOf } from "./better-auth/store/offline/module-delete.js";
38
+ import { restoredKeysSql } from "./better-auth/store/offline/archive-revival.js";
35
39
  import { bucketsCommentPrefix } from "./computed/buckets-sql.js";
36
40
  import { AppliedStep } from "./better-auth/store/step-record.js";
37
41
  import { LiveStore, baselineStore } from "./better-auth/store/offline/baseline-store.js";
@@ -47,4 +51,4 @@ import { recordsRuntimeModel } from "./migration-record/check-record.js";
47
51
  import { plainStoreDb } from "./better-auth/store/store-db.js";
48
52
  import { moduleDifference, retiredDifference } from "./schema-modules/module-difference.js";
49
53
  import { keptStoreModules } from "./better-auth/auth-schema.js";
50
- export { type AfterIndex, type AppAuthInput, type AppliedStep, type AuthPlugins, type KeptModule, type LastSteps, type LintedStep, type LiveStore, type ModuleId, type ModuleInput, type ModuleModel, type ModuleTargets, type ModulesModel, type OffChoice, type OrganizationsInput, type RecordModel, type SchemaModule, type SchemaModuleId, type SnapshotStore, type SquawkFinding, type StoreModel, type StoreNames, appAuthOptions, appDialect, appPool, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractingRules, contractingSql, createAuth, declaredJob, fileProviderOf, forceSetting, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, retiredDifference, retiredSchema, revivalCheckSql, revivalRefusal, runtimeModel, s3Files, schemaModules, settingsStoreNames, squawkReport, stepRecordMigration, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, webhooksModule, workflowPlugins, workflowsModule };
54
+ export { type AfterIndex, type AppAuthInput, type AppliedStep, type ArchivedModule, type AuthPlugins, type DeferredOff, type KeptModule, type LastSteps, type LintedStep, type LiveStore, type ModuleId, type ModuleInput, type ModuleModel, type ModuleTargets, type ModulesModel, type OffChoice, type OrganizationsInput, type RecordModel, type RetiredName, type SchemaModule, type SchemaModuleId, type SignedOff, type SnapshotStore, type SquawkFinding, type StepRecord, type StoreModel, type StoreNames, appAuthOptions, appDialect, appPool, archiveSchema, archiveStatements, archivedColumn, archivedModule, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractMark, contractingRules, contractingSql, createAuth, declaredJob, deleteStatements, fileProviderOf, forceSetting, forgetStepsSql, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, markedSql, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, restoredKeysSql, retiredDifference, retiredNames, retiredSchema, revivalCheckSql, revivalRefusal, revokeStatements, runtimeModel, s3Files, schemaModules, settingsStoreNames, signOffGate, squawkReport, stepRecordMigration, stepRecordOf, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, webhooksModule, workflowPlugins, workflowsModule };
package/dist/internal.js CHANGED
@@ -42,7 +42,11 @@ import { checkCallsOptions } from "./calls/calls-options.js";
42
42
  import { settingsStoreNames } from "./better-auth/store/offline/settings-names.js";
43
43
  import { offlineStepsMigration } from "./better-auth/store/offline/offline-steps.js";
44
44
  import { retiredSchema } from "./better-auth/store/offline/retired-watch.js";
45
- import { forceSetting, keepSql, keptTables, offChoices, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
45
+ import { forceSetting, keepSql, keptTables, offChoices, retiredNames, revivalCheckSql, revivalRefusal, unwatchSql } from "./better-auth/store/offline/module-switches.js";
46
+ import { contractMark, markedSql, signOffGate } from "./better-auth/store/offline/contract-gate.js";
47
+ import { archiveSchema, archiveStatements, archivedColumn, archivedModule, revokeStatements } from "./better-auth/store/offline/module-archive.js";
48
+ import { deleteStatements, forgetStepsSql, stepRecordOf } from "./better-auth/store/offline/module-delete.js";
49
+ import { restoredKeysSql } from "./better-auth/store/offline/archive-revival.js";
46
50
  import { contractingRules, lintSteps, lockingRules, squawkReport } from "./better-auth/store/steps/step-lint.js";
47
51
  import { contractingSql } from "./migration-sql/additive-statements.js";
48
- export { appAuthOptions, appDialect, appPool, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractingRules, contractingSql, createAuth, declaredJob, fileProviderOf, forceSetting, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, retiredDifference, retiredSchema, revivalCheckSql, revivalRefusal, runtimeModel, s3Files, schemaModules, settingsStoreNames, squawkReport, stepRecordMigration, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, webhooksModule, workflowPlugins, workflowsModule };
52
+ export { appAuthOptions, appDialect, appPool, archiveSchema, archiveStatements, archivedColumn, archivedModule, baselineStore, betterAuthAuthenticator, bucketsCommentPrefix, bucketsRefreshes, buildAppAuth, buildAuth, buildAuthenticator, captureNames, checkCallsOptions, checkNotificationsOptions, checkStatusOptions, contractMark, contractingRules, contractingSql, createAuth, declaredJob, deleteStatements, fileProviderOf, forceSetting, forgetStepsSql, isOverSignIn, isSubscription, keepSql, keptModule, keptNames, keptStoreModules, keptTables, latestModules, latestSteps, legacyVersions, lintSteps, loadAuthPlugins, localFiles, lockingRules, longQueryPool, markedSql, modelHash, moduleDifference, nameChanges, noInput, offChoices, offlineStepsMigration, organizationsEnabled, organizationsInput, plainStoreDb, readOrigins, readPasskeyDomain, recordTable, recordTableSql, recordsRuntimeModel, refreshBuckets, resolveNames, restoredKeysSql, retiredDifference, retiredNames, retiredSchema, revivalCheckSql, revivalRefusal, revokeStatements, runtimeModel, s3Files, schemaModules, settingsStoreNames, signOffGate, squawkReport, stepRecordMigration, stepRecordOf, stepsOfVersions, storeModel, storeNames, storeNamesList, targetIds, uncapturedMessage, unwatchSql, webhooksModule, workflowPlugins, workflowsModule };
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.130.0";
2
+ var version = "0.130.1";
3
3
  //#endregion
4
4
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/server",
3
- "version": "0.130.0",
3
+ "version": "0.130.1",
4
4
  "description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -44,11 +44,11 @@
44
44
  "@better-auth/sso": "^1.7.12",
45
45
  "@livekit/protocol": "1.53.1",
46
46
  "@modelcontextprotocol/server": "^2.3.1",
47
- "@protobase/layout": "0.130.0",
48
- "@protobase/query": "0.130.0",
49
- "@protobase/schema": "0.130.0",
50
- "@protobase/workflow-plugins": "0.130.0",
51
- "@protobase/workflows": "0.130.0",
47
+ "@protobase/layout": "0.130.1",
48
+ "@protobase/query": "0.130.1",
49
+ "@protobase/schema": "0.130.1",
50
+ "@protobase/workflow-plugins": "0.130.1",
51
+ "@protobase/workflows": "0.130.1",
52
52
  "@react-email/render": "^2.1.0",
53
53
  "@react-pdf/primitives": "^4.4.0",
54
54
  "@react-pdf/renderer": "^4.9.0",