@uncutsql/core 0.1.0 → 0.2.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/dist/index.js CHANGED
@@ -1,10 +1,16 @@
1
- import { Data, Effect } from "effect";
1
+ import { Data, Effect, Option, Schema } from "effect";
2
2
  // src/model.ts
3
3
  const tableKey = (table) => JSON.stringify([
4
4
  table.catalog ?? null,
5
5
  table.schema ?? null,
6
6
  table.name
7
7
  ]);
8
+ const namespaceKey = (namespace) => JSON.stringify([namespace.catalog ?? null, namespace.name]);
9
+ /** The namespace that contains an object, or undefined when its identity has no schema level. */
10
+ const namespaceOf = (identity) => identity.schema === void 0 ? void 0 : identity.catalog === void 0 ? { name: identity.schema } : {
11
+ catalog: identity.catalog,
12
+ name: identity.schema
13
+ };
8
14
  /** Object property insertion order is not semantic; array order is retained. */
9
15
  const schemaValueEqual = (before, after) => {
10
16
  if (before === after) return true;
@@ -84,6 +90,34 @@ const validateDatabase = (database, side) => {
84
90
  });
85
91
  triggers.add(id);
86
92
  }
93
+ const namespaces = /* @__PURE__ */ new Set();
94
+ for (const namespace of database.namespaces ?? []) {
95
+ const id = namespaceKey(namespace.identity);
96
+ if (namespaces.has(id)) diagnostics.push({
97
+ code: "DuplicateNamespace",
98
+ message: `Duplicate namespace ${id}`,
99
+ side,
100
+ table: namespace.identity
101
+ });
102
+ namespaces.add(id);
103
+ }
104
+ if (database.namespaces) {
105
+ const undeclared = (identity, owner, role) => {
106
+ const namespace = namespaceOf(identity);
107
+ if (namespace && !namespaces.has(namespaceKey(namespace))) diagnostics.push({
108
+ code: "UndeclaredNamespace",
109
+ message: `${role} ${tableKey(identity)} belongs to undeclared namespace ${namespaceKey(namespace)}`,
110
+ side,
111
+ table: owner
112
+ });
113
+ };
114
+ for (const table of database.tables) undeclared(table.identity, table.identity, "Table");
115
+ for (const view of database.views ?? []) undeclared(view.identity, view.identity, "View");
116
+ for (const trigger of database.triggers ?? []) {
117
+ undeclared(trigger.identity, trigger.identity, "Trigger");
118
+ undeclared(trigger.target, trigger.identity, "Target of trigger");
119
+ }
120
+ }
87
121
  return diagnostics;
88
122
  };
89
123
  const constraintsEqual = (before, after) => before.length === after.length && before.every((item, index) => item.kind === after[index].kind && schemaValueEqual(item.properties, after[index].properties));
