@dbsp/core 6.3.0 → 7.1.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.
@@ -1,6 +1,6 @@
1
1
  import * as _dbsp_types from '@dbsp/types';
2
- import { REF_BRAND, ColumnType, ColumnJsReadType as ColumnJsReadType$1, WhereIntent, OnDeleteAction, TableReaddressDeclaration, ModelIR, DbCasing, PlanOptions, PlanReport, RecursivePlanOptions, RecursivePlanReport, RangeAllocator, ResolvedRange, RelationIR, DialectCapabilities, ResolvedIncludeStrategy, ExclusiveTransitionTarget, TransitionSessionClient, TransitionLessor, TransitionQueryClient, ObservationContext, TransitionRunMetadata, TransitionRule, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, FingerprintManifest, ObservationIssuer, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, DurableIntentRecord, OperationEffectAssessment, IssuedObservation, ApplyGuard, RecoveryArtefact, OperationExecutionOutcome, ManagedStepClaimMaterial, LedgerPayload, TransactionalCompletionRecord, StepJournal, TransitionRunJournal, ProvenPlanShape, ApplyPolicy, ResourceAddress, JsonValue as JsonValue$1, DeclarationSet, ApplicableAssessment, ApplyResult, ExecutionContract, DurableApplyOutcome, CompareOutcome, ProofClaim, PlanAssessment, InapplicableAssessment, TransactionBeginOptions, Dump, SortDirection, DumpMeta, Adapter, CompileOptions, CompiledQuery, DumpSequenceStep, EXPRESSION_BRAND, PREDICATE_BRAND } from '@dbsp/types';
3
- import { QueryIntent, RecursiveIntent, IncludeIntent, WhereIntent as WhereIntent$1, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, SetOperationIntent, LockStrength, LockWaitPolicy, MutationIntent as MutationIntent$1, UpsertConflictTarget, UpsertConflictAction, CompileOnlyAdapter, ExpressionIntent, IncludeOrderByIntent, SelectIntent, ComparisonOperator, WhereSubqueryIntent, SubqueryRefIntent, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereRelationFilterIntent, RecursiveExistsOptions, WhereExistsIntent, WhereInIntent, WhereNullIntent, WhereLikeIntent, WhereNotIntent, WhereNotExistsIntent, WhereOrIntent, WhereRawExistsIntent, WhereRawNotExistsIntent, WhereExpressionIntent, StandaloneWhereExpressionIntent, AggOrderByArg, PredicateOperator } from '@dbsp/types/internal';
2
+ import { REF_BRAND, ColumnJsReadType as ColumnJsReadType$1, OnDeleteAction, ColumnType, WhereIntent, TableReaddressDeclaration, ModelIR, DbCasing, PlanOptions, PlanReport, RecursivePlanOptions, RecursivePlanReport, RangeAllocator, ResolvedRange, RelationIR, DialectCapabilities, ResolvedIncludeStrategy, ExclusiveTransitionTarget, TransitionSessionClient, TransitionLessor, TransitionQueryClient, ObservationContext, TransitionRunMetadata, TransitionRule, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, FingerprintManifest, ObservationIssuer, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, DurableIntentRecord, OperationEffectAssessment, IssuedObservation, ApplyGuard, RecoveryArtefact, OperationExecutionOutcome, ManagedStepClaimMaterial, LedgerPayload, TransactionalCompletionRecord, StepJournal, TransitionRunJournal, ProvenPlanShape, ApplyPolicy, ResourceAddress, JsonValue as JsonValue$1, DeclarationSet, ApplicableAssessment, ApplyResult, ExecutionContract, DurableApplyOutcome, CompareOutcome, ProofClaim, PlanAssessment, InapplicableAssessment, TransactionBeginOptions, Dump, SortDirection, DumpMeta, Adapter, CompileOptions, CompiledQuery, DumpSequenceStep, EXPRESSION_BRAND, PREDICATE_BRAND } from '@dbsp/types';
3
+ import { QueryIntent, RecursiveIntent, IncludeIntent, WhereIntent as WhereIntent$1, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, SetOperationIntent, LockStrength, LockWaitPolicy, MutationIntent as MutationIntent$1, UpsertConflictTarget, UpsertConflictAction, CompileOnlyAdapter, ExpressionIntent, IncludeOrderByIntent, SelectIntent, ComparisonOperator, WhereSubqueryIntent, SubqueryRefIntent, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereExpressionIntent, WhereRelationFilterIntent, RecursiveExistsOptions, WhereExistsIntent, WhereInIntent, WhereNullIntent, WhereLikeIntent, WhereNotIntent, WhereNotExistsIntent, WhereOrIntent, WhereRawExistsIntent, WhereRawNotExistsIntent, StandaloneWhereExpressionIntent, AggOrderByArg, PredicateOperator } from '@dbsp/types/internal';
4
4
  import { NqlCompilerOptions, CompiledNqlQuery } from '@dbsp/nql';
5
5
 
6
6
  /**
@@ -1856,21 +1856,21 @@ declare const MSSQL_CAPABILITIES: DialectCapabilities;
1856
1856
  /**
1857
1857
  * Comparison operators for object filter syntax.
1858
1858
  * Use `$` prefix to distinguish from field names.
1859
- * Values can be literal values or SubqueryExpression for scalar subqueries.
1859
+ * Values can be literal values or expressions (ADR 0011 value position).
1860
1860
  */
