heliosdb-nano 3.23.2

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
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
//! Temporal diff helpers (FR 3 §3.3).
//!
//! `lsp_references_diff`, `lsp_body_diff`, and `ast_diff` run the
//! equivalent lsp_* query at two temporal points and classify the
//! results as `added`, `removed`, or `moved`.
//!
//! The temporal points are expressed as `AsOfRef` which is a thin
//! wrapper over Nano's native `AS OF` clause (`COMMIT`, `TIMESTAMP`,
//! `NOW`). Callers build these with `AsOfRef::commit("abc")`,
//! `AsOfRef::timestamp("2025-01-02")`, or `AsOfRef::now()`.

use std::collections::HashMap;

use crate::{EmbeddedDatabase, Result, Value};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AsOfRef {
    Now,
    Commit(String),
    Timestamp(String),
}

impl AsOfRef {
    pub fn commit(sha: impl Into<String>) -> Self {
        Self::Commit(sha.into())
    }
    pub fn timestamp(ts: impl Into<String>) -> Self {
        Self::Timestamp(ts.into())
    }
    pub fn now() -> Self {
        Self::Now
    }

    /// Render the SQL `AS OF …` clause fragment, or empty when `Now`.
    pub fn to_sql_clause(&self) -> String {
        match self {
            AsOfRef::Now => String::new(),
            AsOfRef::Commit(sha) => format!(" AS OF COMMIT '{}'", escape(sha)),
            AsOfRef::Timestamp(ts) => format!(" AS OF TIMESTAMP '{}'", escape(ts)),
        }
    }
}

