dinoco_engine 2.0.5

Database adapters, query execution, and migration engine components for Dinoco.
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use std::vec;

use crate::DinocoValue;

#[derive(Debug, Clone)]
pub enum FindOrderBy {
    Asc(&'static str),
    Desc(&'static str),
}

#[derive(Debug, Clone)]
pub struct FindQuery {
    pub fields: &'static [&'static str],
    pub from: &'static str,

    pub conditions: Vec<FindWhere>,

    pub limit: i32,
    pub skip: i32,

    pub order_by: Option<FindOrderBy>,
    // pub relations: Vec<EntityRelation>,
}

#[derive(Debug, Clone)]
pub struct InsertQuery {
    pub table: &'static str,
    pub fields: Vec<&'static str>,
    pub rows: Vec<Vec<DinocoValue>>,
    pub returning: Option<&'static [&'static str]>,
}

#[derive(Debug, Clone)]
pub struct UpdateQuery {
    pub table: &'static str,
    pub sets: Vec<UpdateSet>,
    pub conditions: Vec<FindWhere>,
    pub returning: Option<&'static [&'static str]>,
}

impl UpdateQuery {
    /// Builds a stable post-update lookup for adapters without `RETURNING`.
    /// A known `id` is always preferred. Otherwise predicates on changed
    /// fields are replaced by exact values from `set(...)` operations, while
    /// unaffected predicates remain available to narrow the lookup.
    pub fn post_update_reload_conditions(&self) -> Vec<FindWhere> {
        if let Some(id) = find_equality_value(&self.conditions, "id") {
            return vec![FindWhere::Eq("id", id)];
        }

        let mut conditions = self
            .conditions
            .iter()
            .filter(|condition| !condition_references_updated_field(condition, &self.sets))
            .cloned()
            .collect::<Vec<_>>();
        conditions.extend(
            self.sets
                .iter()
                .filter(|set| set.operation == UpdateOperation::Set)
                .map(|set| FindWhere::Eq(set.field, set.value.clone())),
        );

        if conditions.is_empty() { self.conditions.clone() } else { conditions }
    }
}

fn find_equality_value(conditions: &[FindWhere], field: &'static str) -> Option<DinocoValue> {
    conditions.iter().find_map(|condition| match condition {
        FindWhere::Eq(candidate, value) if *candidate == field => Some(value.clone()),
        FindWhere::And(conditions) | FindWhere::Or(conditions) => find_equality_value(conditions, field),
        FindWhere::Not(condition) => find_equality_value(std::slice::from_ref(condition.as_ref()), field),
        _ => None,
    })
}

fn condition_references_updated_field(condition: &FindWhere, sets: &[UpdateSet]) -> bool {
    let updated = |field: &'static str| sets.iter().any(|set| set.field == field);
    match condition {
        FindWhere::Eq(field, _)
        | FindWhere::Neq(field, _)
        | FindWhere::Gt(field, _)
        | FindWhere::Gte(field, _)
        | FindWhere::Lt(field, _)
        | FindWhere::Lte(field, _)
        | FindWhere::Like(field, _)
        | FindWhere::Between(field, _, _)
        | FindWhere::Batch(field, _)
        | FindWhere::Null(field)
        | FindWhere::NotNull(field) => updated(field),
        FindWhere::FullText(fields, _) => fields.iter().any(|field| updated(field)),
        FindWhere::ManyToMany(match_) => updated(match_.local_key),
        FindWhere::And(conditions) | FindWhere::Or(conditions) => {
            conditions.iter().any(|condition| condition_references_updated_field(condition, sets))
        }
        FindWhere::Not(condition) => condition_references_updated_field(condition, sets),
    }
}

