sim-relation-plan 0.1.0

Admission and sealed checked logical relational plans for SIM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use sim_relation_core::{
    BindingName, Cell, ColumnName, ConstraintName, FieldName, ParameterName, RelationId, Row,
    RowType, SourceName, TableName,
};
use std::fmt;

/// An explicitly qualified field reference.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FieldRef {
    /// Relation binding.
    pub binding: BindingName,
    /// Field within the binding.
    pub field: FieldName,
}
/// A named scalar projection.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NamedScalar {
    /// Output field name.
    pub name: FieldName,
    /// Expression.
    pub scalar: Scalar,
}
/// A named aggregate projection.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NamedAggregate {
    /// Output field name.
    pub name: FieldName,
    /// Aggregate expression.
    pub aggregate: Aggregate,
}
/// Join semantics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JoinKind {
    /// Matching rows only.
    Inner,
    /// All left rows, nullable right side.
    Left,
    /// Cartesian product.
    Cross,
}
/// Set operation semantics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SetOp {
    /// Deduplicating union.
    Union,
    /// Multiset union.
    UnionAll,
    /// Intersection.
    Intersect,
    /// Difference.
    Except,
}
/// Sort direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OrderDirection {
    /// Ascending.
    Asc,
    /// Descending.
    Desc,
}
/// A typed ordering expression.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OrderKey {
    /// Expression.
    pub scalar: Scalar,
    /// Direction.
    pub direction: OrderDirection,
}
/// Portable scalar operators.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScalarOp {
    /// Boolean conjunction.
    And,
    /// Boolean disjunction.
    Or,
    /// Boolean negation.
    Not,
    /// Equality.
    Eq,
    /// Inequality.
    Ne,
    /// Less than.
    Lt,
    /// Less than or equal.
    Le,
    /// Greater than.
    Gt,
    /// Greater than or equal.
    Ge,
    /// Addition.
    Add,
    /// Subtraction.
    Sub,
    /// Multiplication.
    Mul,
    /// Division.
    Div,
    /// Null test.
    IsNull,
    /// Null coalescing.
    Coalesce,
}
/// A scalar expression. Subqueries retain lexical access to their outer scope.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Scalar {
    /// Bound field.
    Field(FieldRef),
    /// Typed literal.
    Literal(Cell),
    /// Declared parameter.
    Param(ParameterName),
    /// Portable operator call.
    Call(ScalarOp, Vec<Scalar>),
    /// Conditional expression.
    Case {
        /// Ordered predicate/value branches.
        branches: Vec<(Scalar, Scalar)>,
        /// Optional else expression.
        otherwise: Option<Box<Scalar>>,
    },
    /// Existence subquery.
    Exists(Box<Rel>),
    /// Membership subquery.
    InQuery {
        /// Compared expression.
        value: Box<Scalar>,
        /// Single-column query.
        query: Box<Rel>,
    },
    /// Single-value subquery.
    ScalarQuery(Box<Rel>),
}
/// Aggregate operations with domain-derived result types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Aggregate {
    /// Count all input rows.
    CountAll,
    /// Count non-null values.
    Count(Scalar),
    /// Sum ordered numeric values.
    Sum(Scalar),
    /// Minimum ordered value.
    Min(Scalar),
    /// Maximum ordered value.
    Max(Scalar),
}
/// Complete logical relation algebra.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Rel {
    /// Catalog table scan.
    Scan {
        /// Provider source.
        source: SourceName,
        /// Schema table.
        table: TableName,
        /// Introduced binding.
        bind: BindingName,
    },
    /// Bounded literal rows.
    Values {
        /// Introduced binding.
        bind: BindingName,
        /// Declared row type.
        row_type: RowType,
        /// Rows.
        rows: Vec<Row>,
    },
    /// Projection.
    Project {
        /// Input.
        input: Box<Rel>,
        /// Introduced output binding.
        bind: BindingName,
        /// Fields.
        fields: Vec<NamedScalar>,
    },
    /// Predicate filter.
    Filter {
        /// Input.
        input: Box<Rel>,
        /// Boolean predicate.
        predicate: Scalar,
    },
    /// Binary join.
    Join {
        /// Left relation.
        left: Box<Rel>,
        /// Right relation.
        right: Box<Rel>,
        /// Kind.
        kind: JoinKind,
        /// Boolean condition; ignored only for cross joins.
        on: Scalar,
    },
    /// Grouped projection.
    Group {
        /// Input.
        input: Box<Rel>,
        /// Introduced output binding.
        bind: BindingName,
        /// Group keys.
        keys: Vec<NamedScalar>,
        /// Aggregates.
        aggregates: Vec<NamedAggregate>,
        /// Post-aggregate predicate.
        having: Option<Scalar>,
    },
    /// Compatible set operation.
    Set {
        /// Operation.
        op: SetOp,
        /// Two or more inputs.
        inputs: Vec<Rel>,
    },
    /// Duplicate elimination.
    Distinct(Box<Rel>),
    /// Stable ordering.
    Order {
        /// Input.
        input: Box<Rel>,
        /// Ordering keys.
        keys: Vec<OrderKey>,
    },
    /// Bounded result window.
    Limit {
        /// Input.
        input: Box<Rel>,
        /// Optional maximum rows.
        count: Option<u64>,
        /// Rows skipped.
        offset: u64,
    },
}

