effect-qb 0.14.0 → 0.16.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 (146) hide show
  1. package/dist/mysql.js +61555 -4252
  2. package/dist/postgres/metadata.js +728 -104
  3. package/dist/postgres.js +6906 -4023
  4. package/package.json +15 -2
  5. package/src/internal/aggregation-validation.ts +3 -3
  6. package/src/internal/case-analysis.d.ts +18 -0
  7. package/src/internal/case-analysis.ts +4 -4
  8. package/src/internal/coercion/analysis.d.ts +7 -0
  9. package/src/internal/{coercion-analysis.ts → coercion/analysis.ts} +3 -3
  10. package/src/internal/coercion/errors.d.ts +17 -0
  11. package/src/internal/{coercion-errors.ts → coercion/errors.ts} +1 -1
  12. package/src/internal/coercion/kind.d.ts +4 -0
  13. package/src/internal/{coercion-kind.ts → coercion/kind.ts} +2 -2
  14. package/src/internal/{coercion-normalize.ts → coercion/normalize.ts} +1 -1
  15. package/src/internal/coercion/rules.d.ts +6 -0
  16. package/src/internal/{coercion-rules.ts → coercion/rules.ts} +2 -2
  17. package/src/internal/column-state.d.ts +190 -0
  18. package/src/internal/column-state.ts +43 -47
  19. package/src/internal/column.ts +43 -305
  20. package/src/internal/datatypes/define.d.ts +17 -0
  21. package/src/internal/datatypes/define.ts +18 -4
  22. package/src/internal/datatypes/lookup.d.ts +44 -0
  23. package/src/internal/datatypes/lookup.ts +61 -152
  24. package/src/internal/datatypes/shape.d.ts +16 -0
  25. package/src/internal/datatypes/shape.ts +1 -1
  26. package/src/internal/derived-table.d.ts +4 -0
  27. package/src/internal/derived-table.ts +21 -16
  28. package/src/internal/dialect.ts +12 -1
  29. package/src/internal/dsl-mutation-runtime.ts +378 -0
  30. package/src/internal/dsl-plan-runtime.ts +387 -0
  31. package/src/internal/dsl-query-runtime.ts +160 -0
  32. package/src/internal/dsl-transaction-ddl-runtime.ts +263 -0
  33. package/src/internal/executor.ts +146 -34
  34. package/src/internal/expression-ast.ts +15 -5
  35. package/src/internal/grouping-key.d.ts +3 -0
  36. package/src/internal/grouping-key.ts +1 -1
  37. package/src/internal/implication-runtime.d.ts +15 -0
  38. package/src/internal/implication-runtime.ts +4 -4
  39. package/src/internal/json/ast.d.ts +30 -0
  40. package/src/internal/json/ast.ts +1 -1
  41. package/src/internal/json/errors.d.ts +8 -0
  42. package/src/internal/json/path.d.ts +75 -0
  43. package/src/internal/json/path.ts +1 -1
  44. package/src/internal/json/types.d.ts +62 -0
  45. package/src/internal/predicate/analysis.d.ts +20 -0
  46. package/src/internal/predicate/analysis.ts +183 -0
  47. package/src/internal/predicate/atom.d.ts +28 -0
  48. package/src/internal/{predicate-atom.ts → predicate/atom.ts} +7 -0
  49. package/src/internal/{predicate-branches.ts → predicate/branches.ts} +2 -2
  50. package/src/internal/predicate/context.d.ts +67 -0
  51. package/src/internal/{predicate-context.ts → predicate/context.ts} +163 -20
  52. package/src/internal/predicate/formula.d.ts +35 -0
  53. package/src/internal/{predicate-formula.ts → predicate/formula.ts} +1 -1
  54. package/src/internal/predicate/key.d.ts +11 -0
  55. package/src/internal/predicate/key.ts +73 -0
  56. package/src/internal/{predicate-nnf.ts → predicate/nnf.ts} +2 -2
  57. package/src/internal/predicate/normalize.d.ts +53 -0
  58. package/src/internal/{predicate-normalize.ts → predicate/normalize.ts} +130 -49
  59. package/src/internal/predicate/runtime.d.ts +31 -0
  60. package/src/internal/{predicate-runtime.ts → predicate/runtime.ts} +127 -17
  61. package/src/internal/projection-alias.d.ts +13 -0
  62. package/src/internal/projections.d.ts +31 -0
  63. package/src/internal/projections.ts +1 -1
  64. package/src/internal/query-ast.d.ts +217 -0
  65. package/src/internal/query-ast.ts +1 -1
  66. package/src/internal/query-requirements.d.ts +20 -0
  67. package/src/internal/query.d.ts +775 -0
  68. package/src/internal/query.ts +683 -369
  69. package/src/internal/renderer.ts +11 -21
  70. package/src/internal/row-set.d.ts +53 -0
  71. package/src/internal/{plan.ts → row-set.ts} +11 -9
  72. package/src/internal/runtime/driver-value-mapping.ts +186 -0
  73. package/src/internal/{runtime-normalize.ts → runtime/normalize.ts} +9 -31
  74. package/src/internal/{runtime-schema.ts → runtime/schema.ts} +13 -38
  75. package/src/internal/runtime/value.d.ts +22 -0
  76. package/src/internal/{runtime-value.ts → runtime/value.ts} +2 -2
  77. package/src/internal/scalar.d.ts +107 -0
  78. package/src/internal/scalar.ts +202 -0
  79. package/src/internal/schema-derivation.d.ts +105 -0
  80. package/src/internal/schema-expression.d.ts +18 -0
  81. package/src/internal/schema-expression.ts +38 -7
  82. package/src/internal/table-options.d.ts +94 -0
  83. package/src/internal/table-options.ts +8 -2
  84. package/src/internal/table.d.ts +173 -0
  85. package/src/internal/table.ts +32 -14
  86. package/src/mysql/column.ts +95 -18
  87. package/src/mysql/datatypes/index.ts +47 -7
  88. package/src/mysql/errors/generated.ts +57336 -0
  89. package/src/mysql/errors/index.ts +1 -0
  90. package/src/mysql/errors/normalize.ts +55 -53
  91. package/src/mysql/errors/types.ts +74 -0
  92. package/src/mysql/executor.ts +88 -11
  93. package/src/mysql/function/aggregate.ts +1 -5
  94. package/src/mysql/function/core.ts +1 -4
  95. package/src/mysql/function/index.ts +0 -1
  96. package/src/mysql/function/string.ts +1 -5
  97. package/src/mysql/function/temporal.ts +12 -15
  98. package/src/mysql/function/window.ts +1 -6
  99. package/src/{internal/mysql-dialect.ts → mysql/internal/dialect.ts} +12 -6
  100. package/src/{internal/mysql-query.ts → mysql/internal/dsl.ts} +1299 -2143
  101. package/src/mysql/internal/renderer.ts +46 -0
  102. package/src/mysql/internal/sql-expression-renderer.ts +1501 -0
  103. package/src/mysql/json.ts +2 -0
  104. package/src/mysql/query.ts +111 -91
  105. package/src/mysql/renderer.ts +8 -3
  106. package/src/mysql/table.ts +1 -1
  107. package/src/mysql.ts +6 -4
  108. package/src/postgres/cast.ts +30 -16
  109. package/src/postgres/column.ts +179 -46
  110. package/src/postgres/datatypes/index.d.ts +515 -0
  111. package/src/postgres/datatypes/index.ts +22 -13
  112. package/src/postgres/datatypes/spec.d.ts +412 -0
  113. package/src/postgres/errors/generated.ts +2636 -0
  114. package/src/postgres/errors/index.ts +1 -0
  115. package/src/postgres/errors/normalize.ts +47 -62
  116. package/src/postgres/errors/types.ts +92 -34
  117. package/src/postgres/executor.ts +54 -7
  118. package/src/postgres/function/aggregate.ts +1 -5
  119. package/src/postgres/function/core.ts +12 -6
  120. package/src/postgres/function/index.ts +0 -1
  121. package/src/postgres/function/string.ts +1 -5
  122. package/src/postgres/function/temporal.ts +12 -15
  123. package/src/postgres/function/window.ts +1 -6
  124. package/src/{internal/postgres-dialect.ts → postgres/internal/dialect.ts} +12 -6
  125. package/src/{internal/postgres-query.ts → postgres/internal/dsl.ts} +1356 -2133
  126. package/src/{internal/postgres-renderer.ts → postgres/internal/renderer.ts} +17 -8
  127. package/src/postgres/internal/schema-ddl.ts +108 -0
  128. package/src/{internal/postgres-schema-model.ts → postgres/internal/schema-model.ts} +12 -6
  129. package/src/{internal → postgres/internal}/sql-expression-renderer.ts +79 -25
  130. package/src/postgres/{function/json.ts → json.ts} +77 -85
  131. package/src/postgres/metadata.ts +2 -2
  132. package/src/postgres/query.ts +113 -89
  133. package/src/postgres/renderer.ts +8 -13
  134. package/src/postgres/schema-expression.ts +2 -1
  135. package/src/postgres/schema-management.ts +1 -1
  136. package/src/postgres/table.ts +12 -4
  137. package/src/postgres/type.ts +33 -2
  138. package/src/postgres.ts +6 -4
  139. package/src/internal/expression.ts +0 -327
  140. package/src/internal/mysql-renderer.ts +0 -37
  141. package/src/internal/predicate-analysis.ts +0 -81
  142. package/src/internal/predicate-key.ts +0 -28
  143. package/src/internal/schema-ddl.ts +0 -55
  144. package/src/mysql/function/json.ts +0 -4
  145. package/src/mysql/private/query.ts +0 -1
  146. package/src/postgres/private/query.ts +0 -1
@@ -1,7 +1,8 @@
1
1
  import { pipeArguments, type Pipeable } from "effect/Pipeable"
2
+ import type * as Schema from "effect/Schema"
2
3
 
3
- import * as Expression from "./expression.js"
4
- import * as Plan from "./plan.js"
4
+ import * as Expression from "./scalar.js"
5
+ import * as RowSet from "./row-set.js"
5
6
  import * as Table from "./table.js"
6
7
  import * as ExpressionAst from "./expression-ast.js"
7
8
  import * as QueryAst from "./query-ast.js"
@@ -9,10 +10,23 @@ import type { JsonNode } from "./json/ast.js"
9
10
  import type * as JsonPath from "./json/path.js"
10
11
  import type { QueryCapability } from "./query-requirements.js"
11
12
  import type { CaseBranchAssumeFalse, CaseBranchAssumeTrue, CaseBranchDecision } from "./case-analysis.js"
12
- import type { ContradictsFormula, GuaranteedNonNullKeys, GuaranteedNullKeys, GuaranteedSourceNames } from "./predicate-analysis.js"
13
- import type { ColumnKeyOfExpression } from "./predicate-key.js"
14
- import type { PredicateFormula, TrueFormula } from "./predicate-formula.js"
15
- import { trueFormula } from "./predicate-runtime.js"
13
+ import type {
14
+ ContradictsFormula,
15
+ EmptyFacts,
16
+ FactsOfFormula,
17
+ GuaranteedLiteralSetInFacts,
18
+ GuaranteedNeqLiteralInFacts,
19
+ GuaranteedJsonLiteralSetInFacts,
20
+ GuaranteedNonNullKeysInFacts,
21
+ GuaranteedNullKeysInFacts,
22
+ GuaranteedSourceNamesInFacts,
23
+ PredicateState
24
+ } from "./predicate/analysis.js"
25
+ import type { AssumeFactsFalse, AssumeFactsTrue, PredicateContext } from "./predicate/context.js"
26
+ import type { FormulaOfPredicate } from "./predicate/normalize.js"
27
+ import type { ColumnKeyOfAst, ColumnKeyOfExpression, PredicateKeyOfAst } from "./predicate/key.js"
28
+ import type { PredicateFormula, TrueFormula } from "./predicate/formula.js"
29
+ import { trueFormula } from "./predicate/runtime.js"
16
30
 