#[derive(Debug, Clone)]
pub struct UpdateSet {
    pub field: &'static str,
    pub value: DinocoValue,
    pub operation: UpdateOperation,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateOperation {
    Set,
    Increment,
    Decrement,
    Multiply,
    Divide,
    Connect,
    Disconnect,
    ConnectManyToMany(ManyToManyUpdate),
    DisconnectManyToMany(ManyToManyUpdate),
    /// Assigns the database's current UTC timestamp (`@updated_at` on a
    /// `DateTime` field). Binds no parameter: the value comes from the server.
    CurrentTimestamp,
    /// Assigns the database's current UTC date (`@updated_at` on a `Date`
    /// field). Binds no parameter.
    CurrentDate,
}

/// The SQL each dialect evaluates to "now" when assigning
/// [`UpdateOperation::CurrentTimestamp`]/[`UpdateOperation::CurrentDate`].
/// Both are UTC so they match the values Dinoco itself writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurrentTimeSql {
    pub timestamp: &'static str,
    pub date: &'static str,
}

impl UpdateOperation {
    pub fn is_scalar(self) -> bool {
        matches!(
            self,
            Self::Set
                | Self::Increment
                | Self::Decrement
                | Self::Multiply
                | Self::Divide
                | Self::CurrentTimestamp
                | Self::CurrentDate
        )
    }

    /// Whether the assignment consumes the set's value as a bind parameter.
    pub fn binds_value(self) -> bool {
        self.is_scalar() && !matches!(self, Self::CurrentTimestamp | Self::CurrentDate)
    }

    /// Builds the right-hand side of a scalar assignment. Identifiers,
    /// placeholders and the current-time expressions are supplied by the
    /// active dialect and values remain bind parameters. `placeholder` is
    /// ignored by operations that do not [bind a value](Self::binds_value).
    pub fn assignment_sql(self, field: &str, placeholder: &str, now: CurrentTimeSql) -> Option<String> {
        match self {
            Self::Set => Some(format!("{field} = {placeholder}")),
            Self::Increment => Some(format!("{field} = {field} + {placeholder}")),
            Self::Decrement => Some(format!("{field} = {field} - {placeholder}")),
            Self::Multiply => Some(format!("{field} = {field} * {placeholder}")),
            Self::Divide => Some(format!("{field} = {field} / {placeholder}")),
            Self::CurrentTimestamp => Some(format!("{field} = {}", now.timestamp)),
            Self::CurrentDate => Some(format!("{field} = {}", now.date)),
            Self::Connect | Self::Disconnect | Self::ConnectManyToMany(_) | Self::DisconnectManyToMany(_) => None,
        }
    }
}

/// A column the database refreshes on every scalar `UPDATE` of its row
/// (`@updated_at` in the schema), unless the update sets it explicitly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UpdatedAtField {
    pub name: &'static str,
    /// [`UpdateOperation::CurrentTimestamp`] or [`UpdateOperation::CurrentDate`].
    pub operation: UpdateOperation,
}

impl UpdatedAtField {
    pub const fn timestamp(name: &'static str) -> Self {
        Self { name, operation: UpdateOperation::CurrentTimestamp }
    }

    pub const fn date(name: &'static str) -> Self {
        Self { name, operation: UpdateOperation::CurrentDate }
    }