fn escape(s: &str) -> String {
    s.replace('\'', "''")
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffChange {
    Added,
    Removed,
    Moved,
}

impl DiffChange {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Added => "added",
            Self::Removed => "removed",
            Self::Moved => "moved",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct RefDiffRow {
    pub change: DiffChange,
    pub path: String,
    pub line: i32,
    pub caller_symbol_id: Option<i64>,
}

/// `lsp_references_diff(symbol_id, at_a, at_b)` — added / removed /
/// moved refs between two points in time.
///
/// * `added` — present at B, not at A.
/// * `removed` — present at A, not at B.
/// * `moved` — present at both, but at a different `(path, line)`.
///
/// Matching key is `caller_symbol_id`. Refs without a caller id (the
/// unresolved-heuristic bucket) are compared by `(path, line, kind)`.
pub fn lsp_references_diff(
    db: &EmbeddedDatabase,
    symbol_id: i64,
    at_a: &AsOfRef,
    at_b: &AsOfRef,
) -> Result<Vec<RefDiffRow>> {
    let a = fetch_refs(db, symbol_id, at_a)?;
    let b = fetch_refs(db, symbol_id, at_b)?;

    let key_a: HashMap<RefKey, (String, i32)> = a
        .iter()
        .map(|r| (r.key(), (r.path.clone(), r.line)))
        .collect();
    let key_b: HashMap<RefKey, (String, i32)> = b
        .iter()
        .map(|r| (r.key(), (r.path.clone(), r.line)))
        .collect();

    let mut out: Vec<RefDiffRow> = Vec::new();
    for r in &a {
        match key_b.get(&r.key()) {
            None => out.push(RefDiffRow {
                change: DiffChange::Removed,
                path: r.path.clone(),
                line: r.line,
                caller_symbol_id: r.caller_symbol_id,
            }),
            Some((p, l)) if *p != r.path || *l != r.line => {
                out.push(RefDiffRow {
                    change: DiffChange::Moved,
                    path: p.clone(),
                    line: *l,
                    caller_symbol_id: r.caller_symbol_id,
                })
            }
            _ => {}
        }
    }
    for r in &b {
        if !key_a.contains_key(&r.key()) {
            out.push(RefDiffRow {
                change: DiffChange::Added,
                path: r.path.clone(),
                line: r.line,
                caller_symbol_id: r.caller_symbol_id,
            });
        }
    }
    // Stable order: change, path, line.
    out.sort_by(|x, y| {
        x.change
            .as_str()
            .cmp(y.change.as_str())
            .then_with(|| x.path.cmp(&y.path))
            .then_with(|| x.line.cmp(&y.line))
    });
    Ok(out)
}

#[derive(Debug, Clone, PartialEq)]
pub struct BodyDiffLine {
    pub line_a: i32,
    pub line_b: i32,
    pub op: BodyOp,
    pub text: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BodyOp {
    Equal,
    Added,
    Removed,
}

impl BodyOp {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Equal => "equal",
            Self::Added => "added",
            Self::Removed => "removed",
        }
    }
}

/// Line-level diff of a symbol's body (via its signature field, which
/// we track as first-line text).  Returns Myers-diff-shaped
/// `BodyDiffLine` rows suitable for UI rendering.
pub fn lsp_body_diff(
    db: &EmbeddedDatabase,
    symbol_id: i64,
    at_a: &AsOfRef,
    at_b: &AsOfRef,
) -> Result<Vec<BodyDiffLine>> {
    let a = fetch_signature(db, symbol_id, at_a)?;
    let b = fetch_signature(db, symbol_id, at_b)?;
    Ok(myers_diff(&a, &b))
}

#[derive(Debug, Clone, PartialEq)]
pub struct AstDiffRow {
    pub change: DiffChange,
    pub kind: String,
    pub qualified: String,
    pub line_a: Option<i32>,
    pub line_b: Option<i32>,
}

/// File-level structural diff — which symbols exist / moved / disappeared
/// between two temporal points. Matching key is `qualified`.
pub fn ast_diff(
    db: &EmbeddedDatabase,
    file_path: &str,
    at_a: &AsOfRef,
    at_b: &AsOfRef,
) -> Result<Vec<AstDiffRow>> {
    let a = fetch_symbols_for_path(db, file_path, at_a)?;
    let b = fetch_symbols_for_path(db, file_path, at_b)?;
    let a_map: HashMap<String, (String, i32)> = a
        .iter()
        .map(|s| (s.qualified.clone(), (s.kind.clone(), s.line_start)))
        .collect();
    let b_map: HashMap<String, (String, i32)> = b
        .iter()
        .map(|s| (s.qualified.clone(), (s.kind.clone(), s.line_start)))
        .collect();
    let mut out = Vec::new();
    for s in &a {
        match b_map.get(&s.qualified) {
            None => out.push(AstDiffRow {
                change: DiffChange::Removed,
                kind: s.kind.clone(),
                qualified: s.qualified.clone(),
                line_a: Some(s.line_start),
                line_b: None,
            }),
            Some((_, lb)) if *lb != s.line_start => out.push(AstDiffRow {
                change: DiffChange::Moved,
                kind: s.kind.clone(),
                qualified: s.qualified.clone(),
                line_a: Some(s.line_start),
                line_b: Some(*lb),
            }),
            _ => {}
        }
    }
    for s in &b {
        if !a_map.contains_key(&s.qualified) {
            out.push(AstDiffRow {
                change: DiffChange::Added,
                kind: s.kind.clone(),
                qualified: s.qualified.clone(),
                line_a: None,
                line_b: Some(s.line_start),
            });
        }
    }
    out.sort_by(|x, y| {
        x.change
            .as_str()
            .cmp(y.change.as_str())
            .then_with(|| x.qualified.cmp(&y.qualified))
    });
    Ok(out)
}

// ---------- internals ------------------------------------------------------

struct RefAt {
    path: String,
    line: i32,
    kind: String,
    caller_symbol_id: Option<i64>,
}

impl RefAt {
    fn key(&self) -> RefKey {
        match self.caller_symbol_id {
            Some(id) => RefKey::ByCaller(id),
            None => RefKey::ByLocation(self.path.clone(), self.line, self.kind.clone()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum RefKey {
    ByCaller(i64),
    ByLocation(String, i32, String),
}

fn fetch_refs(
    db: &EmbeddedDatabase,
    symbol_id: i64,
    at: &AsOfRef,
) -> Result<Vec<RefAt>> {
    let clause = at.to_sql_clause();
    let sql = format!(
        "SELECT f.path, r.line, r.kind, r.from_symbol \
         FROM _hdb_code_symbol_refs r{clause} \
         JOIN _hdb_code_files f{clause} ON f.node_id = r.file_id \
         WHERE r.to_symbol = {symbol_id}"
    );
    let rows = db.query(&sql, &[])?;
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        let path = match row.values.first() {
            Some(Value::String(s)) => s.clone(),
            _ => continue,
        };
        let line = match row.values.get(1) {
            Some(Value::Int4(n)) => *n,
            Some(Value::Int8(n)) => *n as i32,
            _ => continue,
        };
        let kind = match row.values.get(2) {
            Some(Value::String(s)) => s.clone(),
            _ => String::new(),
        };
        let caller = match row.values.get(3) {
            Some(Value::Int4(n)) => Some(*n as i64),
            Some(Value::Int8(n)) => Some(*n),
            _ => None,
        };
        out.push(RefAt {
            path,
            line,
            kind,
            caller_symbol_id: caller,
        });
    }
    Ok(out)
}

fn fetch_signature(
    db: &EmbeddedDatabase,
    symbol_id: i64,
    at: &AsOfRef,
) -> Result<String> {
    let clause = at.to_sql_clause();
    let sql = format!(
        "SELECT signature FROM _hdb_code_symbols s{clause} \
         WHERE s.node_id = {symbol_id}"
    );
    let rows = db.query(&sql, &[])?;
    Ok(match rows.first().and_then(|r| r.values.first()) {
        Some(Value::String(s)) => s.clone(),
        _ => String::new(),
    })
}

struct SymAt {
    qualified: String,
    kind: String,
    line_start: i32,
}

fn fetch_symbols_for_path(
    db: &EmbeddedDatabase,
    file_path: &str,
    at: &AsOfRef,
) -> Result<Vec<SymAt>> {
    let clause = at.to_sql_clause();
    let esc = file_path.replace('\'', "''");
    let sql = format!(
        "SELECT s.qualified, s.kind, s.line_start \
         FROM _hdb_code_symbols s{clause} \
         JOIN _hdb_code_files f{clause} ON f.node_id = s.file_id \
         WHERE f.path = '{esc}'"
    );
    let rows = db.query(&sql, &[])?;
    let mut out = Vec::with_capacity(rows.len());
    for row in rows {
        let qualified = match row.values.first() {
            Some(Value::String(s)) => s.clone(),
            _ => continue,
        };
        let kind = match row.values.get(1) {
            Some(Value::String(s)) => s.clone(),
            _ => String::new(),
        };
        let line_start = match row.values.get(2) {
            Some(Value::Int4(n)) => *n,
            Some(Value::Int8(n)) => *n as i32,
            _ => 0,
        };
        out.push(SymAt {
            qualified,
            kind,
            line_start,
        });
    }
    Ok(out)
}

/// Minimal line-by-line Myers-style diff over two strings split on
/// newline.  Good enough for `lsp_body_diff` — proper word / char
/// diff is explicitly out of scope (callers can wrap if they want).
fn myers_diff(a: &str, b: &str) -> Vec<BodyDiffLine> {
    let a_lines: Vec<&str> = a.lines().collect();
    let b_lines: Vec<&str> = b.lines().collect();
    // LCS table
    let (m, n) = (a_lines.len(), b_lines.len());
    let mut dp = vec![vec![0usize; n + 1]; m + 1];
    for i in 0..m {
        for j in 0..n {
            dp[i + 1][j + 1] = if a_lines[i] == b_lines[j] {
                dp[i][j] + 1
            } else {
                dp[i + 1][j].max(dp[i][j + 1])
            };
        }
    }
    let (mut i, mut j) = (m, n);
    let mut out: Vec<BodyDiffLine> = Vec::with_capacity(m + n);
    while i > 0 || j > 0 {
        if i > 0 && j > 0 && a_lines[i - 1] == b_lines[j - 1] {
            out.push(BodyDiffLine {
                line_a: i as i32,
                line_b: j as i32,
                op: BodyOp::Equal,
                text: a_lines[i - 1].to_string(),
            });
            i -= 1;
            j -= 1;
        } else if j > 0 && (i == 0 || dp[i][j - 1] >= dp[i - 1][j]) {
            out.push(BodyDiffLine {
                line_a: 0,
                line_b: j as i32,
                op: BodyOp::Added,
                text: b_lines[j - 1].to_string(),
            });
            j -= 1;
        } else {
            out.push(BodyDiffLine {
                line_a: i as i32,
                line_b: 0,
                op: BodyOp::Removed,
                text: a_lines[i - 1].to_string(),
            });
            i -= 1;
        }
    }
    out.reverse();
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn as_of_clause_renders() {
        assert_eq!(AsOfRef::Now.to_sql_clause(), "");
        assert_eq!(
            AsOfRef::commit("abc").to_sql_clause(),
            " AS OF COMMIT 'abc'"
        );
        assert_eq!(
            AsOfRef::timestamp("2025-01-01").to_sql_clause(),
            " AS OF TIMESTAMP '2025-01-01'"
        );
    }

    #[test]
    fn escapes_quote_in_as_of_literal() {
        assert_eq!(
            AsOfRef::commit("a'b").to_sql_clause(),
            " AS OF COMMIT 'a''b'"
        );
    }

    #[test]
    fn myers_diff_identifies_added_removed_equal() {
        let diff = myers_diff("fn foo()\nbody\n", "fn foo()\nchanged\n");
        let ops: Vec<BodyOp> = diff.iter().map(|d| d.op).collect();
        assert!(ops.contains(&BodyOp::Equal));
        assert!(ops.contains(&BodyOp::Added));
        assert!(ops.contains(&BodyOp::Removed));
    }
}