fsqlite 0.1.5

Public API facade
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
//! Integration tests for the frankensqlite migration framework.
//!
//! Bead: coding_agent_session_search-15tra
//!
//! Validates the MigrationRunner lifecycle including fresh installs,
//! partial resumes, idempotency, failure handling, and multi-statement
//! migrations.

use fsqlite::Connection;
use fsqlite::compat::*;
use fsqlite::migrate::{MigrationResult, MigrationRunner};
use fsqlite::params;
use fsqlite_types::value::SqliteValue;

// ===========================================================================
// Fresh database
// ===========================================================================

#[test]
fn fresh_database_applies_all_migrations() {
    let conn = Connection::open(":memory:").unwrap();

    let result = MigrationRunner::new()
        .add(
            1,
            "create_conversations",
            "CREATE TABLE conversations (
                id TEXT PRIMARY KEY,
                agent TEXT NOT NULL,
                created_at INTEGER NOT NULL
             );",
        )
        .add(
            2,
            "create_messages",
            "CREATE TABLE messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id TEXT NOT NULL,
                role TEXT NOT NULL,
                content TEXT
             );",
        )
        .add(
            3,
            "add_model_column",
            "ALTER TABLE conversations ADD COLUMN model TEXT;",
        )
        .run(&conn)
        .unwrap();

    assert!(result.was_fresh, "should detect fresh database");
    assert_eq!(result.applied, vec![1, 2, 3]);
    assert_eq!(result.current, 3);

    // Verify schema was applied
    conn.execute_compat(
        "INSERT INTO conversations (id, agent, created_at, model) VALUES (?1, ?2, ?3, ?4)",
        params!["s-001", "claude", 1700000000_i64, "opus"],
    )
    .unwrap();

    let row = conn
        .query_row("SELECT model FROM conversations WHERE id = 's-001'")
        .unwrap();
    assert_eq!(row.get(0).unwrap(), &SqliteValue::Text("opus".into()));
}

// ===========================================================================
// Partial resume
// ===========================================================================

#[test]
fn partial_resume_only_applies_new_migrations() {
    let conn = Connection::open(":memory:").unwrap();

    // First run: apply V1 and V2
    let runner_v2 = MigrationRunner::new()
        .add(
            1,
            "create_items",
            "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT);",
        )
        .add(
            2,
            "add_count",
            "ALTER TABLE items ADD COLUMN count INTEGER DEFAULT 0;",
        );

    let r1 = runner_v2.run(&conn).unwrap();
    assert_eq!(r1.applied, vec![1, 2]);
    assert_eq!(r1.current, 2);
    assert!(r1.was_fresh);

    // Second run: add V3 - only V3 should apply
    let runner_v3 = MigrationRunner::new()
        .add(
            1,
            "create_items",
            "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT);",
        )
        .add(
            2,
            "add_count",
            "ALTER TABLE items ADD COLUMN count INTEGER DEFAULT 0;",
        )
        .add(
            3,
            "add_desc",
            "ALTER TABLE items ADD COLUMN description TEXT;",
        );

    let r2 = runner_v3.run(&conn).unwrap();
    assert_eq!(r2.applied, vec![3]);
    assert_eq!(r2.current, 3);
    assert!(!r2.was_fresh);

    // Verify column exists
    conn.execute("INSERT INTO items (id, name, description) VALUES (1, 'test', 'desc')")
        .unwrap();
    let row = conn
        .query_row("SELECT description FROM items WHERE id = 1")
        .unwrap();
    assert_eq!(row.get(0).unwrap(), &SqliteValue::Text("desc".into()));
}

// ===========================================================================
// Idempotency
// ===========================================================================

#[test]
fn idempotent_rerun_applies_nothing() {
    let conn = Connection::open(":memory:").unwrap();

    let runner = MigrationRunner::new()
        .add(1, "create_t", "CREATE TABLE t (x INTEGER);")
        .add(2, "create_u", "CREATE TABLE u (y TEXT);");

    let r1 = runner.run(&conn).unwrap();
    assert_eq!(r1.applied, vec![1, 2]);

    let r2 = runner.run(&conn).unwrap();
    assert!(r2.applied.is_empty(), "second run should apply nothing");
    assert_eq!(r2.current, 2);
    assert!(!r2.was_fresh);
}

