@uncutsql/core 0.4.0 → 0.5.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.cjs CHANGED
@@ -1322,6 +1322,54 @@ function swap(value) {
1322
1322
  before: value.after
1323
1323
  };
1324
1324
  }
1325
+ // src/dialect.ts
1326
+ var StatementEditError = class extends effect.Data.TaggedError("StatementEditError") {};
1327
+ // src/structure.ts
1328
+ const changesOf = (before, after, keyOf) => {
1329
+ const known = new Map((before ?? []).map((item) => [keyOf(item), item]));
1330
+ return (after ?? []).flatMap((external) => {
1331
+ const key = keyOf(external);
1332
+ const old = known.get(key);
1333
+ if (old !== void 0 && schemaValueEqual(old, external)) return [];
1334
+ return [{
1335
+ change: old === void 0 ? "new" : "changed",
1336
+ external,
1337
+ key
1338
+ }];
1339
+ });
1340
+ };
1341
+ /**
1342
+ * The externals that are new or changed from `before` to `after`: enums, extensions, functions,
1343
+ * then tables, each in the order of `after`. An external is changed when its declaration is not
1344
+ * structurally equal. Removed externals are not listed.
1345
+ */
1346
+ const changedExternals = (before, after) => [
1347
+ ...changesOf(before?.enums, after?.enums, (item) => tableKey(item.identity)).map((item) => ({
1348
+ ...item,
1349
+ kind: "enum"
1350
+ })),
1351
+ ...changesOf(before?.extensions, after?.extensions, (item) => item.name).map((item) => ({
1352
+ ...item,
1353
+ kind: "extension"
1354
+ })),
1355
+ ...changesOf(before?.functions, after?.functions, functionKey).map((item) => ({
1356
+ ...item,
1357
+ kind: "function"
1358
+ })),
1359
+ ...changesOf(before?.tables, after?.tables, (item) => tableKey(item.identity)).map((item) => ({
1360
+ ...item,
1361
+ kind: "table"
1362
+ }))
1363
+ ];
1364
+ /**
1365
+ * Structural comparison of two models (ADR 0036 Decision 5): `diffDatabases` after the
1366
+ * dialect's `normalizeSchema`, applied to both sides, or the identity when absent. The two
1367
+ * structures are equal when the result has no change.
1368
+ */
1369
+ const diffStructures = (dialect, a, b) => {
1370
+ const normal = (schema) => dialect.normalizeSchema?.(schema) ?? effect.Effect.succeed(schema);
1371
+ return effect.Effect.flatMap(effect.Effect.all([normal(a), normal(b)]), ([before, after]) => diffDatabases(before, after));
1372
+ };
1325
1373
  // src/decode.ts
1326
1374
  var SchemaModelError = class extends effect.Data.TaggedError("SchemaModelError") {};
