kevy-sql 7.0.0

Declaration-time SQL compiler for kevy: CREATE TABLE/INDEX/VIEW compile ONCE into explicit TABLE.DECLARE / VIEW.CREATE commands and query cards — never a query engine.
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
//! Pass 1 — accumulate statements per table and emit ONE
//! `TABLE.DECLARE` argv per table, folding its indexes and orderpaths
//! in. All checks are compiler-side so every error carries the SQL
//! source line; the emitted argv additionally round-trips through
//! kevy-index's own wire parser in the test suite, so the two
//! implementations cannot drift.

use crate::ast::{AlterKind, CreateIndex, CreateTable, CreateView, Stmt};
use crate::{SqlError, ValType, typemap};

/// Mirrors kevy-index `MAX_COMPOSITE_COLS` (asserted by the round-trip
/// test — a drift fails there, loudly).
const MAX_COMPOSITE_COLS: usize = 8;
/// Mirrors kevy-index `MAX_TABLES`.
const MAX_TABLES: usize = 64;

/// One declared secondary index (single column).
#[derive(Debug)]
pub(crate) struct Ix {
    pub(crate) column: String,
    pub(crate) unique: bool,
    /// `INCLUDE` covering columns → stored `VALUES`.
    pub(crate) values: Vec<String>,
}

/// One composite path (multi-column index).
#[derive(Debug)]
pub(crate) struct OrderPath {
    pub(crate) name: String,
    pub(crate) on: Vec<(String, bool)>,
}

/// One fully-accumulated table.
#[derive(Debug)]
pub(crate) struct Table {
    pub(crate) name: String,
    pub(crate) pk: String,
    /// `(name, type)` in declaration order.
    pub(crate) columns: Vec<(String, ValType)>,
    pub(crate) indexes: Vec<Ix>,
    pub(crate) orderpaths: Vec<OrderPath>,
}

impl Table {
    pub(crate) fn column_type(&self, c: &str) -> Option<ValType> {
        self.columns.iter().find(|(n, _)| n == c).map(|(_, t)| *t)
    }

    /// The key-prefix domain: `<table>:`.
    pub(crate) fn prefix(&self) -> String {
        format!("{}:", self.name)
    }

    pub(crate) fn index_on(&self, col: &str) -> Option<&Ix> {
        self.indexes.iter().find(|ix| ix.column == col)
    }
}

type Built = (Vec<Table>, Vec<CreateView>, Vec<String>);

/// Fold the pg_dump-dialect `ALTER TABLE … ADD CONSTRAINT` statements
/// back onto their `CREATE TABLE`s (a dump never writes inline PKs —
/// without this every dumped table refuses for "no PRIMARY KEY").
/// Returns the statement list with the alters consumed, plus the
/// failures (unknown table, second PK) for the caller's severity.
fn apply_alters(stmts: &[Stmt], notes: &mut Vec<String>) -> (Vec<Stmt>, Vec<(String, SqlError)>) {
    let mut out: Vec<Stmt> = Vec::with_capacity(stmts.len());
    let mut failed: Vec<(String, SqlError)> = Vec::new();
    for st in stmts {
        let Stmt::Alter(a) = st else {
            out.push(st.clone());
            continue;
        };
        let target = out.iter_mut().find_map(|s| match s {
            Stmt::Table(t) if t.name == a.table => Some(t),
            _ => None,
        });
        let Some(t) = target else {
            failed.push((
                a.table.clone(),
                SqlError::at(
                    a.line,
                    a.col,
                    format!("ALTER TABLE names unknown table '{}'", a.table),
                ),
            ));
            continue;
        };
        apply_one_alter(t, a, notes, &mut failed);
    }
    (out, failed)
}

