shutro 0.3.6 → 0.3.7

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.
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { type CompiledSql } from '../sql/index.js';
7
7
  /** What happened. `su` rows record a superuser scope (RFC 0003 §7.6). */
8
- export type AuditAction = 'create' | 'write' | 'unlink' | 'su' | 'elevate' | 'security';
8
+ export type AuditAction = 'create' | 'write' | 'unlink' | 'su' | 'elevate' | 'security' | 'sequence';
9
9
  /** One row of the trail. */
10
10
  export interface AuditEntry {
11
11
  readonly id: number;
@@ -8,6 +8,7 @@ import type { Id } from '../model/id.js';
8
8
  import { type Fx } from '../money/fx.js';
9
9
  import type { ChangeRow } from '../recordset/changes.js';
10
10
  import { type RecordCache } from '../recordset/recordset.js';
11
+ import { type SequenceAdmin } from '../recordset/sequence-admin.js';
11
12
  import type { ListLoaded, ModelName, ModelRef, RecordSet } from '../recordset/types.js';
12
13
  import type { Registry } from '../registry/registry.js';
13
14
  import { type RuntimeSecurity, type RuntimeSecurityDescription } from '../security/runtime.js';
@@ -262,6 +263,12 @@ export declare class Env<S = unknown> {
262
263
  * registry, audited, and reloaded by every process once committed. Needs `createShutro({ runtimeSecurity: true })`.
263
264
  */
264
265
  get securityAdmin(): SecurityAdmin;
266
+ /**
267
+ * Document numbering administered at runtime (Kosh request #31): each sequence's format for the current
268
+ * company — prefix, suffix, padding, when it restarts — on top of the code's, and the next number of a
269
+ * counter, never set below one already issued. Administrators (or superuser scopes) only; audited.
270
+ */
271
+ get sequenceAdmin(): SequenceAdmin;
265
272
  /**
266
273
  * Emits a domain event in this transaction (RFC 0018 §7.2): it exists if and only if the transaction commits, and
267
274
  * subscribers (`shutro.subscribe`) receive it at least once. Returns the event id.
@@ -13,6 +13,7 @@ import { trackElevation, trackSecurityChange, trackSuperuser } from '../recordse
13
13
  import { invalidateCached } from '../recordset/compute.js';
14
14
  import { companyCurrencyId, createRecordCache, currencyById, flushAll, modelRef, } from '../recordset/recordset.js';
15
15
  import { assertAccess, assertPermission, assertRecords, canAccess, canField, hasPermission, } from '../recordset/security.js';
16
+ import { sequenceAdmin } from '../recordset/sequence-admin.js';
16
17
  import { mapConstraintError } from '../recordset/sqlErrors.js';
17
18
  import { administratorCodes, changeStatement, closureWith, describeRuntimeSecurity, isAdministratorWith, loadRuntimeSecurity, SECURITY_CHANNEL, validateChange, } from '../security/runtime.js';
18
19
  import { assertGrants, assertLang, assertReason, resolveIdentity, SYSTEM_UID, } from './identity.js';
@@ -219,6 +220,14 @@ export class Env {
219
220
  }),
220
221
  };
221
222
  }
223
+ /**
224
+ * Document numbering administered at runtime (Kosh request #31): each sequence's format for the current
225
+ * company — prefix, suffix, padding, when it restarts — on top of the code's, and the next number of a
226
+ * counter, never set below one already issued. Administrators (or superuser scopes) only; audited.
227
+ */
228
+ get sequenceAdmin() {
229
+ return sequenceAdmin(internalsOf(this));
230
+ }
222
231
  /**
223
232
  * Emits a domain event in this transaction (RFC 0018 §7.2): it exists if and only if the transaction commits, and
224
233
  * subscribers (`shutro.subscribe`) receive it at least once. Returns the event id.
@@ -9,7 +9,7 @@
9
9
  export { type AuditAction, type AuditEntry, auditTableStatements, readTrail, type TrailFilter, } from '../audit/index.js';
10
10
  export { isTranslations, mergeTranslation, resolveTranslation, type Translations, } from '../i18n/index.js';
11
11
  export { type AccessSpec, createKeyRing, defineGroup, definePermission, EncryptionError, type FieldGroups, type FieldGroupsInput, type GroupDefinition, type KeyRing, type Perm, type PermissionDefinition, type RulePerm, type RuleSpec, SecurityDefinitionError, } from '../security/index.js';
12
- export { defineSequence, InvalidSequenceError, type SequenceDefinition, type SequenceInput, type SequenceReset, } from '../sequence/index.js';
12
+ export { defineSequence, InvalidSequenceError, type SequenceDefinition, type SequenceFormat, type SequenceInput, type SequenceReset, } from '../sequence/index.js';
13
13
  export { type CompiledSql, compile, type SqlFragment, sql } from '../sql/index.js';
14
14
  export { buildComputeGraph, type ComputedField, type ComputeGraph, type PathStep, type Trigger, } from './compute/graph.js';
15
15
  export { type DataRecord, type DataRef, isRef, override, record, ref, } from './data/data.js';
@@ -41,6 +41,7 @@ export type { RoundingMethod } from './money/rounding.js';
41
41
  export { coalesceAudit, isTracked } from './recordset/audit.js';
42
42
  export { type JunctionTable, junctionTable } from './recordset/relations.js';
43
43
  export { modelPolicies, rlsStatements, ruleCondition } from './recordset/rls.js';
44
+ export type { SequenceAdmin, SequenceDescription } from './recordset/sequence-admin.js';
44
45
  export { UNNUMBERED } from './recordset/sequences.js';
45
46
  export type { Access, AggregateQuery, AggregateRow, ComputedKeys, ComputeRec, ComputeSet, CreateValues, DefaultLoaded, Defaults, Domain, Draft, DraftValue, FieldsOf, Granularity, GroupKey, IdOnly, ListKeys, ListLoaded, LoadedKeys, LoadSpec, Many2oneKeys, Measure, Merge, MethodsOf, ModelName, ModelRef, NotLoaded, OnchangeInput, OnchangeResult, PendingSet, PlainRow, Rec, RecordSet, RecordSetApi, RelKeys, ScalarKeys, SearchOrder, SearchQuery, SequenceKeys, SummableKeys, SumOf, Target, ToLoaded, TranslatedKeys, WriteValues, X2ManyKeys, } from './recordset/types.js';
46
47
  export { copyField } from './recordset/writes.js';
@@ -19,6 +19,8 @@ export declare function trackSuperuser(internals: ScopeInternals, reason: string
19
19
  export declare function trackElevation(internals: ScopeInternals, grants: readonly string[], reason: string): void;
20
20
  /** Records a runtime security change (RFC 0014 §7.10). */
21
21
  export declare function trackSecurityChange(internals: ScopeInternals, change: object): void;
22
+ /** A change of document numbering by an administrator (a format, a next number): what changed, in `new`. */
23
+ export declare function trackSequenceChange(internals: ScopeInternals, change: object): void;
22
24
  /** Coalesces `write` rows per (model, record, field): the first old, the last new; unchanged values are dropped. */
23
25
  export declare function coalesceAudit(rows: readonly AuditRowInput[]): AuditRowInput[];
24
26
  /** Writes the pending rows of `model` (or every row) in one statement. */
@@ -168,6 +168,22 @@ export function trackSecurityChange(internals, change) {
168
168
  new: change,
169
169
  });
170
170
  }
