icydb 0.156.1

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
use crate::db::{
    EntityFieldDescription, EntitySchemaDescription,
    sql::{SqlGroupedRowsOutput, SqlProjectionRows, SqlQueryRowsOutput},
};

#[cfg_attr(
    doc,
    doc = "Render one SQL EXPLAIN text payload as endpoint output lines."
)]
#[must_use]
pub fn render_explain_lines(explain: &str) -> Vec<String> {
    let mut lines = vec!["surface=explain".to_string()];
    lines.extend(explain.lines().map(ToString::to_string));

    lines
}

#[cfg_attr(
    doc,
    doc = "Render one typed `DESCRIBE` payload into deterministic shell output lines."
)]
#[must_use]
pub fn render_describe_lines(description: &EntitySchemaDescription) -> Vec<String> {
    let mut lines = Vec::new();

    // Phase 1: emit top-level entity identity metadata.
    lines.push(format!("entity: {}", description.entity_name()));
    lines.push(format!("path: {}", description.entity_path()));

    // Phase 2: emit field descriptors in stable model order using the same
    // padded ASCII table shape as shell query results.
    lines.push(String::new());
    lines.push("fields:".to_string());
    render_describe_field_section(&mut lines, description.fields());

    // Phase 3: emit index descriptors or explicit empty marker.
    lines.push(String::new());
    if description.indexes().is_empty() {
        lines.push("indexes: []".to_string());
    } else {
        lines.push("indexes:".to_string());
        let index_rows = description
            .indexes()
            .iter()
            .map(|index| {
                vec![
                    index.name().to_string(),
                    index.fields().join(", "),
                    if index.unique() {
                        "yes".to_string()
                    } else {
                        "no".to_string()
                    },
                ]
            })
            .collect::<Vec<_>>();
        render_describe_table_section(
            &mut lines,
            &[
                "name".to_string(),
                "fields".to_string(),
                "unique".to_string(),
            ],
            &index_rows,
        );
    }

    // Phase 4: emit relation descriptors or explicit empty marker.
    lines.push(String::new());
    if description.relations().is_empty() {
        lines.push("relations: []".to_string());
    } else {
        lines.push("relations:".to_string());
        let relation_rows = description
            .relations()
            .iter()
            .map(|relation| {
                vec![
                    relation.field().to_string(),
                    relation.target_entity_name().to_string(),
                    format!("{:?}", relation.strength()),
                    format!("{:?}", relation.cardinality()),
                ]
            })
            .collect::<Vec<_>>();
        render_describe_table_section(
            &mut lines,
            &[
                "field".to_string(),
                "target".to_string(),
                "strength".to_string(),
                "cardinality".to_string(),
            ],
            &relation_rows,
        );
    }

    lines
}

// Render the shared field table used by both full `DESCRIBE` output and the
// narrower `SHOW COLUMNS` surface. Keeping the table logic here prevents the
// two shell commands from drifting into different human-facing formats.
fn render_describe_field_section(lines: &mut Vec<String>, fields: &[EntityFieldDescription]) {
    let field_rows = fields
        .iter()
        .map(|field| {
            vec![
                field.name().to_string(),
                field
                    .slot()
                    .map_or_else(|| "-".to_string(), |slot| slot.to_string()),
                field.kind().to_string(),
                if field.primary_key() {
                    "yes".to_string()
                } else {
                    "no".to_string()
                },
                if field.queryable() {
                    "yes".to_string()
                } else {
                    "no".to_string()
                },
            ]
        })
        .collect::<Vec<_>>();
    render_describe_table_section(
        lines,
        &[
            "name".to_string(),
            "slot".to_string(),
            "type".to_string(),
            "pk".to_string(),
            "queryable".to_string(),
        ],
        &field_rows,
    );
}

// Render one `DESCRIBE` subsection as the same deterministic ASCII table shape
// used by shell-facing projection output.
fn render_describe_table_section(
    lines: &mut Vec<String>,
    headers: &[String],
    rows: &[Vec<String>],
) {
    let mut widths = headers.iter().map(String::len).collect::<Vec<_>>();
    for row in rows {
        for (index, value) in row.iter().enumerate() {
            widths[index] = widths[index].max(value.len());
        }
    }

    let separator = render_table_separator(widths.as_slice());
    lines.push(separator.clone());
    lines.push(render_table_row(headers, widths.as_slice()));
    lines.push(separator.clone());
    for row in rows {
        lines.push(render_table_row(row.as_slice(), widths.as_slice()));
    }
    if !rows.is_empty() {
        lines.push(separator);
    }
}