@@ -157,9 +191,27 @@ const compareTable = (before, after) => {
157
191
  const diffDatabases = (before, after) => Effect.gen(function* () {
158
192
  const diagnostics = [...validateDatabase(before, "before"), ...validateDatabase(after, "after")];
159
193
  if (diagnostics.length) return yield* Effect.fail(new SchemaDiffError({ diagnostics }));
194
+ const changes = [];
195
+ const oldNamespaces = new Map((before.namespaces ?? []).map((namespace) => [namespaceKey(namespace.identity), namespace]));
196
+ const newNamespaces = new Map((after.namespaces ?? []).map((namespace) => [namespaceKey(namespace.identity), namespace]));
197
+ for (const [key, namespace] of oldNamespaces) if (!newNamespaces.has(key)) changes.push({
198
+ _tag: "NamespaceRemoved",
199
+ namespace
200
+ });
201
+ for (const [key, namespace] of newNamespaces) {
202
+ const old = oldNamespaces.get(key);
203
+ if (!old) changes.push({
204
+ _tag: "NamespaceAdded",
205
+ namespace
206
+ });
207
+ else if (old.name !== namespace.name || !schemaValueEqual(old.options, namespace.options)) changes.push({
208
+ _tag: "NamespaceChanged",
209
+ after: namespace,
210
+ before: old
211
+ });
212
+ }
160
213
  const previous = new Map(before.tables.map((table) => [tableKey(table.identity), table]));
161
214
  const next = new Map(after.tables.map((table) => [tableKey(table.identity), table]));
162
- const changes = [];
163
215
  for (const [key, table] of previous) if (!next.has(key)) changes.push({
164
216
  _tag: "TableRemoved",
165
217
  definition: table,
@@ -227,6 +279,16 @@ const planDatabaseMigration = (diff) => ({
227
279
  ...diff.dropGuards ? { dropGuards: diff.dropGuards } : {},
228
280
  procedures: diff.changes.map((change) => {
229
281
  switch (change._tag) {
282
+ case "NamespaceAdded":
283
+ case "NamespaceRemoved": return {
284
+ _tag: change._tag === "NamespaceAdded" ? "CreateNamespace" : "DropNamespace",
285
+ namespace: change.namespace
286
+ };
287
+ case "NamespaceChanged": return {
288
+ _tag: "AlterNamespace",
289
+ after: change.after,
290
+ before: change.before
291
+ };
230
292
  case "TriggerAdded":
231
293
  case "TriggerRemoved": return {
232
294
  _tag: change._tag === "TriggerAdded" ? "CreateTrigger" : "DropTrigger",
@@ -292,6 +354,14 @@ const planDownMigration = (up) => {
292
354
  _tag: step._tag === "CreateView" ? "DropView" : "CreateView"
293
355
  });
294
356
  break;
357
+ case "CreateNamespace":
358
+ case "DropNamespace":
359
+ procedures.push({
360
+ ...step,
361
+ _tag: step._tag === "CreateNamespace" ? "DropNamespace" : "CreateNamespace"
362
+ });
363
+ break;
364
+ case "AlterNamespace":
295
365
  case "ReplaceView":
296
366
  case "ReplaceTrigger":
297
367
  procedures.push(swap(step));
@@ -448,6 +518,20 @@ const view = (value, path) => {
448
518
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
449
519
  semanticValue(item.query, `${path}.query`);
450
520
  };
521
+ const namespace = (value, path) => {
522
+ const item = record$1(value, path);
523
+ fields(item, [
524
+ "identity",
525
+ "name",
526
+ "options"
527
+ ], path);
528
+ const identity = record$1(item.identity, `${path}.identity`);
529
+ fields(identity, ["catalog", "name"], `${path}.identity`);
530
+ text(identity.name, `${path}.identity.name`);
531
+ if (Object.hasOwn(identity, "catalog")) text(identity.catalog, `${path}.identity.catalog`);
532
+ text(item.name, `${path}.name`);
533
+ properties(item.options, `${path}.options`);
534
+ };
451
535
  const table = (value, path) => {
452
536
  const item = record$1(value, path);
453
537
  fields(item, [
@@ -474,16 +558,42 @@ const decodeDatabaseSchema = (value) => Effect.try({
474
558
  try: () => {
475
559
  const database = record$1(value, "$database");
476
560
  fields(database, [
561
+ "namespaces",
477
562
  "tables",
478
563
  "views",
479
564
  "triggers"
480
565
  ], "$database");
566
+ if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
481
567
  array(database.tables, "$database.tables", table);
482
568
  if (Object.hasOwn(database, "views")) array(database.views, "$database.views", view);
483
569
  if (Object.hasOwn(database, "triggers")) array(database.triggers, "$database.triggers", trigger);
484
570
  return value;
485
571
  }
486
572
  });
573
+ // src/executor.ts
574
+ const checksumPattern = /^[a-f0-9]{64}$/;
575
+ /** The run, or `undefined` when IDs, baseline, checkpoint, SQL or checksums are invalid. */
576
+ const migrationRun = (direction, migrations, checkpoint, sha256) => {
577
+ const down = direction === "down";
578
+ const baseline = migrations[0]?.baselineCheckpoint !== void 0 ? migrations[0] : void 0;
579
+ const checkpointId = checkpoint?.id ?? 0;
580
+ const firstUpId = baseline?.id ?? checkpointId + 1;
581
+ const offset = down ? Math.max(0, checkpointId - 1) : firstUpId - 1;
582
+ if (baseline !== void 0 && (down || checkpointId !== 0 || !Number.isSafeInteger(baseline.id) || baseline.id < 2 || !checksumPattern.test(baseline.baselineCheckpoint)) || down && checkpoint !== void 0 && (migrations.length !== (checkpoint.id ? 1 : 0) || checkpoint.id > 0 && migrations[0]?.sha256 !== checkpoint.sha256) || migrations.some((migration, index) => index > 0 && migration.baselineCheckpoint !== void 0 || migration.id !== offset + index + 1 || !migration.sql.trim() || migration.sql.includes("\0") || sha256(migration.sql) !== migration.sha256)) return;
583
+ return {
584
+ ...baseline ? { baseline } : {},
585
+ direction,
586
+ lastId: offset + migrations.length,
587
+ offset
588
+ };
589
+ };
590
+ /** Whether the history tip read under the write transaction is a matching prefix of the run. */
591
+ const continuesRun = (run, migrations, checkpoint, tip) => {
592
+ const applied = migrations[tip.id - run.offset - 1];
593
+ return !((checkpoint && tip.id === checkpoint.id ? checkpoint.sha256 : tip.id === 0 ? null : applied?.baselineCheckpoint ?? applied?.sha256) !== tip.sha256 || tip.id < (checkpoint?.id ?? 0) || run.direction === "down" && checkpoint !== void 0 && tip.id !== checkpoint.id);
594
+ };
595
+ /** The file to execute after the tip, or `undefined` when the run is complete. */
596
+ const nextMigration = (run, migrations, tipId) => run.baseline && tipId === 0 ? run.baseline : migrations[tipId - run.offset - (run.direction === "down" ? 1 : 0)];
487
597
  // src/decisions.ts
488
598
  var MigrationDecisionError = class extends Data.TaggedError("MigrationDecisionError") {};
489
599
  const equal = (a, b) => schemaValueEqual(a, b);
@@ -724,4 +834,163 @@ const resolveMigrationDecisions = (before, after, supplied) => Effect.gen(functi
724
834
  diff: resolved
725
835
  };
726
836
  });
727
- export { MigrationDecisionError, SchemaDiffError, SchemaModelError, compareTable, decodeDatabaseSchema, diffDatabases, mergeMigrationDecisions, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, resolveMigrationDecisions, schemaValueEqual, tableKey, validateDatabase };
837
+ // src/language-service.ts
838
+ /** Returns the first reference whose half-open span contains `offset`. */
839
+ const referenceAt = (analysis, offset) => analysis.references.find((reference) => reference.start <= offset && offset < reference.end);
840
+ /** Returns the selections of the declarations whose key equals the reference key, in declaration order. */
841
+ const definitions = (reference, analysis) => analysis.declarations.filter((declaration) => declaration.key === reference.key).map((declaration) => declaration.selection);
842
+ // src/codegen.ts
843
+ var CodegenError = class extends Data.TaggedError("CodegenError") {};
844
+ const generatedFileHeader = "// Generated by UncutSQL. Do not edit.";
845
+ // src/codegen-validation.ts
846
+ const identifier = Schema.Trimmed.check(Schema.isNonEmpty());
847
+ const version = Schema.Int.check(Schema.isGreaterThan(0));
848
+ const applicationContract = Schema.Struct({
849
+ id: identifier,
850
+ version
851
+ });
852
+ const generatorInput = Schema.Struct({
853
+ id: identifier,
854
+ versions: Schema.NonEmptyArray(version)
855
+ });
856
+ const mapperDescriptor = Schema.Struct({
857
+ name: identifier,
858
+ output: applicationContract
859
+ });
860
+ const generatorDescriptor = Schema.Struct({
861
+ input: generatorInput,
862
+ name: identifier
863
+ });
864
+ const relationIdentitySchema = Schema.Struct({
865
+ catalog: Schema.optionalKey(Schema.String),
866
+ name: Schema.String,
867
+ schema: Schema.optionalKey(Schema.String)
868
+ });
869
+ const codegenDiagnosticSchema = Schema.Struct({
870
+ code: identifier,
871
+ message: Schema.NonEmptyString,
872
+ severity: Schema.Literals(["error", "warning"]),
873
+ subjects: Schema.Array(Schema.Union([Schema.Struct({
874
+ identity: Schema.Struct({
875
+ key: Schema.String,
876
+ table: relationIdentitySchema
877
+ }),
878
+ kind: Schema.Literal("column")
879
+ }), Schema.Struct({
880
+ identity: relationIdentitySchema,
881
+ kind: Schema.Literal("relation")
882
+ })]))
883
+ });
884
+ const diagnostics = Schema.Array(codegenDiagnosticSchema);
885
+ const taggedCodegenError = Schema.Struct({
886
+ _tag: Schema.Literal("CodegenError"),
887
+ code: identifier,
888
+ diagnostics: Schema.optionalKey(diagnostics),
889
+ message: Schema.String,
890
+ path: Schema.optionalKey(Schema.String)
891
+ });
892
+ const artifactPathSchema = Schema.String.check(Schema.makeFilter((path) => !path.includes("\\") && !path.includes(":") && !path.includes("\0") && path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".."), { expected: "a slash-separated relative file path without traversal" }));
893
+ const artifact = Schema.Struct({
894
+ content: Schema.String,
895
+ path: artifactPathSchema
896
+ });
897
+ const generationResult = Schema.Struct({
898
+ artifacts: Schema.Array(artifact),
899
+ diagnostics
900
+ });
901
+ const mappingResult = Schema.Struct({
902
+ diagnostics,
903
+ schema: Schema.Unknown
904
+ });
905
+ const wrapError = (cause, code, path, fallback) => {
906
+ if (cause instanceof CodegenError) return cause;
907
+ const details = Schema.decodeUnknownOption(taggedCodegenError)(cause);
908
+ if (Option.isSome(details)) {
909
+ const { _tag, ...fields } = details.value;
910
+ return new CodegenError({
911
+ ...fields,
912
+ cause
913
+ });
914
+ }
915
+ return new CodegenError({
916
+ cause,
917
+ code,
918
+ message: cause instanceof Error ? cause.message : fallback,
919
+ path
920
+ });
921
+ };
922
+ const validate = (decode, code, path) => Effect.try({
923
+ catch: (cause) => wrapError(cause, code, path, "Invalid codegen value"),
924
+ try: decode
925
+ });
926
+ /** Check the exact application contract ID and an explicitly accepted version. */
927
+ const validateApplicationCompatibility = (output, input) => Effect.gen(function* () {
928
+ const contract = yield* validate(() => Schema.decodeUnknownSync(applicationContract)(output), "invalid-contract", "output");
929
+ const accepted = yield* validate(() => Schema.decodeUnknownSync(generatorInput)(input), "invalid-contract", "input");
930
+ if (contract.id !== accepted.id || !accepted.versions.includes(contract.version)) return yield* new CodegenError({
931
+ code: "incompatible-contract",
932
+ message: `Received application contract ${contract.id}@${contract.version}. Expected ${accepted.id} at one of versions ${accepted.versions.join(", ")}.`,
933
+ path: "input"
934
+ });
935
+ return contract;
936
+ });
937
+ /** Validate the text artifact and diagnostic envelopes before handing results to a consumer. */
938
+ const decodeGenerationResult = (value) => validate(() => Schema.decodeUnknownSync(generationResult)(value), "invalid-result", "generation");
939
+ const readExport = (value, kind) => {
940
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`Expected a ${kind} plugin object`);
941
+ return value;
942
+ };
943
+ const method = (plugin, name) => {
944
+ const callback = plugin[name];
945
+ if (typeof callback !== "function") throw new CodegenError({
946
+ code: "invalid-plugin",
947
+ message: `Plugin requires a ${name}() method`,
948
+ path: name
949
+ });
950
+ return (...args) => Reflect.apply(callback, plugin, args);
951
+ };
952
+ const invoke = (callback, code, path) => Effect.flatMap(validate(() => {
953
+ const result = callback();
954
+ if (!Effect.isEffect(result)) throw new CodegenError({
955
+ code: "invalid-plugin",
956
+ message: `${path}() must return an Effect`,
957
+ path
958
+ });
959
+ return result;
960
+ }, "invalid-plugin", path), (effect) => Effect.mapError(effect, (cause) => wrapError(cause, code, path, `Plugin ${path}() failed`)));
961
+ /** Validate the mapper value selected from a module by the consumer. */
962
+ const decodeMapperPlugin = (value) => validate(() => {
963
+ const plugin = readExport(value, "mapper");
964
+ const descriptor = Schema.decodeUnknownSync(mapperDescriptor)(plugin.descriptor);
965
+ const decodeInput = method(plugin, "decodeInput");
966
+ const decodeOptions = method(plugin, "decodeOptions");
967
+ const map = method(plugin, "map");
968
+ return {
969
+ descriptor,
970
+ map: (schema, options) => Effect.gen(function* () {
971
+ const input = yield* invoke(() => decodeInput(schema), "invalid-input", "decodeInput");
972
+ const settings = yield* invoke(() => decodeOptions(options), "invalid-options", "decodeOptions");
973
+ const result = yield* invoke(() => map(input, settings), "mapping-failed", "map");
974
+ return yield* validate(() => Schema.decodeUnknownSync(mappingResult)(result), "invalid-result", "mapping");
975
+ })
976
+ };
977
+ }, "invalid-plugin", "mapper");
978
+ /** Validate the generator value selected from a module by the consumer. */
979
+ const decodeGeneratorPlugin = (value) => validate(() => {
980
+ const plugin = readExport(value, "generator");
981
+ const descriptor = Schema.decodeUnknownSync(generatorDescriptor)(plugin.descriptor);
982
+ const decodeInput = method(plugin, "decodeInput");
983
+ const decodeOptions = method(plugin, "decodeOptions");
984
+ const generate = method(plugin, "generate");
985
+ return {
986
+ descriptor,
987
+ generate: (contract, schema, options) => Effect.gen(function* () {
988
+ const compatible = yield* validateApplicationCompatibility(contract, descriptor.input);
989
+ const input = yield* invoke(() => decodeInput(schema, compatible), "invalid-input", "decodeInput");
990
+ const settings = yield* invoke(() => decodeOptions(options), "invalid-options", "decodeOptions");
991
+ const result = yield* invoke(() => generate(input, settings), "generation-failed", "generate");
992
+ return yield* decodeGenerationResult(result);
993
+ })
994
+ };
995
+ }, "invalid-plugin", "generator");
996
+ export { CodegenError, MigrationDecisionError, SchemaDiffError, SchemaModelError, artifactPathSchema, codegenDiagnosticSchema, compareTable, continuesRun, decodeDatabaseSchema, decodeGenerationResult, decodeGeneratorPlugin, decodeMapperPlugin, definitions, diffDatabases, generatedFileHeader, mergeMigrationDecisions, migrationRun, namespaceKey, namespaceOf, nextMigration, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, referenceAt, relationIdentitySchema, resolveMigrationDecisions, schemaValueEqual, tableKey, validateApplicationCompatibility, validateDatabase };
package/package.json CHANGED
@@ -1,6 +1,11 @@
1
1
  {
2
2
  "name": "@uncutsql/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/cahnory/uncutsql.git",
7
+ "directory": "libs/core"
8
+ },
4
9
  "files": [
5
10
  "dist"
6
11
  ],