171
+ /** A change of document numbering by an administrator (a format, a next number): what changed, in `new`. */
172
+ export function trackSequenceChange(internals, change) {
173
+ if (!internals.env.flags.tracking)
174
+ return;
175
+ internals.auditRows.push({
176
+ ...base(internals),
177
+ su: internals.env.su,
178
+ reason: null,
179
+ action: 'sequence',
180
+ model: null,
181
+ recordId: null,
182
+ field: null,
183
+ old: null,
184
+ new: change,
185
+ });
186
+ }
171
187
  function same(a, b) {
172
188
  return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
173
189
  }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Sequences administered at runtime (Kosh request #31): what a company's numbers look like and when they restart,
3
+ * on top of the code's definitions, and the next number of a counter — never set below one it already issued.
4
+ * Administrators (or superuser scopes) only; every change is audited. Allocation reads the formats in the business
5
+ * transaction, so a change counts from the commit on, in every process.
6
+ */
7
+ import { type SequenceDefinition, type SequenceFormat } from '../../sequence/index.js';
8
+ import type { ScopeInternals } from '../env/env.js';
9
+ /** A sequence as an administrator sees it for the current company. */
10
+ export interface SequenceDescription {
11
+ readonly code: string;
12
+ /** What the code declares. */
13
+ readonly declared: SequenceDefinition;
14
+ /** What the administrator changed for this company; `null`: nothing. */
15
+ readonly format: SequenceFormat | null;
16
+ /** What numbers are made with: the declaration with the changes. */
17
+ readonly effective: SequenceDefinition;
18
+ /** The counter period `date` falls in (`''` when it never restarts). */
19
+ readonly period: string;
20
+ /** The next number the counter of that period issues. */
21
+ readonly next: number;
22
+ /** That number as a document would carry it. */
23
+ readonly preview: string;
24
+ }
25
+ /** `env.sequenceAdmin` (Kosh request #31). */
26
+ export interface SequenceAdmin {
27
+ /** Every sequence of the registry — or the ones named — for the current company, as of `date` (today). */
28
+ describe(options?: {
29
+ readonly codes?: readonly string[];
30
+ readonly date?: string;
31
+ }): Promise<SequenceDescription[]>;
32
+ /**
33
+ * Changes how a sequence's numbers look for the current company — prefix, suffix, padding, when it restarts —,
34
+ * or, with `null`, goes back to the code's. Validated like a definition.
35
+ * @throws {InvalidSequenceError} for a format that is none
36
+ */
37
+ setFormat(code: string, format: SequenceFormat | null): Promise<SequenceDescription>;
38
+ /**
39
+ * What `setFormat` (and `setNext`, with `next`) would give, without changing anything: the screen's preview.
40
+ * @throws {InvalidSequenceError} for a format that is none
41
+ */
42
+ preview(code: string, format: SequenceFormat | null, options?: {
43
+ readonly date?: string;
44
+ readonly next?: number;
45
+ }): Promise<SequenceDescription>;
46
+ /**
47
+ * Sets the next number of the counter `date` (today) falls in.
48
+ * @throws {ValidationError} when `next` is below the number the counter would issue now: it was used already
49
+ */
50
+ setNext(code: string, next: number, options?: {
51
+ readonly date?: string;
52
+ }): Promise<SequenceDescription>;
53
+ }
54
+ /** The formats of a sequence for these companies, read through the transaction. */
55
+ export declare function formatsOf(internals: ScopeInternals, code: string, companies: readonly number[]): Promise<Map<number, SequenceFormat>>;
56
+ export declare function sequenceAdmin(internals: ScopeInternals): SequenceAdmin;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Sequences administered at runtime (Kosh request #31): what a company's numbers look like and when they restart,
3
+ * on top of the code's definitions, and the next number of a counter — never set below one it already issued.
4
+ * Administrators (or superuser scopes) only; every change is audited. Allocation reads the formats in the business
5
+ * transaction, so a change counts from the commit on, in every process.
6
+ */
7
+ import { counterStatement, deleteFormatStatement, formatNumber, formatOfRow, formatsStatement, InvalidSequenceError, periodKey, saveFormatStatement, setCounterStatement, withFormat, } from '../../sequence/index.js';
8
+ import { AccessError, UnknownSequenceError, ValidationError } from '../errors.js';
9
+ import { trackSequenceChange } from './audit.js';
10
+ import { ensureSequenceTables } from './sequences.js';
11
+ const RESETS = ['never', 'yearly', 'monthly', 'daily'];
12
+ /** The formats of a sequence for these companies, read through the transaction. */
13
+ export async function formatsOf(internals, code, companies) {
14
+ const out = new Map();
15
+ if (companies.length === 0)
16
+ return out;
17
+ for (const row of await internals.query(formatsStatement(code, companies)))
18
+ out.set(Number(row['company_id']), formatOfRow(row));
19
+ return out;
20
+ }
21
+ /** A format's parts, each what it may be. @throws {InvalidSequenceError} */
22
+ function checkFormat(code, format) {
23
+ if (format === null)
24
+ return;
25
+ if (format.reset !== undefined && !RESETS.includes(format.reset))
26
+ throw new InvalidSequenceError(`Sequence '${code}': reset ${JSON.stringify(format.reset)} is unknown.`, `Use one of: ${RESETS.join(', ')}.`);
27
+ for (const text of [format.prefix, format.suffix])
28
+ if (text !== undefined && (typeof text !== 'string' || text.length > 60))
29
+ throw new InvalidSequenceError(`Sequence '${code}': a prefix or suffix is text of at most 60 characters.`, 'Shorten it.');
30
+ }
31
+ export function sequenceAdmin(internals) {
32
+ const { env } = internals;
33
+ const allowed = () => {
34
+ if (!env.su && !env.administrator)
35
+ throw new AccessError('sequence', 'manage', {
36
+ problem: 'only administrators can read or change document numbering.',
37
+ hint: 'Use an administrator account (defineGroup({ administrator: true })).',
38
+ });
39
+ };
40
+ const declared = (code) => {
41
+ const definition = internals.registry.sequences.get(code);
42
+ if (definition === undefined)
43
+ throw new UnknownSequenceError(code, 'sequenceAdmin');
44
+ return definition;
45
+ };
46
+ const companyOf = (definition) => {
47
+ if (!definition.perCompany)
48
+ return 0;
49
+ const company = env.companyId;
50
+ if (company === null || company === undefined)
51
+ throw new ValidationError('sequence', ['company'], `Sequence '${definition.code}' counts per company.`, 'Run in a scope with a current company.');
52
+ return company;
53
+ };
54
+ const describeOne = async (code, date) => {
55
+ const definition = declared(code);
56
+ const company = companyOf(definition);
57
+ const format = (await formatsOf(internals, code, [company])).get(company) ?? null;
58
+ const effective = withFormat(definition, format);
59
+ const period = periodKey(effective, date);
60
+ const [row] = await internals.query(counterStatement(code, company, period));
61
+ const next = row === undefined ? effective.start : Number(row.next);
62
+ return {
63
+ code,
64
+ declared: definition,
65
+ format,
66
+ effective,
67
+ period,
68
+ next,
69
+ preview: formatNumber(effective, next, date),
70
+ };
71
+ };
72
+ const day = (date) => {
73
+ const value = date ?? env.today();
74
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value))
75
+ throw new ValidationError('sequence', ['date'], `'${value}' is not a date.`, 'Use YYYY-MM-DD.');
76
+ return value;
77
+ };
78
+ return {
79
+ async describe(options = {}) {
80
+ allowed();
81
+ await ensureSequenceTables(internals.driver);
82
+ const date = day(options.date);
83
+ const codes = options.codes ?? [...internals.registry.sequences.keys()].sort();
84
+ const out = [];
85
+ for (const code of codes) {
86
+ const definition = declared(code);
87
+ // A sequence that counts per company has nothing to show without one.
88
+ if (definition.perCompany && (env.companyId === null || env.companyId === undefined))
89
+ continue;
90
+ out.push(await describeOne(code, date));
91
+ }
92
+ return out;
93
+ },
94
+ async setFormat(code, format) {
95
+ allowed();
96
+ await ensureSequenceTables(internals.driver);
97
+ const definition = declared(code);
98
+ const company = companyOf(definition);
99
+ if (format === null) {
100
+ await internals.query(deleteFormatStatement(code, company));
101
+ }
102
+ else {
103
+ checkFormat(code, format);
104
+ // Validated as the definition it makes.
105
+ withFormat(definition, format);
106
+ await internals.query(saveFormatStatement(code, company, format));
107
+ }
108
+ trackSequenceChange(internals, { kind: 'format', code, company, format });
109
+ return describeOne(code, env.today());
110
+ },
111
+ async preview(code, format, options = {}) {
112
+ allowed();
113
+ await ensureSequenceTables(internals.driver);
114
+ const date = day(options.date);
115
+ const definition = declared(code);
116
+ const company = companyOf(definition);
117
+ checkFormat(code, format);
118
+ const effective = withFormat(definition, format);
119
+ const period = periodKey(effective, date);
120
+ const [row] = await internals.query(counterStatement(code, company, period));
121
+ const current = row === undefined ? effective.start : Number(row.next);
122
+ const next = options.next !== undefined && Number.isSafeInteger(options.next) && options.next >= current
123
+ ? options.next
124
+ : current;
125
+ return {
126
+ code,
127
+ declared: definition,
128
+ format,
129
+ effective,
130
+ period,
131
+ next,
132
+ preview: formatNumber(effective, next, date),
133
+ };
134
+ },
135
+ async setNext(code, next, options = {}) {
136
+ allowed();
137
+ await ensureSequenceTables(internals.driver);
138
+ const date = day(options.date);
139
+ if (!Number.isSafeInteger(next) || next < 0)
140
+ throw new ValidationError('sequence', ['next'], `${String(next)} is not a number a document can carry.`, 'Use a whole number, zero or more.');
141
+ const before = await describeOne(code, date);
142
+ const company = companyOf(before.declared);
143
+ const rows = await internals.query(setCounterStatement(code, company, before.period, next));
144
+ if (rows.length === 0 || next < before.next)
145
+ throw new ValidationError('sequence', ['next'], `Sequence '${code}' already issued numbers up to ${before.next - before.effective.step}.`, `The next number is ${before.next} or more: a number is never issued twice.`);
146
+ trackSequenceChange(internals, {
147
+ kind: 'next',
148
+ code,
149
+ company,
150
+ period: before.period,
151
+ from: before.next,
152
+ to: next,
153
+ });
154
+ return describeOne(code, date);
155
+ },
156
+ };
157
+ }
@@ -3,11 +3,14 @@
3
3
  * transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