1327
1375
  const fail = (path, expected) => {
@@ -2202,7 +2250,9 @@ exports.CodegenError = CodegenError;
2202
2250
  exports.MigrationDecisionError = MigrationDecisionError;
2203
2251
  exports.SchemaDiffError = SchemaDiffError;
2204
2252
  exports.SchemaModelError = SchemaModelError;
2253
+ exports.StatementEditError = StatementEditError;
2205
2254
  exports.artifactPathSchema = artifactPathSchema;
2255
+ exports.changedExternals = changedExternals;
2206
2256
  exports.checkManagedScope = checkManagedScope;
2207
2257
  exports.codegenDiagnosticSchema = codegenDiagnosticSchema;
2208
2258
  exports.commentObjects = commentObjects;
@@ -2221,6 +2271,7 @@ exports.diffDatabases = diffDatabases;
2221
2271
  exports.diffEnums = diffEnums;
2222
2272
  exports.diffFunctions = diffFunctions;
2223
2273
  exports.diffSequences = diffSequences;
2274
+ exports.diffStructures = diffStructures;
2224
2275
  exports.diffTriggers = diffTriggers;
2225
2276
  exports.enumObjects = enumObjects;
2226
2277
  exports.extensionObjects = extensionObjects;
package/dist/index.d.cts CHANGED
@@ -276,12 +276,29 @@ export declare const namespaceKey: (namespace: NamespaceIdentity) => string;
276
276
  export declare const namespaceOf: (identity: TableIdentity) => NamespaceIdentity | undefined;
277
277
  /** Object property insertion order is not semantic; array order is retained. */
278
278
  export declare const schemaValueEqual: (before: SchemaValue, after: SchemaValue) => boolean;
279
+ /** A table or other relation by catalog names, or one of its columns. */
280
+ export interface MissingObject {
281
+ readonly column?: string;
282
+ readonly table: TableIdentity;
283
+ }
279
284
  export interface DiffDiagnostic {
280
285
  /** Dialect adapters may contribute their own validation codes. */
281
286
  readonly code: string;
282
287
  readonly column?: string;
288
+ /**
289
+ * 0-based index of the failing statement's document in the parts given to
290
+ * `Dialect.combineSchemas`; absent for one document.
291
+ */
292
+ readonly document?: number;
283
293
  readonly message: string;
294
+ /**
295
+ * The object an `Undeclared<Kind>` diagnostic misses, when `table` and `column` do not name it
296
+ * (the statement refers to it from another object). Set and read by the dialect.
297
+ */
298
+ readonly missing?: MissingObject;
284
299
  readonly side: "before" | "after";
300
+ /** 0-based index of the failing statement in its document. */
301
+ readonly statement?: number;
285
302
  readonly table: TableIdentity;
286
303
  }
287
304
  declare const SchemaDiffError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
@@ -735,16 +752,63 @@ interface SemanticSchemaResolution {
735
752
  readonly diagnostics: readonly SemanticDiagnostic[];
736
753
  readonly schema: SemanticDatabaseSchema;
737
754
  }
755
+ /** One change of one statement of a source (ADR 0037 Decision 3). */
756
+ type StatementEdit = {
757
+ readonly action: "skip";
758
+ /** 0-based index of the statement in the source, as `DiffDiagnostic.statement`. */
759
+ readonly statement: number;
760
+ } | {
761
+ readonly action: "retarget";
762
+ /** The `Undeclared<Kind>` failure of the statement, as `toDatabaseSchema` reported it. */
763
+ readonly diagnostic: DiffDiagnostic;
764
+ readonly statement: number;
765
+ /** The name of an existing object of the same kind and owner, written as the dialect's SQL. */
766
+ readonly target: string;
767
+ };
768
+ declare const StatementEditError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
769
+ readonly _tag: "StatementEditError";
770
+ } & Readonly<A>;
771
+ export declare class StatementEditError extends StatementEditError_base<{
772
+ readonly message: string;
773
+ readonly reason: "DuplicateEdit" | "InvalidTarget" | "OutOfRange" | "UnsupportedRetarget";
774
+ /** The index the refused edit gave. */
775
+ readonly statement: number;
776
+ }> {}
777
+ /**
778
+ * What a statement resolved against externals (ADR 0038 Decision 1), told to the
779
+ * `onExternalUse` option of `Dialect.toDatabaseSchema`.
780
+ */
781
+ interface ExternalUse {
782
+ /** Index of the document in a combined schema, as in `DiffDiagnostic`. */
783
+ readonly document?: number;
784
+ /** The part used: a table with only the used columns and keys, a function, an enum or an extension. */
785
+ readonly externals: DatabaseExternals;
786
+ readonly statement: number;
787
+ }
738
788
  /** Dialect capabilities. The caller owns comparison and logical planning. */
