effect-qb 0.15.0 → 0.17.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.
Files changed (88) hide show
  1. package/dist/mysql.js +1957 -595
  2. package/dist/postgres/metadata.js +2507 -182
  3. package/dist/postgres.js +9587 -8201
  4. package/dist/sqlite.js +8360 -0
  5. package/package.json +7 -2
  6. package/src/internal/column-state.ts +7 -0
  7. package/src/internal/column.ts +22 -0
  8. package/src/internal/derived-table.ts +29 -3
  9. package/src/internal/dialect.ts +14 -1
  10. package/src/internal/dsl-mutation-runtime.ts +173 -4
  11. package/src/internal/dsl-plan-runtime.ts +165 -20
  12. package/src/internal/dsl-query-runtime.ts +60 -6
  13. package/src/internal/dsl-transaction-ddl-runtime.ts +72 -2
  14. package/src/internal/executor.ts +62 -13
  15. package/src/internal/expression-ast.ts +3 -2
  16. package/src/internal/grouping-key.ts +141 -1
  17. package/src/internal/implication-runtime.ts +2 -1
  18. package/src/internal/json/types.ts +155 -40
  19. package/src/internal/predicate/analysis.ts +103 -1
  20. package/src/internal/predicate/atom.ts +7 -0
  21. package/src/internal/predicate/context.ts +170 -17
  22. package/src/internal/predicate/key.ts +64 -2
  23. package/src/internal/predicate/normalize.ts +115 -34
  24. package/src/internal/predicate/runtime.ts +144 -13
  25. package/src/internal/query.ts +563 -103
  26. package/src/internal/renderer.ts +39 -2
  27. package/src/internal/runtime/driver-value-mapping.ts +244 -0
  28. package/src/internal/runtime/normalize.ts +62 -38
  29. package/src/internal/runtime/schema.ts +5 -3
  30. package/src/internal/runtime/value.ts +153 -30
  31. package/src/internal/scalar.ts +11 -0
  32. package/src/internal/table-options.ts +108 -1
  33. package/src/internal/table.ts +87 -29
  34. package/src/mysql/column.ts +19 -2
  35. package/src/mysql/datatypes/index.ts +21 -0
  36. package/src/mysql/errors/catalog.ts +5 -5
  37. package/src/mysql/errors/normalize.ts +2 -2
  38. package/src/mysql/executor.ts +20 -5
  39. package/src/mysql/internal/dialect.ts +12 -6
  40. package/src/mysql/internal/dsl.ts +995 -263
  41. package/src/mysql/internal/renderer.ts +13 -3
  42. package/src/mysql/internal/sql-expression-renderer.ts +530 -128
  43. package/src/mysql/query.ts +9 -2
  44. package/src/mysql/renderer.ts +7 -2
  45. package/src/mysql/table.ts +38 -12
  46. package/src/postgres/cast.ts +22 -7
  47. package/src/postgres/column.ts +5 -2
  48. package/src/postgres/errors/normalize.ts +2 -2
  49. package/src/postgres/executor.ts +68 -10
  50. package/src/postgres/function/core.ts +19 -1
  51. package/src/postgres/internal/dialect.ts +12 -6
  52. package/src/postgres/internal/dsl.ts +958 -288
  53. package/src/postgres/internal/renderer.ts +13 -3
  54. package/src/postgres/internal/schema-ddl.ts +2 -1
  55. package/src/postgres/internal/schema-model.ts +6 -3
  56. package/src/postgres/internal/sql-expression-renderer.ts +477 -96
  57. package/src/postgres/json.ts +57 -17
  58. package/src/postgres/query.ts +9 -2
  59. package/src/postgres/renderer.ts +7 -2
  60. package/src/postgres/schema-management.ts +91 -4
  61. package/src/postgres/schema.ts +1 -1
  62. package/src/postgres/table.ts +189 -53
  63. package/src/postgres/type.ts +4 -0
  64. package/src/sqlite/column.ts +128 -0
  65. package/src/sqlite/datatypes/index.ts +79 -0
  66. package/src/sqlite/datatypes/spec.ts +98 -0
  67. package/src/sqlite/errors/catalog.ts +103 -0
  68. package/src/sqlite/errors/fields.ts +19 -0
  69. package/src/sqlite/errors/index.ts +19 -0
  70. package/src/sqlite/errors/normalize.ts +229 -0
  71. package/src/sqlite/errors/requirements.ts +71 -0
  72. package/src/sqlite/errors/types.ts +29 -0
  73. package/src/sqlite/executor.ts +227 -0
  74. package/src/sqlite/function/aggregate.ts +2 -0
  75. package/src/sqlite/function/core.ts +2 -0
  76. package/src/sqlite/function/index.ts +19 -0
  77. package/src/sqlite/function/string.ts +2 -0
  78. package/src/sqlite/function/temporal.ts +100 -0
  79. package/src/sqlite/function/window.ts +2 -0
  80. package/src/sqlite/internal/dialect.ts +37 -0
  81. package/src/sqlite/internal/dsl.ts +6926 -0
  82. package/src/sqlite/internal/renderer.ts +47 -0
  83. package/src/sqlite/internal/sql-expression-renderer.ts +1821 -0
  84. package/src/sqlite/json.ts +2 -0
  85. package/src/sqlite/query.ts +196 -0
  86. package/src/sqlite/renderer.ts +24 -0
  87. package/src/sqlite/table.ts +183 -0
  88. package/src/sqlite.ts +22 -0
@@ -6,12 +6,26 @@ import * as RowSet from "./row-set.js"
6
6
  import * as Table from "./table.js"
7
7
  import * as ExpressionAst from "./expression-ast.js"
8
8
  import * as QueryAst from "./query-ast.js"
9
+ import type * as ProjectionAlias from "./projection-alias.js"
9
10
  import type { JsonNode } from "./json/ast.js"
10
11
  import type * as JsonPath from "./json/path.js"
11
12
  import type { QueryCapability } from "./query-requirements.js"
12
13
  import type { CaseBranchAssumeFalse, CaseBranchAssumeTrue, CaseBranchDecision } from "./case-analysis.js"
13
- import type { ContradictsFormula, GuaranteedNonNullKeys, GuaranteedNullKeys, GuaranteedSourceNames } from "./predicate/analysis.js"
14
- import type { ColumnKeyOfExpression } from "./predicate/key.js"
14
+ import type {
15
+ ContradictsFormula,
16
+ EmptyFacts,
17
+ FactsOfFormula,
18
+ GuaranteedLiteralSetInFacts,
19
+ GuaranteedNeqLiteralInFacts,
20
+ GuaranteedJsonLiteralSetInFacts,
21
+ GuaranteedNonNullKeysInFacts,
22
+ GuaranteedNullKeysInFacts,
23
+ GuaranteedSourceNamesInFacts,
24
+ PredicateState
25
+ } from "./predicate/analysis.js"
26
+ import type { AssumeFactsFalse, AssumeFactsTrue, PredicateContext } from "./predicate/context.js"
27
+ import type { FormulaOfPredicate } from "./predicate/normalize.js"
28
+ import type { ColumnKey, ColumnKeyOfAst, ColumnKeyOfExpression, PredicateKeyOfAst } from "./predicate/key.js"
15
29
  import type { PredicateFormula, TrueFormula } from "./predicate/formula.js"
16
30
  import { trueFormula } from "./predicate/runtime.js"
17
31
 
@@ -113,12 +127,14 @@ export interface QueryState<
113
127
  Capabilities extends QueryCapability,
114
128
  Statement extends QueryAst.QueryStatement,
115
129
  Target,