fn apply_one_alter(
    t: &mut CreateTable,
    a: &crate::ast::AlterConstraint,
    notes: &mut Vec<String>,
    failed: &mut Vec<(String, SqlError)>,
) {
    match &a.kind {
        AlterKind::PrimaryKey(col) => {
            if t.pk.is_some() || t.columns.iter().any(|c| c.inline_pk) {
                failed.push((
                    t.name.clone(),
                    SqlError::at(a.line, a.col, "more than one PRIMARY KEY".to_string()),
                ));
            } else {
                t.pk = Some((col.clone(), a.line, a.col));
            }
        }
        AlterKind::Unique(col) => t.uniques.push((col.clone(), a.line, a.col)),
        AlterKind::Noted(why) => notes.push(format!("{}: {why}", t.name)),
    }
}

/// Accumulate all statements: tables (with their indexes folded in),
/// views (compiled in pass 2), honest-mapping notes.
pub(crate) fn build(stmts: &[Stmt]) -> Result<Built, SqlError> {
    let mut tables: Vec<Table> = Vec::new();
    let mut views: Vec<CreateView> = Vec::new();
    let mut notes: Vec<String> = Vec::new();
    let (stmts, alter_failures) = apply_alters(stmts, &mut notes);
    if let Some((_, e)) = alter_failures.into_iter().next() {
        return Err(e);
    }
    for s in &stmts {
        match s {
            Stmt::Table(t) => {
                let built = build_table(t, &tables, &mut notes)?;
                if tables.len() >= MAX_TABLES {
                    return Err(SqlError::at(t.line, t.col, "table limit reached (64)"));
                }
                tables.push(built);
            }
            Stmt::Index(ix) => attach_index(ix, &mut tables, &mut notes)?,
            Stmt::View(v) => views.push(v.clone()),
            // Consumed by apply_alters above.
            Stmt::Alter(_) => {}
        }
    }
    Ok((tables, views, notes))
}

/// [`build`], but a table that cannot be declared becomes a
/// `(name, reason)` row instead of killing the whole build — the plan
/// face's contract ("report every fate") extended down to DDL: a
/// pg_dump with one refused type in one table must still yield a plan
/// for the other twenty (the V2 drill's second wall). Indexes and
/// views over a dropped table are skipped; the table's own row
/// already names why.
pub(crate) fn build_lenient(stmts: &[Stmt]) -> (Built, Vec<(String, String)>) {
    let mut tables: Vec<Table> = Vec::new();
    let mut views: Vec<CreateView> = Vec::new();
    let mut notes: Vec<String> = Vec::new();
    let mut dropped: Vec<(String, String)> = Vec::new();
    let (stmts, alter_failures) = apply_alters(stmts, &mut notes);
    for (name, e) in alter_failures {
        dropped.push((name, e.message));
    }
    for s in &stmts {
        match s {
            Stmt::Table(t) => match build_table(t, &tables, &mut notes) {
                Ok(built) if tables.len() < MAX_TABLES => tables.push(built),
                Ok(_) => dropped.push((t.name.clone(), "table limit reached (64)".into())),
                Err(e) => dropped.push((t.name.clone(), e.message)),
            },
            Stmt::Index(ix) => {
                if dropped.iter().any(|(n, _)| *n == ix.table) {
                    continue;
                }
                if let Err(e) = attach_index(ix, &mut tables, &mut notes) {
                    dropped.push((format!("index on {}", ix.table), e.message));
                }
            }
            Stmt::View(v) => views.push(v.clone()),
            // Consumed by apply_alters above.
            Stmt::Alter(_) => {}
        }
    }
    ((tables, views, notes), dropped)
}

/// The honest-mapping notes one column carries: the unenforceable
/// constraints it wrote (NOT NULL / DEFAULT — note-carried, never
/// refused, or every real pg_dump would wall at the first mile) plus
/// the type-mapping note when the mapping loses something.
fn column_notes(table: &str, c: &crate::ast::ColumnDef, notes: &mut Vec<String>) {
    if c.not_null {
        notes.push(format!(
            "{table}.{}: NOT NULL is not enforced — kevy enforces no schema at \
             write time (Law 3); an absent field reads as NULL and the row \
             simply leaves the index",
            c.name
        ));
    }
    if c.dropped_default {
        notes.push(format!(
            "{table}.{}: DEFAULT dropped — kevy enforces no schema; write the \
             default value app-side",
            c.name
        ));
    }
    if let Some(n) = typemap::mapping_note(table, &c.name, &c.sql_ty) {
        notes.push(n);
    }
}