17
31
  export type {
18
32
  MergeCapabilities,
@@ -25,7 +39,7 @@ export type {
25
39
  RuntimeOfDbType,
26
40
  TextCompatibleDbType,
27
41
  CastableDbType
28
- } from "./coercion-analysis.js"
42
+ } from "./coercion/analysis.js"
29
43
  export type {
30
44
  CanonicalSegment as JsonPathSegment,
31
45
  DescendSegment as JsonPathDescendSegment,
@@ -60,12 +74,12 @@ export type {
60
74
  export type {
61
75
  CoercionKind,
62
76
  CoercionKindOf
63
- } from "./coercion-kind.js"
77
+ } from "./coercion/kind.js"
64
78
  export type {
65
79
  CanCastDbType,
66
80
  CanCompareDbTypes,
67
81
  CanContainDbTypes
68
- } from "./coercion-rules.js"
82
+ } from "./coercion/rules.js"
69
83
  export type {
70
84
  ConflictClause,
71
85
  LockClause,
@@ -99,12 +113,12 @@ const PlanProto = {
99
113
  }
100
114
 
101
115
  /** Internal symbol used to preserve query-only phantom metadata through inference. */
102
- const QueryTypeId: unique symbol = Symbol.for("effect-qb/Query/internal")
116
+ export const QueryTypeId: unique symbol = Symbol.for("effect-qb/Query/internal")
103
117
 
104
118
  type InsertSourceState = "ready" | "missing"
105
119
 
106
120
  /** Internal phantom state tracked on query plans. */
107
- interface QueryState<
121
+ export interface QueryState<
108
122
  Outstanding extends string,
109
123
  AvailableNames extends string,
110
124
  Grouped extends string,
@@ -112,26 +126,26 @@ interface QueryState<
112
126
  Capabilities extends QueryCapability,
113
127
  Statement extends QueryAst.QueryStatement,
114
128
  Target,
115
- InsertState extends InsertSourceState
129
+ InsertState extends InsertSourceState,
130
+ Facts extends PredicateContext
116
131
  > {
117
132
  readonly required: Outstanding
118
133
  readonly availableNames: AvailableNames
119
134
  readonly grouped: Grouped
120
135
  readonly assumptions: Assumptions
136
+ readonly facts: Facts
121
137
  readonly capabilities: Capabilities
122
138
  readonly statement: Statement
123
139
  readonly target: Target
124
140
  readonly insertSource: InsertState
125
141
  }
126
142
 
127
- /** Source provenance attached to an expression. */
128
- export type SourceOf<Value extends Expression.Any> = Value[typeof Expression.TypeId]["source"]
129
143
  /** Effective SQL dialect carried by an expression. */
130
144
  export type DialectOf<Value extends Expression.Any> = Value[typeof Expression.TypeId]["dialect"]
131
- /** Source dependency map carried by an expression. */
145
+ /** Source dependency union carried by an expression. */
132
146
  export type DependenciesOf<Value extends Expression.Any> = Expression.DependenciesOf<Value>
133
147
  /** Aggregation kind carried by an expression. */
134
- export type AggregationOf<Value extends Expression.Any> = Value[typeof Expression.TypeId]["aggregation"]
148
+ export type KindOf<Value extends Expression.Any> = Value[typeof Expression.TypeId]["kind"]
135
149
  type AstOf<Value extends Expression.Any> = Value extends { readonly [ExpressionAst.TypeId]: infer Ast extends ExpressionAst.Any } ? Ast : never
136
150
 
137
151
  /**
@@ -143,11 +157,11 @@ type AstOf<Value extends Expression.Any> = Value extends { readonly [ExpressionA
143
157
  export type LiteralValue = string | number | boolean | null | Date
144
158
 
145
159
  /** Runtime expression type produced by `literal(...)` for a primitive value. */
146
- type LiteralExpression<Value extends LiteralValue> = Expression.Expression<
160
+ type LiteralExpression<Value extends LiteralValue> = Expression.Scalar<
147
161
  Value,
148
162
  LiteralDbType<Value>,
149
163
  LiteralNullability<Value>,
150
- "postgres",
164
+ string,
151
165
  "scalar",
152
166
  never
153
167
  >
@@ -161,21 +175,19 @@ type LiteralExpression<Value extends LiteralValue> = Expression.Expression<
161
175
  export type ExpressionInput = Expression.Any | LiteralValue
162
176
 
163
177
  /** Input accepted by numeric clauses such as `limit(...)` and `offset(...)`. */
164
- export type NumericExpressionInput = Expression.Expression<
178
+ export type NumericExpressionInput = Expression.Scalar<
165
179
  number,
166
180
  Expression.DbType.Any,
167
181
  Expression.Nullability,
168
182
  string,
169
183
  "scalar",
170
- any,
171
- Expression.SourceDependencies,
172
- Expression.SourceNullabilityMode
184
+ Expression.BindingId
173
185
  > | number
174
186
 
175
187
  /** Values accepted by mutation payload fields. */
176
188
  export type MutationValueInput<Value> =
177
189
  | Value
178
- | Expression.Expression<Value, Expression.DbType.Any, Expression.Nullability, string, Expression.AggregationKind, any, any, any>
190
+ | Expression.Scalar<Value, Expression.DbType.Any, Expression.Nullability, string, Expression.ScalarKind, Expression.BindingId>
179
191
 
180
192
  /** Maps a payload shape to values or expressions of the same runtime type. */
181
193
  export type MutationInputOf<Shape> = {
@@ -185,74 +197,64 @@ export type MutationInputOf<Shape> = {
185
197
  type Simplify<T> = { readonly [K in keyof T]: T[K] } & {}
186
198
 
187
199
  /** Input accepted by boolean plan clauses such as `where(...)` and joins. */
188
- export type PredicateInput = Expression.Expression<
200
+ export type PredicateInput = Expression.Scalar<
189
201
  boolean,
190
202
  Expression.DbType.Any,
191
203
  Expression.Nullability,
192
204
  string,
193
205
  "scalar",
194
- any,
195
- Expression.SourceDependencies,
196
- Expression.SourceNullabilityMode
206
+ Expression.BindingId
197
207
  > | boolean
198
208
 
199
209
  /** Input accepted by `having(...)`. */
200
- export type HavingPredicateInput = Expression.Expression<
210
+ export type HavingPredicateInput = Expression.Scalar<
201
211
  boolean,
202
212
  Expression.DbType.Any,
203
213
  Expression.Nullability,
204
214
  string,
205
215
  "scalar" | "aggregate",
206
- any,
207
- Expression.SourceDependencies,
208
- Expression.SourceNullabilityMode
216
+ Expression.BindingId
209
217
  > | boolean
210
218
 
211
219
  /** Input accepted by `GROUP BY`. */
212
- export type GroupByInput = Expression.Expression<
220
+ export type GroupByInput = Expression.Scalar<
213
221
  any,
214
222
  Expression.DbType.Any,
215
223
  Expression.Nullability,
216
224
  string,
217
225
  "scalar",
218
- any
226
+ Expression.BindingId
219
227
  >
220
228
 
221
229
  /** Maps a literal runtime value to its SQL-level DB type descriptor. */
222
230
  type LiteralDbType<Value extends LiteralValue> =
223
- Value extends string ? Expression.DbType.PgText :
224
- Value extends number ? Expression.DbType.PgNumeric :
225
- Value extends boolean ? Expression.DbType.PgBool :
226
- Value extends Date ? Expression.DbType.PgTimestamp :
227
- Expression.DbType.Base<"postgres", "null">
231
+ Value extends string ? Expression.DbType.Base<string, "text"> :
232
+ Value extends number ? Expression.DbType.Base<string, "numeric"> :
233
+ Value extends boolean ? Expression.DbType.Base<string, "boolean"> :
234
+ Value extends Date ? Expression.DbType.Base<string, "timestamp"> :
235
+ Expression.DbType.Base<string, "null">
228
236
 
229
237
  /** Maps a literal runtime value to its static nullability state. */
230
238
  type LiteralNullability<Value extends LiteralValue> = Value extends null ? "always" : "never"
231
239
  /** Converts a supported input into its canonical expression type. */
232
240
  type AsExpression<Value extends ExpressionInput> = Value extends Expression.Any ? Value : LiteralExpression<Extract<Value, LiteralValue>>
233
- /** Extracts provenance from an operator input after coercion. */
234
- type SourceOfInput<Value extends ExpressionInput> = SourceOf<AsExpression<Value>>
235
241
  /** Extracts dialect from an operator input after coercion. */
236
242
  type DialectOfInput<Value extends ExpressionInput> = DialectOf<AsExpression<Value>>
237
243
  /** Extracts dependencies from an operator input after coercion. */
238
244
  type DependenciesOfInput<Value extends ExpressionInput> = DependenciesOf<AsExpression<Value>>
239
- /** Extracts required sources from an operator input after coercion. */
240
- type RequiredFromInput<Value extends ExpressionInput> = RequiredFromDependencies<DependenciesOfInput<Value>>
245
+ /** Extracts required bindings from an operator input after coercion. */
246
+ type RequiredFromInput<Value extends ExpressionInput> = DependenciesOfInput<Value>
241
247
  /** String-valued expressions accepted by text operators. */
242
- export type StringExpressionInput = Expression.Expression<
248
+ export type StringExpressionInput = Expression.Scalar<
243
249
  string | null,
244
250
  Expression.DbType.Any,
245
251
  Expression.Nullability,
246
252
  string,
247
- Expression.AggregationKind,
248
- any,
249
- Expression.SourceDependencies,
250
- Expression.SourceNullabilityMode
253
+ Expression.ScalarKind,
254
+ Expression.BindingId
251
255
  > | string
252
256
  /** Converts a string operator input into its canonical expression type. */
253
257
  type AsStringExpression<Value extends StringExpressionInput> = Value extends Expression.Any ? Value : LiteralExpression<Extract<Value, string>>
254
- /** Extracts provenance from a string operator input after coercion. */
255
- type SourceOfStringInput<Value extends StringExpressionInput> = SourceOf<AsStringExpression<Value>>
256
258
  /** Extracts dialect from a string operator input after coercion. */
257
259
  type DialectOfStringInput<Value extends StringExpressionInput> = DialectOf<AsStringExpression<Value>>
258
260
  /** Extracts dependencies from a string operator input after coercion. */
@@ -260,10 +262,8 @@ type DependenciesOfStringInput<Value extends StringExpressionInput> = Dependenci
260
262
  /** Extracts intrinsic nullability from a string operator input after coercion. */
261
263
  type NullabilityOfStringInput<Value extends StringExpressionInput> = Expression.NullabilityOf<AsStringExpression<Value>>
262
264
 
263
- /** Extracts a required table name from expression provenance. */
264
- type RequiredFromSource<Source> = Source extends { readonly tableName: infer Name extends string } ? Name : never
265
- /** Extracts required table names from an expression dependency map. */
266
- export type RequiredFromDependencies<Dependencies extends Expression.SourceDependencies> = Extract<keyof Dependencies, string>
265
+ /** Extracts required bindings from an expression dependency union. */
266
+ export type RequiredFromDependencies<Dependencies extends Expression.BindingId> = Dependencies
267
267
 
268
268
  type LiteralGroupingKey<Value> =
269
269
  Value extends string ? `string:${Value}` :
@@ -378,8 +378,13 @@ type GroupingKeyOfAst<Ast extends ExpressionAst.Any> =
378
378
  ? "exists(subquery)"
379
379
  : never
380
380
 
381
- /** Canonical grouping identity for an expression AST. */
382
- export type GroupingKeyOfExpression<Value extends Expression.Any> = GroupingKeyOfAst<AstOf<Value>>
381
+ /** Canonical grouping identity for an expression. */
382
+ export type GroupingKeyOfExpression<Value extends Expression.Any> =
383
+ Expression.GroupKeyOf<Value> extends infer GroupKey extends string
384
+ ? string extends GroupKey
385
+ ? GroupingKeyOfAst<AstOf<Value>>
386
+ : GroupKey
387
+ : GroupingKeyOfAst<AstOf<Value>>
383
388
 
384
389
  /**
385
390
  * Recursive selection tree accepted by `select(...)`.
@@ -418,7 +423,7 @@ export type ExtractDialect<Selection> = Selection extends Expression.Any
418
423
  * The query layer only needs the plan metadata and the static table name. It
419
424
  * deliberately avoids depending on the full table-definition surface.
420
425
  */
421
- export type TableLike<Name extends string = string, Dialect extends string = string> = Plan.Plan<any, any, Record<string, Plan.AnySource>, Dialect> & {
426
+ export type TableLike<Name extends string = string, Dialect extends string = string> = RowSet.RowSet<any, any, Record<string, RowSet.AnySource>, Dialect> & {
422
427
  readonly [Table.TypeId]: {
423
428
  readonly name: Name
424
429
  readonly baseName: string
@@ -556,6 +561,9 @@ export type TableFunctionSource<
556
561
  readonly columns: DerivedSelectionOf<Selection, Alias>
557
562
  }
558
563
 
564
+ /** Broad structural shape for table-function sources when used as composable inputs. */
565
+ export type AnyTableFunctionSource = TableFunctionSource<Record<string, Expression.Any>, string, string, string>
566
+
559
567
  /** Accepts either a physical table or a derived table source. */
560
568
  type DerivedSourceShape = {
561
569
  readonly kind: "derived"
@@ -649,12 +657,12 @@ type JsonMutationDbKindError<
649
657
  ExpectedKind extends string,
650
658
  ReceivedKind extends string
651
659
  > = {
652
- readonly __effect_qb_error__: "effect-qb: incompatible postgres json mutation value"
660
+ readonly __effect_qb_error__: "effect-qb: incompatible json mutation value"
653
661
  readonly __effect_qb_column__: ColumnName
654
- readonly __effect_qb_reason__: "postgres json/jsonb kinds do not match"
662
+ readonly __effect_qb_reason__: "json kinds do not match"
655
663
  readonly __effect_qb_expected_json_kind__: ExpectedKind
656
664
  readonly __effect_qb_received_json_kind__: ReceivedKind
657
- readonly __effect_qb_hint__: "Use postgres.Function.json for json columns and postgres.Function.jsonb for jsonb columns"
665
+ readonly __effect_qb_hint__: "Use the dialect Json helpers that match the target json kind"
658
666
  }
659
667
 
660
668
  type JsonMutationShapeError<
@@ -662,7 +670,7 @@ type JsonMutationShapeError<
662
670
  Expected,
663
671
  Received
664
672
  > = {
665
- readonly __effect_qb_error__: "effect-qb: incompatible postgres json mutation value"
673
+ readonly __effect_qb_error__: "effect-qb: incompatible json mutation value"
666
674
  readonly __effect_qb_column__: ColumnName
667
675
  readonly __effect_qb_reason__: "json value is not assignable to the target column schema"
668
676
  readonly __effect_qb_json_issues__: JsonShapeIssues<Expected, Received>
@@ -705,6 +713,13 @@ type JsonArrayPath<Path extends string> = Path extends ""
705
713
  ? "[number]"
706
714
  : `${Path}[number]`
707
715
 
716
+ type JsonTupleIndexPath<
717
+ Path extends string,
718
+ Index extends string
719
+ > = Path extends ""
720
+ ? `[${Index}]`
721
+ : `${Path}[${Index}]`
722
+
708
723
  type JsonIssueKeyPath<Path extends string> = Path extends ""
709
724
  ? "root"
710
725
  : Path
@@ -751,6 +766,22 @@ type JsonObjectShapeIssues<
751
766
  JsonShapeIssues<Expected[K], Received[K], JsonObjectKeyPath<Path, K>>
752
767
  }[JsonSharedKeys<Expected, Received>]
753
768
 
769
+ type JsonTupleIndices<Value extends readonly unknown[]> = Extract<keyof Value, `${number}`>
770
+
771
+ type JsonTupleShapeIssues<
772
+ Expected extends readonly unknown[],
773
+ Received extends readonly unknown[],
774
+ Path extends string
775
+ > =
776
+ | {
777
+ readonly [K in Exclude<JsonTupleIndices<Expected>, JsonTupleIndices<Received>>]:
778
+ JsonShapeIssue<JsonTupleIndexPath<Path, K>, "missing_required_property", Expected[K], undefined>
779
+ }[Exclude<JsonTupleIndices<Expected>, JsonTupleIndices<Received>>]
780
+ | {
781
+ readonly [K in Extract<JsonTupleIndices<Expected>, JsonTupleIndices<Received>>]:
782
+ JsonShapeIssues<Expected[K], Received[K], JsonTupleIndexPath<Path, K>>
783
+ }[Extract<JsonTupleIndices<Expected>, JsonTupleIndices<Received>>]
784
+
754
785
  type JsonShapeIssues<
755
786
  Expected,
756
787
  Received,
@@ -759,7 +790,15 @@ type JsonShapeIssues<
759
790
  ? never
760
791
  : [Expected] extends [readonly (infer ExpectedElement)[]]
761
792
  ? [Received] extends [readonly (infer ReceivedElement)[]]
762
- ? JsonShapeIssues<ExpectedElement, ReceivedElement, JsonArrayPath<Path>>
793
+ ? number extends Expected["length"]
794
+ ? JsonShapeIssues<ExpectedElement, ReceivedElement, JsonArrayPath<Path>>
795
+ : number extends Received["length"]
796
+ ? JsonShapeIssues<ExpectedElement, ReceivedElement, JsonArrayPath<Path>>
797
+ : JsonTupleShapeIssues<Expected, Received, Path> extends infer Issues
798
+ ? [Issues] extends [never]
799
+ ? JsonShapeIssue<Path, "type_mismatch", Expected, Received>
800
+ : Issues
801
+ : never
763
802
  : JsonShapeIssue<Path, "type_mismatch", Expected, Received>
764
803
  : [Expected] extends [object]
765
804
  ? [Expected] extends [Function]
@@ -776,7 +815,7 @@ type JsonShapeIssues<
776
815
  : JsonShapeIssue<Path, "type_mismatch", Expected, Received>
777
816
 
778
817
  type MutationAcceptedInput<Column> =
779
- Column extends Expression.Expression<infer Runtime, any, any, any, any, any, any, any>
818
+ Column extends Expression.Scalar<infer Runtime, any, any, any, any, any>
780
819
  ? MutationValueInput<Runtime>
781
820
  : never
782
821
 
@@ -784,14 +823,14 @@ type MutationValueCompatibilityIssue<
784
823
  Column,
785
824
  Value,
786
825
  ColumnName extends string
787
- > = Column extends Expression.Expression<any, infer ColumnDb extends Expression.DbType.Any, any, any, any, any, any, any>
788
- ? ColumnDb extends Expression.DbType.Json<"postgres", infer ExpectedKind>
789
- ? Value extends Expression.Expression<any, infer ValueDb extends Expression.DbType.Any, any, any, any, any, any, any>
790
- ? ValueDb extends Expression.DbType.Json<"postgres", infer ReceivedKind>
826
+ > = Column extends Expression.Scalar<any, infer ColumnDb extends Expression.DbType.Any, any, any, any, any>
827
+ ? ColumnDb extends Expression.DbType.Json<infer ColumnDialect extends string, infer ExpectedKind>
828
+ ? Value extends Expression.Scalar<any, infer ValueDb extends Expression.DbType.Any, any, any, any, any>
829
+ ? ValueDb extends Expression.DbType.Json<ColumnDialect, infer ReceivedKind>
791
830
  ? [ExpectedKind] extends [ReceivedKind]
792
831
  ? [ReceivedKind] extends [ExpectedKind]
793
- ? Value extends Expression.Expression<infer ReceivedRuntime, any, any, any, any, any, any, any>
794
- ? Column extends Expression.Expression<infer ExpectedRuntime, any, any, any, any, any, any, any>
832
+ ? Value extends Expression.Scalar<infer ReceivedRuntime, any, any, any, any, any>
833
+ ? Column extends Expression.Scalar<infer ExpectedRuntime, any, any, any, any, any>
795
834
  ? [ReceivedRuntime] extends [ExpectedRuntime]
796
835
  ? never
797
836
  : JsonMutationShapeError<ColumnName, ExpectedRuntime, ReceivedRuntime>
@@ -799,29 +838,29 @@ type MutationValueCompatibilityIssue<
799
838
  : never
800
839
  : JsonMutationDbKindError<ColumnName, ExpectedKind, ReceivedKind>
801
840
  : JsonMutationDbKindError<ColumnName, ExpectedKind, ReceivedKind>
802
- : Value extends Expression.Expression<infer ReceivedRuntime, any, any, any, any, any, any, any>
803
- ? Column extends Expression.Expression<infer ExpectedRuntime, any, any, any, any, any, any, any>
841
+ : Value extends Expression.Scalar<infer ReceivedRuntime, any, any, any, any, any>
842
+ ? Column extends Expression.Scalar<infer ExpectedRuntime, any, any, any, any, any>
804
843
  ? [ReceivedRuntime] extends [ExpectedRuntime]
805
844
  ? never
806
845
  : JsonMutationShapeError<ColumnName, ExpectedRuntime, ReceivedRuntime>
807
846
  : never
808
- : Column extends Expression.Expression<infer ExpectedRuntime, any, any, any, any, any, any, any>
847
+ : Column extends Expression.Scalar<infer ExpectedRuntime, any, any, any, any, any>
809
848
  ? [Value] extends [ExpectedRuntime]
810
849
  ? never
811
850
  : JsonMutationShapeError<ColumnName, ExpectedRuntime, Value>
812
851
  : never
813
- : Column extends Expression.Expression<infer ExpectedRuntime, any, any, any, any, any, any, any>
852
+ : Column extends Expression.Scalar<infer ExpectedRuntime, any, any, any, any, any>
814
853
  ? [Value] extends [ExpectedRuntime]
815
854
  ? never
816
855
  : JsonMutationShapeError<ColumnName, ExpectedRuntime, Value>
817
856
  : never
818
- : Value extends Expression.Expression<infer ReceivedRuntime, any, any, any, any, any, any, any>
819
- ? Column extends Expression.Expression<infer ExpectedRuntime, any, any, any, any, any, any, any>
857
+ : Value extends Expression.Scalar<infer ReceivedRuntime, any, any, any, any, any>
858
+ ? Column extends Expression.Scalar<infer ExpectedRuntime, any, any, any, any, any>
820
859
  ? [ReceivedRuntime] extends [ExpectedRuntime]
821
860
  ? never
822
861
  : MutationValueShapeError<ColumnName, ExpectedRuntime, ReceivedRuntime>
823
862
  : never
824
- : Column extends Expression.Expression<infer ExpectedRuntime, any, any, any, any, any, any, any>
863
+ : Column extends Expression.Scalar<infer ExpectedRuntime, any, any, any, any, any>
825
864
  ? [Value] extends [ExpectedRuntime]
826
865
  ? never
827
866
  : MutationValueShapeError<ColumnName, ExpectedRuntime, Value>
@@ -965,15 +1004,13 @@ type DerivedLeafExpression<
965
1004
  Value extends Expression.Any,
966
1005
  Alias extends string,
967
1006
  ColumnName extends string
968
- > = Expression.Expression<
1007
+ > = Expression.Scalar<
969
1008
  Expression.RuntimeOf<Value>,
970
1009
  Expression.DbTypeOf<Value>,
971
1010
  Expression.NullabilityOf<Value>,
972
1011
  DialectOf<Value>,
973
1012
  "scalar",
974
- Expression.ColumnSource<Alias, ColumnName, Alias>,
975
- Record<Alias, true>,
976
- "propagate"
1013
+ Alias
977
1014
  > & {
978
1015
  readonly [ExpressionAst.TypeId]: ExpressionAst.ColumnNode<Alias, ColumnName>
979
1016
  }
@@ -994,41 +1031,66 @@ export type DerivedSelectionOf<
994
1031
  /** Extracts the static SQL table name from a table-like value. */
995
1032
  export type TableNameOf<T extends TableLike> = T[typeof Table.TypeId]["name"]
996
1033
  /** Extracts the effective dialect from a table-like value. */
997
- export type TableDialectOf<T extends TableLike> = T[typeof Plan.TypeId]["dialect"]
1034
+ export type TableDialectOf<T extends TableLike> = T[typeof RowSet.TypeId]["dialect"]
998
1035
  /** Names of sources already available to a plan. */
999
- type AvailableNames<Available extends Record<string, Plan.AnySource>> = Extract<keyof Available, string>
1036
+ type AvailableNames<Available extends Record<string, RowSet.AnySource>> = Extract<keyof Available, string>
1000
1037
  /** Availability mode of a named source within the current plan scope. */
1001
1038
  type SourceModeOf<
1002
- Available extends Record<string, Plan.AnySource>,
1039
+ Available extends Record<string, RowSet.AnySource>,
1003
1040
  Name extends string
1004
1041
  > = Name extends keyof Available ? Available[Name]["mode"] : never
1005
1042
  type TrueAssumptions = TrueFormula
1006
1043
 
1044
+ /** Extracts the public plan state carried under `RowSet.TypeId`. */
1045
+ type QueryPlanParts<
1046
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1047
+ > = PlanValue[typeof RowSet.TypeId]
1048
+
1049
+ /** Extracts the internal phantom query state carried under `QueryTypeId`. */
1050
+ type QueryPlanState<
1051
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1052
+ > = PlanValue[typeof QueryTypeId]
1053
+
1007
1054
  /** Extracts the selection carried by a query plan. */
1008
- export type SelectionOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1009
- PlanValue[typeof Plan.TypeId]["selection"]
1055
+ export type SelectionOfPlan<
1056
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1057
+ > = QueryPlanParts<PlanValue>["selection"]
1010
1058
  /** Extracts the public required-source state carried by a query plan. */
1011
- export type RequiredOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1012
- PlanValue[typeof Plan.TypeId]["required"]
1059
+ export type RequiredOfPlan<
1060
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1061
+ > = QueryPlanParts<PlanValue>["required"]
1013
1062
  /** Extracts the available-source scope carried by a query plan. */
1014
- export type AvailableOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1015
- PlanValue[typeof Plan.TypeId]["available"]
1063
+ export type AvailableOfPlan<
1064
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1065
+ > = QueryPlanParts<PlanValue>["available"]
1016
1066
  /** Extracts the effective dialect carried by a query plan. */
1017
- export type PlanDialectOf<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1018
- PlanValue[typeof Plan.TypeId]["dialect"]
1067
+ export type PlanDialectOf<
1068
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1069
+ > = QueryPlanParts<PlanValue>["dialect"]
1019
1070
  /** Extracts the grouped-source phantom carried by a query plan. */
1020
- export type GroupedOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1021
- PlanValue extends QueryPlan<any, any, any, any, infer Grouped, any, any, any, any, any> ? Grouped : never
1071
+ export type GroupedOfPlan<
1072
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1073
+ > = QueryPlanState<PlanValue>["grouped"]
1022
1074
  /** Extracts the available-name phantom carried by a query plan. */
1023
- export type ScopedNamesOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1024
- PlanValue extends QueryPlan<any, any, any, any, any, infer ScopedNames, any, any, any, any> ? ScopedNames : never
1075
+ export type ScopedNamesOfPlan<
1076
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1077
+ > = QueryPlanState<PlanValue>["availableNames"]
1025
1078
  /** Extracts the outstanding-required-source phantom carried by a query plan. */
1026
- export type OutstandingOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1027
- PlanValue extends QueryPlan<any, any, any, any, any, any, infer Outstanding, any, any, any> ? Outstanding : never
1028
- export type AssumptionsOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1029
- PlanValue extends QueryPlan<any, any, any, any, any, any, any, infer Assumptions, any, any> ? Assumptions : TrueAssumptions
1030
- export type CapabilitiesOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1031
- PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, infer Capabilities, any> ? Capabilities : never
1079
+ export type OutstandingOfPlan<
1080
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1081
+ > = QueryPlanState<PlanValue>["required"]
1082
+ export type AssumptionsOfPlan<
1083
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1084
+ > = QueryPlanState<PlanValue>["assumptions"]
1085
+ export type FactsOfPlan<
1086
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1087
+ > = QueryPlanState<PlanValue>["facts"]
1088
+ export type PredicateStateOfPlan<
1089
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1090
+ > = PredicateState<AssumptionsOfPlan<PlanValue>, FactsOfPlan<PlanValue>>
1091
+ export type CapabilitiesOfPlan<
1092
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1093
+ > = QueryPlanState<PlanValue>["capabilities"]
1032
1094
  /** Extracts capabilities contributed by a source wrapper. */
1033
1095
  export type SourceCapabilitiesOf<Source extends SourceLike> =
1034
1096
  Source extends TableLike<any, any> ? never :
@@ -1037,14 +1099,20 @@ export type SourceCapabilitiesOf<Source extends SourceLike> =
1037
1099
  Source extends { readonly kind: "lateral"; readonly plan: infer PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any> } ? CapabilitiesOfPlan<PlanValue> :
1038
1100
  never
1039
1101
  /** Extracts the statement kind carried by a query plan. */
1040
- export type StatementOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1041
- PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, infer Statement> ? Statement : never
1102
+ export type StatementOfPlan<
1103
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1104
+ > = QueryPlanState<PlanValue>["statement"]
1042
1105
  /** Extracts the mutation target phantom carried by a query plan. */
1043
- export type MutationTargetOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1044
- PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, infer Target> ? Target : never
1106
+ export type MutationTargetOfPlan<
1107
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1108
+ > = QueryPlanState<PlanValue>["target"]
1045
1109
  /** Extracts whether an insert plan still needs a source attached. */
1046
- export type InsertSourceStateOfPlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1047
- PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, infer InsertState> ? InsertState : "ready"
1110
+ export type InsertSourceStateOfPlan<
1111
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1112
+ > = QueryPlanState<PlanValue>["insertSource"]
1113
+ export type StateOfPlan<
1114
+ PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any, any, any>
1115
+ > = QueryPlanParts<PlanValue>
1048
1116
 
1049
1117
  type PresenceWitnessKeysOfSelection<Selection> = Selection extends Expression.Any
1050
1118
  ? AstOf<Selection> extends ExpressionAst.ColumnNode<any, any>
@@ -1060,7 +1128,7 @@ type PresenceWitnessKeysOfSelection<Selection> = Selection extends Expression.An
1060
1128
 
1061
1129
  export type PresenceWitnessKeysOfSource<Source extends SourceLike> =
1062
1130
  Source extends TableLike<any, any>
1063
- ? PresenceWitnessKeysOfSelection<Source[typeof Plan.TypeId]["selection"]>
1131
+ ? PresenceWitnessKeysOfSelection<Source[typeof RowSet.TypeId]["selection"]>
1064
1132
  : Source extends { readonly columns: infer Columns }
1065
1133
  ? PresenceWitnessKeysOfSelection<Columns>
1066
1134
  : never
@@ -1071,21 +1139,21 @@ export type PresenceWitnessKeysOfSource<Source extends SourceLike> =
1071
1139
  * This is used by `from(...)` and the join builders.
1072
1140
  */
1073
1141
  export type AddAvailable<
1074
- Available extends Record<string, Plan.AnySource>,
1142
+ Available extends Record<string, RowSet.AnySource>,
1075
1143
  Name extends string,
1076
- Mode extends Plan.SourceMode = "required",
1144
+ Mode extends RowSet.SourceMode = "required",
1077
1145
  PresentFormula extends PredicateFormula = TrueFormula,
1078
1146
  PresenceWitness extends string = never
1079
- > = Available & Record<Name, Plan.Source<Name, Mode, PresentFormula, PresenceWitness>>
1147
+ > = Available & Record<Name, RowSet.Source<Name, Mode, PresentFormula, PresenceWitness>>
1080
1148
 
1081
1149
  export type AddAvailableMany<
1082
- Available extends Record<string, Plan.AnySource>,
1150
+ Available extends Record<string, RowSet.AnySource>,
1083
1151
  Names extends string,
1084
- Mode extends Plan.SourceMode = "required",
1152
+ Mode extends RowSet.SourceMode = "required",
1085
1153
  PresentFormula extends PredicateFormula = TrueFormula,
1086
1154
  PresenceWitness extends string = never
1087
1155
  > = Available & {
1088
- readonly [K in Names]: Plan.Source<K, Mode, PresentFormula, PresenceWitness>
1156
+ readonly [K in Names]: RowSet.Source<K, Mode, PresentFormula, PresenceWitness>
1089
1157
  }
1090
1158
 
1091
1159
  /** Join mode projected into the plan's source-scope mode lattice. */
@@ -1094,27 +1162,27 @@ export type JoinSourceMode<Kind extends QueryAst.JoinKind> = Kind extends "left"
1094
1162
  : "required"
1095
1163
 
1096
1164
  type DemoteAllAvailable<
1097
- Available extends Record<string, Plan.AnySource>
1165
+ Available extends Record<string, RowSet.AnySource>
1098
1166
  > = {
1099
- readonly [K in keyof Available]: Available[K] extends Plan.Source<
1167
+ readonly [K in keyof Available]: Available[K] extends RowSet.Source<
1100
1168
  infer Name extends string,
1101
1169
  any,
1102
1170
  infer PresentFormula extends PredicateFormula,
1103
1171
  infer PresenceWitness extends string
1104
1172
  >
1105
- ? Plan.Source<Name, "optional", PresentFormula, PresenceWitness>
1173
+ ? RowSet.Source<Name, "optional", PresentFormula, PresenceWitness>
1106
1174
  : never
1107
1175
  }
1108
1176
 
1109
1177
  export type ExistingAvailableAfterJoin<
1110
- Available extends Record<string, Plan.AnySource>,
1178
+ Available extends Record<string, RowSet.AnySource>,
1111
1179
  Kind extends QueryAst.JoinKind
1112
1180
  > = Kind extends "right" | "full"
1113
1181
  ? DemoteAllAvailable<Available>
1114
1182
  : Available
1115
1183
 
1116
1184
  export type AvailableAfterJoin<
1117
- Available extends Record<string, Plan.AnySource>,
1185
+ Available extends Record<string, RowSet.AnySource>,
1118
1186
  JoinedName extends string,
1119
1187
  Kind extends QueryAst.JoinKind,
1120
1188
  PresentFormula extends PredicateFormula = TrueFormula,
@@ -1134,7 +1202,7 @@ export type AvailableAfterJoin<
1134
1202
  */
1135
1203
  export type AddExpressionRequired<
1136
1204
  Required,
1137
- Available extends Record<string, Plan.AnySource>,
1205
+ Available extends Record<string, RowSet.AnySource>,
1138
1206
  Value extends ExpressionInput
1139
1207
  > = Exclude<Required | RequiredFromInput<Value>, AvailableNames<Available>>
1140
1208
 
@@ -1146,7 +1214,7 @@ export type AddExpressionRequired<
1146
1214
  */
1147
1215
  export type AddJoinRequired<
1148
1216
  Required,
1149
- Available extends Record<string, Plan.AnySource>,
1217
+ Available extends Record<string, RowSet.AnySource>,
1150
1218
  JoinedName extends string,
1151
1219
  Predicate extends PredicateInput | never,
1152
1220
  Kind extends QueryAst.JoinKind = "inner"
@@ -1157,8 +1225,8 @@ export type AddJoinRequired<
1157
1225
 
1158
1226
  /** Merges two aggregation kinds through a derived expression. */
1159
1227
  export type MergeAggregation<
1160
- Left extends Expression.AggregationKind,
1161
- Right extends Expression.AggregationKind
1228
+ Left extends Expression.ScalarKind,
1229
+ Right extends Expression.ScalarKind
1162
1230
  > = Left extends "window"
1163
1231
  ? "window"
1164
1232
  : Right extends "window"
@@ -1172,9 +1240,9 @@ export type MergeAggregation<
1172
1240
  /** Folds aggregation kinds across a tuple of expressions. */
1173
1241
  type MergeAggregationTuple<
1174
1242
  Values extends readonly Expression.Any[],
1175
- Current extends Expression.AggregationKind = "scalar"
1243
+ Current extends Expression.ScalarKind = "scalar"
1176
1244
  > = Values extends readonly [infer Head extends Expression.Any, ...infer Tail extends readonly Expression.Any[]]
1177
- ? MergeAggregationTuple<Tail, MergeAggregation<Current, AggregationOf<Head>>>
1245
+ ? MergeAggregationTuple<Tail, MergeAggregation<Current, KindOf<Head>>>
1178
1246
  : Current
1179
1247
 
1180
1248
  /** Merges two nullability states for null-propagating scalar operators. */
@@ -1204,23 +1272,18 @@ export type TupleDialect<
1204
1272
  Values extends readonly Expression.Any[]
1205
1273
  > = Values[number] extends never ? never : DialectOf<Values[number]>
1206
1274
 
1207
- /** Source union across a tuple of expressions. */
1208
- export type TupleSource<
1209
- Values extends readonly Expression.Any[]
1210
- > = Values[number] extends never ? never : SourceOf<Values[number]>
1211
-
1212
1275
  /** Converts a union into an intersection. */
1213
1276
  type UnionToIntersection<Union> = (
1214
1277
  Union extends any ? (value: Union) => void : never
1215
1278
  ) extends (value: infer Intersection) => void ? Intersection : never
1216
1279
 
1217
- /** Dependency-map intersection suitable for provenance unions across a tuple. */
1280
+ /** Dependency union across a tuple of scalar expressions. */
1218
1281
  export type TupleDependencies<
1219
1282
  Values extends readonly Expression.Any[]
1220
- > = DependencyRecord<Values[number] extends never ? never : Extract<keyof DependenciesOf<Values[number]>, string>>
1283
+ > = Values[number] extends never ? never : DependenciesOf<Values[number]>
1221
1284
 
1222
- /** Builds a canonical dependency map from a string union of table names. */
1223
- export type DependencyRecord<Keys extends string> = [Keys] extends [never] ? {} : Record<Keys, true>
1285
+ /** Builds the canonical dependency union from a string union of table names. */
1286
+ export type DependencyRecord<Keys extends string> = Keys
1224
1287
 
1225
1288
  /** Grouped expression identities carried by a tuple of scalar expressions. */
1226
1289
  export type GroupedKeysFromValues<
@@ -1231,7 +1294,7 @@ export type GroupedKeysFromValues<
1231
1294
 
1232
1295
  /** Whether a selection contains any aggregate expressions. */
1233
1296
  type SelectionHasAggregate<Selection> = Selection extends Expression.Any
1234
- ? AggregationOf<Selection> extends "aggregate" ? true : false
1297
+ ? KindOf<Selection> extends "aggregate" ? true : false
1235
1298
  : Selection extends Record<string, any>
1236
1299
  ? Extract<{
1237
1300
  [K in keyof Selection]: SelectionHasAggregate<Selection[K]>
@@ -1243,9 +1306,9 @@ type IsGroupedSelectionValid<
1243
1306
  Selection,
1244
1307
  Grouped extends string
1245
1308
  > = Selection extends Expression.Any
1246
- ? AggregationOf<Selection> extends "aggregate"
1309
+ ? KindOf<Selection> extends "aggregate"
1247
1310
  ? true
1248
- : AggregationOf<Selection> extends "window"
1311
+ : KindOf<Selection> extends "window"
1249
1312
  ? false
1250
1313
  : RequiredFromDependencies<DependenciesOf<Selection>> extends never
1251
1314
  ? true
@@ -1281,13 +1344,14 @@ type MergeNullabilityStates<
1281
1344
 
1282
1345
  type FoldEffectiveNullability<
1283
1346
  Values extends readonly Expression.Any[],
1284
- Available extends Record<string, Plan.AnySource>,
1285
- Assumptions extends PredicateFormula
1347
+ Available extends Record<string, RowSet.AnySource>,
1348
+ Assumptions extends PredicateFormula,
1349
+ Facts extends PredicateContext
1286
1350
  > = Extract<{
1287
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1351
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1288
1352
  }[number], "always"> extends never
1289
1353
  ? Extract<{
1290
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1354
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1291
1355
  }[number], "maybe"> extends never
1292
1356
  ? "never"
1293
1357
  : "maybe"
@@ -1295,13 +1359,14 @@ type FoldEffectiveNullability<
1295
1359
 
1296
1360
  type CoalesceEffectiveNullability<
1297
1361
  Values extends readonly Expression.Any[],
1298
- Available extends Record<string, Plan.AnySource>,
1299
- Assumptions extends PredicateFormula
1362
+ Available extends Record<string, RowSet.AnySource>,
1363
+ Assumptions extends PredicateFormula,
1364
+ Facts extends PredicateContext
1300
1365
  > = Extract<{
1301
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1366
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1302
1367
  }[number], "never"> extends never
1303
1368
  ? Extract<{
1304
- [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions> : never
1369
+ [K in keyof Values]: Values[K] extends Expression.Any ? EffectiveNullability<Values[K], Available, Assumptions, Facts> : never
1305
1370
  }[number], "maybe"> extends never
1306
1371
  ? "always"
1307
1372
  : "maybe"
@@ -1315,48 +1380,48 @@ type NullabilityOfOutput<Output> =
1315
1380
  type PreciseFactSet<Value extends string> = string extends Value ? never : Value
1316
1381
 
1317
1382
  type KnownGuaranteedNullKeys<
1318
- Assumptions extends PredicateFormula
1319
- > = PreciseFactSet<GuaranteedNullKeys<Assumptions>>
1383
+ Facts extends PredicateContext
1384
+ > = PreciseFactSet<GuaranteedNullKeysInFacts<Facts>>
1320
1385
 
1321
1386
  type KnownGuaranteedNonNullKeys<
1322
- Assumptions extends PredicateFormula
1323
- > = PreciseFactSet<GuaranteedNonNullKeys<Assumptions>>
1387
+ Facts extends PredicateContext
1388
+ > = PreciseFactSet<GuaranteedNonNullKeysInFacts<Facts>>
1324
1389
 
1325
1390
  type KnownGuaranteedSourceNames<
1326
- Assumptions extends PredicateFormula
1327
- > = PreciseFactSet<GuaranteedSourceNames<Assumptions>>
1391
+ Facts extends PredicateContext
1392
+ > = PreciseFactSet<GuaranteedSourceNamesInFacts<Facts>>
1328
1393
 
1329
1394
  type ExplicitlyRequiredSourceNames<
1330
- Available extends Record<string, Plan.AnySource>
1395
+ Available extends Record<string, RowSet.AnySource>
1331
1396
  > = Extract<{
1332
1397
  readonly [K in keyof Available]:
1333
- Available[K] extends Plan.Source<any, infer Mode extends Plan.SourceMode>
1398
+ Available[K] extends RowSet.Source<any, infer Mode extends RowSet.SourceMode>
1334
1399
  ? Mode extends "required" ? K : never
1335
1400
  : never
1336
1401
  }[keyof Available], string>
1337
1402
 
1338
- type PresentFormulaOfSource<Source extends Plan.AnySource> =
1339
- Source extends Plan.Source<any, any, infer PresentFormula extends PredicateFormula, any>
1403
+ type PresentFormulaOfSource<Source extends RowSet.AnySource> =
1404
+ Source extends RowSet.Source<any, any, infer PresentFormula extends PredicateFormula, any>
1340
1405
  ? PresentFormula
1341
1406
  : TrueFormula
1342
1407
 
1343
- type PresenceWitnessesOfSource<Source extends Plan.AnySource> =
1344
- Source extends Plan.Source<any, any, any, infer PresenceWitness extends string>
1408
+ type PresenceWitnessesOfSource<Source extends RowSet.AnySource> =
1409
+ Source extends RowSet.Source<any, any, any, infer PresenceWitness extends string>
1345
1410
  ? PresenceWitness
1346
1411
  : never
1347
1412
 
1348
1413
  type ImpliedSourceNamesFromRequired<
1349
- Available extends Record<string, Plan.AnySource>,
1414
+ Available extends Record<string, RowSet.AnySource>,
1350
1415
  Required extends string
1351
1416
  > = Extract<{
1352
1417
  readonly [K in Extract<keyof Available, string>]:
1353
1418
  K extends Required
1354
- ? PreciseFactSet<GuaranteedSourceNames<PresentFormulaOfSource<Available[K]>>>
1419
+ ? PreciseFactSet<GuaranteedSourceNamesInFacts<FactsOfFormula<PresentFormulaOfSource<Available[K]>>>>
1355
1420
  : never
1356
1421
  }[Extract<keyof Available, string>], string>
1357
1422
 
1358
1423
  type ExpandRequiredSourceNames<
1359
- Available extends Record<string, Plan.AnySource>,
1424
+ Available extends Record<string, RowSet.AnySource>,
1360
1425
  Required extends string
1361
1426
  > = ExpandRequiredSourceNamesStep<
1362
1427
  Available,
@@ -1365,7 +1430,7 @@ type ExpandRequiredSourceNames<
1365
1430
  >
1366
1431
 
1367
1432
  type ExpandRequiredSourceNamesStep<
1368
- Available extends Record<string, Plan.AnySource>,
1433
+ Available extends Record<string, RowSet.AnySource>,
1369
1434
  Current extends string,
1370
1435
  Next extends string
1371
1436
  > = [Exclude<Next, Current>] extends [never]
@@ -1373,33 +1438,36 @@ type ExpandRequiredSourceNamesStep<
1373
1438
  : ExpandRequiredSourceNames<Available, Next>
1374
1439
 
1375
1440
  type DirectlyAbsentSourceNames<
1376
- Available extends Record<string, Plan.AnySource>,
1377
- Assumptions extends PredicateFormula
1441
+ Available extends Record<string, RowSet.AnySource>,
1442
+ Assumptions extends PredicateFormula,
1443
+ Facts extends PredicateContext
1378
1444
  > = Extract<{
1379
1445
  readonly [K in Extract<keyof Available, string>]:
1380
- K extends string
1381
- ? PresenceWitnessesOfSource<Available[K]> extends infer Witnesses extends string
1382
- ? Extract<Witnesses, KnownGuaranteedNullKeys<Assumptions>> extends never
1383
- ? ContradictsFormula<Assumptions, PresentFormulaOfSource<Available[K]>> extends true
1384
- ? K
1385
- : never
1386
- : K
1387
- : never
1446
+ Available[K] extends RowSet.Source<any, infer Mode extends RowSet.SourceMode, any, any>
1447
+ ? Mode extends "required"
1448
+ ? never
1449
+ : PresenceWitnessesOfSource<Available[K]> extends infer Witnesses extends string
1450
+ ? Extract<Witnesses, KnownGuaranteedNullKeys<Facts>> extends never
1451
+ ? ContradictsFormula<Assumptions, PresentFormulaOfSource<Available[K]>> extends true
1452
+ ? K
1453
+ : never
1454
+ : K
1455
+ : never
1388
1456
  : never
1389
1457
  }[Extract<keyof Available, string>], string>
1390
1458
 
1391
1459
  type ImpliedAbsentSourceNames<
1392
- Available extends Record<string, Plan.AnySource>,
1460
+ Available extends Record<string, RowSet.AnySource>,
1393
1461
  Absent extends string
1394
1462
  > = Extract<{
1395
1463
  readonly [K in Extract<keyof Available, string>]:
1396
- Extract<PreciseFactSet<GuaranteedSourceNames<PresentFormulaOfSource<Available[K]>>>, Absent> extends never
1464
+ Extract<PreciseFactSet<GuaranteedSourceNamesInFacts<FactsOfFormula<PresentFormulaOfSource<Available[K]>>>>, Absent> extends never
1397
1465
  ? never
1398
1466
  : K
1399
1467
  }[Extract<keyof Available, string>], string>
1400
1468
 
1401
1469
  type ExpandAbsentSourceNames<
1402
- Available extends Record<string, Plan.AnySource>,
1470
+ Available extends Record<string, RowSet.AnySource>,
1403
1471
  Current extends string
1404
1472
  > = ExpandAbsentSourceNamesStep<
1405
1473
  Available,
@@ -1408,7 +1476,7 @@ type ExpandAbsentSourceNames<
1408
1476
  >
1409
1477
 
1410
1478
  type ExpandAbsentSourceNamesStep<
1411
- Available extends Record<string, Plan.AnySource>,
1479
+ Available extends Record<string, RowSet.AnySource>,
1412
1480
  Current extends string,
1413
1481
  Next extends string
1414
1482
  > = [Exclude<Next, Current>] extends [never]
@@ -1416,35 +1484,38 @@ type ExpandAbsentSourceNamesStep<
1416
1484
  : ExpandAbsentSourceNames<Available, Next>
1417
1485
 
1418
1486
  type AbsentSourceNamesInScope<
1419
- Available extends Record<string, Plan.AnySource>,
1420
- Assumptions extends PredicateFormula
1421
- > = ExpandAbsentSourceNames<Available, DirectlyAbsentSourceNames<Available, Assumptions>>
1487
+ Available extends Record<string, RowSet.AnySource>,
1488
+ Assumptions extends PredicateFormula,
1489
+ Facts extends PredicateContext
1490
+ > = ExpandAbsentSourceNames<Available, DirectlyAbsentSourceNames<Available, Assumptions, Facts>>
1422
1491
 
1423
1492
  type RequiredSourceNamesInScope<
1424
- Available extends Record<string, Plan.AnySource>,
1425
- Assumptions extends PredicateFormula
1493
+ Available extends Record<string, RowSet.AnySource>,
1494
+ Assumptions extends PredicateFormula,
1495
+ Facts extends PredicateContext
1426
1496
  > = Exclude<
1427
1497
  ExpandRequiredSourceNames<
1428
1498
  Available,
1429
- ExplicitlyRequiredSourceNames<Available> | KnownGuaranteedSourceNames<Assumptions>
1499
+ ExplicitlyRequiredSourceNames<Available> | KnownGuaranteedSourceNames<Facts>
1430
1500
  >,
1431
- AbsentSourceNamesInScope<Available, Assumptions>
1501
+ AbsentSourceNamesInScope<Available, Assumptions, Facts>
1432
1502
  >
1433
1503
 
1434
1504
  type EffectiveAvailable<
1435
- Available extends Record<string, Plan.AnySource>,
1436
- Assumptions extends PredicateFormula
1505
+ Available extends Record<string, RowSet.AnySource>,
1506
+ Assumptions extends PredicateFormula,
1507
+ Facts extends PredicateContext
1437
1508
  > = {
1438
1509
  readonly [K in keyof Available]:
1439
- Available[K] extends Plan.Source<
1510
+ Available[K] extends RowSet.Source<
1440
1511
  infer Name extends string,
1441
- infer Mode extends Plan.SourceMode,
1512
+ infer Mode extends RowSet.SourceMode,
1442
1513
  infer PresentFormula extends PredicateFormula,
1443
1514
  infer PresenceWitness extends string
1444
1515
  >
1445
- ? Plan.Source<
1516
+ ? RowSet.Source<
1446
1517
  Name,
1447
- K extends RequiredSourceNamesInScope<Available, Assumptions> ? "required" : Mode,
1518
+ K extends RequiredSourceNamesInScope<Available, Assumptions, Facts> ? "required" : Mode,
1448
1519
  PresentFormula,
1449
1520
  PresenceWitness
1450
1521
  > & {
@@ -1454,133 +1525,363 @@ type EffectiveAvailable<
1454
1525
  }
1455
1526
 
1456
1527
  type HasAbsentSource<
1457
- Dependencies extends Expression.SourceDependencies,
1458
- Available extends Record<string, Plan.AnySource>,
1459
- Assumptions extends PredicateFormula
1528
+ Dependencies extends Expression.BindingId,
1529
+ Available extends Record<string, RowSet.AnySource>,
1530
+ Assumptions extends PredicateFormula,
1531
+ Facts extends PredicateContext
1532
+ > = Extract<Dependencies, AbsentSourceNamesInScope<Available, Assumptions, Facts>> extends never ? false : true
1533
+
1534
+ type OptionalSourceNamesInScope<
1535
+ Available extends Record<string, RowSet.AnySource>
1460
1536
  > = Extract<{
1461
- [K in keyof Dependencies & string]:
1462
- K extends AbsentSourceNamesInScope<Available, Assumptions> ? true : never
1463
- }[keyof Dependencies & string], true> extends never ? false : true
1537
+ [K in keyof Available & string]: SourceModeOf<Available, K> extends "optional" ? K : never
1538
+ }[keyof Available & string], string>
1539
+
1540
+ type EffectiveNullabilityFromBase<
1541
+ Value extends Expression.Any,
1542
+ Available extends Record<string, RowSet.AnySource>,
1543
+ Assumptions extends PredicateFormula,
1544
+ Facts extends PredicateContext
1545
+ > = Expression.NullabilityOf<Value> extends "always" ? "always"
1546
+ : PredicateKeyOfAst<AstOf<Value>> extends infer Key extends string
1547
+ ? IsUnion<Key> extends true
1548
+ ? EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1549
+ : string extends Key
1550
+ ? EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1551
+ : Key extends KnownGuaranteedNullKeys<Facts>
1552
+ ? "always"
1553
+ : Key extends KnownGuaranteedNonNullKeys<Facts>
1554
+ ? "never"
1555
+ : EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1556
+ : EffectiveNullabilityFromSources<Value, Available, Assumptions, Facts>
1557
+
1558
+ type EffectiveNullabilityFromSources<
1559
+ Value extends Expression.Any,
1560
+ Available extends Record<string, RowSet.AnySource>,
1561
+ Assumptions extends PredicateFormula,
1562
+ Facts extends PredicateContext
1563
+ > = HasAbsentSource<DependenciesOf<Value>, Available, Assumptions, Facts> extends true ? "always"
1564
+ : HasOptionalSource<DependenciesOf<Value>, Available> extends true ? "maybe"
1565
+ : Expression.NullabilityOf<Value>
1464
1566
 
1465
1567
  type BaseEffectiveNullability<
1466
1568
  Value extends Expression.Any,
1467
- Available extends Record<string, Plan.AnySource>,
1468
- Assumptions extends PredicateFormula
1569
+ Available extends Record<string, RowSet.AnySource>,
1570
+ Assumptions extends PredicateFormula,
1571
+ Facts extends PredicateContext
1469
1572
  > = AstOf<Value> extends ExpressionAst.ColumnNode<infer TableName extends string, infer ColumnName extends string>
1470
- ? TableName extends AbsentSourceNamesInScope<Available, Assumptions>
1573
+ ? TableName extends AbsentSourceNamesInScope<Available, Assumptions, Facts>
1471
1574
  ? "always"
1472
- : `${TableName}.${ColumnName}` extends KnownGuaranteedNullKeys<Assumptions>
1575
+ : `${TableName}.${ColumnName}` extends KnownGuaranteedNullKeys<Facts>
1473
1576
  ? "always"
1474
- : `${TableName}.${ColumnName}` extends KnownGuaranteedNonNullKeys<Assumptions>
1577
+ : `${TableName}.${ColumnName}` extends KnownGuaranteedNonNullKeys<Facts>
1475
1578
  ? "never"
1476
- : Expression.NullabilityOf<Value> extends "always" ? "always"
1477
- : Expression.SourceNullabilityOf<Value> extends "resolved"
1478
- ? Expression.NullabilityOf<Value>
1479
- : HasAbsentSource<DependenciesOf<Value>, Available, Assumptions> extends true ? "always"
1480
- : HasOptionalSource<DependenciesOf<Value>, Available> extends true ? "maybe"
1481
- : Expression.NullabilityOf<Value>
1482
- : Expression.NullabilityOf<Value> extends "always" ? "always"
1483
- : Expression.SourceNullabilityOf<Value> extends "resolved"
1484
- ? Expression.NullabilityOf<Value>
1485
- : HasAbsentSource<DependenciesOf<Value>, Available, Assumptions> extends true ? "always"
1486
- : HasOptionalSource<DependenciesOf<Value>, Available> extends true ? "maybe"
1487
- : Expression.NullabilityOf<Value>
1579
+ : EffectiveNullabilityFromBase<Value, Available, Assumptions, Facts>
1580
+ : EffectiveNullabilityFromBase<Value, Available, Assumptions, Facts>
1488
1581
 
1489
1582
  type CaseOutputOf<
1490
1583
  Branches extends readonly ExpressionAst.CaseBranchNode[],
1491
1584
  Else extends Expression.Any,
1492
- Available extends Record<string, Plan.AnySource>,
1493
- Assumptions extends PredicateFormula
1585
+ Available extends Record<string, RowSet.AnySource>,
1586
+ Assumptions extends PredicateFormula,
1587
+ Facts extends PredicateContext
1494
1588
  > = Branches extends readonly [
1495
1589
  infer Head extends ExpressionAst.CaseBranchNode,
1496
1590
  ...infer Tail extends readonly ExpressionAst.CaseBranchNode[]
1497
1591
  ]
1498
1592
  ? Head extends ExpressionAst.CaseBranchNode<infer Predicate extends Expression.Any, infer Then extends Expression.Any>
1499
1593
  ? CaseBranchDecision<Assumptions, Predicate> extends "skip"
1500
- ? CaseOutputOf<Tail, Else, Available, Assumptions>
1594
+ ? CaseOutputOf<Tail, Else, Available, Assumptions, Facts>
1501
1595
  : CaseBranchDecision<Assumptions, Predicate> extends "take"
1502
- ? ExpressionOutput<Then, EffectiveAvailable<Available, CaseBranchAssumeTrue<Assumptions, Predicate>>, CaseBranchAssumeTrue<Assumptions, Predicate>>
1503
- : ExpressionOutput<Then, EffectiveAvailable<Available, CaseBranchAssumeTrue<Assumptions, Predicate>>, CaseBranchAssumeTrue<Assumptions, Predicate>> |
1504
- CaseOutputOf<Tail, Else, Available, CaseBranchAssumeFalse<Assumptions, Predicate>>
1596
+ ? FormulaOfPredicate<Predicate> extends infer BranchFormula extends PredicateFormula
1597
+ ? ExpressionOutput<
1598
+ Then,
1599
+ EffectiveAvailable<
1600
+ Available,
1601
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1602
+ AssumeFactsTrue<Facts, BranchFormula>
1603
+ >,
1604
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1605
+ AssumeFactsTrue<Facts, BranchFormula>
1606
+ >
1607
+ : never
1608
+ : FormulaOfPredicate<Predicate> extends infer BranchFormula extends PredicateFormula
1609
+ ? ExpressionOutput<
1610
+ Then,
1611
+ EffectiveAvailable<
1612
+ Available,
1613
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1614
+ AssumeFactsTrue<Facts, BranchFormula>
1615
+ >,
1616
+ CaseBranchAssumeTrue<Assumptions, Predicate>,
1617
+ AssumeFactsTrue<Facts, BranchFormula>
1618
+ > |
1619
+ CaseOutputOf<
1620
+ Tail,
1621
+ Else,
1622
+ Available,
1623
+ CaseBranchAssumeFalse<Assumptions, Predicate>,
1624
+ AssumeFactsFalse<Facts, BranchFormula>
1625
+ >
1626
+ : never
1505
1627
  : never
1506
- : ExpressionOutput<Else, EffectiveAvailable<Available, Assumptions>, Assumptions>
1628
+ : ExpressionOutput<Else, EffectiveAvailable<Available, Assumptions, Facts>, Assumptions, Facts>
1507
1629
 
1508
1630
  /** Effective nullability of an expression after source-scope nullability is applied. */
1631
+ type EffectiveNullabilityOfAst<
1632
+ Value extends Expression.Any,
1633
+ Ast extends ExpressionAst.Any,
1634
+ Available extends Record<string, RowSet.AnySource>,
1635
+ Assumptions extends PredicateFormula = TrueAssumptions,
1636
+ Facts extends PredicateContext = EmptyFacts
1637
+ > = Ast extends ExpressionAst.ColumnNode<any, any>
1638
+ ? BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1639
+ : Ast extends ExpressionAst.LiteralNode<any>
1640
+ ? Expression.NullabilityOf<Value>
1641
+ : Ast extends ExpressionAst.UnaryNode<infer Kind, infer UnaryValue extends Expression.Any>
1642
+ ? Kind extends "upper" | "lower" | "not"
1643
+ ? EffectiveNullability<UnaryValue, Available, Assumptions, Facts>
1644
+ : Kind extends "isNull" | "isNotNull" | "count"
1645
+ ? "never"
1646
+ : Expression.NullabilityOf<Value>
1647
+ : Ast extends ExpressionAst.BinaryNode<"eq", infer Left extends Expression.Any, infer Right extends Expression.Any>
1648
+ ? EffectiveNullability<Left, Available, Assumptions, Facts> extends "never"
1649
+ ? EffectiveNullability<Right, Available, Assumptions, Facts> extends "never" ? "never" : "maybe"
1650
+ : "maybe"
1651
+ : Ast extends ExpressionAst.VariadicNode<infer Kind, infer Values extends readonly Expression.Any[]>
1652
+ ? Kind extends "coalesce"
1653
+ ? CoalesceEffectiveNullability<Values, Available, Assumptions, Facts>
1654
+ : Kind extends "and" | "or" | "concat"
1655
+ ? FoldEffectiveNullability<Values, Available, Assumptions, Facts>
1656
+ : BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1657
+ : Ast extends ExpressionAst.CaseNode<infer Branches extends readonly ExpressionAst.CaseBranchNode[], infer Else extends Expression.Any>
1658
+ ? NullabilityOfOutput<CaseOutputOf<Branches, Else, Available, Assumptions, Facts>>
1659
+ : BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1660
+
1509
1661
  export type EffectiveNullability<
1510
1662
  Value extends Expression.Any,
1511
- Available extends Record<string, Plan.AnySource>,
1512
- Assumptions extends PredicateFormula = TrueAssumptions
1663
+ Available extends Record<string, RowSet.AnySource>,
1664
+ Assumptions extends PredicateFormula = TrueAssumptions,
1665
+ Facts extends PredicateContext = EmptyFacts
1513
1666
  > =
1514
1667
  AstOf<Value> extends infer Ast extends ExpressionAst.Any
1515
- ? Ast extends ExpressionAst.ColumnNode<any, any>
1516
- ? BaseEffectiveNullability<Value, Available, Assumptions>
1517
- : Ast extends ExpressionAst.LiteralNode<any>
1518
- ? Expression.NullabilityOf<Value>
1519
- : Ast extends ExpressionAst.UnaryNode<infer Kind, infer UnaryValue extends Expression.Any>
1520
- ? Kind extends "upper" | "lower" | "not"
1521
- ? EffectiveNullability<UnaryValue, Available, Assumptions>
1522
- : Kind extends "isNull" | "isNotNull" | "count"
1523
- ? "never"
1524
- : Expression.NullabilityOf<Value>
1525
- : Ast extends ExpressionAst.BinaryNode<"eq", infer Left extends Expression.Any, infer Right extends Expression.Any>
1526
- ? EffectiveNullability<Left, Available, Assumptions> extends "never"
1527
- ? EffectiveNullability<Right, Available, Assumptions> extends "never" ? "never" : "maybe"
1528
- : "maybe"
1529
- : Ast extends ExpressionAst.VariadicNode<infer Kind, infer Values extends readonly Expression.Any[]>
1530
- ? Kind extends "coalesce"
1531
- ? CoalesceEffectiveNullability<Values, Available, Assumptions>
1532
- : Kind extends "and" | "or" | "concat"
1533
- ? FoldEffectiveNullability<Values, Available, Assumptions>
1534
- : BaseEffectiveNullability<Value, Available, Assumptions>
1535
- : Ast extends ExpressionAst.CaseNode<infer Branches extends readonly ExpressionAst.CaseBranchNode[], infer Else extends Expression.Any>
1536
- ? NullabilityOfOutput<CaseOutputOf<Branches, Else, Available, Assumptions>>
1537
- : BaseEffectiveNullability<Value, Available, Assumptions>
1538
- : BaseEffectiveNullability<Value, Available, Assumptions>
1668
+ ? EffectiveNullabilityOfAst<Value, Ast, Available, Assumptions, Facts>
1669
+ : BaseEffectiveNullability<Value, Available, Assumptions, Facts>
1670
+
1671
+ type LiteralKeyValue<Value extends string> =
1672
+ Value extends `string:${infer Literal}` ? Literal :
1673
+ Value extends `number:${infer Literal extends number}` ? Literal :
1674
+ Value extends "boolean:true" ? true :
1675
+ Value extends "boolean:false" ? false :
1676
+ never
1677
+
1678
+ type LiteralSetRuntime<Values> =
1679
+ Values extends readonly (infer Value)[] ? LiteralSetRuntime<Value> :
1680
+ Values extends string ? LiteralKeyValue<Values> :
1681
+ never
1682
+
1683
+ type NarrowRuntimeToAllowed<
1684
+ Runtime,
1685
+ Allowed
1686
+ > = Runtime extends unknown
1687
+ ? Extract<Runtime, Allowed> extends infer Extracted
1688
+ ? [Extracted] extends [never]
1689
+ ? Allowed extends Runtime ? Allowed : never
1690
+ : Extracted
1691
+ : never
1692
+ : never
1693
+
1694
+ type RefineRuntimeByAllowedLiterals<
1695
+ Runtime,
1696
+ Values
1697
+ > = [Values] extends [never]
1698
+ ? Runtime
1699
+ : string extends Values
1700
+ ? Runtime
1701
+ : NarrowRuntimeToAllowed<Runtime, LiteralSetRuntime<Values>>
1702
+
1703
+ type RefineRuntimeByExcludedLiterals<
1704
+ Runtime,
1705
+ Values
1706
+ > = [Values] extends [never]
1707
+ ? Runtime
1708
+ : string extends Values
1709
+ ? Runtime
1710
+ : Exclude<Runtime, LiteralSetRuntime<Values>>
1711
+
1712
+ type JsonKeyParts<Key extends string> = string extends Key
1713
+ ? never
1714
+ : Key extends `${infer ColumnKey}#json:${infer Path}`
1715
+ ? readonly [ColumnKey, Path]
1716
+ : never
1717
+
1718
+ type LiteralSetForPredicateKey<
1719
+ Facts extends PredicateContext,
1720
+ Key extends string
1721
+ > = [JsonKeyParts<Key>] extends [never]
1722
+ ? GuaranteedLiteralSetInFacts<Facts, Key>
1723
+ : JsonKeyParts<Key> extends readonly [infer ColumnKey extends string, infer Path extends string]
1724
+ ? GuaranteedJsonLiteralSetInFacts<Facts, ColumnKey, Path>
1725
+ : never
1726
+
1727
+ type RefineRuntimeForPredicateKey<
1728
+ Runtime,
1729
+ Facts extends PredicateContext,
1730
+ Key extends string
1731
+ > = IsUnion<Key> extends true
1732
+ ? Runtime
1733
+ : string extends Key
1734
+ ? Runtime
1735
+ : RefineRuntimeByExcludedLiterals<
1736
+ RefineRuntimeByAllowedLiterals<Runtime, LiteralSetForPredicateKey<Facts, Key>>,
1737
+ GuaranteedNeqLiteralInFacts<Facts, Key>
1738
+ >
1739
+
1740
+ type JsonLiteralSetsForColumn<
1741
+ Facts extends PredicateContext,
1742
+ ColumnKey extends string
1743
+ > = [Facts["jsonLiteralSets"]] extends [{ readonly [C in ColumnKey]: infer Paths }]
1744
+ ? Paths
1745
+ : {}
1746
+
1747
+ type RefineJsonRuntimeAtPath<
1748
+ Runtime,
1749
+ Path extends string,
1750
+ Values
1751
+ > = Runtime extends unknown
1752
+ ? Path extends `${infer Head}.${infer Tail}`
1753
+ ? Runtime extends object
1754
+ ? Head extends keyof Runtime
1755
+ ? RefineJsonRuntimeAtPath<NonNullable<Runtime[Head]>, Tail, Values> extends infer Refined
1756
+ ? [Refined] extends [never]
1757
+ ? never
1758
+ : Omit<Runtime, Head> & { readonly [K in Head]: Refined }
1759
+ : never
1760
+ : never
1761
+ : never
1762
+ : Runtime extends object
1763
+ ? Path extends keyof Runtime
1764
+ ? RefineRuntimeByAllowedLiterals<NonNullable<Runtime[Path]>, Values> extends infer Refined
1765
+ ? [Refined] extends [never]
1766
+ ? never
1767
+ : Omit<Runtime, Path> & { readonly [K in Path]: Refined }
1768
+ : never
1769
+ : never
1770
+ : RefineRuntimeByAllowedLiterals<NonNullable<Runtime>, Values>
1771
+ : never
1772
+
1773
+ type RefineJsonRuntimeWithConstraints<
1774
+ Runtime,
1775
+ Constraints
1776
+ > = [keyof Constraints & string] extends [never]
1777
+ ? Runtime
1778
+ : {
1779
+ readonly [Path in keyof Constraints & string]:
1780
+ [RefineJsonRuntimeAtPath<Runtime, Path, Constraints[Path]>] extends [never] ? Path : never
1781
+ }[keyof Constraints & string] extends never
1782
+ ? UnionToIntersection<{
1783
+ readonly [Path in keyof Constraints & string]: RefineJsonRuntimeAtPath<Runtime, Path, Constraints[Path]>
1784
+ }[keyof Constraints & string]>
1785
+ : never
1786
+
1787
+ type RefineJsonRuntimeForColumn<
1788
+ Runtime,
1789
+ ColumnKey extends string,
1790
+ Facts extends PredicateContext
1791
+ > = Runtime extends object
1792
+ ? Runtime extends unknown
1793
+ ? RefineJsonRuntimeWithConstraints<Runtime, JsonLiteralSetsForColumn<Facts, ColumnKey>>
1794
+ : never
1795
+ : Runtime
1796
+
1797
+ type AssumptionRefinedRuntime<
1798
+ Ast extends ExpressionAst.Any,
1799
+ Runtime,
1800
+ Facts extends PredicateContext
1801
+ > = [PredicateKeyOfAst<Ast>] extends [never]
1802
+ ? Runtime
1803
+ : PredicateKeyOfAst<Ast> extends infer PredicateKey extends string
1804
+ ? [ColumnKeyOfAst<Ast>] extends [never]
1805
+ ? RefineRuntimeForPredicateKey<Runtime, Facts, PredicateKey>
1806
+ : ColumnKeyOfAst<Ast> extends infer ColumnKey extends string
1807
+ ? RefineRuntimeForPredicateKey<RefineJsonRuntimeForColumn<Runtime, ColumnKey, Facts>, Facts, PredicateKey>
1808
+ : Runtime
1809
+ : Runtime
1539
1810
 
1540
1811
  /** Result runtime type of an expression after effective nullability is resolved. */
1541
1812
  export type ExpressionOutput<
1542
1813
  Value extends Expression.Any,
1543
- Available extends Record<string, Plan.AnySource>,
1544
- Assumptions extends PredicateFormula = TrueAssumptions
1545
- > = AstOf<Value> extends ExpressionAst.CaseNode<infer Branches extends readonly ExpressionAst.CaseBranchNode[], infer Else extends Expression.Any>
1546
- ? CaseOutputOf<Branches, Else, Available, Assumptions>
1547
- : EffectiveNullability<Value, Available, Assumptions> extends "never"
1548
- ? Expression.NullabilityOf<Value> extends "never"
1549
- ? Expression.RuntimeOf<Value>
1550
- : NonNullable<Expression.RuntimeOf<Value>>
1551
- : EffectiveNullability<Value, Available, Assumptions> extends "always"
1552
- ? null
1553
- : Expression.RuntimeOf<Value> | null
1814
+ Available extends Record<string, RowSet.AnySource>,
1815
+ Assumptions extends PredicateFormula = TrueAssumptions,
1816
+ Facts extends PredicateContext = EmptyFacts
1817
+ > = AstOf<Value> extends infer Ast extends ExpressionAst.Any
1818
+ ? Ast extends ExpressionAst.CaseNode<infer Branches extends readonly ExpressionAst.CaseBranchNode[], infer Else extends Expression.Any>
1819
+ ? CaseOutputOf<Branches, Else, Available, Assumptions, Facts>
1820
+ : EffectiveNullabilityOfAst<Value, Ast, Available, Assumptions, Facts> extends infer Nullability
1821
+ ? Expression.NullabilityOf<Value> extends infer BaseNullability
1822
+ ? Expression.RuntimeOf<Value> extends infer Runtime
1823
+ ? AssumptionRefinedRuntime<Ast, Runtime, Facts> extends infer RefinedRuntime
1824
+ ? Nullability extends "never"
1825
+ ? BaseNullability extends "never"
1826
+ ? RefinedRuntime
1827
+ : NonNullable<RefinedRuntime>
1828
+ : Nullability extends "always"
1829
+ ? null
1830
+ : RefinedRuntime | null
1831
+ : never
1832
+ : never
1833
+ : never
1834
+ : never
1835
+ : never
1554
1836
 
1555
1837
  /** Result runtime type of a nested selection after source-scope nullability is resolved. */
1556
1838
  export type OutputOfSelection<
1557
1839
  Selection,
1558
- Available extends Record<string, Plan.AnySource>,
1559
- Assumptions extends PredicateFormula = TrueAssumptions
1840
+ Available extends Record<string, RowSet.AnySource>,
1841
+ Assumptions extends PredicateFormula = TrueAssumptions,
1842
+ Facts extends PredicateContext = EmptyFacts
1560
1843
  > = Selection extends Expression.Any
1561
- ? ExpressionOutput<Selection, Available, Assumptions>
1844
+ ? ExpressionOutput<Selection, Available, Assumptions, Facts>
1562
1845
  : Selection extends Record<string, any>
1563
1846
  ? {
1564
- readonly [K in keyof Selection]: OutputOfSelection<Selection[K], Available, Assumptions>
1847
+ readonly [K in keyof Selection]: OutputOfSelection<Selection[K], Available, Assumptions, Facts>
1565
1848
  }
1566
1849
  : never
1567
1850
 
1568
- /** Resolved row type produced by a concrete query plan. */
1569
- export type ResultRow<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> = OutputOfSelection<
1570
- PlanValue[typeof Plan.TypeId]["selection"],
1571
- EffectiveAvailable<PlanValue[typeof Plan.TypeId]["available"], AssumptionsOfPlan<PlanValue>>,
1572
- AssumptionsOfPlan<PlanValue>
1851
+ type ResolvedSelectionOutput<
1852
+ Selection,
1853
+ Available extends Record<string, RowSet.AnySource>,
1854
+ Assumptions extends PredicateFormula,
1855
+ Facts extends PredicateContext
1856
+ > = OutputOfSelection<
1857
+ Selection,
1858
+ EffectiveAvailable<Available, Assumptions, Facts>,
1859
+ Assumptions,
1860
+ Facts
1573
1861
  >
1574
1862
 
1863
+ /** Resolved row type produced by a concrete query plan. */
1864
+ export type ResultRow<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1865
+ SelectionOfPlan<PlanValue> extends infer Selection
1866
+ ? AvailableOfPlan<PlanValue> extends infer Available extends Record<string, RowSet.AnySource>
1867
+ ? AssumptionsOfPlan<PlanValue> extends infer Assumptions extends PredicateFormula
1868
+ ? FactsOfPlan<PlanValue> extends infer Facts extends PredicateContext
1869
+ ? ResolvedSelectionOutput<Selection, Available, Assumptions, Facts>
1870
+ : never
1871
+ : never
1872
+ : never
1873
+ : never
1874
+
1575
1875
  /** Resolved row collection type produced by a concrete query plan. */
1576
1876
  export type ResultRows<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> = ReadonlyArray<ResultRow<PlanValue>>
1577
1877
 
1578
1878
  /** Conservative runtime row shape produced by remapping projection aliases. */
1579
- export type RuntimeResultRow<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> = OutputOfSelection<
1580
- PlanValue[typeof Plan.TypeId]["selection"],
1581
- PlanValue[typeof Plan.TypeId]["available"],
1582
- TrueAssumptions
1583
- >
1879
+ export type RuntimeResultRow<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1880
+ SelectionOfPlan<PlanValue> extends infer Selection
1881
+ ? AvailableOfPlan<PlanValue> extends infer Available extends Record<string, RowSet.AnySource>
1882
+ ? OutputOfSelection<Selection, Available, TrueAssumptions, EmptyFacts>
1883
+ : never
1884
+ : never
1584
1885
 
1585
1886
  /** Conservative runtime row collection type. */
1586
1887
  export type RuntimeResultRows<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> = ReadonlyArray<RuntimeResultRow<PlanValue>>
@@ -1613,7 +1914,7 @@ type DialectCompatibilityError<
1613
1914
  EngineDialect extends string
1614
1915
  > = PlanValue & {
1615
1916
  readonly __effect_qb_error__: "effect-qb: plan dialect is not compatible with the target renderer or executor"
1616
- readonly __effect_qb_plan_dialect__: PlanValue[typeof Plan.TypeId]["dialect"]
1917
+ readonly __effect_qb_plan_dialect__: PlanValue[typeof RowSet.TypeId]["dialect"]
1617
1918
  readonly __effect_qb_target_dialect__: EngineDialect
1618
1919
  readonly __effect_qb_hint__: "Use the matching dialect module or renderer/executor"
1619
1920
  }
@@ -1640,25 +1941,23 @@ type InsertHasOptionalDefaults<
1640
1941
  /** Narrows a query plan to aggregate-compatible selections. */
1641
1942
  export type AggregationCompatiblePlan<
1642
1943
  PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>
1643
- > = PlanValue extends QueryPlan<infer Selection, any, any, any, infer Grouped, any, any, any, any, any>
1644
- ? IsAggregationCompatibleSelection<Selection, Grouped> extends true ? PlanValue : AggregationCompatibilityError<PlanValue>
1645
- : never
1944
+ > = IsAggregationCompatibleSelection<SelectionOfPlan<PlanValue>, GroupedOfPlan<PlanValue>> extends true
1945
+ ? PlanValue
1946
+ : AggregationCompatibilityError<PlanValue>
1646
1947
 
1647
1948
  /** Narrows a query plan to aggregate-compatible, source-complete plans. */
1648
1949
  export type CompletePlan<PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>> =
1649
- PlanValue extends QueryPlan<infer Selection, infer Required, any, any, infer Grouped, any, any, any, any, infer Statement, any, infer InsertState>
1650
- ? Statement extends "insert"
1651
- ? InsertState extends "missing"
1652
- ? InsertHasOptionalDefaults<PlanValue> extends true
1653
- ? PlanValue
1654
- : InsertSourceCompletenessError<PlanValue>
1655
- : HasKnownOutstanding<Required> extends true
1656
- ? SourceCompletenessError<PlanValue, Extract<Required, string>>
1657
- : IsAggregationCompatibleSelection<Selection, Grouped> extends true ? PlanValue : AggregationCompatibilityError<PlanValue>
1658
- : HasKnownOutstanding<Required> extends true
1659
- ? SourceCompletenessError<PlanValue, Extract<Required, string>>
1660
- : IsAggregationCompatibleSelection<Selection, Grouped> extends true ? PlanValue : AggregationCompatibilityError<PlanValue>
1661
- : never
1950
+ StatementOfPlan<PlanValue> extends "insert"
1951
+ ? InsertSourceStateOfPlan<PlanValue> extends "missing"
1952
+ ? InsertHasOptionalDefaults<PlanValue> extends true
1953
+ ? PlanValue
1954
+ : InsertSourceCompletenessError<PlanValue>
1955
+ : HasKnownOutstanding<RequiredOfPlan<PlanValue>> extends true
1956
+ ? SourceCompletenessError<PlanValue, Extract<RequiredOfPlan<PlanValue>, string>>
1957
+ : IsAggregationCompatibleSelection<SelectionOfPlan<PlanValue>, GroupedOfPlan<PlanValue>> extends true ? PlanValue : AggregationCompatibilityError<PlanValue>
1958
+ : HasKnownOutstanding<RequiredOfPlan<PlanValue>> extends true
1959
+ ? SourceCompletenessError<PlanValue, Extract<RequiredOfPlan<PlanValue>, string>>
1960
+ : IsAggregationCompatibleSelection<SelectionOfPlan<PlanValue>, GroupedOfPlan<PlanValue>> extends true ? PlanValue : AggregationCompatibilityError<PlanValue>
1662
1961
 
1663
1962
  /** Whether a plan dialect is compatible with a target engine dialect. */
1664
1963
  type IsDialectCompatible<
@@ -1674,7 +1973,7 @@ type IsDialectCompatible<
1674
1973
  export type DialectCompatiblePlan<
1675
1974
  PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>,
1676
1975
  EngineDialect extends string
1677
- > = IsDialectCompatible<PlanValue[typeof Plan.TypeId]["dialect"], EngineDialect> extends true
1976
+ > = IsDialectCompatible<PlanValue[typeof RowSet.TypeId]["dialect"], EngineDialect> extends true
1678
1977
  ? CompletePlan<PlanValue>
1679
1978
  : DialectCompatibilityError<PlanValue, EngineDialect>
1680
1979
 
@@ -1682,7 +1981,7 @@ export type DialectCompatiblePlan<
1682
1981
  export type DialectCompatibleNestedPlan<
1683
1982
  PlanValue extends QueryPlan<any, any, any, any, any, any, any, any, any, any>,
1684
1983
  EngineDialect extends string
1685
- > = IsDialectCompatible<PlanValue[typeof Plan.TypeId]["dialect"], EngineDialect> extends true
1984
+ > = IsDialectCompatible<PlanValue[typeof RowSet.TypeId]["dialect"], EngineDialect> extends true
1686
1985
  ? AggregationCompatiblePlan<PlanValue>
1687
1986
  : DialectCompatibilityError<PlanValue, EngineDialect>
1688
1987
 
@@ -1767,11 +2066,9 @@ export type SetCompatibleRightPlan<
1767
2066
 
1768
2067
  /** True when any of an expression's dependencies are optional in the current scope. */
1769
2068
  type HasOptionalSource<
1770
- Dependencies extends Expression.SourceDependencies,
1771
- Available extends Record<string, Plan.AnySource>
1772
- > = Extract<{
1773
- [K in keyof Dependencies & string]: SourceModeOf<Available, K> extends "optional" ? true : never
1774
- }[keyof Dependencies & string], true> extends never ? false : true
2069
+ Dependencies extends Expression.BindingId,
2070
+ Available extends Record<string, RowSet.AnySource>
2071
+ > = Extract<Dependencies, OptionalSourceNamesInScope<Available>> extends never ? false : true
1775
2072
 
1776
2073
  /**
1777
2074
  * Concrete query-plan value produced by the query DSL.
@@ -1783,65 +2080,53 @@ type HasOptionalSource<
1783
2080
  export type QueryPlan<
1784
2081
  Selection,
1785
2082
  Required = never,
1786
- Available extends Record<string, Plan.AnySource> = {},
2083
+ Available extends Record<string, RowSet.AnySource> = {},
1787
2084
  Dialect extends string = never,
1788
2085
  Grouped extends string = never,
1789
- ScopedNames extends string = Extract<keyof Available, string>,
1790
- Outstanding extends string = Extract<Required, string>,
2086
+ ScopedNames extends string = never,
2087
+ Outstanding extends string = never,
1791
2088
  Assumptions extends PredicateFormula = TrueAssumptions,
1792
2089
  Capabilities extends QueryCapability = "read",
1793
2090
  Statement extends QueryAst.QueryStatement = "select",
1794
- Target = unknown,
1795
- InsertState extends InsertSourceState = InsertSourceState
1796
- > = Plan.Plan<Selection, Required, Available, Dialect> & {
1797
- readonly [Plan.TypeId]: Plan.State<Selection, Required, Available, Dialect>
2091
+ Target = any,
2092
+ InsertState extends InsertSourceState = InsertSourceState,
2093
+ Facts extends PredicateContext = PredicateContext
2094
+ > = RowSet.RowSet<Selection, Required, Available, Dialect> & {
2095
+ readonly [QueryTypeId]: QueryState<
2096
+ Outstanding,
2097
+ ScopedNames,
2098
+ Grouped,
2099
+ Assumptions,
2100
+ Capabilities,
2101
+ Statement,
2102
+ Target,
2103
+ InsertState,
2104
+ Facts
2105
+ >
1798
2106
  readonly [QueryAst.TypeId]: QueryAst.Ast<Selection, Grouped, Statement>
1799
- readonly [QueryTypeId]: QueryState<Outstanding, ScopedNames, Grouped, Assumptions, Capabilities, Statement, Target, InsertState>
1800
2107
  }
1801
2108
 
1802
- /**
1803
- * Normalizes expression provenance into a flat list.
1804
- *
1805
- * Single-source expressions store one provenance object, while derived
1806
- * operators may carry multiple sources. This helper hides that shape
1807
- * difference.
1808
- */
1809
- const normalizeSources = (source: unknown): readonly unknown[] =>
1810
- source === undefined ? [] : Array.isArray(source) ? source : [source]
1811
-
1812
- /**
1813
- * Merges the provenance of two expressions into one normalized runtime value.
1814
- *
1815
- * The result is:
1816
- * - `undefined` when neither side is sourced
1817
- * - a single provenance object when exactly one source exists
1818
- * - an array when multiple sources are involved
1819
- */
1820
- export const mergeSources = (left: unknown, right?: unknown): unknown => {
1821
- const values = [...normalizeSources(left), ...normalizeSources(right)]
1822
- if (values.length === 0) {
1823
- return undefined
1824
- }
1825
- if (values.length === 1) {
1826
- return values[0]
1827
- }
1828
- return values
2109
+ export namespace Plan {
2110
+ export type Any = QueryPlan<any, any, any, any, any, any, any, any, any, any>
1829
2111
  }
1830
2112
 
1831
- /** Merges two expression dependency maps into a single normalized record. */
1832
- export const mergeDependencies = (
1833
- left: Expression.SourceDependencies,
1834
- right: Expression.SourceDependencies = {}
1835
- ): Expression.SourceDependencies => ({
1836
- ...left,
1837
- ...right
1838
- })
2113
+ /** Merges two expression dependency records into a single normalized record. */
2114
+ export const mergeDependencies = <
2115
+ Left extends Expression.BindingId = never,
2116
+ Right extends Expression.BindingId = never
2117
+ >(
2118
+ left: Record<Left, true> | undefined,
2119
+ right: Record<Right, true> | undefined = undefined
2120
+ ): Record<Left | Right, true> => ({
2121
+ ...(left ?? {}),
2122
+ ...(right ?? {})
2123
+ }) as Record<Left | Right, true>
1839
2124
 
1840
2125
  /** Merges expression aggregation kinds at runtime. */
1841
2126
  export const mergeAggregationRuntime = (
1842
- left: Expression.AggregationKind,
1843
- right: Expression.AggregationKind = "scalar"
1844
- ): Expression.AggregationKind =>
2127
+ left: Expression.ScalarKind,
2128
+ right: Expression.ScalarKind = "scalar"
2129
+ ): Expression.ScalarKind =>
1845
2130
  left === "window" || right === "window"
1846
2131
  ? "window"
1847
2132
  : left === "aggregate" || right === "aggregate"
@@ -1851,10 +2136,10 @@ export const mergeAggregationRuntime = (
1851
2136
  /** Folds runtime aggregation across a list of expressions. */
1852
2137
  export const mergeAggregationManyRuntime = (
1853
2138
  values: readonly Expression.Any[]
1854
- ): Expression.AggregationKind =>
2139
+ ): Expression.ScalarKind =>
1855
2140
  values.reduce(
1856
- (current, value) => mergeAggregationRuntime(current, value[Expression.TypeId].aggregation),
1857
- "scalar" as Expression.AggregationKind
2141
+ (current, value) => mergeAggregationRuntime(current, value[Expression.TypeId].kind),
2142
+ "scalar" as Expression.ScalarKind
1858
2143
  )
1859
2144
 
1860
2145
  /** Merges expression nullability for null-propagating scalar operators. */
@@ -1877,19 +2162,14 @@ export const mergeNullabilityManyRuntime = (
1877
2162
  "never" as Expression.Nullability
1878
2163
  )
1879
2164
 
1880
- /** Merges provenance across a variadic expression input list. */
1881
- export const mergeManySources = (values: readonly Expression.Any[]): unknown =>
1882
- values.reduce<unknown>(
1883
- (current, value) => mergeSources(current, value[Expression.TypeId].source),
1884
- undefined
1885
- )
1886
-
1887
2165
  /** Merges dependency maps across a variadic expression input list. */
1888
- export const mergeManyDependencies = (values: readonly Expression.Any[]): Expression.SourceDependencies =>
1889
- values.reduce(
1890
- (current, value) => mergeDependencies(current, value[Expression.TypeId].dependencies),
1891
- {} as Expression.SourceDependencies
1892
- )
2166
+ export const mergeManyDependencies = <Values extends readonly Expression.Any[]>(
2167
+ values: Values
2168
+ ): Record<TupleDependencies<Values>, true> =>
2169
+ values.reduce<Record<string, true>>(
2170
+ (current, value) => mergeDependencies(current, value[Expression.TypeId].dependencies) as Record<string, true>,
2171
+ {}
2172
+ ) as Record<TupleDependencies<Values>, true>
1893
2173
 
1894
2174
  /**
1895
2175
  * Creates a runtime expression object from fully computed static metadata.
@@ -1902,19 +2182,43 @@ export const makeExpression = <
1902
2182
  Db extends Expression.DbType.Any,
1903
2183
  Nullable extends Expression.Nullability,
1904
2184
  Dialect extends string,
1905
- Aggregation extends Expression.AggregationKind,
1906
- Source,
1907
- Dependencies extends Expression.SourceDependencies = {},
1908
- SourceNullability extends Expression.SourceNullabilityMode = "propagate",
1909
- Ast extends ExpressionAst.Any = ExpressionAst.Any
2185
+ Kind extends Expression.ScalarKind,
2186
+ Deps extends Expression.BindingId = never,
2187
+ Ast extends ExpressionAst.Any = ExpressionAst.Any,
2188
+ GroupKey extends string = GroupingKeyOfAst<Ast>
1910
2189
  >(
1911
- state: Expression.State<Runtime, Db, Nullable, Dialect, Aggregation, Source, Dependencies, SourceNullability>,
2190
+ state: {
2191
+ readonly runtime: Runtime
2192
+ readonly dbType: Db
2193
+ readonly runtimeSchema?: Schema.Schema.Any
2194
+ readonly driverValueMapping?: Expression.DriverValueMapping
2195
+ readonly nullability: Nullable
2196
+ readonly dialect: Dialect
2197
+ readonly kind?: Kind
2198
+ readonly dependencies?: Record<string, true>
2199
+ },
1912
2200
  ast: Ast
1913
- ): Expression.Expression<Runtime, Db, Nullable, Dialect, Aggregation, Source, Dependencies, SourceNullability> & {
2201
+ ): Expression.Scalar<Runtime, Db, Nullable, Dialect, Kind, Deps, GroupKey> & {
1914
2202
  readonly [ExpressionAst.TypeId]: Ast
1915
2203
  } => {
1916
2204
  const expression = Object.create(ExpressionProto)
1917
- expression[Expression.TypeId] = state
2205
+ Object.defineProperty(expression, "pipe", {
2206
+ configurable: true,
2207
+ writable: true,
2208
+ value: function(this: unknown) {
2209
+ return pipeArguments(expression, arguments)
2210
+ }
2211
+ })
2212
+ expression[Expression.TypeId] = {
2213
+ runtime: state.runtime,
2214
+ dbType: state.dbType,
2215
+ runtimeSchema: state.runtimeSchema,
2216
+ driverValueMapping: state.driverValueMapping,
2217
+ nullability: state.nullability,
2218
+ dialect: state.dialect,
2219
+ kind: state.kind ?? ("scalar" as Kind),
2220
+ dependencies: state.dependencies ?? {}
2221
+ } as Expression.State<Runtime, Db, Nullable, Dialect, Kind, Deps>
1918
2222
  expression[ExpressionAst.TypeId] = ast
1919
2223
  return expression
1920
2224
  }
@@ -1926,7 +2230,7 @@ export const makeExpression = <
1926
2230
  export const makePlan = <
1927
2231
  Selection,
1928
2232
  Required,
1929
- Available extends Record<string, Plan.AnySource>,
2233
+ Available extends Record<string, RowSet.AnySource>,
1930
2234
  Dialect extends string,
1931
2235
  Grouped extends string = never,
1932
2236
  ScopedNames extends string = Extract<keyof Available, string>,
@@ -1934,25 +2238,35 @@ export const makePlan = <
1934
2238
  Assumptions extends PredicateFormula = TrueAssumptions,
1935
2239
  Capabilities extends QueryCapability = "read",
1936
2240
  Statement extends QueryAst.QueryStatement = "select",
1937
- Target = never,
1938
- InsertState extends InsertSourceState = "ready"
2241
+ Target = any,
2242
+ InsertState extends InsertSourceState = InsertSourceState,
2243
+ Facts extends PredicateContext = PredicateContext
1939
2244
  >(
1940
- state: Plan.State<Selection, Required, Available, Dialect>,
2245
+ state: RowSet.State<Selection, Required, Available, Dialect>,
1941
2246
  ast: QueryAst.Ast<Selection, Grouped, Statement>,
1942
2247
  _assumptions?: Assumptions,
1943
2248
  _capabilities?: Capabilities,
1944
2249
  _statement?: Statement,
1945
2250
  _target?: Target,
1946
- _insertState?: InsertState
1947
- ): QueryPlan<Selection, Required, Available, Dialect, Grouped, ScopedNames, Outstanding, Assumptions, Capabilities, Statement, Target, InsertState> => {
2251
+ _insertState?: InsertState,
2252
+ _facts?: Facts
2253
+ ): QueryPlan<Selection, Required, Available, Dialect, Grouped, ScopedNames, Outstanding, Assumptions, Capabilities, Statement, Target, InsertState, Facts> => {
1948
2254
  const plan = Object.create(PlanProto)
1949
- plan[Plan.TypeId] = state
2255
+ Object.defineProperty(plan, "pipe", {
2256
+ configurable: true,
2257
+ writable: true,
2258
+ value: function(this: unknown) {
2259
+ return pipeArguments(plan, arguments)
2260
+ }
2261
+ })
2262
+ plan[RowSet.TypeId] = state
1950
2263
  plan[QueryAst.TypeId] = ast
1951
2264
  plan[QueryTypeId] = {
1952
2265
  required: undefined as unknown as Outstanding,
1953
2266
  availableNames: undefined as unknown as ScopedNames,
1954
2267
  grouped: undefined as unknown as Grouped,
1955
2268
  assumptions: ((_assumptions ?? trueFormula()) as Assumptions),
2269
+ facts: ((_facts ?? undefined) as unknown as Facts),
1956
2270
  capabilities: undefined as unknown as Capabilities,
1957
2271
  statement: (_statement ?? ("select" as Statement)) as Statement,
1958
2272
  target: (_target ?? (undefined as unknown as Target)) as Target,
@@ -1973,7 +2287,7 @@ export const getAst = <
1973
2287
  /** Returns the internal phantom query state carried by a query plan. */
1974
2288
  export const getQueryState = (
1975
2289
  plan: QueryPlan<any, any, any, any, any, any, any, any, any, any>
1976
- ): QueryState<any, any, any, any, any, any, any, any> => plan[QueryTypeId]
2290
+ ): QueryState<any, any, any, any, any, any, any, any, any> => plan[QueryTypeId]
1977
2291
 
1978
2292
  /**
1979
2293
  * Collects the required table names referenced by a runtime selection object.