@syncular/typegen 0.93.0 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,6 +92,7 @@ schema guide and suggests `syncular init`.
92
92
  | `tables` | yes, non-empty | Synced tables. **Array order is the handler-declared bootstrap order (§4.7)** and flows unchanged into the IR and `schema.tables`. |
93
93
  | `tables[].name` | yes | Must be created by a migration. |
94
94
  | `tables[].scopes` | yes, ≥ 1 | §3.1 scope patterns: `'prefix:{variable}'` (column = variable) or `{ "pattern", "column" }`. The column must exist on the table; one variable must not map to two different columns. |
95
+ | `tables[].serverColumns` | no (default `[]`) | Columns the server sets inside the push transaction (§6.12). The IR marks each `serverOwned: true`; the TS insert and update types omit it. Unknown, primary key, `NOT NULL`, crdt and encrypted columns fail with `typegen.server_column_unknown`, `_primary_key`, `_not_null`, `_crdt` and `_encrypted`. See [Server-owned columns](../../apps/docs/src/content/guide-server.md#server-owned-columns). |
95
96
  | `tables[].extensions` | no (default `{}`) | Opaque passthrough into the IR table's `extensions` slot. |
96
97
  | `subscriptions` | no (default `[]`) | Unit templates (SPEC §4.1). `name` must be a valid JS identifier and unique. A template names no table: its unit covers every table that declares all of its scope variables. A template whose variables no single table declares fails with `typegen.subscription_uncovered`. |
97
98
  | `subscriptions[].scopes` | yes, non-empty | Map of variable → one value. The value is **either** a literal **or** exactly `"{param}"`. Partial templates (`"p-{x}"`) and `"*"` (§3.2 rejects requested wildcards) fail with `typegen.subscription_invalid_value`. Several values of one variable are several templates. An entry with a `table` key or a value list (the wire version 3 shape) fails with `typegen.subscription_legacy_shape`, whose message names this shape. |
@@ -151,7 +152,9 @@ After that, a deployed migration is immutable. Restore an accidentally edited
151
152
  migration and express the repair in a new `NNNN_name/up.sql`; do not delete and
152
153
  re-baseline the lock. Existing table layouts are append-only and added columns
153
154
  must be nullable so stored payloads and every server backend can upgrade
154
- safely. A SQL `DEFAULT` does not make a required append safe: existing
155
+ safely. The one in-place change is `ALTER TABLE t ALTER [COLUMN] c DROP NOT
156
+ NULL`, which makes a required column nullable (SPEC §2.4); typegen refuses it
157
+ for the primary key, an unknown column and an already nullable column. A SQL `DEFAULT` does not make a required append safe: existing
155
158
  Syncular row payloads remain the source of truth, and no storage backend may
156
159
  silently invent a value for them. `baseline`, `migrations check`, and
157
160
  `generate` therefore reject `ALTER TABLE … ADD COLUMN … NOT NULL`, including
@@ -259,6 +262,7 @@ duplicate ordinals are errors). The parser accepts exactly:
259
262
 
260
263
  - `CREATE TABLE [IF NOT EXISTS] name ( column-defs…, [PRIMARY KEY (col)] ) [WITHOUT ROWID]`
261
264
  - `ALTER TABLE name ADD [COLUMN] column-def`
265
+ - `ALTER TABLE name ALTER [COLUMN] col DROP NOT NULL` (a required column becomes nullable, SPEC §2.4)
262
266
  - `CREATE [UNIQUE] INDEX [IF NOT EXISTS] name ON table ( col [, col…] )`
263
267
  - `DROP INDEX [IF EXISTS] name`
264
268
  - `DROP TABLE [IF EXISTS] name`
@@ -381,6 +385,8 @@ parsing; accepted declarations are enforced at the listed layers.
381
385
  | Column `DEFAULT literal` | accepted, ignored | Nothing. Typegen records no default and fills none; the host runs the migration SQL where a default matters. |
382
386
  | Nullable `ALTER TABLE … ADD COLUMN` | yes | A physical column in every mirror. A SQL `DEFAULT` on the same statement is ignored and never backfills Syncular payloads. |
383
387
  | `ALTER TABLE … ADD COLUMN … NOT NULL` | rejected | not applicable |