fn build_table(
    t: &crate::ast::CreateTable,
    existing: &[Table],
    notes: &mut Vec<String>,
) -> Result<Table, SqlError> {
    if existing.iter().any(|e| e.name == t.name) {
        return Err(SqlError::at(t.line, t.col, format!("duplicate table '{}'", t.name)));
    }
    let mut columns = Vec::new();
    for c in &t.columns {
        if columns.iter().any(|(n, _)| n == &c.name) {
            return Err(SqlError::at(c.line, c.col, format!("duplicate column '{}'", c.name)));
        }
        column_notes(&t.name, c, notes);
        let Some(ty) = c.ty else {
            return Err(SqlError::at(
                c.line,
                c.col,
                format!(
                    "type '{}' is not in the compilable subset \u{2014} kevy \
                     columns are i64|f64|str; map it explicitly (type table: \
                     cookbook \u{a7}22)",
                    c.sql_ty
                ),
            ));
        };
        columns.push((c.name.clone(), ty));
    }
    let pk = resolve_pk(t)?;
    let mut table =
        Table { name: t.name.clone(), pk, columns, indexes: Vec::new(), orderpaths: Vec::new() };
    for (u, line, col) in &t.uniques {
        if table.column_type(u).is_none() {
            return Err(SqlError::at(*line, *col, format!("UNIQUE names unknown column '{u}'")));
        }
        push_index(
            &mut table,
            Ix { column: u.clone(), unique: true, values: Vec::new() },
            *line,
            *col,
        )?;
    }
    Ok(table)
}

/// Exactly one primary key, inline or table-level.
fn resolve_pk(t: &crate::ast::CreateTable) -> Result<String, SqlError> {
    let inline: Vec<&crate::ast::ColumnDef> = t.columns.iter().filter(|c| c.inline_pk).collect();
    match (&t.pk, inline.as_slice()) {
        (Some((pk, line, col)), []) => {
            if !t.columns.iter().any(|c| &c.name == pk) {
                return Err(SqlError::at(
                    *line,
                    *col,
                    format!("PRIMARY KEY names unknown column '{pk}'"),
                ));
            }
            Ok(pk.clone())
        }
        (None, [c]) => Ok(c.name.clone()),
        (None, []) => Err(SqlError::at(
            t.line,
            t.col,
            format!(
                "table '{}' has no PRIMARY KEY \u{2014} kevy rows live at <prefix><pk>; add one",
                t.name
            ),
        )),
        _ => Err(SqlError::at(t.line, t.col, "more than one PRIMARY KEY".to_string())),
    }
}

fn push_index(t: &mut Table, ix: Ix, line: u32, col: u32) -> Result<(), SqlError> {
    if t.indexes.iter().any(|e| e.column == ix.column) {
        return Err(SqlError::at(
            line,
            col,
            format!("duplicate index on column '{}' of table '{}'", ix.column, t.name),
        ));
    }
    t.indexes.push(ix);
    Ok(())
}

/// Attach one `CREATE [UNIQUE] INDEX` to its table: single column →
/// Range/Unique index (with `INCLUDE` → `VALUES`); multi-column →
/// composite ORDERPATH (auto-named `<a>_<b>` when unnamed).
fn attach_index(
    ix: &CreateIndex,
    tables: &mut [Table],
    notes: &mut Vec<String>,
) -> Result<(), SqlError> {
    let Some(t) = tables.iter_mut().find(|t| t.name == ix.table) else {
        return Err(SqlError::at(
            ix.line,
            ix.col,
            format!("INDEX ON unknown table '{}' \u{2014} CREATE TABLE it first", ix.table),
        ));
    };
    for (c, _) in &ix.cols {
        if t.column_type(c).is_none() {
            return Err(SqlError::at(
                ix.line,
                ix.col,
                format!("index names unknown column '{c}' of table '{}'", t.name),
            ));
        }
    }
    // A descending index is an order path even on one column: a Range index
    // reads in one direction only, and `ORDER BY c DESC` needs the other.
    if ix.cols.len() == 1 && !ix.cols[0].1 {
        attach_single(ix, t, notes)
    } else {
        attach_composite(ix, t)
    }
}