// ===========================================================================
// Failed migration
// ===========================================================================

#[test]
fn failed_migration_rolls_back() {
    let conn = Connection::open(":memory:").unwrap();

    let runner = MigrationRunner::new()
        .add(1, "create_t", "CREATE TABLE t (x INTEGER);")
        .add(2, "bad_sql", "THIS IS NOT VALID SQL;");

    let result = runner.run(&conn);
    assert!(result.is_err(), "invalid SQL should fail");

    // V1 may or may not have been applied depending on implementation.
    // What matters is the DB is in a consistent state.
    // The tracking table should exist (created before migrations run).
}

// ===========================================================================
// Multi-statement migration
// ===========================================================================

#[test]
fn multi_statement_migration() {
    let conn = Connection::open(":memory:").unwrap();

    let result = MigrationRunner::new()
        .add(
            1,
            "create_schema",
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
             CREATE TABLE roles (id INTEGER PRIMARY KEY, role TEXT);
             CREATE INDEX idx_users_name ON users(name);",
        )
        .run(&conn)
        .unwrap();

    assert_eq!(result.applied, vec![1]);

    // Verify all three objects exist
    conn.execute("INSERT INTO users (id, name) VALUES (1, 'alice')")
        .unwrap();
    conn.execute("INSERT INTO roles (id, role) VALUES (1, 'admin')")
        .unwrap();

    // Index should speed up queries (no error = index exists)
    let rows = conn
        .query("SELECT name FROM users WHERE name = 'alice'")
        .unwrap();
    assert_eq!(rows.len(), 1);
}

// ===========================================================================
// Empty runner
// ===========================================================================

#[test]
fn empty_runner_on_fresh_db() {
    let conn = Connection::open(":memory:").unwrap();

    let result = MigrationRunner::new().run(&conn).unwrap();
    assert!(result.applied.is_empty());
    assert_eq!(result.current, 0);
    assert!(result.was_fresh);
}

// ===========================================================================
// Migration tracking table
// ===========================================================================

#[test]
fn migration_records_name_in_tracking_table() {
    let conn = Connection::open(":memory:").unwrap();

    MigrationRunner::new()
        .add(1, "init_schema", "CREATE TABLE t (x INTEGER);")
        .add(2, "add_index", "CREATE INDEX idx_t_x ON t(x);")
        .run(&conn)
        .unwrap();

    // Query the tracking table
    let rows = conn
        .query("SELECT version, name FROM _schema_migrations ORDER BY version")
        .unwrap();

    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].get(0).unwrap(), &SqliteValue::Integer(1));
    assert_eq!(
        rows[0].get(1).unwrap(),
        &SqliteValue::Text("init_schema".into())
    );
    assert_eq!(rows[1].get(0).unwrap(), &SqliteValue::Integer(2));
    assert_eq!(
        rows[1].get(1).unwrap(),
        &SqliteValue::Text("add_index".into())
    );
}

#[test]
fn migration_tracking_table_has_applied_at() {
    let conn = Connection::open(":memory:").unwrap();

    MigrationRunner::new()
        .add(1, "init", "CREATE TABLE t (x INTEGER);")
        .run(&conn)
        .unwrap();

    let rows = conn
        .query("SELECT applied_at FROM _schema_migrations WHERE version = 1")
        .unwrap();

    assert_eq!(rows.len(), 1);
    // applied_at should be a non-empty ISO timestamp string
    if let SqliteValue::Text(ts) = rows[0].get(0).unwrap() {
        assert!(!ts.is_empty(), "applied_at should not be empty");
        assert!(
            ts.contains('T') || ts.contains('-'),
            "applied_at should look like an ISO timestamp, got: {ts}"
        );
    } else {
        panic!("applied_at should be text");
    }
}

// ===========================================================================
// Ordering enforcement
// ===========================================================================

#[test]
#[should_panic(expected = "")]
fn panics_on_non_ascending_versions() {
    MigrationRunner::new()
        .add(2, "second", "CREATE TABLE b (y TEXT);")
        .add(1, "first", "CREATE TABLE a (x INTEGER);");
}