116
- InsertState extends InsertSourceState
130
+ InsertState extends InsertSourceState,
131
+ Facts extends PredicateContext
117
132
  > {
118
133
  readonly required: Outstanding
119
134
  readonly availableNames: AvailableNames
120
135
  readonly grouped: Grouped
121
136
  readonly assumptions: Assumptions
137
+ readonly facts: Facts
122
138
  readonly capabilities: Capabilities
123
139
  readonly statement: Statement
124
140
  readonly target: Target
@@ -266,8 +282,57 @@ type JoinGroupingKeys<Keys extends readonly string[]> = Keys extends readonly []
266
282
  ? `${Head},${JoinGroupingKeys<Tail>}`
267
283
  : string
268
284
 
285
+ type EscapeGroupingBackslashes<Value extends string> = string extends Value
286
+ ? string
287
+ : Value extends `${infer Head}\\${infer Tail}`
288
+ ? `${Head}\\\\${EscapeGroupingBackslashes<Tail>}`
289
+ : Value
290
+
291
+ type EscapeGroupingCommas<Value extends string> = string extends Value
292
+ ? string
293
+ : Value extends `${infer Head},${infer Tail}`
294
+ ? `${Head}\\,${EscapeGroupingCommas<Tail>}`
295
+ : Value
296
+
297
+ type EscapeGroupingPipes<Value extends string> = string extends Value
298
+ ? string
299
+ : Value extends `${infer Head}|${infer Tail}`
300
+ ? `${Head}\\|${EscapeGroupingPipes<Tail>}`
301
+ : Value
302
+
303
+ type EscapeGroupingEquals<Value extends string> = string extends Value
304
+ ? string
305
+ : Value extends `${infer Head}=${infer Tail}`
306
+ ? `${Head}\\=${EscapeGroupingEquals<Tail>}`
307
+ : Value
308
+
309
+ type EscapeGroupingGreaterThan<Value extends string> = string extends Value
310
+ ? string
311
+ : Value extends `${infer Head}>${infer Tail}`
312
+ ? `${Head}\\>${EscapeGroupingGreaterThan<Tail>}`
313
+ : Value
314
+
315
+ type EscapeGroupingText<Value extends string> =
316
+ EscapeGroupingGreaterThan<
317
+ EscapeGroupingEquals<
318
+ EscapeGroupingPipes<
319
+ EscapeGroupingCommas<
320
+ EscapeGroupingBackslashes<Value>
321
+ >
322
+ >
323
+ >
324
+ >
325
+
326
+ type JsonStringKeysGroupingKey<Keys extends readonly string[]> = Keys extends readonly []
327
+ ? ""
328
+ : Keys extends readonly [infer Head extends string]
329
+ ? EscapeGroupingText<Head>
330
+ : Keys extends readonly [infer Head extends string, ...infer Tail extends readonly string[]]
331
+ ? `${EscapeGroupingText<Head>},${JsonStringKeysGroupingKey<Tail>}`
332
+ : string
333
+
269
334
  type JsonSegmentGroupingKey<Segment> =
270
- Segment extends JsonPath.KeySegment<infer Key extends string> ? `key:${Key}` :
335
+ Segment extends JsonPath.KeySegment<infer Key extends string> ? `key:${EscapeGroupingText<Key>}` :
271
336
  Segment extends JsonPath.IndexSegment<infer Index extends number> ? `index:${Index}` :
272
337
  Segment extends JsonPath.WildcardSegment ? "wildcard" :
273
338
  Segment extends JsonPath.SliceSegment<infer Start extends number | undefined, infer End extends number | undefined>
@@ -275,7 +340,7 @@ type JsonSegmentGroupingKey<Segment> =
275
340
  : Segment extends JsonPath.DescendSegment
276
341
  ? "descend"
277
342
  : Segment extends string
278
- ? `key:${Segment}`
343
+ ? `key:${EscapeGroupingText<Segment>}`
279
344
  : Segment extends number
280
345
  ? `index:${Segment}`
281
346
  : "unknown"
@@ -291,13 +356,13 @@ type JsonPathGroupingKey<Segments extends readonly any[]> = Segments extends rea
291
356
  type JsonOpaquePathGroupingKey<Value> =
292
357
  Value extends JsonPath.Path<infer Segments extends readonly JsonPath.CanonicalSegment[]>
293
358
  ? `jsonpath:${JsonPathGroupingKey<Segments>}` :
294
- Value extends string ? `jsonpath:${Value}` :
359
+ Value extends string ? `jsonpath:${EscapeGroupingText<Value>}` :
295
360
  Value extends Expression.Any ? `jsonpath:${GroupingKeyOfExpression<Value>}` :
296
361
  "jsonpath:unknown"
297
362
 
298
363
  type JsonEntryGroupingKey<Entry> =
299
364
  Entry extends { readonly key: infer Key extends string; readonly value: infer Value extends Expression.Any }
300
- ? `${Key}=>${GroupingKeyOfExpression<Value>}`
365
+ ? `${EscapeGroupingText<Key>}=>${GroupingKeyOfExpression<Value>}`
301
366
  : "entry:unknown"
302
367
 
303
368
  type JsonEntriesGroupingKey<Entries extends readonly { readonly key: string; readonly value: Expression.Any }[]> = Entries extends readonly []
@@ -323,13 +388,19 @@ type BranchGroupingKeys<
323
388
 
324
389
  type GroupingKeyOfAst<Ast extends ExpressionAst.Any> =
325
390
  Ast extends ExpressionAst.ColumnNode<infer TableName extends string, infer ColumnName extends string>
326
- ? `column:${TableName}.${ColumnName}`
391
+ ? `column:${ColumnKey<TableName, ColumnName>}`
327
392
  : Ast extends ExpressionAst.LiteralNode<infer Value>
328
393
  ? `literal:${LiteralGroupingKey<Value>}`
329
394
  : Ast extends ExpressionAst.ExcludedNode<infer ColumnName extends string>
330
395
  ? `excluded:${ColumnName}`
331
396
  : Ast extends ExpressionAst.CastNode<infer Value extends Expression.Any, infer Target extends Expression.DbType.Any>
332
397
  ? `cast(${GroupingKeyOfExpression<Value>} as ${Target["dialect"]}:${Target["kind"]})`
398
+ : Ast extends ExpressionAst.CollateNode<infer Value extends Expression.Any, infer Collation extends readonly [string, ...string[]]>
399
+ ? `collate(${GroupingKeyOfExpression<Value>},${JsonStringKeysGroupingKey<Collation>})`
400
+ : Ast extends ExpressionAst.FunctionCallNode<infer Name extends string, infer Args extends readonly Expression.Any[]>
401
+ ? `function(${EscapeGroupingText<Name>},${JoinGroupingKeys<{
402
+ readonly [K in keyof Args]: Args[K] extends Expression.Any ? GroupingKeyOfExpression<Args[K]> : never
403
+ } & readonly string[]>})`
333
404
  : Ast extends ExpressionAst.UnaryNode<infer Kind extends ExpressionAst.UnaryKind, infer Value extends Expression.Any>
334
405
  ? `${Kind}(${GroupingKeyOfExpression<Value>})`
335
406
  : Ast extends ExpressionAst.BinaryNode<infer Kind extends ExpressionAst.BinaryKind, infer Left extends Expression.Any, infer Right extends Expression.Any>
@@ -342,7 +413,7 @@ type GroupingKeyOfAst<Ast extends ExpressionAst.Any> =
342
413
  ? Kind extends "jsonGet" | "jsonPath" | "jsonAccess" | "jsonTraverse" | "jsonGetText" | "jsonPathText" | "jsonAccessText" | "jsonTraverseText"
343
414
  ? `json(${Kind},${GroupingKeyOfExpression<Extract<Ast["value"] | Ast["base"] | Ast["left"], Expression.Any>>},${JsonPathGroupingKey<Extract<Ast["segments"] | Ast["path"], readonly any[]>>})`
344
415
  : Kind extends "jsonHasKey" | "jsonKeyExists" | "jsonHasAnyKeys" | "jsonHasAllKeys"
345
- ? `json(${Kind},${GroupingKeyOfExpression<Extract<Ast["value"] | Ast["base"] | Ast["left"], Expression.Any>>},${JoinGroupingKeys<Extract<Ast["keys"], readonly string[]> & readonly string[]>})`
416
+ ? `json(${Kind},${GroupingKeyOfExpression<Extract<Ast["value"] | Ast["base"] | Ast["left"], Expression.Any>>},${JsonStringKeysGroupingKey<Extract<Ast["keys"], readonly string[]> & readonly string[]>})`
346
417
  : Kind extends "jsonConcat" | "jsonMerge" | "jsonDelete" | "jsonDeletePath" | "jsonRemove" | "jsonSet" | "jsonInsert"
347
418
  ? `json(${Kind},${GroupingKeyOfExpression<Extract<Ast["left"] | Ast["base"] | Ast["value"], Expression.Any>>},${GroupingKeyOfExpression<Extract<Ast["right"] | Ast["newValue"] | Ast["insert"], Expression.Any>>},${JsonPathGroupingKey<Extract<Ast["segments"] | Ast["path"], readonly any[]>>})`
348
419
  : Kind extends "jsonPathExists" | "jsonPathMatch"
@@ -985,6 +1056,138 @@ type JoinPath<Segments extends readonly string[]> = Segments extends readonly []
985
1056
  ? `${Head}__${JoinPath<Tail>}`
986
1057
  : string
987
1058
 
1059
+ type ProjectionAliasOf<
1060
+ Value extends Expression.Any,
1061
+ Path extends readonly string[]
1062
+ > = Value extends {
1063
+ readonly [ProjectionAlias.TypeId]: ProjectionAlias.State<infer Alias extends string>
1064
+ } ? Alias : JoinPath<Path>
1065
+
1066
+ type SelectionProjectionEntry<
1067
+ Alias extends string,
1068
+ Path extends readonly string[],
1069
+ ExpectedAlias extends string
1070
+ > = {
1071
+ readonly alias: Alias
1072
+ readonly path: Path
1073
+ readonly expectedAlias: ExpectedAlias
1074
+ }
1075
+
1076
+ type SelectionProjectionEntries<
1077
+ Selection,
1078
+ Path extends readonly string[] = []
1079
+ > = Selection extends Expression.Any
1080
+ ? SelectionProjectionEntry<ProjectionAliasOf<Selection, Path>, Path, JoinPath<Path>>
1081
+ : Selection extends Record<string, any>
1082
+ ? {
1083
+ readonly [K in Extract<keyof Selection, string>]:
1084
+ SelectionProjectionEntries<Selection[K], [...Path, K]>
1085
+ }[Extract<keyof Selection, string>]
1086
+ : never
1087
+
1088
+ type SameProjectionPath<
1089
+ Left extends readonly string[],
1090
+ Right extends readonly string[]
1091
+ > = Left extends readonly []
1092
+ ? Right extends readonly [] ? true : false
1093
+ : Left extends readonly [infer LeftHead extends string, ...infer LeftTail extends readonly string[]]
1094
+ ? Right extends readonly [infer RightHead extends string, ...infer RightTail extends readonly string[]]
1095
+ ? [LeftHead] extends [RightHead]
1096
+ ? [RightHead] extends [LeftHead]
1097
+ ? SameProjectionPath<LeftTail, RightTail>
1098
+ : false
1099
+ : false
1100
+ : false
1101
+ : false
1102
+
1103
+ type SameProjectionAlias<
1104
+ Left extends string,
1105
+ Right extends string
1106
+ > = [Left] extends [Right] ? [Right] extends [Left] ? true : false : false
1107
+
1108
+ type HasDifferentPathForAlias<
1109
+ Entries,
1110
+ Alias extends string,
1111
+ Path extends readonly string[]
1112
+ > = Entries extends SelectionProjectionEntry<infer EntryAlias, infer EntryPath, any>
1113
+ ? SameProjectionAlias<EntryAlias, Alias> extends true
1114
+ ? SameProjectionPath<EntryPath, Path> extends true ? never : true
1115
+ : never
1116
+ : never
1117
+
1118
+ type DuplicateProjectionAliases<
1119
+ Entries,
1120
+ AllEntries = Entries
1121
+ > = Entries extends SelectionProjectionEntry<infer Alias, infer Path, any>
1122
+ ? string extends Alias ? never
1123
+ : true extends HasDifferentPathForAlias<AllEntries, Alias, Path> ? Alias : never
1124
+ : never
1125
+
1126
+ type ProjectionAliasMismatches<Entries> =
1127
+ Entries extends SelectionProjectionEntry<infer Alias, any, infer ExpectedAlias>
1128
+ ? string extends Alias ? never
1129
+ : string extends ExpectedAlias ? never
1130
+ : SameProjectionAlias<Alias, ExpectedAlias> extends true ? never : Alias
1131
+ : never
1132
+
1133
+ type DerivedProjectionDuplicateAliases<Selection> =
1134
+ DuplicateProjectionAliases<SelectionProjectionEntries<Selection>>
1135
+
1136
+ type DerivedProjectionAliasMismatches<Selection> =
1137
+ ProjectionAliasMismatches<SelectionProjectionEntries<Selection>>
1138
+
1139
+ type IsAny<Value> = 0 extends (1 & Value) ? true : false
1140
+
1141
+ type IsBroadSelection<Selection> =
1142
+ IsAny<Selection> extends true ? true :
1143
+ unknown extends Selection ? true : false
1144
+
1145
+ type DerivedProjectionIssues<Selection> =
1146
+ IsBroadSelection<Selection> extends true
1147
+ ? never
1148
+ : | DerivedProjectionDuplicateAliases<Selection>
1149
+ | DerivedProjectionAliasMismatches<Selection>
1150
+
1151
+ export type DerivedSourceProjectionCompatibilityError<
1152
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1153
+ > = PlanValue & {
1154
+ readonly __effect_qb_error__: "effect-qb: derived subqueries require unique path-based projection aliases"
1155
+ readonly __effect_qb_duplicate_projection_aliases__: DerivedProjectionDuplicateAliases<SelectionOfPlan<PlanValue>>
1156
+ readonly __effect_qb_alias_mismatches__: DerivedProjectionAliasMismatches<SelectionOfPlan<PlanValue>>
1157
+ readonly __effect_qb_hint__: "Use unique nested selection paths and do not override projection aliases inside derived subqueries"
1158
+ }
1159
+
1160
+ export type DerivedProjectionCompatiblePlan<
1161
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>,
1162
+ ValidPlan = PlanValue
1163
+ > = [DerivedProjectionIssues<SelectionOfPlan<PlanValue>>] extends [never]
1164
+ ? ValidPlan
1165
+ : ValidPlan & DerivedSourceProjectionCompatibilityError<PlanValue>
1166
+
1167
+ export type DerivedSourceCompatiblePlan<
1168
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1169
+ > = DerivedProjectionCompatiblePlan<PlanValue, CompletePlan<PlanValue>>
1170
+
1171
+ type InlineSourceStatementError<
1172
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1173
+ > = PlanValue & {
1174
+ readonly __effect_qb_error__: "effect-qb: inline derived sources only accept select-like query plans"
1175
+ readonly __effect_qb_statement__: StatementOfPlan<PlanValue>
1176
+ readonly __effect_qb_hint__: "Use select(...) or a set operator for as(...) and lateral(...); use with(...) for data-modifying CTEs where supported"
1177
+ }
1178
+
1179
+ export type DerivedTableCompatiblePlan<
1180
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1181
+ > = StatementOfPlan<PlanValue> extends SelectLikeStatement
1182
+ ? DerivedSourceCompatiblePlan<PlanValue>
1183
+ : InlineSourceStatementError<PlanValue>
1184
+
1185
+ export type LateralSourceCompatiblePlan<
1186
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1187
+ > = StatementOfPlan<PlanValue> extends SelectLikeStatement
1188
+ ? DerivedProjectionCompatiblePlan<PlanValue>
1189
+ : InlineSourceStatementError<PlanValue>
1190
+
988
1191
  type DerivedLeafExpression<
989
1192
  Value extends Expression.Any,
990
1193
  Alias extends string,
@@ -1067,6 +1270,18 @@ export type OutstandingOfPlan<
1067
1270
  export type AssumptionsOfPlan<
1068
1271
  PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1069
1272
  > = QueryPlanState<PlanValue>["assumptions"]
1273
+ export type FactsOfPlan<
1274
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1275
+ > = QueryPlanState<PlanValue>["facts"]
1276
+ export type CommonSetFacts<
1277
+ Left extends QueryPlan<any, any, any, any, any, any, any, any, any, any>,
1278
+ Right extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1279
+ > = [FactsOfPlan<Left>] extends [FactsOfPlan<Right>]
1280
+ ? [FactsOfPlan<Right>] extends [FactsOfPlan<Left>] ? FactsOfPlan<Left> : EmptyFacts
1281
+ : EmptyFacts
1282
+ export type PredicateStateOfPlan<
1283
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1284
+ > = PredicateState<AssumptionsOfPlan<PlanValue>, FactsOfPlan<PlanValue>>
1070
1285
  export type CapabilitiesOfPlan<
1071
1286
  PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1072
1287
  > = QueryPlanState<PlanValue>["capabilities"]
@@ -1196,9 +1411,10 @@ export type AddJoinRequired<
1196
1411
  Available extends Record<string, RowSet.AnySource>,
1197
1412
  JoinedName extends string,
1198
1413
  Predicate extends PredicateInput | never,
1199
- Kind extends QueryAst.JoinKind = "inner"
1414
+ Kind extends QueryAst.JoinKind = "inner",
1415
+ SourceRequired extends string = never
1200
1416
  > = Exclude<
1201
- Required | (Predicate extends never ? never : RequiredFromInput<Predicate>),
1417
+ Required | SourceRequired | (Predicate extends never ? never : RequiredFromInput<Predicate>),
1202
1418
  AvailableNames<AvailableAfterJoin<Available, JoinedName, Kind>>
1203
1419
  >
1204
1420
 
@@ -1324,12 +1540,13 @@ type MergeNullabilityStates<
1324
1540
  type FoldEffectiveNullability<
1325
1541
  Values extends readonly Expression.Any[],
1326
1542
  Available extends Record<string, RowSet.AnySource>,
1327
- Assumptions extends PredicateFormula
1543
+ Assumptions extends PredicateFormula,
1544
+ Facts extends PredicateContext
1328
1545
  > = Extract<{
1329
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1546
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1330
1547
  }[number], "always"> extends never
1331
1548
  ? Extract<{
1332
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1549
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1333
1550
  }[number], "maybe"> extends never
1334
1551
  ? "never"
1335
1552
  : "maybe"
@@ -1338,12 +1555,13 @@ type FoldEffectiveNullability<
1338
1555
  type CoalesceEffectiveNullability<
1339
1556
  Values extends readonly Expression.Any[],
1340
1557
  Available extends Record<string, RowSet.AnySource>,
1341
- Assumptions extends PredicateFormula
1558
+ Assumptions extends PredicateFormula,
1559
+ Facts extends PredicateContext
1342
1560
  > = Extract<{
1343
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1561
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1344
1562
  }[number], "never"> extends never
1345
1563
  ? Extract<{
1346
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1564
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1347
1565
  }[number], "maybe"> extends never
1348
1566
  ? "always"
1349
1567
  : "maybe"
@@ -1357,16 +1575,16 @@ type NullabilityOfOutput<Output> =
1357
1575
  type PreciseFactSet<Value extends string> = string extends Value ? never : Value
1358
1576
 
1359
1577
  type KnownGuaranteedNullKeys<
1360
- Assumptions extends PredicateFormula
1361
- > = PreciseFactSet<GuaranteedNullKeys<Assumptions>>
1578
+ Facts extends PredicateContext
1579
+ > = PreciseFactSet<GuaranteedNullKeysInFacts<Facts>>
1362
1580
 
1363
1581
  type KnownGuaranteedNonNullKeys<
1364
- Assumptions extends PredicateFormula
1365
- > = PreciseFactSet<GuaranteedNonNullKeys<Assumptions>>
1582
+ Facts extends PredicateContext
1583
+ > = PreciseFactSet<GuaranteedNonNullKeysInFacts<Facts>>
1366
1584
 
1367
1585
  type KnownGuaranteedSourceNames<
1368
- Assumptions extends PredicateFormula
1369
- > = PreciseFactSet<GuaranteedSourceNames<Assumptions>>
1586
+ Facts extends PredicateContext
1587
+ > = PreciseFactSet<GuaranteedSourceNamesInFacts<Facts>>
1370
1588
 
1371
1589
  type ExplicitlyRequiredSourceNames<
1372
1590
  Available extends Record<string, RowSet.AnySource>
@@ -1393,7 +1611,7 @@ type ImpliedSourceNamesFromRequired<
1393
1611
  > = Extract<{
1394
1612
  readonly [K in Extract<keyof Available, string>]:
1395
1613
  K extends Required
1396
- ? PreciseFactSet<GuaranteedSourceNames<PresentFormulaOfSource<Available[K]>>>
1614
+ ? PreciseFactSet<GuaranteedSourceNamesInFacts<FactsOfFormula<PresentFormulaOfSource<Available[K]>>>>
1397
1615
  : never
1398
1616
  }[Extract<keyof Available, string>], string>
1399
1617
 
@@ -1416,17 +1634,20 @@ type ExpandRequiredSourceNamesStep<
1416
1634
 
1417
1635
  type DirectlyAbsentSourceNames<
1418
1636
  Available extends Record<string, RowSet.AnySource>,
1419
- Assumptions extends PredicateFormula
1637
+ Assumptions extends PredicateFormula,
1638
+ Facts extends PredicateContext
1420
1639
  > = Extract<{
1421
1640
  readonly [K in Extract<keyof Available, string>]:
1422
- K extends string
1423
- ? PresenceWitnessesOfSource<Available[K]> extends infer Witnesses extends string
1424
- ? Extract<Witnesses, KnownGuaranteedNullKeys<Assumptions>> extends never
1425
- ? ContradictsFormula<Assumptions, PresentFormulaOfSource<Available[K]>> extends true
1426
- ? K
1427
- : never
1428
- : K
1429
- : never
1641
+ Available[K] extends RowSet.Source<any, infer Mode extends RowSet.SourceMode, any, any>
1642
+ ? Mode extends "required"
1643
+ ? never
1644
+ : PresenceWitnessesOfSource<Available[K]> extends infer Witnesses extends string
1645
+ ? Extract<Witnesses, KnownGuaranteedNullKeys<Facts>> extends never
1646
+ ? ContradictsFormula<Assumptions, PresentFormulaOfSource<Available[K]>> extends true
1647
+ ? K
1648
+ : never
1649
+ : K
1650
+ : never
1430
1651
  : never
1431
1652
  }[Extract<keyof Available, string>], string>
1432
1653
 
@@ -1435,7 +1656,7 @@ type ImpliedAbsentSourceNames<
1435
1656
  Absent extends string
1436
1657
  > = Extract<{
1437
1658
  readonly [K in Extract<keyof Available, string>]:
1438
- Extract<PreciseFactSet<GuaranteedSourceNames<PresentFormulaOfSource<Available[K]>>>, Absent> extends never
1659
+ Extract<PreciseFactSet<GuaranteedSourceNamesInFacts<FactsOfFormula<PresentFormulaOfSource<Available[K]>>>>, Absent> extends never
1439
1660
  ? never
1440
1661
  : K
1441
1662
  }[Extract<keyof Available, string>], string>
@@ -1459,23 +1680,26 @@ type ExpandAbsentSourceNamesStep<
1459
1680
 
1460
1681
  type AbsentSourceNamesInScope<
1461
1682
  Available extends Record<string, RowSet.AnySource>,
1462
- Assumptions extends PredicateFormula
1463
- > = ExpandAbsentSourceNames<Available, DirectlyAbsentSourceNames<Available, Assumptions>>
1683
+ Assumptions extends PredicateFormula,
1684
+ Facts extends PredicateContext
1685
+ > = ExpandAbsentSourceNames<Available, DirectlyAbsentSourceNames<Available, Assumptions, Facts>>
1464
1686
 
1465
1687
  type RequiredSourceNamesInScope<
1466
1688
  Available extends Record<string, RowSet.AnySource>,
1467
- Assumptions extends PredicateFormula
1689
+ Assumptions extends PredicateFormula,
1690
+ Facts extends PredicateContext
1468
1691
  > = Exclude<
1469
1692
  ExpandRequiredSourceNames<
1470
1693
  Available,
1471
- ExplicitlyRequiredSourceNames<Available> | KnownGuaranteedSourceNames<Assumptions>
1694
+ ExplicitlyRequiredSourceNames<Available> | KnownGuaranteedSourceNames<Facts>
1472
1695
  >,
1473
- AbsentSourceNamesInScope<Available, Assumptions>
1696
+ AbsentSourceNamesInScope<Available, Assumptions, Facts>
1474
1697
  >
1475
1698
 
1476
1699
  type EffectiveAvailable<
1477
1700
  Available extends Record<string, RowSet.AnySource>,
1478
- Assumptions extends PredicateFormula
1701
+ Assumptions extends PredicateFormula,
1702
+ Facts extends PredicateContext
1479
1703
  > = {
1480
1704
  readonly [K in keyof Available]:
1481
1705
  Available[K] extends RowSet.Source<
@@ -1486,7 +1710,7 @@ type EffectiveAvailable<
1486
1710
  >
1487
1711
  ? RowSet.Source<
1488
1712
  Name,
1489
- K extends RequiredSourceNamesInScope<Available, Assumptions> ? "required" : Mode,
1713
+ K extends RequiredSourceNamesInScope<Available, Assumptions, Facts> ? "required" : Mode,
1490
1714
  PresentFormula,
1491
1715
  PresenceWitness
1492
1716
  > & {
@@ -1498,8 +1722,9 @@ type EffectiveAvailable<
1498
1722
  type HasAbsentSource<
1499
1723
  Dependencies extends Expression.BindingId,
1500
1724
  Available extends Record<string, RowSet.AnySource>,
1501
- Assumptions extends PredicateFormula
1502
- > = Extract<Dependencies, AbsentSourceNamesInScope<Available, Assumptions>> extends never ? false : true
1725
+ Assumptions extends PredicateFormula,
1726
+ Facts extends PredicateContext
1727
+ > = Extract<Dependencies, AbsentSourceNamesInScope<Available, Assumptions, Facts>> extends never ? false : true
1503
1728
 
1504
1729
  type OptionalSourceNamesInScope<
1505
1730
  Available extends Record<string, RowSet.AnySource>
@@ -1507,102 +1732,313 @@ type OptionalSourceNamesInScope<
1507
1732
  [K in keyof Available & string]: SourceModeOf<Available, K> extends "optional" ? K : never
1508
1733
  }[keyof Available & string], string>
1509
1734
 
1735
+ type EffectiveNullabilityFromBase<
1736
+ Value extends Expression.Any,
1737
+ Available extends Record<string, RowSet.AnySource>,
1738
+ Assumptions extends PredicateFormula,
1739
+ Facts extends PredicateContext
1740
+ > = Expression.NullabilityOf<Value> extends "always" ? "always"
1741
+ : PredicateKeyOfAst<AstOf<Value>> extends infer Key extends string
1742
+ ? IsUnion<Key> extends true
1743
+ ? EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1744
+ : string extends Key
1745
+ ? EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1746
+ : Key extends KnownGuaranteedNullKeys<Facts>
1747
+ ? "always"
1748
+ : Key extends KnownGuaranteedNonNullKeys<Facts>
1749
+ ? "never"
1750
+ : EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1751
+ : EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1752
+
1753
+ type EffectiveNullabilityFromSources<
1754
+ Value extends Expression.Any,
1755
+ Available extends Record<string, RowSet.AnySource>,
1756
+ Assumptions extends PredicateFormula,
1757
+ Facts extends PredicateContext
1758
+ > = HasAbsentSource<DependenciesOf<Value>, Available, Assumptions, Facts> extends true ? "always"
1759
+ : HasOptionalSource<DependenciesOf<Value>, Available> extends true ? "maybe"
1760
+ : Expression.NullabilityOf<Value>
1761
+
1510
1762
  type BaseEffectiveNullability<
1511
1763
  Value extends Expression.Any,
1512
1764
  Available extends Record<string, RowSet.AnySource>,
1513
- Assumptions extends PredicateFormula
1765
+ Assumptions extends PredicateFormula,
1766
+ Facts extends PredicateContext
1514
1767
  > = AstOf<Value> extends ExpressionAst.ColumnNode<infer TableName extends string, infer ColumnName extends string>
1515
- ? TableName extends AbsentSourceNamesInScope<Available, Assumptions>
1768
+ ? TableName extends AbsentSourceNamesInScope<Available, Assumptions, Facts>
1516
1769
  ? "always"
1517
- : `${TableName}.${ColumnName}` extends KnownGuaranteedNullKeys<Assumptions>
1770
+ : `${TableName}.${ColumnName}` extends KnownGuaranteedNullKeys<Facts>
1518
1771
  ? "always"
1519
- : `${TableName}.${ColumnName}` extends KnownGuaranteedNonNullKeys<Assumptions>
1772
+ : `${TableName}.${ColumnName}` extends KnownGuaranteedNonNullKeys<Facts>
1520
1773
  ? "never"
1521
- : Expression.NullabilityOf<Value> extends "always" ? "always"
1522
- : HasAbsentSource<DependenciesOf<Value>, Available, Assumptions> extends true ? "always"
1523
- : HasOptionalSource<DependenciesOf<Value>, Available> extends true ? "maybe"
1524
- : Expression.NullabilityOf<Value>
1525
- : Expression.NullabilityOf<Value> extends "always" ? "always"
1526
- : HasAbsentSource<DependenciesOf<Value>, Available, Assumptions> extends true ? "always"
1527
- : HasOptionalSource<DependenciesOf<Value>, Available> extends true ? "maybe"
1528
- : Expression.NullabilityOf<Value>
1774
+ : EffectiveNullabilityFromBase<Value, Available, Assumptions, Facts>
1775
+ : EffectiveNullabilityFromBase<Value, Available, Assumptions, Facts>
1529
1776
 
1530
1777
  type CaseOutputOf<
1531
1778
  Branches extends readonly ExpressionAst.CaseBranchNode[],
1532
1779
  Else extends Expression.Any,
1533
1780
  Available extends Record<string, RowSet.AnySource>,
1534
- Assumptions extends PredicateFormula
1781
+ Assumptions extends PredicateFormula,
1782
+ Facts extends PredicateContext
1535
1783
  > = Branches extends readonly [
1536
1784
  infer Head extends ExpressionAst.CaseBranchNode,
1537
1785
  ...infer Tail extends readonly ExpressionAst.CaseBranchNode[]
1538
1786
  ]
1539
1787
  ? Head extends ExpressionAst.CaseBranchNode<infer Predicate extends Expression.Any, infer Then extends Expression.Any>
1540
1788
  ? CaseBranchDecision<Assumptions, Predicate> extends "skip"
1541
- ? CaseOutputOf<Tail, Else, Available, Assumptions>
1789
+ ? CaseOutputOf<Tail, Else, Available, Assumptions, Facts>
1542
1790
  : CaseBranchDecision<Assumptions, Predicate> extends "take"
1543
- ? ExpressionOutput<Then, EffectiveAvailable<Available, CaseBranchAssumeTrue<Assumptions, Predicate>>, CaseBranchAssumeTrue<Assumptions, Predicate>>
1544
- : ExpressionOutput<Then, EffectiveAvailable<Available, CaseBranchAssumeTrue<Assumptions, Predicate>>, CaseBranchAssumeTrue<Assumptions, Predicate>> |
1545
- CaseOutputOf<Tail, Else, Available, CaseBranchAssumeFalse<Assumptions, Predicate>>
1791
+ ? FormulaOfPredicate<Predicate> extends infer BranchFormula extends PredicateFormula
1792
+ ? ExpressionOutput<
1793
+ Then,
1794
+ EffectiveAvailable<
1795
+ Available,
1796
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1797
+ AssumeFactsTrue<Facts, BranchFormula>
1798
+ >,
1799
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1800
+ AssumeFactsTrue<Facts, BranchFormula>
1801
+ >
1802
+ : never
1803
+ : FormulaOfPredicate<Predicate> extends infer BranchFormula extends PredicateFormula
1804
+ ? ExpressionOutput<
1805
+ Then,
1806
+ EffectiveAvailable<
1807
+ Available,
1808
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1809
+ AssumeFactsTrue<Facts, BranchFormula>
1810
+ >,
1811
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1812
+ AssumeFactsTrue<Facts, BranchFormula>
1813
+ > |
1814
+ CaseOutputOf<
1815
+ Tail,
1816
+ Else,
1817
+ Available,
1818
+ CaseBranchAssumeFalse<Assumptions, Predicate>,
1819
+ AssumeFactsFalse<Facts, BranchFormula>
1820
+ >
1821
+ : never
1546
1822
  : never
1547
- : ExpressionOutput<Else, EffectiveAvailable<Available, Assumptions>, Assumptions>
1823
+ : ExpressionOutput<Else, EffectiveAvailable<Available, Assumptions, Facts>, Assumptions, Facts>
1548
1824
 
1549
1825
  /** Effective nullability of an expression after source-scope nullability is applied. */
1550
1826
  type EffectiveNullabilityOfAst<
1551
1827
  Value extends Expression.Any,
1552
1828
  Ast extends ExpressionAst.Any,
1553
1829
  Available extends Record<string, RowSet.AnySource>,
1554
- Assumptions extends PredicateFormula = TrueAssumptions
1830
+ Assumptions extends PredicateFormula = TrueAssumptions,
1831
+ Facts extends PredicateContext = EmptyFacts
1555
1832
  > = Ast extends ExpressionAst.ColumnNode<any, any>
1556
- ? BaseEffectiveNullability<Value, Available, Assumptions>
1833
+ ? BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1557
1834
  : Ast extends ExpressionAst.LiteralNode<any>
1558
1835
  ? Expression.NullabilityOf<Value>
1559
1836
  : Ast extends ExpressionAst.UnaryNode<infer Kind, infer UnaryValue extends Expression.Any>
1560
1837
  ? Kind extends "upper" | "lower" | "not"
1561
- ? EffectiveNullability<UnaryValue, Available, Assumptions>
1838
+ ? EffectiveNullability<UnaryValue, Available, Assumptions, Facts>
1562
1839
  : Kind extends "isNull" | "isNotNull" | "count"
1563
1840
  ? "never"
1564
1841
  : Expression.NullabilityOf<Value>
1565
1842
  : Ast extends ExpressionAst.BinaryNode<"eq", infer Left extends Expression.Any, infer Right extends Expression.Any>
1566
- ? EffectiveNullability<Left, Available, Assumptions> extends "never"
1567
- ? EffectiveNullability<Right, Available, Assumptions> extends "never" ? "never" : "maybe"
1843
+ ? EffectiveNullability<Left, Available, Assumptions, Facts> extends "never"
1844
+ ? EffectiveNullability<Right, Available, Assumptions, Facts> extends "never" ? "never" : "maybe"
1568
1845
  : "maybe"
1569
1846
  : Ast extends ExpressionAst.VariadicNode<infer Kind, infer Values extends readonly Expression.Any[]>
1570
1847
  ? Kind extends "coalesce"
1571
- ? CoalesceEffectiveNullability<Values, Available, Assumptions>
1848
+ ? CoalesceEffectiveNullability<Values, Available, Assumptions, Facts>
1572
1849
  : Kind extends "and" | "or" | "concat"
1573
- ? FoldEffectiveNullability<Values, Available, Assumptions>
1574
- : BaseEffectiveNullability<Value, Available, Assumptions>
1850
+ ? FoldEffectiveNullability<Values, Available, Assumptions, Facts>
1851
+ : BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1575
1852
  : Ast extends ExpressionAst.CaseNode<infer Branches extends readonly ExpressionAst.CaseBranchNode[], infer Else extends Expression.Any>
1576
- ? NullabilityOfOutput<CaseOutputOf<Branches, Else, Available, Assumptions>>
1577
- : BaseEffectiveNullability<Value, Available, Assumptions>
1853
+ ? NullabilityOfOutput<CaseOutputOf<Branches, Else, Available, Assumptions, Facts>>
1854
+ : BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1578
1855
 
1579
1856
  export type EffectiveNullability<
1580
1857
  Value extends Expression.Any,
1581
1858
  Available extends Record<string, RowSet.AnySource>,
1582
- Assumptions extends PredicateFormula = TrueAssumptions
1859
+ Assumptions extends PredicateFormula = TrueAssumptions,
1860
+ Facts extends PredicateContext = EmptyFacts
1583
1861
  > =
1584
1862
  AstOf<Value> extends infer Ast extends ExpressionAst.Any
1585
- ? EffectiveNullabilityOfAst<Value, Ast, Available, Assumptions>
1586
- : BaseEffectiveNullability<Value, Available, Assumptions>
1863
+ ? EffectiveNullabilityOfAst<Value, Ast, Available, Assumptions, Facts>
1864
+ : BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1865
+
1866
+ type LiteralKeyValue<Value extends string> =
1867
+ Value extends `string:${infer Literal}` ? Literal :
1868
+ Value extends `number:${infer Literal extends number}` ? Literal :
1869
+ Value extends "boolean:true" ? true :
1870
+ Value extends "boolean:false" ? false :
1871
+ never
1872
+
1873
+ type LiteralSetRuntime<Values> =
1874
+ Values extends readonly (infer Value)[] ? LiteralSetRuntime<Value> :
1875
+ Values extends string ? LiteralKeyValue<Values> :
1876
+ never
1877
+
1878
+ type NarrowRuntimeToAllowed<
1879
+ Runtime,
1880
+ Allowed
1881
+ > = Runtime extends unknown
1882
+ ? Extract<Runtime, Allowed> extends infer Extracted
1883
+ ? [Extracted] extends [never]
1884
+ ? Allowed extends Runtime ? Allowed : never
1885
+ : Extracted
1886
+ : never
1887
+ : never
1888
+
1889
+ type RefineRuntimeByAllowedLiterals<
1890
+ Runtime,
1891
+ Values
1892
+ > = [Values] extends [never]
1893
+ ? Runtime
1894
+ : string extends Values
1895
+ ? Runtime
1896
+ : NarrowRuntimeToAllowed<Runtime, LiteralSetRuntime<Values>>
1897
+
1898
+ type RefineRuntimeByExcludedLiterals<
1899
+ Runtime,
1900
+ Values
1901
+ > = [Values] extends [never]
1902
+ ? Runtime
1903
+ : string extends Values
1904
+ ? Runtime
1905
+ : Exclude<Runtime, LiteralSetRuntime<Values>>
1906
+
1907
+ type JsonKeyParts<Key extends string> = string extends Key
1908
+ ? never
1909
+ : Key extends `${infer ColumnKey}#json:${infer Path}`
1910
+ ? readonly [ColumnKey, Path]
1911
+ : never
1912
+
1913
+ type LiteralSetForPredicateKey<
1914
+ Facts extends PredicateContext,
1915
+ Key extends string
1916
+ > = [JsonKeyParts<Key>] extends [never]
1917
+ ? GuaranteedLiteralSetInFacts<Facts, Key>
1918
+ : JsonKeyParts<Key> extends readonly [infer ColumnKey extends string, infer Path extends string]
1919
+ ? GuaranteedJsonLiteralSetInFacts<Facts, ColumnKey, Path>
1920
+ : never
1921
+
1922
+ type RefineRuntimeForPredicateKey<
1923
+ Runtime,
1924
+ Facts extends PredicateContext,
1925
+ Key extends string
1926
+ > = IsUnion<Key> extends true
1927
+ ? Runtime
1928
+ : string extends Key
1929
+ ? Runtime
1930
+ : RefineRuntimeByExcludedLiterals<
1931
+ RefineRuntimeByAllowedLiterals<Runtime, LiteralSetForPredicateKey<Facts, Key>>,
1932
+ GuaranteedNeqLiteralInFacts<Facts, Key>
1933
+ >
1934
+
1935
+ type JsonLiteralSetsForColumn<
1936
+ Facts extends PredicateContext,
1937
+ ColumnKey extends string
1938
+ > = [Facts["jsonLiteralSets"]] extends [{ readonly [C in ColumnKey]: infer Paths }]
1939
+ ? Paths
1940
+ : {}
1941
+
1942
+ type JsonPathHead<
1943
+ Path extends string,
1944
+ Current extends string = ""
1945
+ > = Path extends `\\.${infer Rest}`
1946
+ ? JsonPathHead<Rest, `${Current}.`>
1947
+ : Path extends `\\\\${infer Rest}`
1948
+ ? JsonPathHead<Rest, `${Current}\\`>
1949
+ : Path extends `.${infer Tail}`
1950
+ ? readonly [Current, Tail]
1951
+ : Path extends `${infer Character}${infer Rest}`
1952
+ ? JsonPathHead<Rest, `${Current}${Character}`>
1953
+ : readonly [Current, ""]
1954
+
1955
+ type RefineJsonRuntimeAtPath<
1956
+ Runtime,
1957
+ Path extends string,
1958
+ Values
1959
+ > = Runtime extends unknown
1960
+ ? JsonPathHead<Path> extends readonly [infer Head extends string, infer Tail extends string]
1961
+ ? Tail extends ""
1962
+ ? Runtime extends object
1963
+ ? Head extends keyof Runtime
1964
+ ? RefineRuntimeByAllowedLiterals<NonNullable<Runtime[Head]>, Values> extends infer Refined
1965
+ ? [Refined] extends [never]
1966
+ ? never
1967
+ : Omit<Runtime, Head> & { readonly [K in Head]: Refined }
1968
+ : never
1969
+ : never
1970
+ : RefineRuntimeByAllowedLiterals<NonNullable<Runtime>, Values>
1971
+ : Runtime extends object
1972
+ ? Head extends keyof Runtime
1973
+ ? RefineJsonRuntimeAtPath<NonNullable<Runtime[Head]>, Tail, Values> extends infer Refined
1974
+ ? [Refined] extends [never]
1975
+ ? never
1976
+ : Omit<Runtime, Head> & { readonly [K in Head]: Refined }
1977
+ : never
1978
+ : never
1979
+ : never
1980
+ : never
1981
+ : never
1982
+
1983
+ type RefineJsonRuntimeWithConstraints<
1984
+ Runtime,
1985
+ Constraints
1986
+ > = [keyof Constraints & string] extends [never]
1987
+ ? Runtime
1988
+ : {
1989
+ readonly [Path in keyof Constraints & string]:
1990
+ [RefineJsonRuntimeAtPath<Runtime, Path, Constraints[Path]>] extends [never] ? Path : never
1991
+ }[keyof Constraints & string] extends never
1992
+ ? UnionToIntersection<{
1993
+ readonly [Path in keyof Constraints & string]: RefineJsonRuntimeAtPath<Runtime, Path, Constraints[Path]>
1994
+ }[keyof Constraints & string]>
1995
+ : never
1996
+
1997
+ type RefineJsonRuntimeForColumn<
1998
+ Runtime,
1999
+ ColumnKey extends string,
2000
+ Facts extends PredicateContext
2001
+ > = Runtime extends object
2002
+ ? Runtime extends unknown
2003
+ ? RefineJsonRuntimeWithConstraints<Runtime, JsonLiteralSetsForColumn<Facts, ColumnKey>>
2004
+ : never
2005
+ : Runtime
2006
+
2007
+ type AssumptionRefinedRuntime<
2008
+ Ast extends ExpressionAst.Any,
2009
+ Runtime,
2010
+ Facts extends PredicateContext
2011
+ > = [PredicateKeyOfAst<Ast>] extends [never]
2012
+ ? Runtime
2013
+ : PredicateKeyOfAst<Ast> extends infer PredicateKey extends string
2014
+ ? [ColumnKeyOfAst<Ast>] extends [never]
2015
+ ? RefineRuntimeForPredicateKey<Runtime, Facts, PredicateKey>
2016
+ : ColumnKeyOfAst<Ast> extends infer ColumnKey extends string
2017
+ ? RefineRuntimeForPredicateKey<RefineJsonRuntimeForColumn<Runtime, ColumnKey, Facts>, Facts, PredicateKey>
2018
+ : Runtime
2019
+ : Runtime
1587
2020
 
1588
2021
  /** Result runtime type of an expression after effective nullability is resolved. */
1589
2022
  export type ExpressionOutput<
1590
2023
  Value extends Expression.Any,
1591
2024
  Available extends Record<string, RowSet.AnySource>,
1592
- Assumptions extends PredicateFormula = TrueAssumptions
2025
+ Assumptions extends PredicateFormula = TrueAssumptions,
2026
+ Facts extends PredicateContext = EmptyFacts
1593
2027
  > = AstOf<Value> extends infer Ast extends ExpressionAst.Any
1594
2028
  ? Ast extends ExpressionAst.CaseNode<infer Branches extends readonly ExpressionAst.CaseBranchNode[], infer Else extends Expression.Any>
1595
- ? CaseOutputOf<Branches, Else, Available, Assumptions>
1596
- : EffectiveNullabilityOfAst<Value, Ast, Available, Assumptions> extends infer Nullability
2029
+ ? CaseOutputOf<Branches, Else, Available, Assumptions, Facts>
2030
+ : EffectiveNullabilityOfAst<Value, Ast, Available, Assumptions, Facts> extends infer Nullability
1597
2031
  ? Expression.NullabilityOf<Value> extends infer BaseNullability
1598
2032
  ? Expression.RuntimeOf<Value> extends infer Runtime
1599
- ? Nullability extends "never"
1600
- ? BaseNullability extends "never"
1601
- ? Runtime
1602
- : NonNullable<Runtime>
1603
- : Nullability extends "always"
1604
- ? null
1605
- : Runtime | null
2033
+ ? AssumptionRefinedRuntime<Ast, Runtime, Facts> extends infer RefinedRuntime
2034
+ ? Nullability extends "never"
2035
+ ? BaseNullability extends "never"
2036
+ ? RefinedRuntime
2037
+ : NonNullable<RefinedRuntime>
2038
+ : Nullability extends "always"
2039
+ ? null
2040
+ : RefinedRuntime | null
2041
+ : never
1606
2042
  : never
1607
2043
  : never
1608
2044
  : never
@@ -1612,23 +2048,26 @@ export type ExpressionOutput<
1612
2048
  export type OutputOfSelection<
1613
2049
  Selection,
1614
2050
  Available extends Record<string, RowSet.AnySource>,
1615
- Assumptions extends PredicateFormula = TrueAssumptions
2051
+ Assumptions extends PredicateFormula = TrueAssumptions,
2052
+ Facts extends PredicateContext = EmptyFacts
1616
2053
  > = Selection extends Expression.Any
1617
- ? ExpressionOutput<Selection, Available, Assumptions>
2054
+ ? ExpressionOutput<Selection, Available, Assumptions, Facts>
1618
2055
  : Selection extends Record<string, any>
1619
2056
  ? {
1620
- readonly [K in keyof Selection]: OutputOfSelection<Selection[K], Available, Assumptions>
2057
+ readonly [K in keyof Selection]: OutputOfSelection<Selection[K], Available, Assumptions, Facts>
1621
2058
  }
1622
2059
  : never
1623
2060
 
1624
2061
  type ResolvedSelectionOutput<
1625
2062
  Selection,
1626
2063
  Available extends Record<string, RowSet.AnySource>,
1627
- Assumptions extends PredicateFormula
2064
+ Assumptions extends PredicateFormula,
2065
+ Facts extends PredicateContext
1628
2066
  > = OutputOfSelection<
1629
2067
  Selection,
1630
- EffectiveAvailable<Available, Assumptions>,
1631
- Assumptions
2068
+ EffectiveAvailable<Available, Assumptions, Facts>,
2069
+ Assumptions,
2070
+ Facts
1632
2071
  >
1633
2072
 
1634
2073
  /** Resolved row type produced by a concrete query plan. */
@@ -1636,7 +2075,9 @@ export type ResultRow<PlanValue extends QueryPlan<any, any, any, any, any, any,
1636
2075
  SelectionOfPlan<PlanValue> extends infer Selection
1637
2076
  ? AvailableOfPlan<PlanValue> extends infer Available extends Record<string, RowSet.AnySource>
1638
2077
  ? AssumptionsOfPlan<PlanValue> extends infer Assumptions extends PredicateFormula
1639
- ? ResolvedSelectionOutput<Selection, Available, Assumptions>
2078
+ ? FactsOfPlan<PlanValue> extends infer Facts extends PredicateContext
2079
+ ? ResolvedSelectionOutput<Selection, Available, Assumptions, Facts>
2080
+ : never
1640
2081
  : never
1641
2082
  : never
1642
2083
  : never
@@ -1648,7 +2089,7 @@ export type ResultRows<PlanValue extends QueryPlan<any, any, any, any, any, any,
1648
2089
  export type RuntimeResultRow<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1649
2090
  SelectionOfPlan<PlanValue> extends infer Selection
1650
2091
  ? AvailableOfPlan<PlanValue> extends infer Available extends Record<string, RowSet.AnySource>
1651
- ? OutputOfSelection<Selection, Available, TrueAssumptions>
2092
+ ? OutputOfSelection<Selection, Available, TrueAssumptions, EmptyFacts>
1652
2093
  : never
1653
2094
  : never
1654
2095
 
@@ -1734,9 +2175,9 @@ type IsDialectCompatible<
1734
2175
  EngineDialect extends string
1735
2176
  > = [PlanDialect] extends [never]
1736
2177
  ? true
1737
- : Extract<PlanDialect, EngineDialect> extends never
1738
- ? false
1739
- : true
2178
+ : Exclude<PlanDialect, EngineDialect> extends never
2179
+ ? true
2180
+ : false
1740
2181
 
1741
2182
  /** Narrows a complete plan to those compatible with a target engine dialect. */
1742
2183
  export type DialectCompatiblePlan<
@@ -1746,15 +2187,27 @@ export type DialectCompatiblePlan<
1746
2187
  ? CompletePlan<PlanValue>
1747
2188
  : DialectCompatibilityError<PlanValue, EngineDialect>
1748
2189
 
2190
+ type SelectLikeStatement = "select" | "set"
2191
+
2192
+ type NestedPlanStatementError<
2193
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
2194
+ > = PlanValue & {
2195
+ readonly __effect_qb_error__: "effect-qb: subquery expressions only accept select-like query plans"
2196
+ readonly __effect_qb_statement__: StatementOfPlan<PlanValue>
2197
+ readonly __effect_qb_hint__: "Use select(...) or a set operator as the nested subquery expression"
2198
+ }
2199
+
1749
2200
  /** Nested-plan compatibility used by subquery expressions such as `exists(...)`. */
1750
2201
  export type DialectCompatibleNestedPlan<
1751
2202
  PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>,
1752
2203
  EngineDialect extends string
1753
2204
  > = IsDialectCompatible<PlanValue[typeof RowSet.TypeId]["dialect"], EngineDialect> extends true
1754
- ? AggregationCompatiblePlan<PlanValue>
2205
+ ? StatementOfPlan<PlanValue> extends SelectLikeStatement
2206
+ ? AggregationCompatiblePlan<PlanValue>
2207
+ : NestedPlanStatementError<PlanValue>
1755
2208
  : DialectCompatibilityError<PlanValue, EngineDialect>
1756
2209
 
1757
- type SetOperandStatement = "select" | "set"
2210
+ type SetOperandStatement = SelectLikeStatement
1758
2211
  type IsUnion<Value, All = Value> = Value extends any ? ([All] extends [Value] ? false : true) : never
1759
2212
 
1760
2213
  type SingleSelectedExpressionError<
@@ -1858,7 +2311,8 @@ export type QueryPlan<
1858
2311
  Capabilities extends QueryCapability = "read",
1859
2312
  Statement extends QueryAst.QueryStatement = "select",
1860
2313
  Target = any,
1861
- InsertState extends InsertSourceState = InsertSourceState
2314
+ InsertState extends InsertSourceState = InsertSourceState,
2315
+ Facts extends PredicateContext = PredicateContext
1862
2316
  > = RowSet.RowSet<Selection, Required, Available, Dialect> & {
1863
2317
  readonly [QueryTypeId]: QueryState<
1864
2318
  Outstanding,
@@ -1868,7 +2322,8 @@ export type QueryPlan<
1868
2322
  Capabilities,
1869
2323
  Statement,
1870
2324
  Target,
1871
- InsertState
2325
+ InsertState,
2326
+ Facts
1872
2327
  >
1873
2328
  readonly [QueryAst.TypeId]: QueryAst.Ast<Selection, Grouped, Statement>
1874
2329
  }
@@ -1958,6 +2413,7 @@ export const makeExpression = <
1958
2413
  readonly runtime: Runtime
1959
2414
  readonly dbType: Db
1960
2415
  readonly runtimeSchema?: Schema.Schema.Any
2416
+ readonly driverValueMapping?: Expression.DriverValueMapping
1961
2417
  readonly nullability: Nullable
1962
2418
  readonly dialect: Dialect
1963
2419
  readonly kind?: Kind
@@ -1979,6 +2435,7 @@ export const makeExpression = <
1979
2435
  runtime: state.runtime,
1980
2436
  dbType: state.dbType,
1981
2437
  runtimeSchema: state.runtimeSchema,
2438
+ driverValueMapping: state.driverValueMapping,
1982
2439
  nullability: state.nullability,
1983
2440
  dialect: state.dialect,
1984
2441
  kind: state.kind ?? ("scalar" as Kind),
@@ -2004,7 +2461,8 @@ export const makePlan = <
2004
2461
  Capabilities extends QueryCapability = "read",
2005
2462
  Statement extends QueryAst.QueryStatement = "select",
2006
2463
  Target = any,
2007
- InsertState extends InsertSourceState = InsertSourceState
2464
+ InsertState extends InsertSourceState = InsertSourceState,
2465
+ Facts extends PredicateContext = PredicateContext
2008
2466
  >(
2009
2467
  state: RowSet.State<Selection, Required, Available, Dialect>,
2010
2468
  ast: QueryAst.Ast<Selection, Grouped, Statement>,
@@ -2012,8 +2470,9 @@ export const makePlan = <
2012
2470
  _capabilities?: Capabilities,
2013
2471
  _statement?: Statement,
2014
2472
  _target?: Target,
2015
- _insertState?: InsertState
2016
- ): QueryPlan<Selection, Required, Available, Dialect, Grouped, ScopedNames, Outstanding, Assumptions, Capabilities, Statement, Target, InsertState> => {
2473
+ _insertState?: InsertState,
2474
+ _facts?: Facts
2475
+ ): QueryPlan<Selection, Required, Available, Dialect, Grouped, ScopedNames, Outstanding, Assumptions, Capabilities, Statement, Target, InsertState, Facts> => {
2017
2476
  const plan = Object.create(PlanProto)
2018
2477
  Object.defineProperty(plan, "pipe", {
2019
2478
  configurable: true,
@@ -2029,6 +2488,7 @@ export const makePlan = <
2029
2488
  availableNames: undefined as unknown as ScopedNames,
2030
2489
  grouped: undefined as unknown as Grouped,
2031
2490
  assumptions: ((_assumptions ?? trueFormula()) as Assumptions),
2491
+ facts: ((_facts ?? undefined) as unknown as Facts),
2032
2492
  capabilities: undefined as unknown as Capabilities,
2033
2493
  statement: (_statement ?? ("select" as Statement)) as Statement,
2034
2494
  target: (_target ?? (undefined as unknown as Target)) as Target,
@@ -2049,7 +2509,7 @@ export const getAst = <
2049
2509
  /** Returns the internal phantom query state carried by a query plan. */
2050
2510
  export const getQueryState = (
2051
2511
  plan: QueryPlan<any, any, any, any, any, any, any, any, any, any>
2052
- ): QueryState<any, any, any, any, any, any, any, any> => plan[QueryTypeId]
2512
+ ): QueryState<any, any, any, any, any, any, any, any, any> => plan[QueryTypeId]
2053
2513
 
2054
2514
  /**
2055
2515
  * Collects the required table names referenced by a runtime selection object.