#[cfg_attr(
    doc,
    doc = "Render one SQL count payload into deterministic shell output lines."
)]
#[must_use]
pub fn render_count_lines(entity: &str, row_count: u32) -> Vec<String> {
    vec![format!(
        "surface=count entity={entity} row_count={row_count}"
    )]
}

#[cfg_attr(doc, doc = "Render one SQL DDL payload into deterministic lines.")]
#[must_use]
pub(in crate::db::sql) fn render_sql_ddl_lines(input: SqlDdlRenderInput<'_>) -> Vec<String> {
    vec![format!(
        "surface=ddl entity={} mutation_kind={} target_index={} target_store={} field_path={} status={} rows_scanned={} index_keys_written={}",
        input.entity,
        input.mutation_kind,
        input.target_index,
        input.target_store,
        input.field_path.join("."),
        input.status,
        input.rows_scanned,
        input.index_keys_written,
    )]
}

pub(in crate::db::sql) struct SqlDdlRenderInput<'a> {
    pub(in crate::db::sql) entity: &'a str,
    pub(in crate::db::sql) mutation_kind: &'a str,
    pub(in crate::db::sql) target_index: &'a str,
    pub(in crate::db::sql) target_store: &'a str,
    pub(in crate::db::sql) field_path: &'a [String],
    pub(in crate::db::sql) status: &'a str,
    pub(in crate::db::sql) rows_scanned: u64,
    pub(in crate::db::sql) index_keys_written: u64,
}

#[cfg_attr(
    doc,
    doc = "Render one `SHOW INDEXES` payload into deterministic shell output lines."
)]
#[must_use]
pub fn render_show_indexes_lines(entity: &str, indexes: &[String]) -> Vec<String> {
    let mut lines = vec![format!(
        "surface=indexes entity={entity} index_count={}",
        indexes.len()
    )];
    lines.extend(indexes.iter().cloned());

    lines
}

#[cfg_attr(
    doc,
    doc = "Render one `SHOW COLUMNS` payload into deterministic shell output lines."
)]
#[must_use]
pub fn render_show_columns_lines(entity: &str, columns: &[EntityFieldDescription]) -> Vec<String> {
    let mut lines = vec![
        format!("entity: {entity}"),
        String::new(),
        "fields:".to_string(),
    ];
    render_describe_field_section(&mut lines, columns);

    lines
}

#[cfg_attr(
    doc,
    doc = "Render one helper-level `SHOW ENTITIES` payload into deterministic lines."
)]
#[must_use]
pub fn render_show_entities_lines(entities: &[String]) -> Vec<String> {
    let rows = entities
        .iter()
        .map(|entity| vec![entity.clone()])
        .collect::<Vec<_>>();
    let mut lines = vec!["tables:".to_string()];
    render_describe_table_section(&mut lines, &["name".to_string()], rows.as_slice());
    lines.push(String::new());
    lines.push(render_result_table_count_line(entities.len()));

    lines
}

#[cfg_attr(
    doc,
    doc = "Render one SQL projection payload into pretty table lines for shell output."
)]
#[must_use]
pub fn render_projection_lines(_entity: &str, projection: &SqlProjectionRows) -> Vec<String> {
    render_projection_table(
        projection.columns(),
        projection.rows(),
        projection.row_count(),
    )
}

#[must_use]
pub(in crate::db::sql) fn render_query_rows_lines(projection: &SqlQueryRowsOutput) -> Vec<String> {
    render_projection_table(
        projection.columns.as_slice(),
        projection.rows.as_slice(),
        projection.row_count,
    )
}