4
4
  * `records.assignNumber()` for manual numbering.
5
5
  */
6
+ import type { Driver } from '../../driver-pg/index.js';
6
7
  import type { ScopeInternals } from '../env/env.js';
7
8
  import type { AnyModel } from '../model/model.js';
8
9
  import type { ComputeHost } from './compute.js';
9
10
  /** The placeholder of a manually numbered document (RFC 0012 §7.4). */
10
11
  export declare const UNNUMBERED = "/";
12
+ /** Makes the counter table and the table of runtime formats on first use (outside the transaction). */
13
+ export declare function ensureSequenceTables(driver: Driver): Promise<void>;
11
14
  /** Fills the `on: 'create'` sequence fields of rows that have no value (RFC 0012 §7.4). */
12
15
  export declare function fillSequences(internals: ScopeInternals, model: AnyModel, rows: readonly {
13
16
  readonly stored: Map<string, unknown>;
@@ -3,33 +3,36 @@
3
3
  * transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
4
4
  * `records.assignNumber()` for manual numbering.
5
5
  */
6
- import { allocateStatement, formatNumber, numbersFrom, periodKey, SEQUENCE_TABLE, sequenceTableStatements, } from '../../sequence/index.js';
6
+ import { allocateStatement, formatNumber, numbersFrom, periodKey, SEQUENCE_FORMAT_TABLE, SEQUENCE_TABLE, sequenceFormatTableStatements, sequenceTableStatements, withFormat, } from '../../sequence/index.js';
7
7
  import { UnknownSequenceError, ValidationError } from '../errors.js';
8
8
  import { trackChange } from './audit.js';
9
+ import { formatsOf } from './sequence-admin.js';
9
10
  /** The placeholder of a manually numbered document (RFC 0012 §7.4). */
10
11
  export const UNNUMBERED = '/';
11
12
  const ensured = new WeakSet();
12
- async function ensureTable(driver) {
13
+ /** Makes the counter table and the table of runtime formats on first use (outside the transaction). */
14
+ export async function ensureSequenceTables(driver) {
13
15
  if (ensured.has(driver))
14
16
  return;
15
17
  const [row] = await driver.query({
16
- text: `SELECT to_regclass('${SEQUENCE_TABLE}') IS NOT NULL AS present`,
18
+ text: `SELECT to_regclass('${SEQUENCE_TABLE}') IS NOT NULL AND to_regclass('${SEQUENCE_FORMAT_TABLE}') IS NOT NULL AS present`,
17
19
  params: [],
18
20
  });
19
21
  if (row?.present !== true)
20
- for (const statement of sequenceTableStatements())
22
+ for (const statement of [...sequenceTableStatements(), ...sequenceFormatTableStatements()])
21
23
  await driver.query(statement);
22
24
  ensured.add(driver);
23
25
  }
24
- function groupRequests(definition, requests) {
26
+ function groupRequests(declared, requests, effective) {
25
27
  const groups = new Map();
26
28
  requests.forEach((request, i) => {
27
- const company = definition.perCompany ? (request.company ?? 0) : 0;
29
+ const company = declared.perCompany ? (request.company ?? 0) : 0;
30
+ const definition = effective.get(company) ?? declared;
28
31
  const period = periodKey(definition, request.date);
29
32
  const key = `${company}|${period}`;
30
33
  let group = groups.get(key);
31
34
  if (group === undefined) {
32
- group = { company, period, date: request.date, members: [] };
35
+ group = { definition, company, period, date: request.date, members: [] };
33
36
  groups.set(key, group);
34
37
  }
35
38
  group.members.push(i);
@@ -37,12 +40,18 @@ function groupRequests(definition, requests) {
37
40
  return [...groups.values()];
38
41
  }
39
42
  /** Allocates one formatted number per request, in one statement per (company, period) group. */
40
- async function allocateNumbers(internals, definition, requests) {
43
+ async function allocateNumbers(internals, declared, requests) {
41
44
  const out = new Array(requests.length);
42
45
  if (requests.length === 0)
43
46
  return out;
44
- await ensureTable(internals.driver);
45
- for (const group of groupRequests(definition, requests)) {
47
+ await ensureSequenceTables(internals.driver);
48
+ // What an administrator changed for these companies (Kosh request #31), read in this transaction.
49
+ const companies = [...new Set(requests.map((r) => (declared.perCompany ? (r.company ?? 0) : 0)))];
50
+ const effective = new Map();
51
+ for (const [company, format] of await formatsOf(internals, declared.code, companies))
52
+ effective.set(company, withFormat(declared, format));
53
+ for (const group of groupRequests(declared, requests, effective)) {
54
+ const { definition } = group;
46
55
  const statement = allocateStatement(definition, group.company, group.period, group.members.length);
47
56
  const rows = definition.gapless
48
57
  ? await internals.query(statement) // row lock held until commit: no gaps
@@ -61,3 +61,34 @@ export declare function sequenceTableStatements(): readonly CompiledSql[];
61
61
  export declare function allocateStatement(definition: SequenceDefinition, company: number, period: string, count: number): CompiledSql;
62
62
  /** The numbers of an allocation that returned `first`. */
63
63
  export declare function numbersFrom(definition: SequenceDefinition, first: number, count: number): number[];
64
+ /** What an administrator may change of a sequence, per company: how its numbers look and when they restart. */
65
+ export interface SequenceFormat {
66
+ readonly prefix?: string | undefined;
67
+ readonly suffix?: string | undefined;
68
+ readonly padding?: number | undefined;
69
+ readonly reset?: SequenceReset | undefined;
70
+ }
71
+ /** The table of runtime formats (`company_id` 0: a shared sequence). A missing column value keeps the code's. */
72
+ export declare const SEQUENCE_FORMAT_TABLE = "shutro_sequence_format";
73
+ /** DDL of the format table, idempotent. */
74
+ export declare function sequenceFormatTableStatements(): readonly CompiledSql[];
75
+ /**
76
+ * The definition numbers are made with: the code's, with what the administrator changed. Validated like a
77
+ * definition. @throws {InvalidSequenceError}
78
+ */
79
+ export declare function withFormat(definition: SequenceDefinition, format: SequenceFormat | null | undefined): SequenceDefinition;
80
+ /** The runtime formats of a sequence for some companies. */
81
+ export declare function formatsStatement(code: string, companies: readonly number[]): CompiledSql;
82
+ /** A stored format row, as read. */
83
+ export declare function formatOfRow(row: Readonly<Record<string, unknown>>): SequenceFormat;
84
+ /** Saves the runtime format of a sequence for a company (replacing the one there). */
85
+ export declare function saveFormatStatement(code: string, company: number, format: SequenceFormat): CompiledSql;
86
+ /** Removes the runtime format: the sequence is the code's again. */
87
+ export declare function deleteFormatStatement(code: string, company: number): CompiledSql;
88
+ /** The next number of a counter, if it has issued any. */
89
+ export declare function counterStatement(code: string, company: number, period: string): CompiledSql;
90
+ /**
91
+ * Sets the next number of a counter — never below the one it would issue now, so no number is issued twice: the
92
+ * statement returns no row when `next` is lower. The row is locked until the transaction ends.
93
+ */
94
+ export declare function setCounterStatement(code: string, company: number, period: string, next: number): CompiledSql;
@@ -104,3 +104,74 @@ export function allocateStatement(definition, company, period, count) {
104
104
  export function numbersFrom(definition, first, count) {
105
105
  return Array.from({ length: count }, (_, i) => first + i * definition.step);
106
106
  }
107
+ /** The table of runtime formats (`company_id` 0: a shared sequence). A missing column value keeps the code's. */
108
+ export const SEQUENCE_FORMAT_TABLE = 'shutro_sequence_format';
109
+ /** DDL of the format table, idempotent. */
110
+ export function sequenceFormatTableStatements() {
111
+ return [
112
+ Object.freeze({
113
+ text: `CREATE TABLE IF NOT EXISTS "${SEQUENCE_FORMAT_TABLE}" ("code" text NOT NULL, "company_id" bigint NOT NULL DEFAULT 0, "prefix" text, "suffix" text, "padding" integer, "reset" text, PRIMARY KEY ("code", "company_id"))`,
114
+ params: Object.freeze([]),
115
+ }),
116
+ ];
117
+ }
118
+ /**
119
+ * The definition numbers are made with: the code's, with what the administrator changed. Validated like a
120
+ * definition. @throws {InvalidSequenceError}
121
+ */
122
+ export function withFormat(definition, format) {
123
+ if (format === null || format === undefined)
124
+ return definition;
125
+ return defineSequence({
126
+ ...definition,
127
+ prefix: format.prefix ?? definition.prefix,
128
+ suffix: format.suffix ?? definition.suffix,
129
+ padding: format.padding ?? definition.padding,
130
+ reset: format.reset ?? definition.reset,
131
+ });
132
+ }
133
+ /** The runtime formats of a sequence for some companies. */
134
+ export function formatsStatement(code, companies) {
135
+ return compile(sql `SELECT ${sql.id('company_id')}, ${sql.id('prefix')}, ${sql.id('suffix')}, ${sql.id('padding')}, ${sql.id('reset')}
136
+ FROM ${sql.id(SEQUENCE_FORMAT_TABLE)}
137
+ WHERE ${sql.id('code')} = ${code} AND ${sql.id('company_id')} = ANY(${sql.array([...companies], 'bigint')})`);
138
+ }
139
+ /** A stored format row, as read. */
140
+ export function formatOfRow(row) {
141
+ const text = (v) => (typeof v === 'string' ? v : undefined);
142
+ const padding = row['padding'];
143
+ return {
144
+ prefix: text(row['prefix']),
145
+ suffix: text(row['suffix']),
146
+ padding: padding === null || padding === undefined ? undefined : Number(padding),
147
+ reset: text(row['reset']),
148
+ };
149
+ }
150
+ /** Saves the runtime format of a sequence for a company (replacing the one there). */
151
+ export function saveFormatStatement(code, company, format) {
152
+ return compile(sql `INSERT INTO ${sql.id(SEQUENCE_FORMAT_TABLE)} (${sql.id('code')}, ${sql.id('company_id')}, ${sql.id('prefix')}, ${sql.id('suffix')}, ${sql.id('padding')}, ${sql.id('reset')})
153
+ VALUES (${code}, ${company}, ${format.prefix ?? null}, ${format.suffix ?? null}, ${format.padding ?? null}, ${format.reset ?? null})
154
+ ON CONFLICT (${sql.id('code')}, ${sql.id('company_id')})
155
+ DO UPDATE SET ${sql.id('prefix')} = EXCLUDED.${sql.id('prefix')}, ${sql.id('suffix')} = EXCLUDED.${sql.id('suffix')}, ${sql.id('padding')} = EXCLUDED.${sql.id('padding')}, ${sql.id('reset')} = EXCLUDED.${sql.id('reset')}`);
156
+ }
157
+ /** Removes the runtime format: the sequence is the code's again. */
158
+ export function deleteFormatStatement(code, company) {
159
+ return compile(sql `DELETE FROM ${sql.id(SEQUENCE_FORMAT_TABLE)} WHERE ${sql.id('code')} = ${code} AND ${sql.id('company_id')} = ${company}`);
160
+ }
161
+ /** The next number of a counter, if it has issued any. */
162
+ export function counterStatement(code, company, period) {
163
+ return compile(sql `SELECT ${sql.id('next')} FROM ${sql.id(SEQUENCE_TABLE)}
164
+ WHERE ${sql.id('code')} = ${code} AND ${sql.id('company_id')} = ${company} AND ${sql.id('period')} = ${period}`);
165
+ }
166
+ /**
167
+ * Sets the next number of a counter — never below the one it would issue now, so no number is issued twice: the
168
+ * statement returns no row when `next` is lower. The row is locked until the transaction ends.
169
+ */
170
+ export function setCounterStatement(code, company, period, next) {
171
+ return compile(sql `INSERT INTO ${sql.id(SEQUENCE_TABLE)} (${sql.id('code')}, ${sql.id('company_id')}, ${sql.id('period')}, ${sql.id('next')})
172
+ VALUES (${code}, ${company}, ${period}, ${next})
173
+ ON CONFLICT (${sql.id('code')}, ${sql.id('company_id')}, ${sql.id('period')})
174
+ DO UPDATE SET ${sql.id('next')} = EXCLUDED.${sql.id('next')}
175
+ WHERE ${sql.id(SEQUENCE_TABLE)}.${sql.id('next')} <= EXCLUDED.${sql.id('next')}
176
+ RETURNING ${sql.id('next')}`);
177
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shutro",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "description": "The ORM built for business software: type-safe, secure-by-default, multi-company, audit-ready PostgreSQL ORM for Node.js and TypeScript.",
5
5
  "keywords": [
6
6
  "orm",