#[test]
#[should_panic(expected = "")]
fn panics_on_duplicate_versions() {
    MigrationRunner::new()
        .add(1, "first", "CREATE TABLE a (x INTEGER);")
        .add(1, "duplicate", "CREATE TABLE b (y TEXT);");
}

// ===========================================================================
// Realistic cass-like migration sequence
// ===========================================================================

#[test]
fn cass_like_migration_sequence() {
    let conn = Connection::open(":memory:").unwrap();

    let result = MigrationRunner::new()
        .add(
            1,
            "initial_schema",
            "CREATE TABLE conversations (
                id TEXT PRIMARY KEY,
                agent TEXT NOT NULL,
                workspace TEXT,
                project_dir TEXT,
                created_at INTEGER NOT NULL,
                updated_at INTEGER,
                model TEXT,
                title TEXT,
                message_count INTEGER DEFAULT 0,
                source_id TEXT DEFAULT 'local'
             );
             CREATE TABLE messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id TEXT NOT NULL REFERENCES conversations(id),
                role TEXT NOT NULL,
                content TEXT,
                timestamp INTEGER,
                token_count INTEGER DEFAULT 0
             );
             CREATE INDEX idx_conv_agent ON conversations(agent);
             CREATE INDEX idx_conv_created ON conversations(created_at);
             CREATE INDEX idx_msg_conv ON messages(conversation_id);",
        )
        .add(
            2,
            "add_bookmarks",
            "CREATE TABLE bookmarks (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                conversation_id TEXT NOT NULL,
                message_index INTEGER,
                note TEXT,
                created_at INTEGER NOT NULL
             );",
        )
        .add(
            3,
            "add_tags",
            "ALTER TABLE conversations ADD COLUMN tags TEXT DEFAULT '';",
        )
        .run(&conn)
        .unwrap();

    assert!(result.was_fresh);
    assert_eq!(result.applied, vec![1, 2, 3]);
    assert_eq!(result.current, 3);

    // Insert realistic data
    conn.execute_compat(
        "INSERT INTO conversations (id, agent, created_at, title, tags) VALUES (?1, ?2, ?3, ?4, ?5)",
        params!["s-001", "claude_code", 1700000000_i64, "Debug auth", "rust,auth"],
    ).unwrap();

    conn.execute_compat(
        "INSERT INTO messages (conversation_id, role, content, timestamp) VALUES (?1, ?2, ?3, ?4)",
        params!["s-001", "user", "Why is auth broken?", 1700000000_i64],
    )
    .unwrap();

    conn.execute_compat(
        "INSERT INTO bookmarks (conversation_id, message_index, note, created_at) VALUES (?1, ?2, ?3, ?4)",
        params!["s-001", 0_i64, "Key insight", 1700000001_i64],
    ).unwrap();

    // Verify data roundtrip
    let title: String = conn
        .query_row_map(
            "SELECT title FROM conversations WHERE id = ?1",
            params!["s-001"],
            |row| row.get_typed(0),
        )
        .unwrap();
    assert_eq!(title, "Debug auth");

    let msg_count: i64 = conn
        .query_row_map(
            "SELECT COUNT(*) FROM messages WHERE conversation_id = ?1",
            params!["s-001"],
            |row| row.get_typed(0),
        )
        .unwrap();
    assert_eq!(msg_count, 1);

    let bm_note: String = conn
        .query_row_map(
            "SELECT note FROM bookmarks WHERE conversation_id = ?1",
            params!["s-001"],
            |row| row.get_typed(0),
        )
        .unwrap();
    assert_eq!(bm_note, "Key insight");
}

// ===========================================================================
// Migration result fields
// ===========================================================================

#[test]
fn migration_result_fields_all_correct() {
    let conn = Connection::open(":memory:").unwrap();

    let r: MigrationResult = MigrationRunner::new()
        .add(10, "v10", "CREATE TABLE t10 (x INTEGER);")
        .add(20, "v20", "CREATE TABLE t20 (y TEXT);")
        .run(&conn)
        .unwrap();

    assert!(r.was_fresh);
    assert_eq!(r.applied, vec![10, 20]);
    assert_eq!(r.current, 20);
}