fn render_projection_table(
    columns: &[String],
    rows: &[Vec<String>],
    row_count: u32,
) -> Vec<String> {
    // Phase 1: handle empty-projection output before table layout.
    let mut lines = Vec::new();
    if columns.is_empty() {
        lines.push("(no projected columns)".to_string());
        return lines;
    }

    // Phase 2: compute per-column display widths from headers + row values.
    let mut widths = columns.iter().map(String::len).collect::<Vec<_>>();
    for row in rows {
        for (index, value) in row.iter().enumerate() {
            if index >= widths.len() {
                widths.push(value.len());
            } else {
                widths[index] = widths[index].max(value.len());
            }
        }
    }

    // Phase 3: render deterministic ASCII table surface.
    let separator = render_table_separator(widths.as_slice());
    lines.push(separator.clone());
    lines.push(render_table_row(columns, widths.as_slice()));
    lines.push(separator.clone());
    for row in rows {
        lines.push(render_table_row(row.as_slice(), widths.as_slice()));
    }
    if !rows.is_empty() {
        lines.push(separator);
    }
    lines.push(String::new());
    lines.push(render_result_row_count_line(row_count));

    lines
}

#[cfg_attr(
    doc,
    doc = "Render one grouped SQL payload into pretty table lines for shell output."
)]
#[must_use]
pub fn render_grouped_lines(grouped: &SqlGroupedRowsOutput) -> Vec<String> {
    // Phase 1: expose the outward continuation cursor on its own line when
    // grouped pagination has more rows.
    let mut lines = Vec::new();
    if let Some(next_cursor) = &grouped.next_cursor {
        lines.push(format!("next_cursor={next_cursor}"));
    }
    if grouped.columns.is_empty() {
        lines.push("(no grouped columns)".to_string());
        return lines;
    }

    // Phase 2: compute per-column display widths from headers + grouped row values.
    let mut widths = grouped.columns.iter().map(String::len).collect::<Vec<_>>();
    for row in &grouped.rows {
        for (index, value) in row.iter().enumerate() {
            if index >= widths.len() {
                widths.push(value.len());
            } else {
                widths[index] = widths[index].max(value.len());
            }
        }
    }

    // Phase 3: render the grouped page as the same deterministic ASCII table
    // shape used by projection payloads.
    let separator = render_table_separator(widths.as_slice());
    lines.push(separator.clone());
    lines.push(render_table_row(
        grouped.columns.as_slice(),
        widths.as_slice(),
    ));
    lines.push(separator.clone());
    for row in &grouped.rows {
        lines.push(render_table_row(row.as_slice(), widths.as_slice()));
    }
    if !grouped.rows.is_empty() {
        lines.push(separator);
    }
    lines.push(String::new());
    lines.push(render_result_row_count_line(grouped.row_count));

    lines
}

fn render_result_row_count_line(row_count: u32) -> String {
    let noun = if row_count == 1 { "row" } else { "rows" };
    format!(
        "{} {noun},",
        render_grouped_decimal_usize(row_count as usize)
    )
}

fn render_result_table_count_line(table_count: usize) -> String {
    let noun = if table_count == 1 { "table" } else { "tables" };
    format!("{} {noun},", render_grouped_decimal_usize(table_count))
}

// Render one count with ASCII thousands separators so shell count footers
// remain easy to scan on large result sets.
fn render_grouped_decimal_usize(value: usize) -> String {
    let digits = value.to_string();
    let mut rendered = String::with_capacity(digits.len().saturating_add(digits.len() / 3));
    let leading_group_len = digits.len().rem_euclid(3);

    for (index, ch) in digits.chars().enumerate() {
        if index > 0
            && (index == leading_group_len
                || (index > leading_group_len && (index - leading_group_len).rem_euclid(3) == 0))
        {
            rendered.push(',');
        }
        rendered.push(ch);
    }

    rendered
}

fn render_table_separator(widths: &[usize]) -> String {
    let segments = widths
        .iter()
        .map(|width| "-".repeat(width.saturating_add(2)))
        .collect::<Vec<_>>();

    format!("+{}+", segments.join("+"))
}

fn render_table_row(cells: &[String], widths: &[usize]) -> String {
    let mut parts = Vec::with_capacity(widths.len());
    for (index, width) in widths.iter().copied().enumerate() {
        let value = cells.get(index).map_or("", String::as_str);
        parts.push(format!("{value:<width$}"));
    }

    format!("| {} |", parts.join(" | "))
}