/// A uniqueness target for insert conflicts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConflictTarget {
    /// Primary key.
    PrimaryKey,
    /// Named unique constraint.
    UniqueConstraint(ConstraintName),
    /// Exact unique column sequence.
    Columns(Vec<ColumnName>),
}
/// Complete conflict behavior.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConflictAction {
    /// Raise conflict.
    Fail,
    /// Ignore a matching row.
    DoNothing {
        /// Unique target.
        target: ConflictTarget,
    },
    /// Update a matching row.
    DoUpdate {
        /// Unique target.
        target: ConflictTarget,
        /// Assignments.
        assignments: Vec<(ColumnName, Scalar)>,
        /// Optional update predicate.
        predicate: Option<Scalar>,
    },
}
/// Provider-neutral data mutation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Mutation {
    /// Insert rows produced by a relation.
    Insert {
        /// Target table.
        table: TableName,
        /// Populated columns in input order.
        columns: Vec<ColumnName>,
        /// Row-producing input.
        input: Box<Rel>,
        /// Conflict behavior.
        conflict: ConflictAction,
        /// Returned expressions.
        returning: Vec<NamedScalar>,
    },
    /// Update matching rows.
    Update {
        /// Target table.
        table: TableName,
        /// Target binding.
        bind: BindingName,
        /// Assignments.
        assignments: Vec<(ColumnName, Scalar)>,
        /// Optional filter.
        predicate: Option<Scalar>,
        /// Returned expressions.
        returning: Vec<NamedScalar>,
    },
    /// Delete matching rows.
    Delete {
        /// Target table.
        table: TableName,
        /// Target binding.
        bind: BindingName,
        /// Optional filter.
        predicate: Option<Scalar>,
        /// Returned expressions.
        returning: Vec<NamedScalar>,
    },
}

/// Admission resource limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AdmissionLimits {
    /// Maximum literal rows in one Values node.
    pub max_literal_rows: usize,
}
impl Default for AdmissionLimits {
    fn default() -> Self {
        Self {
            max_literal_rows: 1024,
        }
    }
}
/// Plan admission failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AdmissionError {
    /// Unknown table.
    UnknownTable(TableName),
    /// Unknown binding.
    UnresolvedBinding(BindingName),
    /// Binding shadows a live binding.
    AmbiguousBinding(BindingName),
    /// Unknown field.
    UnresolvedField(FieldRef),
    /// Parameter was not declared.
    UnresolvedParameter(ParameterName),
    /// Domain mismatch or unsupported operator.
    TypeError(&'static str),
    /// Aggregate appears outside aggregate position or grouping is invalid.
    IllegalAggregateScope,
    /// Set inputs disagree.
    IncompatibleSet,
    /// Scalar subquery does not return one field.
    ScalarQueryArity,
    /// Conflict target is not unique.
    UnsafeConflictTarget,
    /// Insert omits a required field.
    MissingRequiredInsertField(ColumnName),
    /// Literal rows exceed policy.
    LiteralRowLimit {
        /// Configured bound.
        limit: usize,
        /// Supplied rows.
        actual: usize,
    },
    /// Duplicate output or assignment name.
    DuplicateName,
}
impl fmt::Display for AdmissionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}
impl std::error::Error for AdmissionError {}

/// Opaque admitted query. Its fields cannot be forged or changed by providers.
#[derive(Clone, Debug)]
pub struct CheckedQuery {
    pub(crate) schema_id: RelationId,
    pub(crate) catalog_id: RelationId,
    pub(crate) parameters: RowType,
    pub(crate) output: RowType,
    pub(crate) plan_id: RelationId,
    pub(crate) raw: Rel,
}
impl CheckedQuery {
    /// Schema identity used for admission.
    pub fn schema_id(&self) -> &RelationId {
        &self.schema_id
    }
    /// Domain catalog identity.
    pub fn catalog_id(&self) -> &RelationId {
        &self.catalog_id
    }
    /// Ordered parameter contract.
    pub fn parameters(&self) -> &RowType {
        &self.parameters
    }
    /// Output row contract.
    pub fn output(&self) -> &RowType {
        &self.output
    }
    /// Canonical plan identity.
    pub fn plan_id(&self) -> &RelationId {
        &self.plan_id
    }
    /// Read-only logical plan for codecs/providers.
    pub fn plan(&self) -> &Rel {
        &self.raw
    }
}
/// Opaque admitted mutation.
#[derive(Clone, Debug)]
pub struct CheckedMutation {
    pub(crate) schema_id: RelationId,
    pub(crate) catalog_id: RelationId,
    pub(crate) parameters: RowType,
    pub(crate) output: RowType,
    pub(crate) plan_id: RelationId,
    pub(crate) raw: Mutation,
}
impl CheckedMutation {
    /// Schema identity used for admission.
    pub fn schema_id(&self) -> &RelationId {
        &self.schema_id
    }
    /// Domain catalog identity.
    pub fn catalog_id(&self) -> &RelationId {
        &self.catalog_id
    }
    /// Parameter contract.
    pub fn parameters(&self) -> &RowType {
        &self.parameters
    }
    /// Returned row contract.
    pub fn output(&self) -> &RowType {
        &self.output
    }
    /// Canonical plan identity.
    pub fn plan_id(&self) -> &RelationId {
        &self.plan_id
    }
    /// Read-only mutation.
    pub fn plan(&self) -> &Mutation {
        &self.raw
    }
}