fn attach_single(ix: &CreateIndex, t: &mut Table, notes: &mut Vec<String>) -> Result<(), SqlError> {
    let (col, _) = &ix.cols[0];
    for v in &ix.include {
        if t.column_type(v).is_none() {
            return Err(SqlError::at(
                ix.line,
                ix.col,
                format!("INCLUDE names unknown column '{v}' of table '{}'", t.name),
            ));
        }
    }
    if let Some(n) = &ix.name {
        notes.push(format!(
            "index {n}: kevy names single-column paths by their column \u{2014} it compiles to {}.{col}",
            t.name
        ));
    }
    push_index(
        t,
        Ix { column: col.clone(), unique: ix.unique, values: ix.include.clone() },
        ix.line,
        ix.col,
    )
}

fn attach_composite(ix: &CreateIndex, t: &mut Table) -> Result<(), SqlError> {
    if ix.unique {
        return Err(SqlError::at(
            ix.line,
            ix.col,
            "a multi-column or DESC UNIQUE index is not compilable \u{2014} order paths are Range; enforce uniqueness app-side (verify-not-enforce, cookbook \u{a7}6), declare the unique index ascending, or concatenate the columns into one".to_string(),
        ));
    }
    if !ix.include.is_empty() {
        return Err(SqlError::at(
            ix.line,
            ix.col,
            "a multi-column or DESC index cannot carry INCLUDE \u{2014} order paths store no VALUES; put INCLUDE on an ascending single-column index, or extend the column chain".to_string(),
        ));
    }
    if ix.cols.len() > MAX_COMPOSITE_COLS {
        return Err(SqlError::at(ix.line, ix.col, "a composite index supports at most 8 columns"));
    }
    let name = ix.name.clone().unwrap_or_else(|| match ix.cols.as_slice() {
        // `CREATE INDEX ON t (c DESC)`: `c` alone would collide with an
        // ascending index on the same column.
        [(c, true)] => format!("{c}_desc"),
        cols => cols.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>().join("_"),
    });
    if t.orderpaths.iter().any(|o| o.name == name) {
        return Err(SqlError::at(ix.line, ix.col, format!("duplicate composite index '{name}'")));
    }
    if t.indexes.iter().any(|e| e.column == name) {
        return Err(SqlError::at(
            ix.line,
            ix.col,
            format!(
                "composite index name '{name}' collides with the single-column index on '{name}' \u{2014} name it explicitly (CREATE INDEX <name> ON \u{2026})"
            ),
        ));
    }
    t.orderpaths.push(OrderPath { name, on: ix.cols.clone() });
    Ok(())
}

/// The `TABLE.DECLARE` argv for one accumulated table — the exact
/// wire shape `kevy_index::parse_table_declare` accepts.
pub(crate) fn declare_argv(t: &Table) -> Vec<String> {
    let mut a: Vec<String> = vec![
        "TABLE.DECLARE".into(),
        t.name.clone(),
        "PREFIX".into(),
        t.prefix(),
        "PK".into(),
        t.pk.clone(),
    ];
    for (name, ty) in &t.columns {
        a.push("COLUMN".into());
        a.push(name.clone());
        a.push(ty.tag().into());
    }
    for ix in &t.indexes {
        a.push("INDEX".into());
        a.push(ix.column.clone());
        a.push(if ix.unique { "unique" } else { "range" }.into());
        if !ix.values.is_empty() {
            a.push("VALUES".into());
            a.extend(ix.values.iter().cloned());
        }
    }
    for op in &t.orderpaths {
        a.push("ORDERPATH".into());
        a.push(op.name.clone());
        a.push("ON".into());
        for (i, (col, desc)) in op.on.iter().enumerate() {
            if i > 0 {
                a.push("THEN".into());
            }
            a.push(col.clone());
            if *desc {
                a.push("DESC".into());
            }
        }
    }
    a
}