739
789
  interface Dialect<Ast, PhysicalPlan, E extends Error = Error, R = never, SemanticError extends Error = E, SemanticServices = R> {
740
790
  /** Combine independently parsed schema documents in source order. */
741
791
  readonly combineSchemas?: (parts: readonly Ast[]) => Ast;
792
+ /**
793
+ * Applies edits to the statements of one source, through the dialect's own parser and codecs,
794
+ * and returns the source with every character outside the edited statements unchanged.
795
+ * `skip` removes the statement and its terminator; `retarget` rewrites, in that statement only,
796
+ * the names that denote the missing object, and writes the statement in its encoded form. The
797
+ * result is not replayed. Absent when the dialect cannot edit statements yet.
798
+ */
799
+ readonly editStatements?: (source: string, edits: readonly StatementEdit[]) => Effect.Effect<string, E | StatementEditError, R>;
742
800
  /** The model of an empty database, used as the migration baseline before the first migration. Defaults to `{ tables: [] }`. */
743
801
  readonly emptyDatabaseSchema?: DatabaseSchema;
744
802
  readonly encodeMigration: (plan: PhysicalPlan) => Effect.Effect<string, E, R>;
745
803
  readonly format: (ast: Ast) => Effect.Effect<string, E, R>;
746
804
  readonly lowerMigration: (migration: DatabaseMigration, before: DatabaseSchema, after: DatabaseSchema) => Effect.Effect<PhysicalPlan, E, R>;
747
805
  readonly name: string;
806
+ /**
807
+ * The normal form used to compare structures (`diffStructures`). It folds only distinctions
808
+ * the engine does not store: the column or table form of a constraint, an omitted constraint
809
+ * name versus the name the engine derives, and constraint order. Identity when absent.
810
+ */
811
+ readonly normalizeSchema?: (schema: DatabaseSchema) => Effect.Effect<DatabaseSchema, E, R>;
748
812
  readonly parse: (source: string) => Effect.Effect<Ast, E, R>;
749
813
  /** Derive semantic facts from a structural schema, including decoded snapshots. */
750
814
  readonly resolveSemanticSchema?: (schema: DatabaseSchema) => Effect.Effect<SemanticSchemaResolution, SemanticError, SemanticServices>;
@@ -755,13 +819,58 @@ interface Dialect<Ast, PhysicalPlan, E extends Error = Error, R = never, Semanti
755
819
  * `false`, a migration with guards is refused before lowering.
756
820
  */
757
821
  readonly supportsDropGuards?: boolean;
822
+ /**
823
+ * When `true`, `toDatabaseSchema` honors `options.externals`: externals declared elsewhere count
824
+ * as declared before the first statement, one is hidden while the structure manages it, and
825
+ * none causes a diagnostic by existing (ADR 0036 amendment A2). When absent or `false`, the
826
+ * options are ignored.
827
+ *
828
+ * `options.onExternalUse` is honored only when this is `true`: it is told what references
829
+ * resolved against externals, seeded or declared in the document, with that declaration's shape.
830
+ * It reports on the same conversion, whose result and diagnostics do not depend on it (ADR 0038
831
+ * Decision 1).
832
+ */
833
+ readonly supportsExternals?: boolean;
758
834
  /**
759
835
  * When `true`, a project may list the schemas it manages (ADR 0024 Decision 1). When absent or
760
836
  * `false`, the caller refuses such a list by name.
761
837
  */
762
838
  readonly supportsManagedSchemas?: boolean;
763
- readonly toDatabaseSchema: (ast: Ast, side?: DiffDiagnostic["side"]) => Effect.Effect<DatabaseSchema, E, R>;
764
- }
839
+ readonly toDatabaseSchema: (ast: Ast, side?: DiffDiagnostic["side"], options?: {
840
+ readonly externals?: DatabaseExternals;
841
+ readonly onExternalUse?: (use: ExternalUse) => void;
842
+ }) => Effect.Effect<DatabaseSchema, E, R>;
843
+ }
844
+ /** An external of `after` that `before` lacks (`new`) or declares differently (`changed`). */
845
+ type ExternalChange = {
846
+ readonly change: "changed" | "new";
847
+ /** The key the model identifies the external by: its name for an extension. */
848
+ readonly key: string;
849
+ } & ({
850
+ readonly external: DatabaseEnum;
851
+ readonly kind: "enum";
852
+ } | {
853
+ readonly external: DatabaseExtension;
854
+ readonly kind: "extension";
855
+ } | {
856
+ readonly external: DatabaseFunction;
857
+ readonly kind: "function";
858
+ } | {
859
+ readonly external: DatabaseTable;
860
+ readonly kind: "table";
861
+ });
862
+ /**
863
+ * The externals that are new or changed from `before` to `after`: enums, extensions, functions,
864
+ * then tables, each in the order of `after`. An external is changed when its declaration is not
865
+ * structurally equal. Removed externals are not listed.
866
+ */
867
+ export declare const changedExternals: (before: DatabaseExternals | undefined, after: DatabaseExternals | undefined) => readonly ExternalChange[];
868
+ /**
869
+ * Structural comparison of two models (ADR 0036 Decision 5): `diffDatabases` after the
870
+ * dialect's `normalizeSchema`, applied to both sides, or the identity when absent. The two
871
+ * structures are equal when the result has no change.
872
+ */
873
+ export declare const diffStructures: <E extends Error, R>(dialect: Pick<Dialect<unknown, unknown, E, R>, "normalizeSchema">, a: DatabaseSchema, b: DatabaseSchema) => Effect.Effect<DatabaseDiff, E | SchemaDiffError, R>;
765
874
  declare const SchemaModelError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
766
875
  readonly _tag: "SchemaModelError";
767
876
  } & Readonly<A>;