    pub fn update_set(self) -> UpdateSet {
        UpdateSet { field: self.name, value: DinocoValue::Null, operation: self.operation }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ManyToManyUpdate {
    pub join_table: &'static str,
    pub parent_field: &'static str,
    pub join_parent_field: &'static str,
    pub join_child_field: &'static str,
}

#[derive(Debug, Clone)]
pub struct DeleteQuery {
    pub table: &'static str,
    pub conditions: Vec<FindWhere>,
    pub returning: Option<&'static [&'static str]>,
}

#[derive(Debug, Clone)]
pub struct CountQuery {
    pub table: &'static str,
    pub conditions: Vec<FindWhere>,
}

#[derive(Debug, Clone)]
pub struct ExistsQuery {
    pub table: &'static str,
    pub conditions: Vec<FindWhere>,
}

/// One `find_many`/`find_first` compiled to run alongside others in a single
/// [`FindBatchQuery`].
#[derive(Debug, Clone)]
pub struct FindBatchItem {
    pub query: FindQuery,
}

/// Backs `find_batch(...)` in "single query" mode: every item is compiled
/// into its own JSON-aggregated subquery (`json_build_object`/`json_agg` on
/// Postgres, `JSON_OBJECT`/`JSON_ARRAYAGG` on MySQL, `json_object`/
/// `json_group_array` on SQLite) and all of them are selected together in one
/// round trip, each producing a JSON array of rows.
#[derive(Debug, Clone)]
pub struct FindBatchQuery {
    pub items: Vec<FindBatchItem>,
}

#[derive(Debug, Clone)]
pub struct RelationCountQuery {
    pub parent_table: &'static str,
    pub child_table: &'static str,
    pub parent_field: &'static str,
    pub child_field: &'static str,
    pub parent_conditions: Vec<FindWhere>,
    pub child_conditions: Vec<FindWhere>,
}

#[derive(Debug, Clone)]
pub struct RelationJoinQuery {
    pub query: FindQuery,
    pub parent_table: &'static str,
    pub child_table: &'static str,
    pub parent_field: &'static str,
    pub child_field: &'static str,
    pub key_count: usize,
}

#[derive(Debug, Clone)]
pub struct RelationBatchQuery {
    pub query: FindQuery,
    pub relation_key_field: &'static str,
}

#[derive(Debug, Clone)]
#[doc(hidden)]
pub struct RelationOccurrenceQuery {
    pub query: FindQuery,
    pub child_field: &'static str,
    pub key_count: usize,
}

#[derive(Debug, Clone)]
pub struct ManyToManyRelationQuery {
    pub query: FindQuery,
    pub join_table: &'static str,
    pub parent_field: &'static str,
    pub child_field: &'static str,
    pub join_parent_field: &'static str,
    pub join_child_field: &'static str,
    pub key_count: usize,
}

#[derive(Debug, Clone)]
pub struct ManyToManyRelationCountQuery {
    pub parent_table: &'static str,
    pub child_table: &'static str,
    pub join_table: &'static str,
    pub parent_field: &'static str,
    pub child_field: &'static str,
    pub join_parent_field: &'static str,
    pub join_child_field: &'static str,
    pub parent_conditions: Vec<FindWhere>,
    pub child_conditions: Vec<FindWhere>,
}

#[derive(Debug, Clone)]
pub struct CreateTableMigration {
    pub table: String,
    pub columns: Vec<MigrationColumn>,
    pub foreign_keys: Vec<MigrationForeignKey>,
    pub if_not_exists: bool,
}

#[derive(Debug, Clone)]
pub struct DropTableMigration {
    pub table: String,
    pub if_exists: bool,
}

#[derive(Debug, Clone)]
pub struct RenameTableMigration {
    pub from: String,
    pub to: String,
}

#[derive(Debug, Clone)]
pub struct AddColumnMigration {
    pub table: String,
    pub column: MigrationColumn,
}

#[derive(Debug, Clone)]
pub struct DropColumnMigration {
    pub table: String,
    pub column: String,
}

#[derive(Debug, Clone)]
pub struct AlterColumnMigration {
    pub table: String,
    pub current: MigrationColumn,
    pub desired: MigrationColumn,
}

#[derive(Debug, Clone)]
pub struct RenameColumnMigration {
    pub table: String,
    pub from: String,
    pub to: String,
}

#[derive(Debug, Clone)]
pub struct AddForeignKeyMigration {
    pub table: String,
    pub foreign_key: MigrationForeignKey,
}

#[derive(Debug, Clone)]
pub struct DropForeignKeyMigration {
    pub table: String,
    pub name: String,
}

#[derive(Debug, Clone)]
pub struct CreateIndexMigration {
    pub table: String,
    pub index: MigrationIndex,
}

#[derive(Debug, Clone)]
pub struct DropIndexMigration {
    pub table: String,
    pub index: MigrationIndex,
}

#[derive(Debug, Clone)]
pub struct CreateEnumMigration {
    pub name: String,
    pub values: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct DropEnumMigration {
    pub name: String,
}

#[derive(Debug, Clone)]
pub struct AlterEnumMigration {
    pub name: String,
    pub current_values: Vec<String>,
    pub desired_values: Vec<String>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MigrationColumn {
    pub name: String,
    pub ty: MigrationColumnType,
    pub primary_key: bool,
    #[serde(default)]
    pub unique: bool,
    pub nullable: bool,
    pub default: Option<MigrationDefault>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MigrationForeignKey {
    pub name: String,
    pub columns: Vec<String>,
    pub references_table: String,
    pub references_columns: Vec<String>,
    pub on_update: ReferentialAction,
    pub on_delete: ReferentialAction,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MigrationIndex {
    pub name: String,
    pub columns: Vec<String>,
    #[serde(default)]
    pub automatic: bool,
    #[serde(default)]
    pub kind: MigrationIndexKind,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MigrationIndexKind {
    #[default]
    Standard,
    Unique,
    FullText,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ReferentialAction {
    Cascade,
    Restrict,
    NoAction,
    SetNull,
    SetDefault,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MigrationColumnType {
    String,
    Boolean,
    Integer,
    Float,
    Text,
    DateTime,
    Date,
    Json,
    Enum { name: String, values: Vec<String> },
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum MigrationDefault {
    String(String),
    Boolean(bool),
    Integer(i64),
    Float(f64),
    CurrentTimestamp,
    AutoIncrement,
}

#[derive(Debug, Clone)]
pub enum FindWhere {
    Eq(&'static str, DinocoValue),
    Neq(&'static str, DinocoValue),

    Gt(&'static str, DinocoValue),
    Gte(&'static str, DinocoValue),
    Lt(&'static str, DinocoValue),
    Lte(&'static str, DinocoValue),
    Like(&'static str, DinocoValue),
    FullText(&'static [&'static str], DinocoValue),
    Between(&'static str, DinocoValue, DinocoValue),

    Batch(&'static str, Vec<DinocoValue>),

    Null(&'static str),
    NotNull(&'static str),

    /// Membership test against a many-to-many join table. Produced by the
    /// generated virtual `Option<PrimaryKey>` fields so a caller can filter a
    /// side of a many-to-many relation by the id of a row on the other side.
    ManyToMany(ManyToManyMatch),

    And(Vec<FindWhere>),
    Or(Vec<FindWhere>),
    Not(Box<FindWhere>),
}

/// Payload for [`FindWhere::ManyToMany`].
///
/// Compiles to `<local_key> IN (SELECT <join_local_field> FROM <join_table>
/// WHERE <predicate>)`, where `predicate` is any [`FindWhere`] built against
/// `join_target_field`. Rendered as `NOT IN` when `negated` is set.
#[derive(Debug, Clone)]
pub struct ManyToManyMatch {
    /// Column on the queried entity's own table (its primary/reference key).
    pub local_key: &'static str,
    /// Join table that connects the two sides of the relation.
    pub join_table: &'static str,
    /// Join-table column that references the queried entity.
    pub join_local_field: &'static str,
    /// Join-table column that references the related entity; the field every
    /// `predicate` condition is expressed against.
    pub join_target_field: &'static str,
    /// `true` renders `NOT IN`, keeping rows that do *not* match the predicate
    /// (including rows with no link at all).
    pub negated: bool,
    /// Condition applied to `join_target_field` inside the subquery.
    pub predicate: Box<FindWhere>,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct WhereComplex;

impl WhereComplex {
    pub fn and<I>(self, conditions: I) -> FindWhere
    where
        I: IntoIterator<Item = FindWhere>,
    {
        FindWhere::And(conditions.into_iter().collect())
    }

    pub fn or(self, left: FindWhere, right: FindWhere) -> FindWhere {
        FindWhere::Or(vec![left, right])
    }

    pub fn or_many<I>(self, conditions: I) -> FindWhere
    where
        I: IntoIterator<Item = FindWhere>,
    {
        FindWhere::Or(conditions.into_iter().collect())
    }

    pub fn not(self, condition: FindWhere) -> FindWhere {
        FindWhere::Not(Box::new(condition))
    }
}

impl FindQuery {
    pub fn new(fields: &'static [&'static str], from: &'static str, limit: i32, skip: i32) -> Self {
        Self {
            fields,
            from,

            // relations: vec![],
            conditions: vec![],
            limit,
            skip,
            order_by: None,
        }
    }
}