1861
1861
  interface FilterOperators<T = unknown> {
1862
- /** Equals (explicit) - value or subquery */
1863
- readonly $eq?: T | SubqueryExpression;
1864
- /** Not equals - value or subquery */
1865
- readonly $neq?: T | SubqueryExpression;
1866
- /** Greater than - value or subquery */
1867
- readonly $gt?: T | SubqueryExpression;
1868
- /** Greater than or equal - value or subquery */
1869
- readonly $gte?: T | SubqueryExpression;
1870
- /** Less than - value or subquery */
1871
- readonly $lt?: T | SubqueryExpression;
1872
- /** Less than or equal - value or subquery */
1873
- readonly $lte?: T | SubqueryExpression;
1862
+ /** Equals (explicit) - value or expression (subquery, column, ExpressionRef) */
1863
+ readonly $eq?: T | ValueExpression;
1864
+ /** Not equals - value or expression (subquery, column, ExpressionRef) */
1865
+ readonly $neq?: T | ValueExpression;
1866
+ /** Greater than - value or expression (subquery, column, ExpressionRef) */
1867
+ readonly $gt?: T | ValueExpression;
1868
+ /** Greater than or equal - value or expression (subquery, column, ExpressionRef) */
1869
+ readonly $gte?: T | ValueExpression;
1870
+ /** Less than - value or expression (subquery, column, ExpressionRef) */
1871
+ readonly $lt?: T | ValueExpression;
1872
+ /** Less than or equal - value or expression (subquery, column, ExpressionRef) */
1873
+ readonly $lte?: T | ValueExpression;
1874
1874
  /** In array */
1875
1875
  readonly $in?: readonly T[];
1876
1876
  /** LIKE pattern matching */
@@ -1887,7 +1887,7 @@ interface FilterOperators<T = unknown> {
1887
1887
  * - null (IS NULL)
1888
1888
  * - Operator object ({ $gt: 18 })
1889
1889
  */
1890
- type FilterValue<T = unknown> = T | null | FilterOperators<T>;
1890
+ type FilterValue<T = unknown> = T | null | ValueExpression | FilterOperators<T>;
1891
1891
  /**
1892
1892
  * Object filter type for WHERE clause.
1893
1893
  * Maps field names to filter values.
@@ -1912,6 +1912,12 @@ type WhereFilter<T = Record<string, unknown>> = {
1912
1912
  };
1913
1913
  /**
1914
1914
  * Check if a value is a WhereIntent (not an object filter).
1915
+ *
1916
+ * True only when `kind` is a `WhereIntent` kind and the object owns that
1917
+ * kind's member (`conditions`, `condition`, `field`, `relation`, `subquery`
1918
+ * or `expr`). An object filter over a column named `kind` is therefore not an
1919
+ * intent; one that also names the kind's member column is, and is written in
1920
+ * operator form instead (`{ kind: { $eq: 'comparison' }, field: 'x' }`).
1915
1921
  */
1916
1922
  declare function isWhereIntent(value: unknown): value is WhereIntent$1;
1917
1923
  /**
@@ -2336,7 +2342,7 @@ interface QueryBuilder<TResult = unknown> {
2336
2342
  columns<const T extends readonly ((keyof TResult & string) | AliasedExprColumn<string>)[]>(columns: T): QueryBuilder<Pick<TResult, Extract<T[number], keyof TResult & string>> & {
2337
2343
  [E in Extract<T[number], AliasedExprColumn<string>> as E['__alias']]: E['__value'];
2338
2344
  }>;
2339
- columns(columns: readonly ColumnSpec[]): QueryBuilder<TResult>;
2345
+ columns(columns: readonly (ColumnSpec | ColumnRef<string, string, unknown> | RefDefinition)[]): QueryBuilder<TResult>;
2340
2346
  /**
2341
2347
  * Add a COALESCE expression to the select, with full type inference.
2342
2348
  *
@@ -2400,7 +2406,7 @@ interface QueryBuilder<TResult = unknown> {
2400
2406
  * ```
2401
2407
  */
2402
2408
  count(options?: AggregateOptions): QueryBuilder<TResult>;
2403
- count(field: string, as?: string): QueryBuilder<TResult>;
2409
+ count(field: string | ColumnRef<string, string, unknown>, as?: string): QueryBuilder<TResult>;
2404
2410
  count(field: DistinctField, as?: string): QueryBuilder<TResult>;
2405
2411
  /**
2406
2412
  * Calculate sum of a field.
@@ -2416,7 +2422,7 @@ interface QueryBuilder<TResult = unknown> {
2416
2422
  * orm.select('orders').sum(distinct('amount'), 'unique_total').execute();
2417
2423
  * ```
2418
2424
  */
2419
- sum(field: string | DistinctField, as?: string): QueryBuilder<TResult>;
2425
+ sum(field: string | ColumnRef<string, string, unknown> | DistinctField, as?: string): QueryBuilder<TResult>;
2420
2426
  /**
2421
2427
  * Calculate average of a field.
2422
2428
  * Supports DISTINCT averaging via the distinct() helper.
@@ -2425,7 +2431,7 @@ interface QueryBuilder<TResult = unknown> {
2425
2431
  * @param as - Optional alias for result column
2426
2432
  * @returns A new QueryBuilder configured for AVG
2427
2433
  */
2428
- avg(field: string | DistinctField, as?: string): QueryBuilder<TResult>;
2434
+ avg(field: string | ColumnRef<string, string, unknown> | DistinctField, as?: string): QueryBuilder<TResult>;
2429
2435
  /**
2430
2436
  * Find minimum value of a field.
2431
2437
  *
@@ -2433,7 +2439,7 @@ interface QueryBuilder<TResult = unknown> {
2433
2439
  * @param as - Optional alias for result column
2434
2440
  * @returns A new QueryBuilder configured for MIN
2435
2441
  */
2436
- min(field: string, as?: string): QueryBuilder<TResult>;
2442
+ min(field: string | ColumnRef<string, string, unknown>, as?: string): QueryBuilder<TResult>;
2437
2443
  /**
2438
2444
  * Find maximum value of a field.
2439
2445
  *
@@ -2441,7 +2447,7 @@ interface QueryBuilder<TResult = unknown> {
2441
2447
  * @param as - Optional alias for result column
2442
2448
  * @returns A new QueryBuilder configured for MAX
2443
2449
  */
2444
- max(field: string, as?: string): QueryBuilder<TResult>;
2450
+ max(field: string | ColumnRef<string, string, unknown>, as?: string): QueryBuilder<TResult>;
2445
2451
  /**
2446
2452
  * Group results by specified fields.
2447
2453
  * Used with aggregate functions like count(), sum(), etc.
@@ -2458,7 +2464,7 @@ interface QueryBuilder<TResult = unknown> {
2458
2464
  * .execute();
2459
2465
  * ```
2460
2466
  */
2461
- groupBy(fields: readonly string[]): QueryBuilder<TResult>;
2467
+ groupBy(fields: readonly (string | ColumnRef<string, string, unknown>)[]): QueryBuilder<TResult>;
2462
2468
  /**
2463
2469
  * Filter grouped results based on aggregate values.
2464
2470
  * Applied after GROUP BY, similar to WHERE but for aggregates.
@@ -2522,7 +2528,7 @@ interface QueryBuilder<TResult = unknown> {
2522
2528
  * // SQL: SELECT DISTINCT ON ("user_id", "action") * FROM "logs"
2523
2529
  * ```
2524
2530
  */
2525
- distinctOn(...columns: string[]): QueryBuilder<TResult>;
2531
+ distinctOn(...columns: (string | ColumnRef<string, string, unknown>)[]): QueryBuilder<TResult>;
2526
2532
  /**
2527
2533
  * Acquire a FOR UPDATE lock on selected rows.
2528
2534
  * Default wait policy is 'block' (wait for the lock).
@@ -2612,6 +2618,13 @@ interface QueryBuilder<TResult = unknown> {
2612
2618
  orderBy(expr: ExpressionSpec, direction?: SortDirection, options?: {
2613
2619
  nulls?: NullsPosition;
2614
2620
  }): QueryBuilder<TResult>;
2621
+ /**
2622
+ * Order by a `ColumnRef` (kept qualified), a `SubqueryExpression`, a schema
2623
+ * `ref()` or an output-column position (a positive integer). ADR 0011.
2624
+ */
2625
+ orderBy(leaf: OrderByLeaf, direction?: SortDirection, options?: {
2626
+ nulls?: NullsPosition;
2627
+ }): QueryBuilder<TResult>;
2615
2628
  /**
2616
2629
  * Limit the number of results returned.
2617
2630
  *
@@ -3314,7 +3327,7 @@ declare class UpdateBuilder<TRow = unknown, TResult = void> extends MutationBuil
3314
3327
  */
3315
3328
  set<TInput extends Updateable<TRow>>(data: ExactMutationPayload<TInput, Updateable<TRow>>): UpdateBuilder<TRow, TResult>;
3316
3329
  /**
3317
- * Add WHERE condition.
3330
+ * Add a WHERE condition. Successive calls are combined with AND.
3318
3331
  */
3319
3332
  where(condition: MutationWhereCondition): UpdateBuilder<TRow, TResult>;
3320
3333
  /**
@@ -3372,7 +3385,7 @@ declare class DeleteBuilder<TRow = unknown, TResult = void> extends MutationBuil
3372
3385
  returning?: readonly string[] | undefined;
3373
3386
  });
3374
3387
  /**
3375
- * Add WHERE condition.
3388
+ * Add a WHERE condition. Successive calls are combined with AND.
3376
3389
  */
3377
3390
  where(condition: MutationWhereCondition): DeleteBuilder<TRow, TResult>;
3378
3391
  /**
@@ -3591,7 +3604,7 @@ interface AggregateOptions {
3591
3604
  /**
3592
3605
  * Field to aggregate (required for SUM, AVG, MIN, MAX; optional for COUNT).
3593
3606
  */
3594
- readonly field?: string;
3607
+ readonly field?: string | ColumnRef<string, string, unknown>;
3595
3608
  /**
3596
3609
  * Alias for the result column.
3597
3610
  */
@@ -3632,7 +3645,7 @@ type OrderByRecord = Readonly<Record<string, SortDirection>>;
3632
3645
  * ```
3633
3646
  */
3634
3647
  interface OrderBySpec {
3635
- readonly column: string;
3648
+ readonly column: OrderByLeaf;
3636
3649
  readonly direction?: SortDirection;
3637
3650
  readonly nulls?: NullsPosition;
3638
3651
  }
@@ -3789,11 +3802,22 @@ interface ListHierarchyOptions {
3789
3802
  * @example
3790
3803
  * // Basic scalar subquery
3791
3804
  * query('products')
3792
- * .where({ price: { $eq: subquery('prices').select('max_price').where({ categoryId: outerRef('categoryId') }) } })
3805
+ * .where({
3806
+ * price: {
3807
+ * $eq: subquery('prices')
3808
+ * .select('max_price')
3809
+ * .where(eq('categoryId', outerRef('categoryId')))
3810
+ * .build(),
3811
+ * },
3812
+ * })
3793
3813
  *
3794
3814
  * // With aggregate
3795
3815
  * query('products')
3796
- * .where({ avgRating: { $gt: subquery('reviews').where({ productId: outerRef('id') }).avg('rating') } })
3816
+ * .where({
3817
+ * avgRating: {
3818
+ * $gt: subquery('reviews').where(eq('productId', outerRef('id'))).avg('rating'),
3819
+ * },
3820
+ * })
3797
3821
  */
3798
3822
  declare class SubqueryBuilder {
3799
3823
  private readonly _from;
@@ -3807,8 +3831,8 @@ declare class SubqueryBuilder {
3807
3831
  */
3808
3832
  select(field: string): SubqueryBuilder;
3809
3833
  /**
3810
- * Add a WHERE condition to the subquery.
3811
- * Can include outerRef() to create correlated subqueries.
3834
+ * Add a WHERE condition to the subquery. Successive calls are combined with
3835
+ * AND. Can include outerRef() to create correlated subqueries.
3812
3836
  */
3813
3837
  where(condition: WhereIntent$1): SubqueryBuilder;
3814
3838
  /**
@@ -3851,7 +3875,7 @@ declare class SubqueryBuilder {
3851
3875
  * // SELECT id, (SELECT count(*) FROM calls WHERE symbol_id = s.id) AS call_count
3852
3876
  * query('symbols').columns([
3853
3877
  * 'id',
3854
- * subquery('calls').where({ symbolId: outerRef('id') }).count().asExpr('call_count'),
3878
+ * subquery('calls').where(eq('symbolId', outerRef('id'))).count().asExpr('call_count'),
3855
3879
  * ])
3856
3880
  */
3857
3881
  asExpr(alias: string): ExpressionSpec;
@@ -3864,8 +3888,15 @@ declare class SubqueryBuilder {
3864
3888
  * Result of building a subquery.
3865
3889
  * This can be used as a value in comparison operations.
3866
3890
  */
3891
+ /**
3892
+ * Brand of a genuine `SubqueryExpression`. `Symbol.for` keeps it recognised
3893
+ * across copies of the package, and a plain object (a JSON value with a
3894
+ * `_type: 'subquery'` key) never carries it.
3895
+ */
3896
+ declare const SUBQUERY_EXPRESSION_BRAND: unique symbol;
3867
3897
  declare class SubqueryExpression {
3868
3898
  readonly _type: "subquery";
3899
+ readonly [SUBQUERY_EXPRESSION_BRAND]: true;
3869
3900
  readonly intent: QueryIntent;
3870
3901
  constructor(intent: QueryIntent);
3871
3902
  /**
@@ -3905,7 +3936,7 @@ declare class SubqueryExpression {
3905
3936
  * price: {
3906
3937
  * $eq: subquery('products')
3907
3938
  * .select('price')
3908
- * .where({ categoryId: outerRef('categoryId') })
3939
+ * .where(eq('categoryId', outerRef('categoryId')))
3909
3940
  * .max('price')
3910
3941
  * }
3911
3942
  * })
@@ -3923,7 +3954,7 @@ declare function subquery(table: string): SubqueryBuilder;
3923
3954
  *
3924
3955
  * @example
3925
3956
  * // Reference parent 'id' column in subquery
3926
- * subquery('reviews').where({ productId: outerRef('id') })
3957
+ * subquery('reviews').where(eq('productId', outerRef('id')))
3927
3958
  */
3928
3959
  declare function outerRef(column: string): SubqueryRefIntent;
3929
3960
 
@@ -3960,10 +3991,16 @@ interface DistinctField {
3960
3991
  * orm.select('orders').sum(distinct('amount'), 'unique_total').execute();
3961
3992
  * ```
3962
3993
  */
3963
- declare function distinct(field: string): DistinctField;
3994
+ declare function distinct(field: string | ColumnRef<string, string, unknown>): DistinctField;
3995
+ /**
3996
+ * A left operand that is neither a column name nor a `ColumnRef`: compared
3997
+ * as an expression (ADR 0011, reference position).
3998
+ */
3999
+ type ExpressionLeftOperand = Exclude<ReferenceLeaf, string | ColumnRef<string, string, unknown>>;
3964
4000
  type ComparisonFilter = {
3965
- <T extends string, C extends string, V>(field: ColumnRef<T, C, V>, value: V): WhereComparisonIntent;
4001
+ <T extends string, C extends string, V>(field: ColumnRef<T, C, V>, value: V | ValueExpression): WhereComparisonIntent;
3966
4002
  (field: string, value: unknown): WhereComparisonIntent;
4003
+ (field: ExpressionLeftOperand, value: unknown): WhereExpressionIntent;
3967
4004
  };
3968
4005
  /**
3969
4006
  * Equals comparison: field = value
@@ -4445,25 +4482,15 @@ declare function sql(sqlFragment: string): SqlRawExpression;
4445
4482
  declare function isSqlRaw(value: unknown): value is SqlRawExpression;
4446
4483
 
4447
4484
  /**
4448
- * Accepted input types for op() and fn() arguments.
4449
- * - `ExpressionRef` → used as-is
4450
- * - `string` → implicitly converted to ref() (column reference)
4451
- * - `number | boolean | readonly unknown[]` → implicitly converted to param() (bound value)
4452
- *
4453
- * Use `ref()` / `param()` explicitly for ambiguous cases (e.g., a string that is a value,
4454
- * not a column name → use `literal()` instead).
4455
- */
4456
- /**
4457
- * Accepted input types for op() and fn() arguments.
4458
- * - `ExpressionRef` → used as-is
4459
- * - `string` → implicitly converted to ref() (column reference)
4460
- * - `number | boolean | readonly unknown[]` → implicitly converted to param() (bound value)
4461
- * - `AggOrderByArg` → ORDER BY entry inside an aggregate (fn() only)
4485
+ * Accepted input types for fn() arguments: a {@link ReferenceLeaf}, or an
4486
+ * `aggOrderBy()` marker placing an ORDER BY entry inside an aggregate.
4462
4487
  *
4463
- * Use `ref()` / `param()` explicitly for ambiguous cases (e.g., a string that is a value,
4464
- * not a column name → use `literal()` instead).
4488
+ * Every leaf follows the reference rule of `coerceReference`: a string is a
4489
+ * column, a finite number or boolean is inlined, an array or `Date` is bound,
4490
+ * an expression object is used as is. Use `literal()` for a string value and
4491
+ * `param()` to bind a value explicitly.
4465
4492
  */
4466
- type ExprInput = ExpressionRef | ExpressionSpec | AggOrderByArg | string | number | boolean | readonly unknown[];
4493
+ type ExprInput = ReferenceLeaf | AggOrderByArg;
4467
4494
 
4468
4495
  type BinaryPredicateOperator = Exclude<PredicateOperator, 'AND' | 'OR' | 'NOT'>;
4469
4496
  type NonPredicateOperator<TOperator extends string> = TOperator extends PredicateOperator ? never : TOperator;
@@ -4570,17 +4597,20 @@ declare function ref(column: string): ExpressionRef;
4570
4597
  declare function param(value: unknown): ExpressionRef;
4571
4598
  /**
4572
4599
  * Type cast — compiles to expr::typeName or CAST(expr AS typeName).
4600
+ * `expr` follows the reference-leaf rule: a string is a column.
4573
4601
  *
4574
4602
  * @example cast(param([0.1, 0.2]), 'vector') → $1::vector
4603
+ * @example cast('title', 'text') → CAST(title AS text)
4575
4604
  * @throws Error if typeName fails validation (injection guard)
4576
4605
  */
4577
- declare function cast(expr: ExpressionRef, typeName: string): ExpressionRef;
4606
+ declare function cast(expr: ReferenceLeaf, typeName: string): ExpressionRef;
4578
4607
  /**
4579
4608
  * Custom binary operator — left OP right.
4580
- * Implicit conversions: string → ref(), number/boolean/array → param().
4609
+ * Leaves follow the reference rule: string → column, finite number/boolean → inlined constant,
4610
+ * non-finite number/array/Date → bound parameter, expression object → used as is.
4581
4611
  *
4582
4612
  * @example op('<=>', ref('embedding'), cast(param([0.1]), 'vector'))
4583
- * @example op('<=>', 'embedding', [0.1, 0.2]) // implicit conversions
4613
+ * @example op('<=>', 'embedding', [0.1, 0.2]) // column <=> $1
4584
4614
  * @throws Error if operator fails validation (injection guard)
4585
4615
  */
4586
4616
  /** Logical AND / OR — both operands must be predicates. */
@@ -4588,9 +4618,9 @@ declare function op(operator: 'AND' | 'OR', left: PredicateRef, right: Predicate
4588
4618
  /** Logical NOT — its sole operand must be a predicate. */
4589
4619
  declare function op(operator: 'NOT', operand: PredicateRef): WhereOnlyPredicate;
4590
4620
  /** Predicate binary operators accept expression operands. */
4591
- declare function op(operator: BinaryPredicateOperator, left: ExprInput, right: ExprInput): ExpressionPredicateRef;
4621
+ declare function op(operator: BinaryPredicateOperator, left: ReferenceLeaf, right: ReferenceLeaf): ExpressionPredicateRef;
4592
4622
  /** Any non-predicate operator remains an ordinary expression. */
4593
- declare function op<TOperator extends string>(operator: NonPredicateOperator<TOperator>, left: ExprInput, right: ExprInput): ExpressionRef;
4623
+ declare function op<TOperator extends string>(operator: NonPredicateOperator<TOperator>, left: ReferenceLeaf, right: ReferenceLeaf): ExpressionRef;
4594
4624
  /**
4595
4625
  * Assert that an arbitrary expression is boolean for use in WHERE.
4596
4626
  *
@@ -4601,7 +4631,8 @@ declare function unsafeAsPredicate(expr: ExpressionRef): PredicateExpressionRef;
4601
4631
  /**
4602
4632
  * Custom function call — name(args...).
4603
4633
  * Supports schema-qualified names (e.g., 'paradedb.score', 'ST_Distance').
4604
- * Implicit conversions: string → ref(), number/boolean/array → param().
4634
+ * Leaves follow the reference rule: string → column, finite number/boolean → inlined constant,
4635
+ * non-finite number/array/Date → bound parameter, expression object → used as is.
4605
4636
  *
4606
4637
  * @example fn('now') → now()
4607
4638
  * @example fn('paradedb.score', ref('id')) → paradedb.score("id")
@@ -4610,7 +4641,8 @@ declare function unsafeAsPredicate(expr: ExpressionRef): PredicateExpressionRef;
4610
4641
  /**
4611
4642
  * Custom function call — name(args...).
4612
4643
  * Supports schema-qualified names (e.g., 'paradedb.score', 'ST_Distance').
4613
- * Implicit conversions: string → ref(), number/boolean/array → param().
4644
+ * Leaves follow the reference rule: string → column, finite number/boolean → inlined constant,
4645
+ * non-finite number/array/Date → bound parameter, expression object → used as is.
4614
4646
  *
4615
4647
  * Pass `aggOrderBy('col', 'asc')` args to add ORDER BY inside aggregates:
4616
4648
  * `fn('array_agg', ref('name'), aggOrderBy('path'))` → array_agg("name" ORDER BY "path" ASC)
@@ -4655,7 +4687,7 @@ declare function literal(value: string | number | boolean | null): ExpressionRef
4655
4687
  * @example unary('-', ref('score')) → -"score"
4656
4688
  * @throws Error if operator fails validation (injection guard)
4657
4689
  */
4658
- declare function unary(operator: string, expr: ExprInput): ExpressionRef;
4690
+ declare function unary(operator: string, expr: ReferenceLeaf): ExpressionRef;
4659
4691
  /**
4660
4692
  * Named argument for function calls: name => value.
4661
4693
  * Use inside fn() args to produce PostgreSQL named-argument syntax.
@@ -4665,7 +4697,7 @@ declare function unary(operator: string, expr: ExprInput): ExpressionRef;
4665
4697
  * @example namedArg('query_string', param('hello'))
4666
4698
  * → query_string => $1
4667
4699
  */
4668
- declare function namedArg(name: string, value: ExprInput): ExpressionRef;
4700
+ declare function namedArg(name: string, value: ReferenceLeaf): ExpressionRef;
4669
4701
  /** SQL wildcard (*) — use in fn('count', star()) for COUNT(*) */
4670
4702
  declare function star(): ExpressionRef;
4671
4703
  /**
@@ -4674,7 +4706,7 @@ declare function star(): ExpressionRef;
4674
4706
  * @example array(literal(1), literal(2), literal(3)) → ARRAY[1, 2, 3]
4675
4707
  * @example array(ref('name'), ref('kind')) → ARRAY["name", "kind"]
4676
4708
  */
4677
- declare function array(...items: ExprInput[]): ExpressionRef;
4709
+ declare function array(...items: ReferenceLeaf[]): ExpressionRef;
4678
4710
  /**
4679
4711
  * Creates an ORDER BY marker for use as an argument to `fn()`.
4680
4712
  * When passed to `fn()`, the compiler places it in the aggregate's
@@ -4692,7 +4724,7 @@ declare function aggOrderBy(field: string, direction?: 'asc' | 'desc'): AggOrder
4692
4724
  * @example arrayAgg('name', aggOrderBy('path', 'desc')) → array_agg("name" ORDER BY "path" DESC)
4693
4725
  * @example arrayAgg(distinct('name')) → array_agg(DISTINCT name)
4694
4726
  */
4695
- declare function arrayAgg(col: ExpressionRef | string | DistinctField, ...rest: AggOrderByArg[]): ExpressionRef;
4727
+ declare function arrayAgg(col: ReferenceLeaf | DistinctField, ...rest: AggOrderByArg[]): ExpressionRef;
4696
4728
  /**
4697
4729
  * Shorthand for `fn('string_agg', col, separator, ...orderByArgs)`.
4698
4730
  *
@@ -4702,6 +4734,54 @@ declare function arrayAgg(col: ExpressionRef | string | DistinctField, ...rest:
4702
4734
  */
4703
4735
  declare function stringAgg(col: ExpressionRef | string | DistinctField, separator: ExpressionRef, ...rest: AggOrderByArg[]): ExpressionRef;
4704
4736
 
4737
+ /**
4738
+ * @module coerce
4739
+ * The leaf rule shared by the expression constructors and the filter helpers
4740
+ * (ADR 0011).
4741
+ *
4742
+ * A helper first recognises its own grammar (names, operators, cast types,
4743
+ * `distinct()` and `aggOrderBy()` markers). Every scalar leaf left over goes
4744
+ * through one function per position:
4745
+ * - {@link coerceReference} (reference position) turns it into an expression
4746
+ * intent or refuses it by name;
4747
+ * - {@link coerceValue} (value position) keeps plain values for binding and
4748
+ * turns the expression objects core cannot read on its own into an
4749
+ * `ExpressionRef`;
4750
+ * - {@link coerceListElement} and {@link coerceLikePattern} serve the value
4751
+ * positions that cannot carry an expression yet, and refuse one as not yet
4752
+ * supported.
4753
+ *
4754
+ * None of them binds an expression object, a builder, a `ColumnRef`, an
4755
+ * `outerRef()` or a `sql()` marker as a parameter value.
4756
+ */
4757
+
4758
+ /**
4759
+ * A scalar argument of an expression constructor (`fn`, `boolFn`, `op`,
4760
+ * `unary`, `namedArg`, `array`, `cast`, `arrayAgg`, CASE results).
4761
+ *
4762
+ * - a string is a column;
4763
+ * - a finite number, a boolean, or a `bigint` within the safe-integer range
4764
+ * is an inlined constant;
4765
+ * - a non-finite number, a `bigint` outside that range, an array or a `Date`
4766
+ * is a bound parameter;
4767
+ * - an expression object (`ExpressionRef`, `ExpressionSpec`, `ColumnRef`,
4768
+ * `SubqueryExpression`, schema `ref()`) is used as is.
4769
+ *
4770
+ * Use `literal()`, `param()` or `exprRef()` to force a position.
4771
+ */
4772
+ type ReferenceLeaf = string | number | boolean | bigint | Date | readonly unknown[] | ExpressionRef | ExpressionSpec | ColumnRef<string, string, unknown> | SubqueryExpression | RefDefinition;
4773
+ /**
4774
+ * A single `orderBy` leaf (ADR 0011, reference position): a column name, an
4775
+ * output-column position, an expression, a `ColumnRef`, a subquery or a schema
4776
+ * `ref()`. Arrays, `Date`s, booleans and `bigint`s do not order rows.
4777
+ */
4778
+ type OrderByLeaf = string | number | ExpressionRef | ExpressionSpec | ColumnRef<string, string, unknown> | SubqueryExpression | RefDefinition;
4779
+ /**
4780
+ * An expression object accepted in a value position (a filter's right
4781
+ * operand, an object-filter value): it is compiled as SQL, never bound.
4782
+ */
4783
+ type ValueExpression = ExpressionRef | ExpressionSpec | ColumnRef<string, string, unknown> | SubqueryExpression | RefDefinition | SubqueryRefIntent;
4784
+
4705
4785
  /**
4706
4786
  * Assertion Parser for .assert.dbsp files.
4707
4787
  *
@@ -4976,4 +5056,4 @@ declare const assertIntentHasWhere: (result: AssertionQueryResult, expected: boo
4976
5056
  declare const assertIntentHasGroupBy: (result: AssertionQueryResult, expected: boolean) => AssertionOutcome;
4977
5057
  declare const assertIntentHasOrderBy: (result: AssertionQueryResult, expected: boolean) => AssertionOutcome;
4978
5058
 
4979
- export { type AssertionOutcome as $, type AliasedExprColumn as A, type BatchValuesRef as B, type ColumnSpec as C, type DefaultFilters as D, ExpressionRef as E, type AssertionBlock as F, type AssertionQueryResult as G, type HookStore as H, type IncludeOptionsWithRecursive as I, type AssertionSummary as J, type HookManager as K, type ListHierarchyOptions as L, type AfterMutationHook as M, type NullsPosition as N, type ObserverErrorHandler as O, PackRegistry as P, type QueryBuilder as Q, type RecursiveIncludeOptions as R, type StreamOptions as S, type TransitionRunPersister as T, UpdateBuilder as U, type AfterMutationObserver as V, type WhereFilter as W, type AfterQueryHook as X, type AfterQueryObserver as Y, AmbiguousPlanError as Z, type Assertion as _, type HookErrorHandler as a, isSqlRaw as a$, type BeforeMutationHook as a0, type BeforeQueryHook as a1, type ColumnDef as a2, type IncludeOptions as a3, type IntentSummary as a4, type JsonValue as a5, type ManyToManyDefinition as a6, type ManyToManyOptions as a7, type MutationDump as a8, type MutationHookContext as a9, assertParamsEquals as aA, assertParamsType as aB, assertSQLEquals as aC, batchValues as aD, boolFn as aE, cast as aF, coalesce as aG, col as aH, createHookManager as aI, distinct as aJ, eq as aK, every as aL, exists as aM, ref as aN, extractPseudoColumnKeywords as aO, fn as aP, getSchemaFromDb as aQ, gt as aR, gte as aS, inArray as aT, inSubquery as aU, isBatchValuesRef as aV, isDistinctFrom as aW, isNotNull as aX, isNull as aY, isOperationRuntime as aZ, isRef as a_, type NqlBuilder as aa, type OnErrorHook as ab, POSTGRESQL_CAPABILITIES as ac, type ParseError as ad, type ParseResult as ae, type QueryAssertionResult as af, type QueryHookContext as ag, type RefOptions as ah, type RelationRef as ai, type SchemaColumnType as aj, type SchemaIndexOptions as ak, type SchemaOptions as al, type SchemaTableOptions as am, type SelfRefRoles as an, type SqlRawExpression as ao, SubqueryBuilder as ap, SubqueryExpression as aq, TABLE_META as ar, type TableDef as as, admitRecordedIdentity as at, aggOrderBy as au, and as av, any as aw, array as ax, arrayAgg as ay, assertEquals as az, type RelationHints as b, assertIntentHasWhere as b$, like as b0, literal as b1, lt as b2, lte as b3, manyToMany as b4, namedArg as b5, neq as b6, none as b7, not as b8, notExists as b9, type ExecutionCoordinator as bA, MSSQL_CAPABILITIES as bB, MYSQL_CAPABILITIES as bC, type ManagedOutcomeExecutionRequest as bD, type ManagedOutcomePreflightRequest as bE, type NonRollbackableExecutionTracker as bF, type PlanScope as bG, type RefDefinition as bH, type RegisteredOperationSemantics as bI, SQLITE_CAPABILITIES as bJ, TRANSITION_LESSOR_REJECTION as bK, type TransitionExecutionClient as bL, type TransitionLeaseFailure as bM, type TransitionPack as bN, acquireExclusiveTransitionLease as bO, acquireTransitionLease as bP, acquireTransitionTargetLease as bQ, assertCanonicalizableJson as bR, assertContains as bS, assertDbColumnExists as bT, assertDbOutput as bU, assertDbRowsEquals as bV, assertDbRowsMax as bW, assertDbRowsMin as bX, assertDbValueEquals as bY, assertIntentHasGroupBy as bZ, assertIntentHasOrderBy as b_, nqlRaw as ba, op as bb, or as bc, outerRef as bd, param as be, parseAssertionFile as bf, plan as bg, planRecursive as bh, raw as bi, rawExists as bj, ref$1 as bk, relationColumn as bl, schema as bm, some as bn, sql as bo, star as bp, subquery as bq, unary as br, unsafeAsPredicate as bs, validateAssertionBlocks as bt, type Applier as bu, type InProcessProvenPlan as bv, type Prover as bw, ASSERTION_TYPES as bx, DUCKDB_CAPABILITIES as by, type DurablyLoadedRun as bz, type AggregateOptions as c, assertIntentTable as c0, assertIntentType as c1, assertIntentWith as c2, assertMatches as c3, assertParamsLength as c4, assertParamsValue as c5, assertSQLColumn as c6, assertSQLJoin as c7, assertSQLTable as c8, assertSuccess as c9, validateDeclarationModel as cA, validateIncludeInput as cB, validateIncludeOptions as cC, validateIncludeOrdering as cD, validateIncludeStrategy as cE, validateRecursiveIncludeStrategy as cF, validateRecursiveSetOperation as cG, validateResolvedIncludeStrategy as cH, validateSchemaIndexOptions as cI, validateTypeName as cJ, bindDeclarationSet as ca, compileNqlRead as cb, createBindingFinalPlan as cc, createExclusiveTransitionTarget as cd, createPackRegistry as ce, createTransitionLessor as cf, declarationSetFromModel as cg, isDurablyLoadedRun as ch, isExclusiveTransitionTarget as ci, isExpressionSpec as cj, isOverallSuccess as ck, isTransitionLessor as cl, isWhereIntent as cm, loadVerifiedRecoveryJournal as cn, markTransitionClientCompromised as co, mintDurablyLoadedRun as cp, normalizeRecursiveIncludeOptions as cq, objectToWhereIntent as cr, planInScope as cs, planOperationSession as ct, rawNotExists as cu, requiresDatabase as cv, resolveQueryIndex as cw, serverVersionNum as cx, stringAgg as cy, transitionPhysicalSessionIsCompromised as cz, type DistinctField as d, type OrderByRecord as e, type OrderBySpec as f, type ExpressionSpec as g, type PredicateRef as h, type DumpMetaInput as i, type PaginateOptions as j, type PaginatedResult as k, type CursorPaginateOptions as l, type CursorPaginatedResult as m, type SetOperationBuilder as n, type TableRef as o, type ColumnRef as p, InsertBuilder as q, DeleteBuilder as r, UpsertBuilder as s, type InferTableRow as t, type NqlTag as u, type BatchValuesOptions as v, type Schema as w, type SchemaDefinition as x, type InferDB as y, type PredicateExpressionRef as z };
5059
+ export { AmbiguousPlanError as $, type AliasedExprColumn as A, type BatchValuesRef as B, type ColumnSpec as C, type DefaultFilters as D, type ExpressionSpec as E, ExpressionRef as F, type PredicateExpressionRef as G, type HookStore as H, type IncludeOptionsWithRecursive as I, type AssertionBlock as J, type AssertionQueryResult as K, type ListHierarchyOptions as L, type AssertionSummary as M, type NullsPosition as N, type ObserverErrorHandler as O, PackRegistry as P, type QueryBuilder as Q, type RecursiveIncludeOptions as R, type StreamOptions as S, type TransitionRunPersister as T, UpdateBuilder as U, type HookManager as V, type WhereFilter as W, type AfterMutationHook as X, type AfterMutationObserver as Y, type AfterQueryHook as Z, type AfterQueryObserver as _, type HookErrorHandler as a, isOperationRuntime as a$, type Assertion as a0, type AssertionOutcome as a1, type BeforeMutationHook as a2, type BeforeQueryHook as a3, type ColumnDef as a4, type IncludeOptions as a5, type IntentSummary as a6, type JsonValue as a7, type ManyToManyDefinition as a8, type ManyToManyOptions as a9, arrayAgg as aA, assertEquals as aB, assertParamsEquals as aC, assertParamsType as aD, assertSQLEquals as aE, batchValues as aF, boolFn as aG, cast as aH, coalesce as aI, col as aJ, createHookManager as aK, distinct as aL, eq as aM, every as aN, exists as aO, ref as aP, extractPseudoColumnKeywords as aQ, fn as aR, getSchemaFromDb as aS, gt as aT, gte as aU, inArray as aV, inSubquery as aW, isBatchValuesRef as aX, isDistinctFrom as aY, isNotNull as aZ, isNull as a_, type MutationDump as aa, type MutationHookContext as ab, type NqlBuilder as ac, type OnErrorHook as ad, POSTGRESQL_CAPABILITIES as ae, type ParseError as af, type ParseResult as ag, type QueryAssertionResult as ah, type QueryHookContext as ai, type RefOptions as aj, type RelationRef as ak, type SchemaColumnType as al, type SchemaIndexOptions as am, type SchemaOptions as an, type SchemaTableOptions as ao, type SelfRefRoles as ap, type SqlRawExpression as aq, SubqueryBuilder as ar, SubqueryExpression as as, TABLE_META as at, type TableDef as au, admitRecordedIdentity as av, aggOrderBy as aw, and as ax, any as ay, array as az, type RelationHints as b, assertIntentHasGroupBy as b$, isRef as b0, isSqlRaw as b1, like as b2, literal as b3, lt as b4, lte as b5, manyToMany as b6, namedArg as b7, neq as b8, none as b9, DUCKDB_CAPABILITIES as bA, type DurablyLoadedRun as bB, type ExecutionCoordinator as bC, MSSQL_CAPABILITIES as bD, MYSQL_CAPABILITIES as bE, type ManagedOutcomeExecutionRequest as bF, type ManagedOutcomePreflightRequest as bG, type NonRollbackableExecutionTracker as bH, type PlanScope as bI, type RefDefinition as bJ, type RegisteredOperationSemantics as bK, SQLITE_CAPABILITIES as bL, TRANSITION_LESSOR_REJECTION as bM, type TransitionExecutionClient as bN, type TransitionLeaseFailure as bO, type TransitionPack as bP, acquireExclusiveTransitionLease as bQ, acquireTransitionLease as bR, acquireTransitionTargetLease as bS, assertCanonicalizableJson as bT, assertContains as bU, assertDbColumnExists as bV, assertDbOutput as bW, assertDbRowsEquals as bX, assertDbRowsMax as bY, assertDbRowsMin as bZ, assertDbValueEquals as b_, not as ba, notExists as bb, nqlRaw as bc, op as bd, or as be, outerRef as bf, param as bg, parseAssertionFile as bh, plan as bi, planRecursive as bj, raw as bk, rawExists as bl, ref$1 as bm, relationColumn as bn, schema as bo, some as bp, sql as bq, star as br, subquery as bs, unary as bt, unsafeAsPredicate as bu, validateAssertionBlocks as bv, type Applier as bw, type InProcessProvenPlan as bx, type Prover as by, ASSERTION_TYPES as bz, type AggregateOptions as c, assertIntentHasOrderBy as c0, assertIntentHasWhere as c1, assertIntentTable as c2, assertIntentType as c3, assertIntentWith as c4, assertMatches as c5, assertParamsLength as c6, assertParamsValue as c7, assertSQLColumn as c8, assertSQLJoin as c9, stringAgg as cA, transitionPhysicalSessionIsCompromised as cB, validateDeclarationModel as cC, validateIncludeInput as cD, validateIncludeOptions as cE, validateIncludeOrdering as cF, validateIncludeStrategy as cG, validateRecursiveIncludeStrategy as cH, validateRecursiveSetOperation as cI, validateResolvedIncludeStrategy as cJ, validateSchemaIndexOptions as cK, validateTypeName as cL, assertSQLTable as ca, assertSuccess as cb, bindDeclarationSet as cc, compileNqlRead as cd, createBindingFinalPlan as ce, createExclusiveTransitionTarget as cf, createPackRegistry as cg, createTransitionLessor as ch, declarationSetFromModel as ci, isDurablyLoadedRun as cj, isExclusiveTransitionTarget as ck, isExpressionSpec as cl, isOverallSuccess as cm, isTransitionLessor as cn, isWhereIntent as co, loadVerifiedRecoveryJournal as cp, markTransitionClientCompromised as cq, mintDurablyLoadedRun as cr, normalizeRecursiveIncludeOptions as cs, objectToWhereIntent as ct, planInScope as cu, planOperationSession as cv, rawNotExists as cw, requiresDatabase as cx, resolveQueryIndex as cy, serverVersionNum as cz, type ColumnRef as d, type DistinctField as e, type OrderByLeaf as f, type OrderByRecord as g, type OrderBySpec as h, type PredicateRef as i, type DumpMetaInput as j, type PaginateOptions as k, type PaginatedResult as l, type CursorPaginateOptions as m, type CursorPaginatedResult as n, type SetOperationBuilder as o, type TableRef as p, InsertBuilder as q, DeleteBuilder as r, UpsertBuilder as s, type InferTableRow as t, type NqlTag as u, type BatchValuesOptions as v, type Schema as w, type SchemaDefinition as x, type InferDB as y, type ReferenceLeaf as z };