@@ -775,10 +884,14 @@ interface MigrationSource {
775
884
  /** A root baseline records the original prefix tip as the logical checkpoint. */
776
885
  readonly baselineCheckpoint?: string;
777
886
  readonly down?: {
887
+ /** What the down SQL relies on (ADR 0038 Decision 2). */
888
+ readonly externals?: DatabaseExternals;
778
889
  readonly sql: string;
779
890
  } | {
780
891
  readonly reason: string;
781
892
  };
893
+ /** What the up SQL relies on (ADR 0038 Decision 2). */
894
+ readonly externals?: DatabaseExternals;
782
895
  readonly id: number;
783
896
  readonly sha256: string;
784
897
  /** The whole migration file, including the CLI's `-- ` header lines. */
@@ -799,6 +912,10 @@ interface ReplayOptions {
799
912
  /** A database to replay in instead of the driver's default; nothing is kept in it. */
800
913
  readonly replayDatabase?: string;
801
914
  }
915
+ interface ExecutionOptions {
916
+ /** Told, at most once per call, that the call is waiting for the migration lock. */
917
+ readonly onLockWait?: (message: string) => Effect.Effect<void>;
918
+ }
802
919
  interface ExtractOptions {
803
920
  /** ADR 0024 managed schemas. Set only when configured and the dialect supports them. */
804
921
  readonly managedSchemas?: readonly string[];
@@ -835,8 +952,8 @@ interface MigrationExecutor<E extends Error = Error, R = never> {
835
952
  readonly apply: <V extends Error, RV>(target: string, migrations: readonly MigrationSource[], desired: DatabaseSchema, verifySchema: (actual: DatabaseSchema, expected: DatabaseSchema, stage: "applied" | "desired") => Effect.Effect<void, V, RV>,
836
953
  /** With a checkpoint, files start immediately after it (at it for rollback).
837
954
  * Recheck the database position under the write transaction before executing. */
838
- checkpoint?: MigrationCheckpoint) => Effect.Effect<ExecutionResult, E | V, R | RV>;
839
- readonly checkpoint: (target: string) => Effect.Effect<MigrationCheckpoint, E, R>;
955
+ checkpoint?: MigrationCheckpoint, options?: ExecutionOptions) => Effect.Effect<ExecutionResult, E | V, R | RV>;
956
+ readonly checkpoint: (target: string, options?: ExecutionOptions) => Effect.Effect<MigrationCheckpoint, E, R>;
840
957
  /** Replay a verified prefix on an empty database and render its state as one SQL migration. */
841
958
  readonly compact?: (migrations: readonly MigrationSource[], options?: ReplayOptions) => Effect.Effect<string, E, R>;
842
959
  /** Equal to the `Dialect.name` that produced the lock. Core and the CLI compare it only for equality. */
@@ -1000,7 +1117,11 @@ export interface SchemaCandidate {
1000
1117
  readonly text: string;
1001
1118
  }
1002
1119
  export interface LanguageService {
1003
- /** Analyzes one document. Synchronous and total: it never throws, and a parse failure is a diagnostic. */
1120
+ /**
1121
+ * Analyzes one document. Synchronous and total: it never throws. Each diagnostic is either a
1122
+ * parse failure or a statement whose precondition fails (it cannot apply). Either kind means the
1123
+ * document has errors, which suspends project checks.
1124
+ */
1004
1125
  readonly analyze: (source: string) => SchemaAnalysis;
1005
1126
  /** The completion context at `offset`. Pure, synchronous and total; `undefined` where no site is known. */
1006
1127
  readonly complete?: (source: string, offset: number) => SchemaCompletion | undefined;
@@ -1138,4 +1259,4 @@ interface DynamicGeneratorPlugin {
1138
1259
  export declare const decodeMapperPlugin: (value: unknown) => Effect.Effect<DynamicMapperPlugin, CodegenError>;
1139
1260
  /** Validate the generator value selected from a module by the consumer. */
1140
1261
  export declare const decodeGeneratorPlugin: (value: unknown) => Effect.Effect<DynamicGeneratorPlugin, CodegenError>;
1141
- export type { ApplicationContract, ApplicationMapper, CodegenDiagnostic, ColumnIdentity, Dialect, DynamicGeneratorPlugin, DynamicMapperPlugin, ExecutionResult, ExtractOmission, ExtractOptions, ExtractResult, ExtractedPart, GeneratedFile, GenerationResult, Generator, GeneratorDescriptor, GeneratorPlugin, MapperDescriptor, MapperPlugin, MappingResult, MigrationCheckpoint, MigrationExecutor, MigrationRun, MigrationSource, ReplayOptions, SemanticColumn, SemanticColumnType, SemanticDatabaseSchema, SemanticDiagnostic, SemanticDiagnosticSubject, SemanticElement, SemanticFact, SemanticForeignKey, SemanticForeignKeyTarget, SemanticInsertPolicy, SemanticKey, SemanticRelation, SemanticSchemaResolution, SemanticStructField, SemanticValueDomain, SemanticWritePolicy };
1262
+ export type { ApplicationContract, ApplicationMapper, CodegenDiagnostic, ColumnIdentity, Dialect, DynamicGeneratorPlugin, DynamicMapperPlugin, ExecutionOptions, ExecutionResult, ExternalChange, ExternalUse, ExtractOmission, ExtractOptions, ExtractResult, ExtractedPart, GeneratedFile, GenerationResult, Generator, GeneratorDescriptor, GeneratorPlugin, MapperDescriptor, MapperPlugin, MappingResult, MigrationCheckpoint, MigrationExecutor, MigrationRun, MigrationSource, ReplayOptions, SemanticColumn, SemanticColumnType, SemanticDatabaseSchema, SemanticDiagnostic, SemanticDiagnosticSubject, SemanticElement, SemanticFact, SemanticForeignKey, SemanticForeignKeyTarget, SemanticInsertPolicy, SemanticKey, SemanticRelation, SemanticSchemaResolution, SemanticStructField, SemanticValueDomain, SemanticWritePolicy, StatementEdit };
package/dist/index.d.ts CHANGED
@@ -276,12 +276,29 @@ export declare const namespaceKey: (namespace: NamespaceIdentity) => string;
276
276
  export declare const namespaceOf: (identity: TableIdentity) => NamespaceIdentity | undefined;
277
277
  /** Object property insertion order is not semantic; array order is retained. */
278
278
  export declare const schemaValueEqual: (before: SchemaValue, after: SchemaValue) => boolean;
279
+ /** A table or other relation by catalog names, or one of its columns. */
280
+ export interface MissingObject {
281
+ readonly column?: string;
282
+ readonly table: TableIdentity;
283
+ }
279
284
  export interface DiffDiagnostic {
280
285
  /** Dialect adapters may contribute their own validation codes. */
281
286
  readonly code: string;
282
287
  readonly column?: string;
288
+ /**
289
+ * 0-based index of the failing statement's document in the parts given to
290
+ * `Dialect.combineSchemas`; absent for one document.
291
+ */
292
+ readonly document?: number;
283
293
  readonly message: string;
294
+ /**
295
+ * The object an `Undeclared<Kind>` diagnostic misses, when `table` and `column` do not name it
296
+ * (the statement refers to it from another object). Set and read by the dialect.
297
+ */
298
+ readonly missing?: MissingObject;
284
299
  readonly side: "before" | "after";
300
+ /** 0-based index of the failing statement in its document. */
301
+ readonly statement?: number;
285
302
  readonly table: TableIdentity;
286
303
  }
287
304
  declare const SchemaDiffError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
@@ -735,16 +752,63 @@ interface SemanticSchemaResolution {
735
752
  readonly diagnostics: readonly SemanticDiagnostic[];
736
753
  readonly schema: SemanticDatabaseSchema;
737
754
  }
755
+ /** One change of one statement of a source (ADR 0037 Decision 3). */
756
+ type StatementEdit = {
757
+ readonly action: "skip";
758
+ /** 0-based index of the statement in the source, as `DiffDiagnostic.statement`. */
759
+ readonly statement: number;
760
+ } | {
761
+ readonly action: "retarget";
762
+ /** The `Undeclared<Kind>` failure of the statement, as `toDatabaseSchema` reported it. */
763
+ readonly diagnostic: DiffDiagnostic;
764
+ readonly statement: number;
765
+ /** The name of an existing object of the same kind and owner, written as the dialect's SQL. */
766
+ readonly target: string;
767
+ };
768
+ declare const StatementEditError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
769
+ readonly _tag: "StatementEditError";
770
+ } & Readonly<A>;
771
+ export declare class StatementEditError extends StatementEditError_base<{
772
+ readonly message: string;
773
+ readonly reason: "DuplicateEdit" | "InvalidTarget" | "OutOfRange" | "UnsupportedRetarget";
774
+ /** The index the refused edit gave. */
775
+ readonly statement: number;
776
+ }> {}
777
+ /**
778
+ * What a statement resolved against externals (ADR 0038 Decision 1), told to the
779
+ * `onExternalUse` option of `Dialect.toDatabaseSchema`.
780
+ */
781
+ interface ExternalUse {
782
+ /** Index of the document in a combined schema, as in `DiffDiagnostic`. */
783
+ readonly document?: number;
784
+ /** The part used: a table with only the used columns and keys, a function, an enum or an extension. */
785
+ readonly externals: DatabaseExternals;
786
+ readonly statement: number;
787
+ }
738
788
  /** Dialect capabilities. The caller owns comparison and logical planning. */
739
789
  interface Dialect<Ast, PhysicalPlan, E extends Error = Error, R = never, SemanticError extends Error = E, SemanticServices = R> {
740
790
  /** Combine independently parsed schema documents in source order. */
741
791
  readonly combineSchemas?: (parts: readonly Ast[]) => Ast;
792
+ /**
793
+ * Applies edits to the statements of one source, through the dialect's own parser and codecs,
794
+ * and returns the source with every character outside the edited statements unchanged.
795
+ * `skip` removes the statement and its terminator; `retarget` rewrites, in that statement only,
796
+ * the names that denote the missing object, and writes the statement in its encoded form. The
797
+ * result is not replayed. Absent when the dialect cannot edit statements yet.
798
+ */
799
+ readonly editStatements?: (source: string, edits: readonly StatementEdit[]) => Effect.Effect<string, E | StatementEditError, R>;
742
800
  /** The model of an empty database, used as the migration baseline before the first migration. Defaults to `{ tables: [] }`. */
743
801
  readonly emptyDatabaseSchema?: DatabaseSchema;
744
802
  readonly encodeMigration: (plan: PhysicalPlan) => Effect.Effect<string, E, R>;
745
803
  readonly format: (ast: Ast) => Effect.Effect<string, E, R>;
746
804
  readonly lowerMigration: (migration: DatabaseMigration, before: DatabaseSchema, after: DatabaseSchema) => Effect.Effect<PhysicalPlan, E, R>;
747
805
  readonly name: string;
806
+ /**
807
+ * The normal form used to compare structures (`diffStructures`). It folds only distinctions
808
+ * the engine does not store: the column or table form of a constraint, an omitted constraint
809
+ * name versus the name the engine derives, and constraint order. Identity when absent.
810
+ */
811
+ readonly normalizeSchema?: (schema: DatabaseSchema) => Effect.Effect<DatabaseSchema, E, R>;
748
812
  readonly parse: (source: string) => Effect.Effect<Ast, E, R>;
749
813
  /** Derive semantic facts from a structural schema, including decoded snapshots. */
750
814
  readonly resolveSemanticSchema?: (schema: DatabaseSchema) => Effect.Effect<SemanticSchemaResolution, SemanticError, SemanticServices>;
@@ -755,13 +819,58 @@ interface Dialect<Ast, PhysicalPlan, E extends Error = Error, R = never, Semanti
755
819
  * `false`, a migration with guards is refused before lowering.
756
820
  */
757
821
  readonly supportsDropGuards?: boolean;
822
+ /**
823
+ * When `true`, `toDatabaseSchema` honors `options.externals`: externals declared elsewhere count
824
+ * as declared before the first statement, one is hidden while the structure manages it, and
825
+ * none causes a diagnostic by existing (ADR 0036 amendment A2). When absent or `false`, the
826
+ * options are ignored.
827
+ *
828
+ * `options.onExternalUse` is honored only when this is `true`: it is told what references
829
+ * resolved against externals, seeded or declared in the document, with that declaration's shape.
830
+ * It reports on the same conversion, whose result and diagnostics do not depend on it (ADR 0038
831
+ * Decision 1).
832
+ */
833
+ readonly supportsExternals?: boolean;
758
834
  /**
759
835
  * When `true`, a project may list the schemas it manages (ADR 0024 Decision 1). When absent or
760
836
  * `false`, the caller refuses such a list by name.
761
837
  */
762
838
  readonly supportsManagedSchemas?: boolean;
763
- readonly toDatabaseSchema: (ast: Ast, side?: DiffDiagnostic["side"]) => Effect.Effect<DatabaseSchema, E, R>;
764
- }
839
+ readonly toDatabaseSchema: (ast: Ast, side?: DiffDiagnostic["side"], options?: {
840
+ readonly externals?: DatabaseExternals;
841
+ readonly onExternalUse?: (use: ExternalUse) => void;
842
+ }) => Effect.Effect<DatabaseSchema, E, R>;
843
+ }
844
+ /** An external of `after` that `before` lacks (`new`) or declares differently (`changed`). */
845
+ type ExternalChange = {
846
+ readonly change: "changed" | "new";
847
+ /** The key the model identifies the external by: its name for an extension. */
848
+ readonly key: string;
849
+ } & ({
850
+ readonly external: DatabaseEnum;
851
+ readonly kind: "enum";
852
+ } | {
853
+ readonly external: DatabaseExtension;
854
+ readonly kind: "extension";
855
+ } | {
856
+ readonly external: DatabaseFunction;
857
+ readonly kind: "function";
858
+ } | {
859
+ readonly external: DatabaseTable;
860
+ readonly kind: "table";
861
+ });
862
+ /**
863
+ * The externals that are new or changed from `before` to `after`: enums, extensions, functions,
864
+ * then tables, each in the order of `after`. An external is changed when its declaration is not
865
+ * structurally equal. Removed externals are not listed.
866
+ */
867
+ export declare const changedExternals: (before: DatabaseExternals | undefined, after: DatabaseExternals | undefined) => readonly ExternalChange[];
868
+ /**
869
+ * Structural comparison of two models (ADR 0036 Decision 5): `diffDatabases` after the
870
+ * dialect's `normalizeSchema`, applied to both sides, or the identity when absent. The two
871
+ * structures are equal when the result has no change.
872
+ */
873
+ export declare const diffStructures: <E extends Error, R>(dialect: Pick<Dialect<unknown, unknown, E, R>, "normalizeSchema">, a: DatabaseSchema, b: DatabaseSchema) => Effect.Effect<DatabaseDiff, E | SchemaDiffError, R>;
765
874
  declare const SchemaModelError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
766
875
  readonly _tag: "SchemaModelError";
767
876
  } & Readonly<A>;
@@ -775,10 +884,14 @@ interface MigrationSource {
775
884
  /** A root baseline records the original prefix tip as the logical checkpoint. */
776
885
  readonly baselineCheckpoint?: string;
777
886
  readonly down?: {
887
+ /** What the down SQL relies on (ADR 0038 Decision 2). */
888
+ readonly externals?: DatabaseExternals;
778
889
  readonly sql: string;
779
890
  } | {
780
891
  readonly reason: string;
781
892
  };
893
+ /** What the up SQL relies on (ADR 0038 Decision 2). */
894
+ readonly externals?: DatabaseExternals;
782
895
  readonly id: number;
783
896
  readonly sha256: string;
784
897
  /** The whole migration file, including the CLI's `-- ` header lines. */
@@ -799,6 +912,10 @@ interface ReplayOptions {
799
912
  /** A database to replay in instead of the driver's default; nothing is kept in it. */
800
913
  readonly replayDatabase?: string;
801
914
  }
915
+ interface ExecutionOptions {
916
+ /** Told, at most once per call, that the call is waiting for the migration lock. */
917
+ readonly onLockWait?: (message: string) => Effect.Effect<void>;
918
+ }
802
919
  interface ExtractOptions {
803
920
  /** ADR 0024 managed schemas. Set only when configured and the dialect supports them. */
804
921
  readonly managedSchemas?: readonly string[];
@@ -835,8 +952,8 @@ interface MigrationExecutor<E extends Error = Error, R = never> {
835
952
  readonly apply: <V extends Error, RV>(target: string, migrations: readonly MigrationSource[], desired: DatabaseSchema, verifySchema: (actual: DatabaseSchema, expected: DatabaseSchema, stage: "applied" | "desired") => Effect.Effect<void, V, RV>,
836
953
  /** With a checkpoint, files start immediately after it (at it for rollback).
837
954
  * Recheck the database position under the write transaction before executing. */
838
- checkpoint?: MigrationCheckpoint) => Effect.Effect<ExecutionResult, E | V, R | RV>;
839
- readonly checkpoint: (target: string) => Effect.Effect<MigrationCheckpoint, E, R>;
955
+ checkpoint?: MigrationCheckpoint, options?: ExecutionOptions) => Effect.Effect<ExecutionResult, E | V, R | RV>;
956
+ readonly checkpoint: (target: string, options?: ExecutionOptions) => Effect.Effect<MigrationCheckpoint, E, R>;
840
957
  /** Replay a verified prefix on an empty database and render its state as one SQL migration. */
841
958
  readonly compact?: (migrations: readonly MigrationSource[], options?: ReplayOptions) => Effect.Effect<string, E, R>;
842
959
  /** Equal to the `Dialect.name` that produced the lock. Core and the CLI compare it only for equality. */
@@ -1000,7 +1117,11 @@ export interface SchemaCandidate {
1000
1117
  readonly text: string;
1001
1118
  }
1002
1119
  export interface LanguageService {
1003
- /** Analyzes one document. Synchronous and total: it never throws, and a parse failure is a diagnostic. */
1120
+ /**
1121
+ * Analyzes one document. Synchronous and total: it never throws. Each diagnostic is either a
1122
+ * parse failure or a statement whose precondition fails (it cannot apply). Either kind means the
1123
+ * document has errors, which suspends project checks.
1124
+ */
1004
1125
  readonly analyze: (source: string) => SchemaAnalysis;
1005
1126
  /** The completion context at `offset`. Pure, synchronous and total; `undefined` where no site is known. */
1006
1127
  readonly complete?: (source: string, offset: number) => SchemaCompletion | undefined;
@@ -1138,4 +1259,4 @@ interface DynamicGeneratorPlugin {
1138
1259
  export declare const decodeMapperPlugin: (value: unknown) => Effect.Effect<DynamicMapperPlugin, CodegenError>;
1139
1260
  /** Validate the generator value selected from a module by the consumer. */
1140
1261
  export declare const decodeGeneratorPlugin: (value: unknown) => Effect.Effect<DynamicGeneratorPlugin, CodegenError>;
1141
- export type { ApplicationContract, ApplicationMapper, CodegenDiagnostic, ColumnIdentity, Dialect, DynamicGeneratorPlugin, DynamicMapperPlugin, ExecutionResult, ExtractOmission, ExtractOptions, ExtractResult, ExtractedPart, GeneratedFile, GenerationResult, Generator, GeneratorDescriptor, GeneratorPlugin, MapperDescriptor, MapperPlugin, MappingResult, MigrationCheckpoint, MigrationExecutor, MigrationRun, MigrationSource, ReplayOptions, SemanticColumn, SemanticColumnType, SemanticDatabaseSchema, SemanticDiagnostic, SemanticDiagnosticSubject, SemanticElement, SemanticFact, SemanticForeignKey, SemanticForeignKeyTarget, SemanticInsertPolicy, SemanticKey, SemanticRelation, SemanticSchemaResolution, SemanticStructField, SemanticValueDomain, SemanticWritePolicy };
1262
+ export type { ApplicationContract, ApplicationMapper, CodegenDiagnostic, ColumnIdentity, Dialect, DynamicGeneratorPlugin, DynamicMapperPlugin, ExecutionOptions, ExecutionResult, ExternalChange, ExternalUse, ExtractOmission, ExtractOptions, ExtractResult, ExtractedPart, GeneratedFile, GenerationResult, Generator, GeneratorDescriptor, GeneratorPlugin, MapperDescriptor, MapperPlugin, MappingResult, MigrationCheckpoint, MigrationExecutor, MigrationRun, MigrationSource, ReplayOptions, SemanticColumn, SemanticColumnType, SemanticDatabaseSchema, SemanticDiagnostic, SemanticDiagnosticSubject, SemanticElement, SemanticFact, SemanticForeignKey, SemanticForeignKeyTarget, SemanticInsertPolicy, SemanticKey, SemanticRelation, SemanticSchemaResolution, SemanticStructField, SemanticValueDomain, SemanticWritePolicy, StatementEdit };
package/dist/index.js CHANGED
@@ -1321,6 +1321,54 @@ function swap(value) {
1321
1321
  before: value.after
1322
1322
  };
1323
1323
  }
1324
+ // src/dialect.ts
1325
+ var StatementEditError = class extends Data.TaggedError("StatementEditError") {};
1326
+ // src/structure.ts
1327
+ const changesOf = (before, after, keyOf) => {
1328
+ const known = new Map((before ?? []).map((item) => [keyOf(item), item]));
1329
+ return (after ?? []).flatMap((external) => {
1330
+ const key = keyOf(external);
1331
+ const old = known.get(key);
1332
+ if (old !== void 0 && schemaValueEqual(old, external)) return [];
1333
+ return [{
1334
+ change: old === void 0 ? "new" : "changed",
1335
+ external,
1336
+ key
1337
+ }];
1338
+ });
1339
+ };
1340
+ /**
1341
+ * The externals that are new or changed from `before` to `after`: enums, extensions, functions,
1342
+ * then tables, each in the order of `after`. An external is changed when its declaration is not
1343
+ * structurally equal. Removed externals are not listed.
1344
+ */
1345
+ const changedExternals = (before, after) => [
1346
+ ...changesOf(before?.enums, after?.enums, (item) => tableKey(item.identity)).map((item) => ({
1347
+ ...item,
1348
+ kind: "enum"
1349
+ })),
1350
+ ...changesOf(before?.extensions, after?.extensions, (item) => item.name).map((item) => ({
1351
+ ...item,
1352
+ kind: "extension"
1353
+ })),
1354
+ ...changesOf(before?.functions, after?.functions, functionKey).map((item) => ({
1355
+ ...item,
1356
+ kind: "function"
1357
+ })),
1358
+ ...changesOf(before?.tables, after?.tables, (item) => tableKey(item.identity)).map((item) => ({
1359
+ ...item,
1360
+ kind: "table"
1361
+ }))
1362
+ ];
1363
+ /**
1364
+ * Structural comparison of two models (ADR 0036 Decision 5): `diffDatabases` after the
1365
+ * dialect's `normalizeSchema`, applied to both sides, or the identity when absent. The two
1366
+ * structures are equal when the result has no change.
1367
+ */
1368
+ const diffStructures = (dialect, a, b) => {
1369
+ const normal = (schema) => dialect.normalizeSchema?.(schema) ?? Effect.succeed(schema);
1370
+ return Effect.flatMap(Effect.all([normal(a), normal(b)]), ([before, after]) => diffDatabases(before, after));
1371
+ };
1324
1372
  // src/decode.ts
1325
1373
  var SchemaModelError = class extends Data.TaggedError("SchemaModelError") {};
1326
1374
  const fail = (path, expected) => {
@@ -2197,4 +2245,4 @@ const decodeGeneratorPlugin = (value) => validate(() => {
2197
2245
  })
2198
2246
  };
2199
2247
  }, "invalid-plugin", "generator");
2200
- export { CodegenError, MigrationDecisionError, SchemaDiffError, SchemaModelError, artifactPathSchema, checkManagedScope, codegenDiagnosticSchema, commentObjects, compareTable, completionCandidates, constraintsEqual, continuesRun, declarationAt, decodeDatabaseSchema, decodeGenerationResult, decodeGeneratorPlugin, decodeMapperPlugin, definitions, diffComments, diffDatabases, diffEnums, diffFunctions, diffSequences, diffTriggers, enumObjects, extensionObjects, externalObjects, formatExtractOmissions, functionKey, functionLabel, generatedFileHeader, mergeMigrationDecisions, migrationRun, nameSpan, namespaceKey, namespaceOf, nextMigration, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, referenceAt, referencesTo, relationIdentitySchema, renameSiteAt, renameSpans, resolveMigrationDecisions, schemaValueEqual, sequenceRenames, tableKey, triggerKey, validateApplicationCompatibility, validateDatabase };
2248
+ export { CodegenError, MigrationDecisionError, SchemaDiffError, SchemaModelError, StatementEditError, artifactPathSchema, changedExternals, checkManagedScope, codegenDiagnosticSchema, commentObjects, compareTable, completionCandidates, constraintsEqual, continuesRun, declarationAt, decodeDatabaseSchema, decodeGenerationResult, decodeGeneratorPlugin, decodeMapperPlugin, definitions, diffComments, diffDatabases, diffEnums, diffFunctions, diffSequences, diffStructures, diffTriggers, enumObjects, extensionObjects, externalObjects, formatExtractOmissions, functionKey, functionLabel, generatedFileHeader, mergeMigrationDecisions, migrationRun, nameSpan, namespaceKey, namespaceOf, nextMigration, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, referenceAt, referencesTo, relationIdentitySchema, renameSiteAt, renameSpans, resolveMigrationDecisions, schemaValueEqual, sequenceRenames, tableKey, triggerKey, validateApplicationCompatibility, validateDatabase };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uncutsql/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",