388
+ | `ALTER TABLE … ALTER [COLUMN] … DROP NOT NULL` | yes | The column becomes nullable in the IR. The server drops the projection's `NOT NULL` at the bump (PostgreSQL in place, SQLite and D1 by a table rebuild) and keeps every payload; the bump raises the schema floor to its version (SPEC §2.4). |
389
+ | Any other `ALTER COLUMN` action | rejected | not applicable |
384
390
  | Column `REFERENCES parent(pk) [ON DELETE RESTRICT\|CASCADE\|SET NULL]` | yes | The server commit boundary only (§6.11); the local SQLite DDL deliberately omits the clause. |
385
391
  | `CREATE [UNIQUE] INDEX` over existing columns | yes | A physical index in both client mirrors, the server relational projection, and typegen's named-query type-check DB. The `UNIQUE` variant additionally enforces uniqueness atomically on a local write (§7.2: `sync.constraint_violation`, no outbox entry, no revision advance) and on the server commit. |
386
392
  | Inline column `CHECK (expr)` | rejected | not applicable (see the gap below) |
package/dist/emit.js CHANGED
@@ -50,6 +50,8 @@ function emitRowInterfaces(table, naming) {
50
50
  lines.push(`/** Insert shape: nullable columns may be omitted. */`);
51
51
  lines.push(`export interface ${type}Insert {`);
52
52
  for (const column of table.columns) {
53
+ if (column.serverOwned === true)
54
+ continue;
53
55
  const ts = TS_TYPE[appColumnType(column)];
54
56
  lines.push(column.nullable
55
57
  ? ` ${key(column.name)}?: ${ts} | null;`
@@ -60,6 +62,8 @@ function emitRowInterfaces(table, naming) {
60
62
  lines.push(`/** Update shape: primary key required, all other columns optional. */`);
61
63
  lines.push(`export interface ${type}Update {`);
62
64
  for (const column of table.columns) {
65
+ if (column.serverOwned === true)
66
+ continue;
63
67
  const ts = TS_TYPE[appColumnType(column)];
64
68
  if (column.name === table.primaryKey) {
65
69
  lines.push(` ${key(column.name)}: ${ts};`);
package/dist/generate.js CHANGED
@@ -55,7 +55,7 @@ function buildTable(manifestTable, parsed) {
55
55
  throw new TypegenError(MANIFEST_FILENAME, `table ${parsed.name}: variable ${JSON.stringify(scope.variable)} maps to two different columns (§3.1)`);
56
56
  }
57
57
  }
58
- const columns = applyEncryption(parsed, scopes, manifestTable.encryptedColumns);
58
+ const columns = applyServerColumns(parsed, manifestTable.serverColumns, applyEncryption(parsed, scopes, manifestTable.encryptedColumns));
59
59
  return {
60
60
  name: parsed.name,
61
61
  primaryKey: parsed.primaryKey,
@@ -120,6 +120,41 @@ function applyEncryption(parsed, scopes, encryptedColumns) {
120
120
  };
121
121
  });
122
122
  }
123
+ /**
124
+ * §6.12: mark each `serverColumns` entry `serverOwned`. Hard errors: unknown
125
+ * column, primary key, non-nullable column (a client's optimistic row holds
126
+ * NULL until the server row arrives), crdt column, encrypted column.
127
+ */
128
+ function applyServerColumns(parsed, serverColumns, columns) {
129
+ if (serverColumns.length === 0)
130
+ return columns;
131
+ const owned = new Set(serverColumns);
132
+ for (const name of owned) {
133
+ const column = columns.find((c) => c.name === name);
134
+ const fail = (message, code) => {
135
+ throw new TypegenError(MANIFEST_FILENAME, message, code, {
136
+ table: parsed.name,
137
+ column: name,
138
+ });
139
+ };
140
+ if (column === undefined) {
141
+ fail('serverColumns names an unknown column', 'typegen.server_column_unknown');
142
+ }
143
+ else if (name === parsed.primaryKey) {
144
+ fail('the primary key cannot be a server column', 'typegen.server_column_primary_key');
145
+ }
146
+ else if (column.type === 'crdt') {
147
+ fail('a crdt column cannot be a server column', 'typegen.server_column_crdt');
148
+ }
149
+ else if (column.encrypted === true) {
150
+ fail('an encrypted column cannot be a server column', 'typegen.server_column_encrypted');
151
+ }
152
+ else if (!column.nullable) {
153
+ fail('a server column must be nullable (§6.12)', 'typegen.server_column_not_null');
154
+ }
155
+ }
156
+ return columns.map((column) => owned.has(column.name) ? { ...column, serverOwned: true } : column);
157
+ }
123
158
  /**
124
159
  * §6.11 hard errors: a declared reference must name an existing parent table
125
160
  * whose primary key has the child column's type, and parent and child must
package/dist/ir.d.ts CHANGED
@@ -16,6 +16,10 @@ export interface IrColumn {
16
16
  readonly encrypted?: boolean;
17
17
  /** §5.11: the app-side type of an encrypted column. Present iff `encrypted`. */
18
18
  readonly declaredType?: IrColumnType;
19
+ /** §6.12: the server sets this column inside the push transaction and a
20
+ * client never authors it. IR metadata only (never on the wire). Present
21
+ * only for server-owned columns, so other columns stay byte-identical. */
22
+ readonly serverOwned?: boolean;
19
23
  }
20
24
  /** §5.11: the app-side type of a column. An encrypted column rides the wire
21
25
  * as `bytes`; generated rows expose its declared type (the local mirror is
package/dist/ir.js CHANGED
@@ -62,6 +62,7 @@ function serializeTableShape(table, scopes) {
62
62
  ...(column.encrypted === true
63
63
  ? { encrypted: true, declaredType: column.declaredType }
64
64
  : {}),
65
+ ...(column.serverOwned === true ? { serverOwned: true } : {}),
65
66
  })),
66
67
  scopes,
67
68
  ...(table.references.length > 0
@@ -19,6 +19,12 @@ export interface ManifestTable {
19
19
  * an unknown column) are enforced at generate time.
20
20
  */
21
21
  readonly encryptedColumns: readonly string[];
22
+ /**
23
+ * §6.12: columns the server sets inside the push transaction. The IR marks
24
+ * each `serverOwned`. Hard errors (unknown, pk, non-nullable, crdt or
25
+ * encrypted column) are enforced at generate time.
26
+ */
27
+ readonly serverColumns: readonly string[];
22
28
  }
23
29
  export interface ManifestSubscription {
24
30
  readonly name: string;
package/dist/manifest.js CHANGED
@@ -159,7 +159,7 @@ function parseRustOutput(value) {
159
159
  function parseTable(value, index) {
160
160
  const context = `tables[${index}]`;
161
161
  const obj = asObject(value, context);
162
- rejectUnknownKeys(obj, ['name', 'scopes', 'extensions', 'encryptedColumns'], context);
162
+ rejectUnknownKeys(obj, ['name', 'scopes', 'extensions', 'encryptedColumns', 'serverColumns'], context);
163
163
  const name = asString(obj.name, `${context}.name`);
164
164
  if (!Array.isArray(obj.scopes) || obj.scopes.length === 0) {
165
165
  fail(`table ${name}: scopes must be a non-empty array (§3.1)`);
@@ -178,11 +178,26 @@ function parseTable(value, index) {
178
178
  seen.add(col);
179
179
  }
180
180
  }
181
+ let serverColumns = [];
182
+ if (obj.serverColumns !== undefined) {
183
+ if (!Array.isArray(obj.serverColumns)) {
184
+ fail(`table ${name}: serverColumns must be an array of column names`);
185
+ }
186
+ serverColumns = obj.serverColumns.map((c, i) => asString(c, `table ${name} serverColumns[${i}]`));
187
+ const seen = new Set();
188
+ for (const col of serverColumns) {
189
+ if (seen.has(col)) {
190
+ fail(`table ${name}: duplicate serverColumns entry ${JSON.stringify(col)}`);
191
+ }
192
+ seen.add(col);
193
+ }
194
+ }
181
195
  return {
182
196
  name,
183
197
  scopes: obj.scopes.map((spec, i) => parseScopeSpec(spec, `table ${name} scopes[${i}]`)),
184
198
  extensions: parseExtensions(obj.extensions, `table ${name}`),
185
199
  encryptedColumns,
200
+ serverColumns,
186
201
  };
187
202
  }
188
203
  const IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
package/dist/sql.js CHANGED
@@ -6,6 +6,8 @@
6
6
  * - `CREATE TABLE [IF NOT EXISTS] name (columns…, [PRIMARY KEY (col)])
7
7
  * [WITHOUT ROWID]`
8
8
  * - `ALTER TABLE name ADD [COLUMN] coldef`
9
+ * - `ALTER TABLE name ALTER [COLUMN] col DROP NOT NULL` (SPEC §2.4, relaxing a
10
+ * required column)
9
11
  * - `CREATE [UNIQUE] INDEX [IF NOT EXISTS] name ON table (col [, col…])`
10
12
  * - `DROP INDEX [IF EXISTS] name`
11
13
  * - `DROP TABLE [IF EXISTS] name`
@@ -731,9 +733,38 @@ function parseAlterTable(cursor, tables, source, options) {
731
733
  if (table === undefined) {
732
734
  cursor.fail(`ALTER TABLE ${name}: table does not exist at this point`);
733
735
  }
734
- const action = cursor.identifier('an ALTER TABLE action');
735
- if (action.toUpperCase() !== 'ADD') {
736
- cursor.fail(`ALTER TABLE ${name}: unsupported action ${JSON.stringify(action)} (only ADD COLUMN)`);
736
+ const action = cursor.identifier('an ALTER TABLE action').toUpperCase();
737
+ if (action === 'ALTER') {
738
+ // §2.4 "Relaxing a required column": the one in-place column change.
739
+ cursor.eatWord('COLUMN');
740
+ const columnName = cursor.identifier('a column name');
741
+ cursor.expectWord('DROP', `after ALTER COLUMN ${columnName}`);
742
+ cursor.expectWord('NOT', `after ALTER COLUMN ${columnName} DROP`);
743
+ cursor.expectWord('NULL', `after ALTER COLUMN ${columnName} DROP NOT`);
744
+ cursor.expectEnd();
745
+ const index = table.columns.findIndex((c) => c.name === columnName);
746
+ const column = table.columns[index];
747
+ if (column === undefined) {
748
+ cursor.fail(`ALTER TABLE ${name}: column ${JSON.stringify(columnName)} does not exist at this point`);
749
+ }
750
+ if (columnName === table.primaryKey) {
751
+ cursor.fail(`ALTER TABLE ${name}: primary-key column ${JSON.stringify(columnName)} cannot become nullable`);
752
+ }
753
+ if (column.nullable) {
754
+ cursor.fail(`ALTER TABLE ${name}: column ${JSON.stringify(columnName)} is already nullable`);
755
+ }
756
+ const relaxed = { ...column, nullable: true };
757
+ table.columns[index] = relaxed;
758
+ const columnSource = columnIdentifierSources.get(column);
759
+ if (columnSource !== undefined) {
760
+ columnIdentifierSources.set(relaxed, columnSource);
761
+ }
762
+ if (lockedHistoryObjects.has(column))
763
+ lockedHistoryObjects.add(relaxed);
764
+ return;
765
+ }
766
+ if (action !== 'ADD') {
767
+ cursor.fail(`ALTER TABLE ${name}: unsupported action ${JSON.stringify(action)} (only ADD COLUMN and ALTER COLUMN … DROP NOT NULL)`);
737
768
  }
738
769
  cursor.eatWord('COLUMN');
739
770
  const def = parseColumnDef(cursor, false);
@@ -836,7 +867,7 @@ export function applyMigrationSql(tables, sql, source, droppedTables = new Set()
836
867
  parseDrop(cursor, tables, droppedTables);
837
868
  }
838
869
  else {
839
- throw new TypegenError(source, `unsupported SQL statement starting with ${JSON.stringify(head.text)} (only CREATE TABLE, CREATE [UNIQUE] INDEX, CREATE VIRTUAL TABLE … USING fts5, ALTER TABLE … ADD COLUMN, DROP INDEX, and DROP TABLE)`);
870
+ throw new TypegenError(source, `unsupported SQL statement starting with ${JSON.stringify(head.text)} (only CREATE TABLE, CREATE [UNIQUE] INDEX, CREATE VIRTUAL TABLE … USING fts5, ALTER TABLE … ADD COLUMN, ALTER TABLE … ALTER COLUMN … DROP NOT NULL, DROP INDEX, and DROP TABLE)`);
840
871
  }
841
872
  const names = new Set([...tables.keys(), ...droppedTables].map((name) => name.toLowerCase()));
842
873
  for (const token of tokens)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/typegen",
3
- "version": "0.93.0",
3
+ "version": "0.95.0",
4
4
  "description": "Syncular schema-to-TypeScript type generator and the `syncular` CLI",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -56,9 +56,9 @@
56
56
  "!dist/**/*.test.d.ts"
57
57
  ],
58
58
  "dependencies": {
59
- "@syncular/core": "0.93.0"
59
+ "@syncular/core": "0.95.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@syncular/server": "0.93.0"
62
+ "@syncular/server": "0.95.0"
63
63
  }
64
64
  }
package/src/emit.ts CHANGED
@@ -70,6 +70,7 @@ function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
70
70
  lines.push(`/** Insert shape: nullable columns may be omitted. */`);
71
71
  lines.push(`export interface ${type}Insert {`);
72
72
  for (const column of table.columns) {
73
+ if (column.serverOwned === true) continue;
73
74
  const ts = TS_TYPE[appColumnType(column)];
74
75
  lines.push(
75
76
  column.nullable
@@ -84,6 +85,7 @@ function emitRowInterfaces(table: IrTable, naming: NamingMode): string {
84
85
  );
85
86
  lines.push(`export interface ${type}Update {`);
86
87
  for (const column of table.columns) {
88
+ if (column.serverOwned === true) continue;
87
89
  const ts = TS_TYPE[appColumnType(column)];
88
90
  if (column.name === table.primaryKey) {
89
91
  lines.push(` ${key(column.name)}: ${ts};`);
package/src/generate.ts CHANGED
@@ -119,6 +119,7 @@ function buildTable(
119
119
  readonly scopes: readonly ManifestScopeSpec[];
120
120
  readonly extensions: Readonly<Record<string, unknown>>;
121
121
  readonly encryptedColumns: readonly string[];
122
+ readonly serverColumns: readonly string[];
122
123
  },
123
124
  parsed: ParsedTable,
124
125
  ): IrTable {
@@ -134,10 +135,10 @@ function buildTable(
134
135
  );
135
136
  }
136
137
  }
137
- const columns = applyEncryption(
138
+ const columns = applyServerColumns(
138
139
  parsed,
139
- scopes,
140
- manifestTable.encryptedColumns,
140
+ manifestTable.serverColumns,
141
+ applyEncryption(parsed, scopes, manifestTable.encryptedColumns),
141
142
  );
142
143
  return {
143
144
  name: parsed.name,
@@ -227,6 +228,58 @@ function applyEncryption(
227
228
  });
228
229
  }
229
230
 
231
+ /**
232
+ * §6.12: mark each `serverColumns` entry `serverOwned`. Hard errors: unknown
233
+ * column, primary key, non-nullable column (a client's optimistic row holds
234
+ * NULL until the server row arrives), crdt column, encrypted column.
235
+ */
236
+ function applyServerColumns(
237
+ parsed: ParsedTable,
238
+ serverColumns: readonly string[],
239
+ columns: readonly IrColumn[],
240
+ ): readonly IrColumn[] {
241
+ if (serverColumns.length === 0) return columns;
242
+ const owned = new Set(serverColumns);
243
+ for (const name of owned) {
244
+ const column = columns.find((c) => c.name === name);
245
+ const fail = (message: string, code: string): never => {
246
+ throw new TypegenError(MANIFEST_FILENAME, message, code, {
247
+ table: parsed.name,
248
+ column: name,
249
+ });
250
+ };
251
+ if (column === undefined) {
252
+ fail(
253
+ 'serverColumns names an unknown column',
254
+ 'typegen.server_column_unknown',
255
+ );
256
+ } else if (name === parsed.primaryKey) {
257
+ fail(
258
+ 'the primary key cannot be a server column',
259
+ 'typegen.server_column_primary_key',
260
+ );
261
+ } else if (column.type === 'crdt') {
262
+ fail(
263
+ 'a crdt column cannot be a server column',
264
+ 'typegen.server_column_crdt',
265
+ );
266
+ } else if (column.encrypted === true) {
267
+ fail(
268
+ 'an encrypted column cannot be a server column',
269
+ 'typegen.server_column_encrypted',
270
+ );
271
+ } else if (!column.nullable) {
272
+ fail(
273
+ 'a server column must be nullable (§6.12)',
274
+ 'typegen.server_column_not_null',
275
+ );
276
+ }
277
+ }
278
+ return columns.map((column) =>
279
+ owned.has(column.name) ? { ...column, serverOwned: true } : column,
280
+ );
281
+ }
282
+
230
283
  /**
231
284
  * §6.11 hard errors: a declared reference must name an existing parent table
232
285
  * whose primary key has the child column's type, and parent and child must
package/src/ir.ts CHANGED
@@ -40,6 +40,10 @@ export interface IrColumn {
40
40
  readonly encrypted?: boolean;
41
41
  /** §5.11: the app-side type of an encrypted column. Present iff `encrypted`. */
42
42
  readonly declaredType?: IrColumnType;
43
+ /** §6.12: the server sets this column inside the push transaction and a
44
+ * client never authors it. IR metadata only (never on the wire). Present
45
+ * only for server-owned columns, so other columns stay byte-identical. */
46
+ readonly serverOwned?: boolean;
43
47
  }
44
48
 
45
49
  /** §5.11: the app-side type of a column. An encrypted column rides the wire
@@ -199,6 +203,7 @@ function serializeTableShape(
199
203
  ...(column.encrypted === true
200
204
  ? { encrypted: true, declaredType: column.declaredType }
201
205
  : {}),
206
+ ...(column.serverOwned === true ? { serverOwned: true } : {}),
202
207
  })),
203
208
  scopes,
204
209
  ...(table.references.length > 0
package/src/manifest.ts CHANGED
@@ -66,6 +66,12 @@ export interface ManifestTable {
66
66
  * an unknown column) are enforced at generate time.
67
67
  */
68
68
  readonly encryptedColumns: readonly string[];
69
+ /**
70
+ * §6.12: columns the server sets inside the push transaction. The IR marks
71
+ * each `serverOwned`. Hard errors (unknown, pk, non-nullable, crdt or
72
+ * encrypted column) are enforced at generate time.
73
+ */
74
+ readonly serverColumns: readonly string[];
69
75
  }
70
76
 
71
77
  export interface ManifestSubscription {
@@ -290,7 +296,7 @@ function parseTable(value: unknown, index: number): ManifestTable {
290
296
  const obj = asObject(value, context);
291
297
  rejectUnknownKeys(
292
298
  obj,
293
- ['name', 'scopes', 'extensions', 'encryptedColumns'],
299
+ ['name', 'scopes', 'extensions', 'encryptedColumns', 'serverColumns'],
294
300
  context,
295
301
  );
296
302
  const name = asString(obj.name, `${context}.name`);
@@ -315,6 +321,24 @@ function parseTable(value: unknown, index: number): ManifestTable {
315
321
  seen.add(col);
316
322
  }
317
323
  }
324
+ let serverColumns: string[] = [];
325
+ if (obj.serverColumns !== undefined) {
326
+ if (!Array.isArray(obj.serverColumns)) {
327
+ fail(`table ${name}: serverColumns must be an array of column names`);
328
+ }
329
+ serverColumns = obj.serverColumns.map((c, i) =>
330
+ asString(c, `table ${name} serverColumns[${i}]`),
331
+ );
332
+ const seen = new Set<string>();
333
+ for (const col of serverColumns) {
334
+ if (seen.has(col)) {
335
+ fail(
336
+ `table ${name}: duplicate serverColumns entry ${JSON.stringify(col)}`,
337
+ );
338
+ }
339
+ seen.add(col);
340
+ }
341
+ }
318
342
  return {
319
343
  name,
320
344
  scopes: obj.scopes.map((spec, i) =>
@@ -322,6 +346,7 @@ function parseTable(value: unknown, index: number): ManifestTable {
322
346
  ),
323
347
  extensions: parseExtensions(obj.extensions, `table ${name}`),
324
348
  encryptedColumns,
349
+ serverColumns,
325
350
  };
326
351
  }
327
352
 
package/src/sql.ts CHANGED
@@ -6,6 +6,8 @@
6
6
  * - `CREATE TABLE [IF NOT EXISTS] name (columns…, [PRIMARY KEY (col)])
7
7
  * [WITHOUT ROWID]`
8
8
  * - `ALTER TABLE name ADD [COLUMN] coldef`
9
+ * - `ALTER TABLE name ALTER [COLUMN] col DROP NOT NULL` (SPEC §2.4, relaxing a
10
+ * required column)
9
11
  * - `CREATE [UNIQUE] INDEX [IF NOT EXISTS] name ON table (col [, col…])`
10
12
  * - `DROP INDEX [IF EXISTS] name`
11
13
  * - `DROP TABLE [IF EXISTS] name`
@@ -969,10 +971,44 @@ function parseAlterTable(
969
971
  if (table === undefined) {
970
972
  cursor.fail(`ALTER TABLE ${name}: table does not exist at this point`);
971
973
  }
972
- const action = cursor.identifier('an ALTER TABLE action');
973
- if (action.toUpperCase() !== 'ADD') {
974
+ const action = cursor.identifier('an ALTER TABLE action').toUpperCase();
975
+ if (action === 'ALTER') {
976
+ // §2.4 "Relaxing a required column": the one in-place column change.
977
+ cursor.eatWord('COLUMN');
978
+ const columnName = cursor.identifier('a column name');
979
+ cursor.expectWord('DROP', `after ALTER COLUMN ${columnName}`);
980
+ cursor.expectWord('NOT', `after ALTER COLUMN ${columnName} DROP`);
981
+ cursor.expectWord('NULL', `after ALTER COLUMN ${columnName} DROP NOT`);
982
+ cursor.expectEnd();
983
+ const index = table.columns.findIndex((c) => c.name === columnName);
984
+ const column = table.columns[index];
985
+ if (column === undefined) {
986
+ cursor.fail(
987
+ `ALTER TABLE ${name}: column ${JSON.stringify(columnName)} does not exist at this point`,
988
+ );
989
+ }
990
+ if (columnName === table.primaryKey) {
991
+ cursor.fail(
992
+ `ALTER TABLE ${name}: primary-key column ${JSON.stringify(columnName)} cannot become nullable`,
993
+ );
994
+ }
995
+ if (column.nullable) {
996
+ cursor.fail(
997
+ `ALTER TABLE ${name}: column ${JSON.stringify(columnName)} is already nullable`,
998
+ );
999
+ }
1000
+ const relaxed = { ...column, nullable: true };
1001
+ table.columns[index] = relaxed;
1002
+ const columnSource = columnIdentifierSources.get(column);
1003
+ if (columnSource !== undefined) {
1004
+ columnIdentifierSources.set(relaxed, columnSource);
1005
+ }
1006
+ if (lockedHistoryObjects.has(column)) lockedHistoryObjects.add(relaxed);
1007
+ return;
1008
+ }
1009
+ if (action !== 'ADD') {
974
1010
  cursor.fail(
975
- `ALTER TABLE ${name}: unsupported action ${JSON.stringify(action)} (only ADD COLUMN)`,
1011
+ `ALTER TABLE ${name}: unsupported action ${JSON.stringify(action)} (only ADD COLUMN and ALTER COLUMN … DROP NOT NULL)`,
976
1012
  );
977
1013
  }
978
1014
  cursor.eatWord('COLUMN');
@@ -1102,7 +1138,7 @@ export function applyMigrationSql(
1102
1138
  } else {
1103
1139
  throw new TypegenError(
1104
1140
  source,
1105
- `unsupported SQL statement starting with ${JSON.stringify(head.text)} (only CREATE TABLE, CREATE [UNIQUE] INDEX, CREATE VIRTUAL TABLE … USING fts5, ALTER TABLE … ADD COLUMN, DROP INDEX, and DROP TABLE)`,
1141
+ `unsupported SQL statement starting with ${JSON.stringify(head.text)} (only CREATE TABLE, CREATE [UNIQUE] INDEX, CREATE VIRTUAL TABLE … USING fts5, ALTER TABLE … ADD COLUMN, ALTER TABLE … ALTER COLUMN … DROP NOT NULL, DROP INDEX, and DROP TABLE)`,
1106
1142
  );
1107
1143
  }
1108
1144
  const names = new Set(