@syncular/typegen 0.57.0 → 0.59.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 +43 -25
- package/dist/cli.js +8 -3
- package/dist/emit-dart.d.ts +4 -3
- package/dist/emit-dart.js +39 -88
- package/dist/emit-kotlin.d.ts +3 -3
- package/dist/emit-kotlin.js +39 -86
- package/dist/emit-queries-dart.d.ts +1 -1
- package/dist/emit-queries-dart.js +17 -26
- package/dist/emit-queries-kotlin.d.ts +1 -1
- package/dist/emit-queries-kotlin.js +15 -24
- package/dist/emit-queries-rust.d.ts +1 -1
- package/dist/emit-queries-rust.js +1 -6
- package/dist/emit-queries-swift.d.ts +1 -1
- package/dist/emit-queries-swift.js +22 -26
- package/dist/emit-queries.d.ts +1 -1
- package/dist/emit-queries.js +1 -6
- package/dist/emit-swift.d.ts +3 -3
- package/dist/emit-swift.js +41 -89
- package/dist/emit.d.ts +1 -1
- package/dist/emit.js +33 -98
- package/dist/errors.d.ts +6 -2
- package/dist/errors.js +10 -2
- package/dist/generate.d.ts +4 -3
- package/dist/generate.js +32 -49
- package/dist/init.js +1 -1
- package/dist/ir.d.ts +11 -0
- package/dist/ir.js +66 -47
- package/dist/lower.d.ts +0 -7
- package/dist/lower.js +0 -62
- package/dist/migration-lock.d.ts +32 -23
- package/dist/migration-lock.js +115 -92
- package/dist/naming.d.ts +25 -0
- package/dist/naming.js +92 -0
- package/dist/query.d.ts +54 -14
- package/dist/query.js +484 -462
- package/dist/sql.js +18 -3
- package/dist/syql-lowering.js +10 -1
- package/dist/syql-validator.js +13 -220
- package/package.json +3 -3
- package/src/cli.ts +9 -3
- package/src/emit-dart.ts +41 -102
- package/src/emit-kotlin.ts +38 -102
- package/src/emit-queries-dart.ts +23 -32
- package/src/emit-queries-kotlin.ts +20 -30
- package/src/emit-queries-rust.ts +7 -12
- package/src/emit-queries-swift.ts +26 -32
- package/src/emit-queries.ts +5 -11
- package/src/emit-swift.ts +42 -104
- package/src/emit.ts +33 -116
- package/src/errors.ts +13 -2
- package/src/generate.ts +74 -76
- package/src/init.ts +4 -1
- package/src/ir.ts +87 -50
- package/src/lower.ts +0 -53
- package/src/migration-lock.ts +192 -137
- package/src/naming.ts +154 -0
- package/src/query.ts +615 -504
- package/src/sql.ts +30 -3
- package/src/syql-lowering.ts +15 -1
- package/src/syql-validator.ts +21 -279
package/dist/sql.js
CHANGED
|
@@ -169,7 +169,9 @@ function tokenizeStatements(sql, source) {
|
|
|
169
169
|
}
|
|
170
170
|
i = end;
|
|
171
171
|
}
|
|
172
|
-
else if (DIGIT.test(ch)
|
|
172
|
+
else if (DIGIT.test(ch) ||
|
|
173
|
+
((ch === '-' || ch === '+') && DIGIT.test(sql[i + 1] ?? ''))) {
|
|
174
|
+
// A leading sign belongs to the number: `DEFAULT -1` is a literal.
|
|
173
175
|
let end = i + 1;
|
|
174
176
|
while (end < sql.length && /[0-9.]/.test(sql[end]))
|
|
175
177
|
end += 1;
|
|
@@ -241,8 +243,8 @@ class Cursor {
|
|
|
241
243
|
throw new TypegenError(this.source, `unsupported trailing SQL ${JSON.stringify(token.text)}`);
|
|
242
244
|
}
|
|
243
245
|
}
|
|
244
|
-
fail(message) {
|
|
245
|
-
throw new TypegenError(this.source, message);
|
|
246
|
+
fail(message, code, details) {
|
|
247
|
+
throw new TypegenError(this.source, message, code, details);
|
|
246
248
|
}
|
|
247
249
|
}
|
|
248
250
|
function parseColumnType(cursor, columnName) {
|
|
@@ -290,6 +292,19 @@ function parseColumnDef(cursor, allowPrimaryKey) {
|
|
|
290
292
|
if (value.kind === 'punct') {
|
|
291
293
|
cursor.fail(`column ${name}: DEFAULT expressions are unsupported (only literals)`);
|
|
292
294
|
}
|
|
295
|
+
// A word is a literal only as one of SQLite's keyword literals, so
|
|
296
|
+
// `DEFAULT NOT NULL` cannot swallow the NOT of a constraint.
|
|
297
|
+
if (value.kind === 'word' &&
|
|
298
|
+
![
|
|
299
|
+
'NULL',
|
|
300
|
+
'TRUE',
|
|
301
|
+
'FALSE',
|
|
302
|
+
'CURRENT_TIME',
|
|
303
|
+
'CURRENT_DATE',
|
|
304
|
+
'CURRENT_TIMESTAMP',
|
|
305
|
+
].includes(value.text.toUpperCase())) {
|
|
306
|
+
cursor.fail('DEFAULT needs a literal value: a number, a string, NULL, TRUE, FALSE, or CURRENT_TIME/DATE/TIMESTAMP', 'typegen.invalid_default', { column: name, found: value.text });
|
|
307
|
+
}
|
|
293
308
|
// Literal defaults are accepted and ignored: typegen extracts the
|
|
294
309
|
// schema shape; running migrations is the host's job.
|
|
295
310
|
}
|
package/dist/syql-lowering.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Revision-1 SYQL logical-to-physical lowering (§§15–17). */
|
|
2
2
|
import { TypegenError } from './errors.js';
|
|
3
|
-
import { buildNamingMap } from './naming.js';
|
|
3
|
+
import { buildNamingMap, validateQueryIdentifier } from './naming.js';
|
|
4
4
|
import { analyzeStatement, } from './query.js';
|
|
5
5
|
import { lexSyqlSqlSource } from './syql-lexer.js';
|
|
6
6
|
import { syqlRangeEndBind, syqlRangeStartBind } from './syql-semantics.js';
|
|
@@ -232,6 +232,15 @@ function publicInputs(validated, naming) {
|
|
|
232
232
|
maxSize: validated.limit.maxSize,
|
|
233
233
|
});
|
|
234
234
|
}
|
|
235
|
+
for (const input of result) {
|
|
236
|
+
for (const langName of [
|
|
237
|
+
input.langName,
|
|
238
|
+
...(input.kind === 'group' ? input.members : []).map((m) => m.langName),
|
|
239
|
+
...(input.kind === 'sort' ? input.profiles : []).map((p) => p.langName),
|
|
240
|
+
]) {
|
|
241
|
+
validateQueryIdentifier(langName, naming.targets, query.module.file, `query ${declaration.name} input`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
235
244
|
return result;
|
|
236
245
|
}
|
|
237
246
|
function valueOwners(validated) {
|
package/dist/syql-validator.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { analyzeStatement, inferParamTypeEvidence, PLAIN_REF_RE, scanRelations, splitSelectList, scanTableRefs, stripCommentsAndStrings, } from './query.js';
|
|
1
|
+
import { AGGREGATE_FUNCTIONS, analyzeStatement, inferParamTypeEvidence, PLAIN_REF_RE, scanRelations, scopeProofs, sqlIdentifier, splitSelectList, scanTableRefs, stripCommentsAndStrings, } from './query.js';
|
|
2
2
|
import { isSyqlTrivia, lexSyqlSqlSource, SyqlFrontendError, } from './syql-lexer.js';
|
|
3
3
|
import { syqlRangeEndBind, syqlRangeStartBind } from './syql-semantics.js';
|
|
4
|
-
const IDENT_SOURCE = '[A-Za-z_][A-Za-z0-9_]*';
|
|
5
4
|
const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
6
5
|
const SQLITE_SUBJECT_RE = '[A-Za-z_][A-Za-z0-9_$]*';
|
|
7
6
|
const NONDETERMINISTIC_FUNCTIONS = new Set([
|
|
@@ -59,26 +58,6 @@ function suggestion(authored, candidates) {
|
|
|
59
58
|
const nearest = nearestName(authored, candidates);
|
|
60
59
|
return nearest === undefined ? '' : `; did you mean \`${nearest}\`?`;
|
|
61
60
|
}
|
|
62
|
-
function identifierText(token) {
|
|
63
|
-
if (token?.kind === 'identifier')
|
|
64
|
-
return token.text;
|
|
65
|
-
if (token?.kind !== 'quoted-identifier')
|
|
66
|
-
return undefined;
|
|
67
|
-
if (token.text.startsWith('[') && token.text.endsWith(']')) {
|
|
68
|
-
return token.text.slice(1, -1).replaceAll(']]', ']');
|
|
69
|
-
}
|
|
70
|
-
const quote = token.text[0];
|
|
71
|
-
return token.text.slice(1, -1).replaceAll(`${quote}${quote}`, quote ?? '');
|
|
72
|
-
}
|
|
73
|
-
const AGGREGATE_FUNCTIONS = new Set([
|
|
74
|
-
'avg',
|
|
75
|
-
'count',
|
|
76
|
-
'group_concat',
|
|
77
|
-
'max',
|
|
78
|
-
'min',
|
|
79
|
-
'sum',
|
|
80
|
-
'total',
|
|
81
|
-
]);
|
|
82
61
|
/**
|
|
83
62
|
* The function surface of the standard SQLite 3.46.0 amalgamation.
|
|
84
63
|
*
|
|
@@ -733,7 +712,7 @@ class Validator {
|
|
|
733
712
|
#sqlSubjectSpan(logical, subject, focus) {
|
|
734
713
|
const tokens = significant(logical.declaration.statement.tokens);
|
|
735
714
|
const [qualifier, column] = subject.split('.', 2);
|
|
736
|
-
const matches = (token, expected) =>
|
|
715
|
+
const matches = (token, expected) => sqlIdentifier(token)?.toLowerCase() === expected.toLowerCase();
|
|
737
716
|
if (focus === 'table') {
|
|
738
717
|
for (let index = 0; index < tokens.length - 1; index += 1) {
|
|
739
718
|
const keyword = tokenLower(tokens[index]);
|
|
@@ -834,115 +813,9 @@ class Validator {
|
|
|
834
813
|
// bodies are identical because `when` is confined to the outer clauses.
|
|
835
814
|
const refs = relations.tables;
|
|
836
815
|
const refScope = (ref) => relations.scopeAt(ref.start);
|
|
837
|
-
const
|
|
838
|
-
const structure = this.#inspect(cleaned, logical.declaration.statement.span.file);
|
|
839
|
-
const markerScopes = scanRelations(markerSql, this.#ir);
|
|
840
|
-
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
841
|
-
const requiredAt = (index) => {
|
|
842
|
-
const scope = markerScopes.scopeAt(index);
|
|
843
|
-
if (scope === 'nested')
|
|
844
|
-
return false;
|
|
845
|
-
const cte = markerScopes.cteScopes.find((candidate) => `cte:${candidate.name}` === scope);
|
|
846
|
-
const scopeItems = cte === undefined
|
|
847
|
-
? structure.outer
|
|
848
|
-
: structure.tokens.filter((item) => item.depth === 1 &&
|
|
849
|
-
item.token.span.start.offset >= cte.start &&
|
|
850
|
-
item.token.span.end.offset <= cte.end);
|
|
851
|
-
let whereStart;
|
|
852
|
-
for (const item of scopeItems) {
|
|
853
|
-
if (item.token.span.start.offset >= index)
|
|
854
|
-
break;
|
|
855
|
-
const lower = tokenLower(item.token);
|
|
856
|
-
if (lower === 'where')
|
|
857
|
-
whereStart = item.token.span.end.offset;
|
|
858
|
-
else if (OUTER_CLAUSE_ENDERS.has(lower ?? ''))
|
|
859
|
-
whereStart = undefined;
|
|
860
|
-
}
|
|
861
|
-
if (whereStart === undefined)
|
|
862
|
-
return false;
|
|
863
|
-
const clauseEnd = scopeItems.find((item) => item.token.span.start.offset > index &&
|
|
864
|
-
OUTER_CLAUSE_ENDERS.has(tokenLower(item.token) ?? ''))?.token.span.start.offset ??
|
|
865
|
-
cte?.end ??
|
|
866
|
-
cleaned.length;
|
|
867
|
-
const matchStack = [];
|
|
868
|
-
for (let cursor = whereStart; cursor < index; cursor += 1) {
|
|
869
|
-
if (cleaned[cursor] === '(')
|
|
870
|
-
matchStack.push(cursor);
|
|
871
|
-
else if (cleaned[cursor] === ')')
|
|
872
|
-
matchStack.pop();
|
|
873
|
-
}
|
|
874
|
-
// Parenthesized boolean expressions are valid, but predicates inside a
|
|
875
|
-
// CTE or subquery are not outer proof obligations for sync coverage.
|
|
876
|
-
if (matchStack.some((open) => /\b(?:SELECT|WITH)\b/i.test(cleaned.slice(open + 1, index)))) {
|
|
877
|
-
return false;
|
|
878
|
-
}
|
|
879
|
-
// Negated equality does not constrain the result to that scope.
|
|
880
|
-
const prefix = cleaned.slice(whereStart, index);
|
|
881
|
-
const boundaries = [...prefix.matchAll(/\b(?:AND|OR)\b/gi)].map((match) => (match.index ?? -1) + match[0].length);
|
|
882
|
-
const lastBoundary = Math.max(prefix.lastIndexOf('('), ...boundaries);
|
|
883
|
-
if (/\bNOT\b/i.test(prefix.slice(lastBoundary + 1)))
|
|
884
|
-
return false;
|
|
885
|
-
if (matchStack.some((open) => /\bNOT\s*$/i.test(cleaned.slice(whereStart, open)))) {
|
|
886
|
-
return false;
|
|
887
|
-
}
|
|
888
|
-
const stack = [];
|
|
889
|
-
for (let cursor = whereStart; cursor < clauseEnd; cursor += 1) {
|
|
890
|
-
const char = cleaned[cursor];
|
|
891
|
-
if (char === '(')
|
|
892
|
-
stack.push(cursor);
|
|
893
|
-
else if (char === ')')
|
|
894
|
-
stack.pop();
|
|
895
|
-
if ((cursor === 0 || !/[A-Za-z0-9_:]/.test(cleaned[cursor - 1] ?? '')) &&
|
|
896
|
-
/^OR\b/i.test(cleaned.slice(cursor)) &&
|
|
897
|
-
stack.length <= matchStack.length &&
|
|
898
|
-
stack.every((open, stackIndex) => matchStack[stackIndex] === open)) {
|
|
899
|
-
return false;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
return true;
|
|
903
|
-
};
|
|
904
|
-
const joinEqualityContextAt = (index) => {
|
|
905
|
-
const prefix = cleaned.slice(0, index);
|
|
906
|
-
const clauses = [
|
|
907
|
-
...prefix.matchAll(/\b(ON|JOIN|WHERE|GROUP\s+BY|ORDER\s+BY|HAVING|LIMIT|UNION|EXCEPT|INTERSECT)\b/gi),
|
|
908
|
-
];
|
|
909
|
-
const last = clauses.at(-1);
|
|
910
|
-
if (last?.[1]?.toUpperCase() !== 'ON')
|
|
911
|
-
return undefined;
|
|
912
|
-
const start = (last.index ?? 0) + last[0].length;
|
|
913
|
-
const next = /\b(?:JOIN|WHERE|GROUP\s+BY|ORDER\s+BY|HAVING|LIMIT|UNION|EXCEPT|INTERSECT)\b/i.exec(cleaned.slice(index));
|
|
914
|
-
const end = next === null ? cleaned.length : index + next.index;
|
|
915
|
-
const clause = cleaned.slice(start, end);
|
|
916
|
-
if (/\b(?:OR|NOT|SELECT|WITH)\b/i.test(clause))
|
|
917
|
-
return undefined;
|
|
918
|
-
const join = clauses.at(-2);
|
|
919
|
-
if (join?.[1]?.toUpperCase() !== 'JOIN')
|
|
920
|
-
return undefined;
|
|
921
|
-
const joinIndex = join.index ?? 0;
|
|
922
|
-
const outerKind = /\b(LEFT|RIGHT|FULL)(?:\s+OUTER)?\s*$/i
|
|
923
|
-
.exec(prefix.slice(0, joinIndex))?.[1]
|
|
924
|
-
?.toUpperCase();
|
|
925
|
-
if (outerKind === undefined)
|
|
926
|
-
return { kind: 'inner' };
|
|
927
|
-
// A FULL join preserves both operands, so its ON constrains neither.
|
|
928
|
-
if (outerKind === 'FULL')
|
|
929
|
-
return undefined;
|
|
930
|
-
const introducedAlias = (prefix
|
|
931
|
-
.slice(joinIndex + join[0].length, last.index)
|
|
932
|
-
.match(new RegExp(IDENT_SOURCE, 'g')) ?? [])
|
|
933
|
-
.filter((word) => word.toUpperCase() !== 'AS')
|
|
934
|
-
.at(-1)
|
|
935
|
-
?.toLowerCase();
|
|
936
|
-
if (introducedAlias === undefined)
|
|
937
|
-
return undefined;
|
|
938
|
-
return {
|
|
939
|
-
kind: 'outer',
|
|
940
|
-
introducedAlias,
|
|
941
|
-
nullExtended: outerKind === 'LEFT' ? 'introduced' : 'prior',
|
|
942
|
-
};
|
|
943
|
-
};
|
|
944
|
-
const refByAlias = new Map(refs.map((ref) => [`${refScope(ref)}\0${ref.alias.toLowerCase()}`, ref]));
|
|
816
|
+
const proofs = scopeProofs(markerSql, this.#ir);
|
|
945
817
|
const scopeNode = (scope, alias, column) => `${scope}\0${alias.toLowerCase()}\0${column.toLowerCase()}`;
|
|
818
|
+
const nodeOf = (column) => scopeNode(column.scope, column.alias, column.column);
|
|
946
819
|
const parents = new Map();
|
|
947
820
|
const find = (node) => {
|
|
948
821
|
const parent = parents.get(node);
|
|
@@ -1000,55 +873,12 @@ class Validator {
|
|
|
1000
873
|
}
|
|
1001
874
|
return seen;
|
|
1002
875
|
};
|
|
1003
|
-
const
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
return (table?.scopes.some((scope) => scope.column.toLowerCase() === column.toLowerCase()) === true);
|
|
1007
|
-
};
|
|
1008
|
-
// Scope inheritance across a join relies on a satisfied predicate proving
|
|
1009
|
-
// both operands non-NULL. `IS` is null-safe (`NULL IS NULL` holds), so it
|
|
1010
|
-
// would let a null-extended row on an outer join's preserved side carry a
|
|
1011
|
-
// scope proof it never satisfies; only `=`/`==` qualify here.
|
|
1012
|
-
const qualifiedEquality = new RegExp(`(${IDENT_SOURCE})\\.(${IDENT_SOURCE})\\s*(?:=|==)\\s*(${IDENT_SOURCE})\\.(${IDENT_SOURCE})`, 'gi');
|
|
1013
|
-
for (const match of cleaned.matchAll(qualifiedEquality)) {
|
|
1014
|
-
const leftAlias = match[1];
|
|
1015
|
-
const leftColumn = match[2];
|
|
1016
|
-
const rightAlias = match[3];
|
|
1017
|
-
const rightColumn = match[4];
|
|
1018
|
-
const index = match.index ?? 0;
|
|
1019
|
-
const scope = markerScopes.scopeAt(index);
|
|
1020
|
-
if (!scopeColumn(scope, leftAlias, leftColumn) ||
|
|
1021
|
-
!scopeColumn(scope, rightAlias, rightColumn)) {
|
|
1022
|
-
continue;
|
|
1023
|
-
}
|
|
1024
|
-
const leftNode = scopeNode(scope, leftAlias, leftColumn);
|
|
1025
|
-
const rightNode = scopeNode(scope, rightAlias, rightColumn);
|
|
1026
|
-
if (requiredAt(index)) {
|
|
1027
|
-
union(leftNode, rightNode);
|
|
1028
|
-
continue;
|
|
1029
|
-
}
|
|
1030
|
-
const context = joinEqualityContextAt(index);
|
|
1031
|
-
if (context === undefined)
|
|
1032
|
-
continue;
|
|
1033
|
-
if (context.kind === 'inner') {
|
|
1034
|
-
// An inner join's ON filters every result row, so the equality
|
|
1035
|
-
// constrains both operands symmetrically.
|
|
1036
|
-
union(leftNode, rightNode);
|
|
1037
|
-
continue;
|
|
1038
|
-
}
|
|
1039
|
-
const leftIntroduced = leftAlias.toLowerCase() === context.introducedAlias;
|
|
1040
|
-
const rightIntroduced = rightAlias.toLowerCase() === context.introducedAlias;
|
|
1041
|
-
// An equality with both operands on one side of the outer join proves
|
|
1042
|
-
// nothing across it; preserved-side rows appear regardless of the ON.
|
|
1043
|
-
if (leftIntroduced === rightIntroduced)
|
|
1044
|
-
continue;
|
|
1045
|
-
const introducedNode = leftIntroduced ? leftNode : rightNode;
|
|
1046
|
-
const priorNode = leftIntroduced ? rightNode : leftNode;
|
|
1047
|
-
if (context.nullExtended === 'introduced') {
|
|
1048
|
-
addInheritEdge(introducedNode, priorNode);
|
|
876
|
+
for (const equality of proofs.equalities) {
|
|
877
|
+
if (equality.symmetric) {
|
|
878
|
+
union(nodeOf(equality.target), nodeOf(equality.source));
|
|
1049
879
|
}
|
|
1050
880
|
else {
|
|
1051
|
-
addInheritEdge(
|
|
881
|
+
addInheritEdge(nodeOf(equality.target), nodeOf(equality.source));
|
|
1052
882
|
}
|
|
1053
883
|
}
|
|
1054
884
|
const required = new Set([...symbols.values()].flatMap((symbol) => symbol.parameter.kind === 'value' &&
|
|
@@ -1064,48 +894,11 @@ class Validator {
|
|
|
1064
894
|
continue;
|
|
1065
895
|
const inferred = [];
|
|
1066
896
|
for (const scope of table.scopes) {
|
|
1067
|
-
const
|
|
1068
|
-
const
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
const other = this.#ir.tables.find((item) => item.name === candidate.table);
|
|
1073
|
-
return other?.columns.some((item) => item.name === scope.column);
|
|
1074
|
-
}).length;
|
|
1075
|
-
const subject = unqualifiedMatches === 1
|
|
1076
|
-
? `(?<![A-Za-z0-9_.:])(?:${alias}\\.)?${column}\\b`
|
|
1077
|
-
: `(?<![A-Za-z0-9_.:])${alias}\\.${column}\\b`;
|
|
1078
|
-
const found = [];
|
|
1079
|
-
const equality = new RegExp(`${subject}\\s*(?:=|==|\\bIS\\b)\\s*:([A-Za-z_][A-Za-z0-9_]*)\\b|:([A-Za-z_][A-Za-z0-9_]*)\\b\\s*(?:=|==)\\s*${subject}`, 'gi');
|
|
1080
|
-
const inScope = (index) => markerScopes.scopeAt(index) === refScope(ref) && requiredAt(index);
|
|
1081
|
-
for (const match of cleaned.matchAll(equality)) {
|
|
1082
|
-
if (!inScope(match.index))
|
|
1083
|
-
continue;
|
|
1084
|
-
const name = match[1] ?? match[2];
|
|
1085
|
-
if (name !== undefined && required.has(name)) {
|
|
1086
|
-
found.push({ name, operator: 'equal' });
|
|
1087
|
-
}
|
|
1088
|
-
}
|
|
1089
|
-
const inList = new RegExp(`${subject}\\s+IN\\s*\\(([^)]*)\\)`, 'gi');
|
|
1090
|
-
for (const match of cleaned.matchAll(inList)) {
|
|
1091
|
-
if (!inScope(match.index))
|
|
1092
|
-
continue;
|
|
1093
|
-
const body = match[1] ?? '';
|
|
1094
|
-
const bodyStart = match.index + match[0].length - body.length - 1;
|
|
1095
|
-
const bodyTokens = significant(lexSyqlSqlSource(logical.declaration.statement.span.file, markerSql.slice(bodyStart, bodyStart + body.length)));
|
|
1096
|
-
const validBindList = bodyTokens.every((token, index) => index % 2 === 0
|
|
1097
|
-
? token.kind === 'bind'
|
|
1098
|
-
: token.kind === 'punctuation' && token.text === ',');
|
|
1099
|
-
const params = bodyTokens
|
|
1100
|
-
.filter((_, index) => index % 2 === 0)
|
|
1101
|
-
.map((token) => token.text.slice(1));
|
|
1102
|
-
if (validBindList &&
|
|
1103
|
-
params.length > 0 &&
|
|
1104
|
-
params.every((name) => required.has(name))) {
|
|
1105
|
-
for (const name of params)
|
|
1106
|
-
found.push({ name, operator: 'in' });
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
897
|
+
const node = scopeNode(refScope(ref), ref.alias, scope.column);
|
|
898
|
+
const found = proofs.binds
|
|
899
|
+
.filter((proof) => nodeOf(proof) === node &&
|
|
900
|
+
proof.params.every((name) => required.has(name)))
|
|
901
|
+
.flatMap((proof) => proof.params.map((name) => ({ name, operator: proof.operator })));
|
|
1109
902
|
const params = [...new Set(found.map((item) => item.name))];
|
|
1110
903
|
if (params.length > 0) {
|
|
1111
904
|
const evidence = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syncular/typegen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.59.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.
|
|
59
|
+
"@syncular/core": "0.59.0"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
|
-
"@syncular/server": "0.
|
|
62
|
+
"@syncular/server": "0.59.0"
|
|
63
63
|
}
|
|
64
64
|
}
|
package/src/cli.ts
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { existsSync, readFileSync, watch, writeFileSync } from 'node:fs';
|
|
19
19
|
import { resolve } from 'node:path';
|
|
20
|
+
import { TypegenError } from './errors';
|
|
20
21
|
import { formatSyql } from './fmt';
|
|
21
22
|
import {
|
|
22
23
|
baselineMigrationHistory,
|
|
@@ -60,7 +61,7 @@ fmt options:
|
|
|
60
61
|
migrations options:
|
|
61
62
|
baseline create the first immutable history lock; refuses overwrite
|
|
62
63
|
check validate the committed history without generating outputs
|
|
63
|
-
upgrade-lock
|
|
64
|
+
upgrade-lock convert a validated format-1 or format-2 lock to format 3
|
|
64
65
|
--manifest-dir <dir> directory holding syncular.json (default: .)
|
|
65
66
|
|
|
66
67
|
init options:
|
|
@@ -207,7 +208,12 @@ function parseManifestDir(argv: readonly string[]): string {
|
|
|
207
208
|
|
|
208
209
|
/** Add a docs pointer to the fail-loud missing-input errors. */
|
|
209
210
|
function friendlyGenerateError(error: unknown): string {
|
|
210
|
-
const message =
|
|
211
|
+
const message =
|
|
212
|
+
error instanceof TypegenError && error.code !== undefined
|
|
213
|
+
? `${error.message}\n${error.code} ${JSON.stringify(error.details ?? {})}`
|
|
214
|
+
: error instanceof Error
|
|
215
|
+
? error.message
|
|
216
|
+
: String(error);
|
|
211
217
|
if (
|
|
212
218
|
message.includes('manifest not found') ||
|
|
213
219
|
message.includes('migrations directory does not exist') ||
|
|
@@ -370,7 +376,7 @@ function runMigrations(argv: readonly string[]): void {
|
|
|
370
376
|
fail(friendlyGenerateError(error));
|
|
371
377
|
}
|
|
372
378
|
writeFileSync(output.path, output.content, 'utf8');
|
|
373
|
-
console.log(`upgraded ${output.path} to
|
|
379
|
+
console.log(`upgraded ${output.path} to format 3`);
|
|
374
380
|
console.log('review and commit the migration-lock format upgrade');
|
|
375
381
|
return;
|
|
376
382
|
}
|
package/src/emit-dart.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Dart emitter: neutral IR → one standalone `.dart` file exporting
|
|
3
3
|
*
|
|
4
|
-
* - `
|
|
5
|
-
* Object
|
|
4
|
+
* - `final syncularSchema` — the ServerSchema-compatible `Map<String,
|
|
5
|
+
* Object?>`: the exact `serializeSchema` JSON the TS module embeds,
|
|
6
|
+
* decoded from a string literal (fed straight into `SyncularClient.create(
|
|
6
7
|
* schema: …)`),
|
|
7
8
|
* - one class per table with typed fields (per the six §2.4 column types +
|
|
8
9
|
* blob_ref/crdt) and a `fromRow(Map<String, Object?>)` factory,
|
|
@@ -13,8 +14,15 @@
|
|
|
13
14
|
* `query`/`readRows` return. The header carries the IR hash so `--check`
|
|
14
15
|
* verifies freshness byte-exactly.
|
|
15
16
|
*/
|
|
16
|
-
import
|
|
17
|
-
|
|
17
|
+
import {
|
|
18
|
+
appColumnType,
|
|
19
|
+
type IrColumnType,
|
|
20
|
+
type IrDocument,
|
|
21
|
+
type IrSubscription,
|
|
22
|
+
type IrTable,
|
|
23
|
+
serializeSchema,
|
|
24
|
+
} from './ir';
|
|
25
|
+
import { pascalCase, snakeToCamel, stringLiteral } from './naming';
|
|
18
26
|
|
|
19
27
|
/** §2.4 column type → honest Dart type. `json`/`blob_ref` are the raw
|
|
20
28
|
* canonical JSON string; `bytes`/`crdt` are opaque `List<int>`. */
|
|
@@ -29,90 +37,9 @@ const DART_TYPE: Readonly<Record<IrColumnType, string>> = {
|
|
|
29
37
|
crdt: 'List<int>',
|
|
30
38
|
};
|
|
31
39
|
|
|
32
|
-
function appColumnType(column: IrTable['columns'][number]): IrColumnType {
|
|
33
|
-
return column.encrypted === true && column.declaredType !== undefined
|
|
34
|
-
? column.declaredType
|
|
35
|
-
: column.type;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** §5.11: app-side Dart type — declaredType for an encrypted column. */
|
|
39
|
-
function appDartType(column: IrTable['columns'][number]): string {
|
|
40
|
-
return DART_TYPE[appColumnType(column)];
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function pascalCase(name: string): string {
|
|
44
|
-
return name
|
|
45
|
-
.split(/[_-]+/)
|
|
46
|
-
.filter((part) => part.length > 0)
|
|
47
|
-
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
48
|
-
.join('');
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Language-facing field name — the pinned §12 naming map. */
|
|
52
|
-
function camelCase(name: string): string {
|
|
53
|
-
return snakeToCamel(name);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function quote(value: string): string {
|
|
57
|
-
return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\$/g, '\\$')}'`;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function emitSchemaValue(ir: IrDocument, indent: string): string[] {
|
|
61
|
-
const lines: string[] = [];
|
|
62
|
-
const i = indent;
|
|
63
|
-
lines.push(`${i}<String, Object?>{`);
|
|
64
|
-
lines.push(`${i} 'version': ${ir.schemaVersion},`);
|
|
65
|
-
lines.push(`${i} 'tables': [`);
|
|
66
|
-
for (const table of ir.tables) {
|
|
67
|
-
lines.push(`${i} {`);
|
|
68
|
-
lines.push(`${i} 'name': ${quote(table.name)},`);
|
|
69
|
-
lines.push(`${i} 'primaryKey': ${quote(table.primaryKey)},`);
|
|
70
|
-
lines.push(`${i} 'columns': [`);
|
|
71
|
-
for (const column of table.columns) {
|
|
72
|
-
const parts = [
|
|
73
|
-
`'name': ${quote(column.name)}`,
|
|
74
|
-
`'type': ${quote(column.type)}`,
|
|
75
|
-
`'nullable': ${column.nullable}`,
|
|
76
|
-
];
|
|
77
|
-
if (column.crdtType !== undefined) {
|
|
78
|
-
parts.push(`'crdtType': ${quote(column.crdtType)}`);
|
|
79
|
-
}
|
|
80
|
-
if (column.encrypted === true) {
|
|
81
|
-
parts.push("'encrypted': true");
|
|
82
|
-
parts.push(
|
|
83
|
-
`'declaredType': ${quote(column.declaredType ?? column.type)}`,
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
lines.push(`${i} {${parts.join(', ')}},`);
|
|
87
|
-
}
|
|
88
|
-
lines.push(`${i} ],`);
|
|
89
|
-
lines.push(`${i} 'scopes': [`);
|
|
90
|
-
for (const scope of table.scopes) {
|
|
91
|
-
lines.push(
|
|
92
|
-
`${i} {'pattern': ${quote(scope.pattern)}, 'column': ${quote(scope.column)}},`,
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
lines.push(`${i} ],`);
|
|
96
|
-
if (table.ftsIndexes.length > 0) {
|
|
97
|
-
lines.push(`${i} 'ftsIndexes': [`);
|
|
98
|
-
for (const index of table.ftsIndexes) {
|
|
99
|
-
const columns = index.columns.map((column) => quote(column)).join(', ');
|
|
100
|
-
lines.push(
|
|
101
|
-
`${i} {'name': ${quote(index.name)}, 'columns': [${columns}], 'tokenize': ${quote(index.tokenize)}},`,
|
|
102
|
-
);
|
|
103
|
-
}
|
|
104
|
-
lines.push(`${i} ],`);
|
|
105
|
-
}
|
|
106
|
-
lines.push(`${i} },`);
|
|
107
|
-
}
|
|
108
|
-
lines.push(`${i} ],`);
|
|
109
|
-
lines.push(`${i}}`);
|
|
110
|
-
return lines;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
40
|
/** The accessor lifting a §2.4 value out of a `Map<String, Object?>` row. */
|
|
114
41
|
function rowAccessor(column: IrTable['columns'][number]): string {
|
|
115
|
-
const key = `row[${
|
|
42
|
+
const key = `row[${stringLiteral(column.name, 'dart')}]`;
|
|
116
43
|
switch (appColumnType(column)) {
|
|
117
44
|
case 'string':
|
|
118
45
|
case 'json':
|
|
@@ -136,13 +63,13 @@ function emitClass(table: IrTable): string[] {
|
|
|
136
63
|
lines.push(`/// One ${table.name} row (§2.4 column order).`);
|
|
137
64
|
lines.push(`class ${type} {`);
|
|
138
65
|
for (const column of table.columns) {
|
|
139
|
-
const dart =
|
|
66
|
+
const dart = DART_TYPE[appColumnType(column)];
|
|
140
67
|
const opt = column.nullable ? '?' : '';
|
|
141
|
-
lines.push(` final ${dart}${opt} ${
|
|
68
|
+
lines.push(` final ${dart}${opt} ${snakeToCamel(column.name)};`);
|
|
142
69
|
}
|
|
143
70
|
lines.push('');
|
|
144
71
|
const ctorParams = table.columns
|
|
145
|
-
.map((c) => `${c.nullable ? '' : 'required '}this.${
|
|
72
|
+
.map((c) => `${c.nullable ? '' : 'required '}this.${snakeToCamel(c.name)}`)
|
|
146
73
|
.join(', ');
|
|
147
74
|
lines.push(` const ${type}({${ctorParams}});`);
|
|
148
75
|
lines.push('');
|
|
@@ -153,14 +80,14 @@ function emitClass(table: IrTable): string[] {
|
|
|
153
80
|
lines.push(` static ${type}? fromRow(Map<String, Object?> row) {`);
|
|
154
81
|
for (const column of table.columns) {
|
|
155
82
|
if (!column.nullable) {
|
|
156
|
-
const name =
|
|
83
|
+
const name = snakeToCamel(column.name);
|
|
157
84
|
lines.push(` final ${name} = ${rowAccessor(column)};`);
|
|
158
85
|
lines.push(` if (${name} == null) return null;`);
|
|
159
86
|
}
|
|
160
87
|
}
|
|
161
88
|
const args = table.columns
|
|
162
89
|
.map((c) => {
|
|
163
|
-
const name =
|
|
90
|
+
const name = snakeToCamel(c.name);
|
|
164
91
|
return c.nullable ? `${name}: ${rowAccessor(c)}` : `${name}: ${name}`;
|
|
165
92
|
})
|
|
166
93
|
.join(', ');
|
|
@@ -181,21 +108,31 @@ function emitSubscription(sub: IrSubscription): string[] {
|
|
|
181
108
|
}
|
|
182
109
|
const lines: string[] = [];
|
|
183
110
|
lines.push(
|
|
184
|
-
`/// Requested-scope template for the ${
|
|
111
|
+
`/// Requested-scope template for the ${stringLiteral(sub.name, 'dart')} subscription.`,
|
|
185
112
|
);
|
|
186
113
|
lines.push(`class Syncular${pascalCase(sub.name)}Subscription {`);
|
|
187
|
-
lines.push(
|
|
188
|
-
|
|
189
|
-
|
|
114
|
+
lines.push(
|
|
115
|
+
` static const String name = ${stringLiteral(sub.name, 'dart')};`,
|
|
116
|
+
);
|
|
117
|
+
lines.push(
|
|
118
|
+
` static const String table = ${stringLiteral(sub.table, 'dart')};`,
|
|
119
|
+
);
|
|
120
|
+
const args = params
|
|
121
|
+
.map((p) => `required String ${snakeToCamel(p)}`)
|
|
122
|
+
.join(', ');
|
|
190
123
|
const argsClause = args.length > 0 ? `{${args}}` : '';
|
|
191
124
|
lines.push(` static Map<String, List<String>> scopes(${argsClause}) => {`);
|
|
192
125
|
for (const scope of sub.scopes) {
|
|
193
126
|
const values = scope.values
|
|
194
127
|
.map((value) =>
|
|
195
|
-
value.kind === 'literal'
|
|
128
|
+
value.kind === 'literal'
|
|
129
|
+
? stringLiteral(value.value, 'dart')
|
|
130
|
+
: snakeToCamel(value.name),
|
|
196
131
|
)
|
|
197
132
|
.join(', ');
|
|
198
|
-
lines.push(
|
|
133
|
+
lines.push(
|
|
134
|
+
` ${stringLiteral(scope.variable, 'dart')}: [${values}],`,
|
|
135
|
+
);
|
|
199
136
|
}
|
|
200
137
|
lines.push(' };');
|
|
201
138
|
lines.push('}');
|
|
@@ -210,6 +147,8 @@ export function emitDartModule(ir: IrDocument, hash: string): string {
|
|
|
210
147
|
`// irVersion: ${ir.irVersion}`,
|
|
211
148
|
`// irHash: ${hash}`,
|
|
212
149
|
'// ignore_for_file: type=lint',
|
|
150
|
+
'',
|
|
151
|
+
"import 'dart:convert';",
|
|
213
152
|
].join('\n'),
|
|
214
153
|
);
|
|
215
154
|
|
|
@@ -217,11 +156,11 @@ export function emitDartModule(ir: IrDocument, hash: string): string {
|
|
|
217
156
|
const schemaLines: string[] = [];
|
|
218
157
|
schemaLines.push('/// ServerSchema-compatible schema (SPEC §2.4, §3.1) —');
|
|
219
158
|
schemaLines.push('/// pass to `SyncularClient.create(schema: …)`.');
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
159
|
+
// A multi-line literal drops the line break after its opening quotes, so
|
|
160
|
+
// the decoded string is the serializeSchema bytes.
|
|
161
|
+
schemaLines.push(
|
|
162
|
+
`final Map<String, Object?> syncularSchema = jsonDecode('''\n${stringLiteral(serializeSchema(ir), 'dart').slice(1, -1)}''') as Map<String, Object?>;`,
|
|
163
|
+
);
|
|
225
164
|
parts.push(schemaLines.join('\n'));
|
|
226
165
|
|
|
227
166
|
// Shared row-decode helpers — emitted only when a column type references
|