-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathconnection.rs
More file actions
1537 lines (1413 loc) · 59 KB
/
Copy pathconnection.rs
File metadata and controls
1537 lines (1413 loc) · 59 KB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Public `Connection` / `Statement` / `Rows` / `Row` API (Phase 5a + SQLR-23).
//!
//! This is the stable surface external consumers bind against — Rust
//! callers use it directly, language SDKs (Python, Node.js, Go) bind
//! against the C FFI wrapper over these same types in Phase 5b, and
//! the WASM build in Phase 5g re-exposes them via `wasm-bindgen`.
//!
//! The shape mirrors `rusqlite` / Python's `sqlite3` so users
//! familiar with either can pick it up immediately:
//!
//! ```no_run
//! use sqlrite::Connection;
//!
//! let mut conn = Connection::open("foo.sqlrite")?;
//! conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")?;
//! conn.execute("INSERT INTO users (name) VALUES ('alice')")?;
//!
//! let mut stmt = conn.prepare("SELECT id, name FROM users")?;
//! let mut rows = stmt.query()?;
//! while let Some(row) = rows.next()? {
//! let id: i64 = row.get(0)?;
//! let name: String = row.get(1)?;
//! println!("{id}: {name}");
//! }
//! # Ok::<(), sqlrite::SQLRiteError>(())
//! ```
//!
//! **Relationship to the internal engine.** A `Connection` owns a
//! `Database` (which owns a `Pager` for file-backed connections).
//! `execute` and `query` go through the same `process_command`
//! pipeline the REPL uses, just with typed row return instead of
//! pre-rendered tables. The internal `Database` / `Pager` stay
//! accessible via `sqlrite::sql::...` for the engine's own tests
//! and for the desktop app — but those paths aren't considered
//! stable API.
//!
//! # Prepared statements & parameter binding (SQLR-23)
//!
//! `Connection::prepare` parses the SQL once and stashes the AST on
//! the returned `Statement`. Subsequent calls to `Statement::query` /
//! `Statement::run` execute against the cached AST without re-running
//! sqlparser. Bound versions ([`Statement::query_with_params`] /
//! [`Statement::execute_with_params`]) accept a `&[Value]` slice that is
//! substituted into the cached AST at execute time — including
//! `Value::Vector(...)` for HNSW-eligible KNN queries, where binding
//! the query vector skips per-iter lexing of the 4 KB bracket-array
//! literal.
//!
//! [`Connection::prepare_cached`] adds a small per-connection LRU
//! (default cap 16) so a hot SQL string is parsed exactly once across
//! every call, not once per `prepare()`. Matches the rusqlite pattern.
use std::collections::VecDeque;
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard};
use crate::sql::dialect::SqlriteDialect;
use sqlparser::ast::Statement as AstStatement;
use sqlparser::parser::Parser;
use crate::error::{Result, SQLRiteError};
use crate::sql::db::database::Database;
use crate::sql::db::table::Value;
use crate::sql::executor::execute_select_rows;
use crate::sql::pager::{AccessMode, open_database_with_mode, save_database};
use crate::sql::params::{rewrite_placeholders, substitute_params};
use crate::sql::parser::select::SelectQuery;
use crate::sql::process_ast_with_render;
/// Default capacity of the per-connection prepared-statement plan cache.
/// Matches rusqlite's default; tweak with [`Connection::set_prepared_cache_capacity`].
const DEFAULT_PREP_CACHE_CAP: usize = 16;
/// A handle to a SQLRite database. Opens a file or an in-memory DB;
/// drop it to close. Every mutating statement auto-saves (except inside
/// an explicit `BEGIN`/`COMMIT` block — see [Transactions](#transactions)).
///
/// ## Transactions
///
/// ```no_run
/// # use sqlrite::Connection;
/// let mut conn = Connection::open("foo.sqlrite")?;
/// conn.execute("BEGIN")?;
/// conn.execute("INSERT INTO users (name) VALUES ('alice')")?;
/// conn.execute("INSERT INTO users (name) VALUES ('bob')")?;
/// conn.execute("COMMIT")?;
/// # Ok::<(), sqlrite::SQLRiteError>(())
/// ```
///
/// ## Multiple connections (Phase 10.1)
///
/// `Connection` is a thin handle over an `Arc<Mutex<Database>>`. Call
/// [`Connection::connect`] to mint a sibling handle that shares the
/// same backing `Database` — typically one per worker thread. Today
/// every operation still serializes through the single mutex (and the
/// pager's exclusive flock between processes), so the headline
/// behaviour change is that callers can hold and address the same DB
/// from more than one thread without wrapping the whole `Connection`
/// in a `Mutex` themselves. `BEGIN CONCURRENT` and snapshot-isolated
/// reads land in subsequent Phase 10 sub-phases.
///
/// `Connection` is `Send + Sync`. The recommended pattern is one
/// connection per thread (clone via `connect()`); statements still
/// borrow `&mut Connection`, so a single connection isn't suitable
/// for true concurrent statement execution.
pub struct Connection {
/// Shared engine state. Mints sibling connections via
/// [`Connection::connect`] without copying the in-memory tables
/// or the long-lived pager.
inner: Arc<Mutex<Database>>,
/// SQLR-23 — small SQL→cached-plan LRU. Keyed by the verbatim SQL
/// string the caller passed to `prepare_cached`. Stored as a
/// `VecDeque` rather than a HashMap+linked-list because the
/// expected capacity is small (default 16) — linear scan is fine
/// and the implementation stays dependency-free.
///
/// Per-connection (not shared with sibling handles) — each thread
/// gets its own LRU so cache-mutation never crosses a thread
/// boundary.
prep_cache: VecDeque<(String, Arc<CachedPlan>)>,
prep_cache_cap: usize,
}
impl Connection {
/// Opens (or creates) a database file for read-write access.
///
/// If the file doesn't exist, an empty one is materialized with the
/// current format version. Takes an exclusive advisory lock on the
/// file and its `-wal` sidecar; returns `Err` if either is already
/// locked by another process.
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let db_name = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("db")
.to_string();
let db = if path.exists() {
open_database_with_mode(path, db_name, AccessMode::ReadWrite)?
} else {
// Fresh file: materialize on disk and keep the attached
// pager. Setting `source_path` before `save_database` lets
// its `same_path` branch create the pager and stash it
// back on the Database — no reopen needed (and trying to
// reopen here would hit the file's own lock).
let mut fresh = Database::new(db_name);
fresh.source_path = Some(path.to_path_buf());
save_database(&mut fresh, path)?;
fresh
};
Ok(Self::wrap(db))
}
/// Opens an existing database file for read-only access. Takes a
/// shared advisory lock, so multiple read-only connections can
/// coexist on the same file; any open writer excludes them.
/// Mutating statements return `cannot execute: database is opened
/// read-only`.
pub fn open_read_only<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let db_name = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("db")
.to_string();
let db = open_database_with_mode(path, db_name, AccessMode::ReadOnly)?;
Ok(Self::wrap(db))
}
/// Opens a transient in-memory database. No file is touched and no
/// locks are taken; state lives for the lifetime of the
/// `Connection` and is discarded on drop.
pub fn open_in_memory() -> Result<Self> {
Ok(Self::wrap(Database::new("memdb".to_string())))
}
fn wrap(db: Database) -> Self {
Self {
inner: Arc::new(Mutex::new(db)),
prep_cache: VecDeque::new(),
prep_cache_cap: DEFAULT_PREP_CACHE_CAP,
}
}
/// Phase 10.1 — mints another `Connection` sharing the same
/// backing `Database`. Hand the returned handle to a separate
/// thread to address the same in-memory tables and persistent
/// pager from there.
///
/// The new handle starts with an empty prepared-statement cache
/// (caches are per-handle, by design). Inherits the parent's
/// `prepare_cached` capacity. Concurrent operations still
/// serialize through the engine's internal lock and the pager's
/// existing single-writer rule — a true multi-writer story
/// arrives with `BEGIN CONCURRENT` in Phase 10.4.
///
/// ```no_run
/// # use sqlrite::Connection;
/// let mut primary = Connection::open("foo.sqlrite")?;
/// let secondary = primary.connect();
/// std::thread::spawn(move || {
/// let mut conn = secondary;
/// conn.execute("INSERT INTO t (x) VALUES (1)").unwrap();
/// })
/// .join()
/// .unwrap();
/// # Ok::<(), sqlrite::SQLRiteError>(())
/// ```
pub fn connect(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
prep_cache: VecDeque::new(),
prep_cache_cap: self.prep_cache_cap,
}
}
/// Phase 10.1 — number of `Connection` handles currently sharing
/// this database (this handle plus every live `connect()`
/// descendant). Useful for diagnostics and tests; no semantic
/// guarantee beyond that.
pub fn handle_count(&self) -> usize {
Arc::strong_count(&self.inner)
}
/// Locks the shared `Database` and returns the guard. Internal
/// helper — every public method that needs `&mut Database` calls
/// this. The lock is released when the guard drops, so callers
/// must keep the guard alive for the duration of the engine call
/// (typically by binding it to a local).
fn lock(&self) -> MutexGuard<'_, Database> {
// `unwrap` propagates a panic from another thread that held
// the lock — there's no engine-level recovery story for a
// poisoned `Database` (the in-memory tables would be in an
// unknown state), so failing fast is the right behaviour.
self.inner
.lock()
.unwrap_or_else(|e| panic!("sqlrite: database mutex poisoned: {e}"))
}
/// Parses and executes one SQL statement. For DDL (`CREATE TABLE`,
/// `CREATE INDEX`), DML (`INSERT`, `UPDATE`, `DELETE`) and
/// transaction control (`BEGIN`, `COMMIT`, `ROLLBACK`). Returns
/// the status message the engine produced (e.g.
/// `"INSERT Statement executed."`).
///
/// For `SELECT`, `execute` works but discards the row data and
/// just returns the rendered status — use [`Connection::prepare`]
/// and [`Statement::query`] to iterate typed rows.
pub fn execute(&mut self, sql: &str) -> Result<String> {
let mut db = self.lock();
crate::sql::process_command(sql, &mut db)
}
/// Prepares a statement for repeated execution or row iteration.
/// SQLR-23: the SQL is parsed once at prepare time (sqlparser walk
/// plus placeholder rewriting), and the resulting AST is cached
/// on the [`Statement`] for re-execution without further parsing.
///
/// Use [`Statement::query`] / [`Statement::run`] for unbound
/// execution, or [`Statement::query_with_params`] /
/// [`Statement::execute_with_params`] to substitute `?`
/// placeholders.
pub fn prepare<'c>(&'c mut self, sql: &str) -> Result<Statement<'c>> {
let plan = Arc::new(CachedPlan::compile(sql)?);
Ok(Statement { conn: self, plan })
}
/// Same as [`Connection::prepare`], but consults a small
/// per-connection LRU first. SQLR-23 — for hot statements
/// (the body of an INSERT loop, a frequently-rerun lookup) the
/// sqlparser walk is amortized to once across the connection's
/// lifetime, not once per `prepare()`.
///
/// Default cache capacity is 16; tune with
/// [`Connection::set_prepared_cache_capacity`].
pub fn prepare_cached<'c>(&'c mut self, sql: &str) -> Result<Statement<'c>> {
// Lookup-or-insert. Found entries are also moved to the back
// (most-recently-used) so capacity-eviction runs LRU.
let plan = if let Some(pos) = self.prep_cache.iter().position(|(k, _)| k == sql) {
let (k, v) = self.prep_cache.remove(pos).unwrap();
self.prep_cache.push_back((k, Arc::clone(&v)));
v
} else {
let plan = Arc::new(CachedPlan::compile(sql)?);
self.prep_cache
.push_back((sql.to_string(), Arc::clone(&plan)));
while self.prep_cache.len() > self.prep_cache_cap {
self.prep_cache.pop_front();
}
plan
};
Ok(Statement { conn: self, plan })
}
/// SQLR-23 — sets the maximum number of cached prepared plans
/// (matches `prepare_cached`'s default 16). Reducing below the
/// current size evicts the oldest entries; setting to 0 disables
/// caching but `prepare_cached` still works (it just always
/// re-parses).
pub fn set_prepared_cache_capacity(&mut self, cap: usize) {
self.prep_cache_cap = cap;
while self.prep_cache.len() > cap {
self.prep_cache.pop_front();
}
}
/// SQLR-23 — current number of plans held by the prepared-statement
/// cache. Useful for tests / introspection; not load-bearing for
/// the public API.
pub fn prepared_cache_len(&self) -> usize {
self.prep_cache.len()
}
/// Returns `true` while a `BEGIN … COMMIT/ROLLBACK` block is open
/// against this connection.
pub fn in_transaction(&self) -> bool {
self.lock().in_transaction()
}
/// Returns the current auto-VACUUM threshold (SQLR-10). After a
/// page-releasing DDL (DROP TABLE / DROP INDEX / ALTER TABLE DROP
/// COLUMN) commits, the engine compacts the file in place if the
/// freelist exceeds this fraction of `page_count`. New connections
/// default to `Some(0.25)` (SQLite parity); `None` means the
/// trigger is disabled. See [`Connection::set_auto_vacuum_threshold`].
pub fn auto_vacuum_threshold(&self) -> Option<f32> {
self.lock().auto_vacuum_threshold()
}
/// Sets the auto-VACUUM threshold (SQLR-10). `Some(t)` with `t` in
/// `0.0..=1.0` arms the trigger; `None` disables it. Values outside
/// `0.0..=1.0` (or NaN / infinite) return a typed error rather than
/// silently saturating. The setting is per-database runtime state —
/// closing the last connection to a database drops it; new
/// connections start at the default `Some(0.25)`.
///
/// Calling this on an in-memory or read-only database is allowed
/// (it just won't fire — there's nothing to compact / no writes
/// will reach the trigger).
pub fn set_auto_vacuum_threshold(&mut self, threshold: Option<f32>) -> Result<()> {
self.lock().set_auto_vacuum_threshold(threshold)
}
/// Returns `true` if the connection was opened read-only. Mutating
/// statements on a read-only connection return a typed error.
pub fn is_read_only(&self) -> bool {
self.lock().is_read_only()
}
/// Escape hatch for advanced callers — locks the shared `Database`
/// and hands back the guard. Not part of the stable API; will move
/// or change as Phase 10's MVCC sub-phases land.
///
/// Bind the guard to a local before calling functions that take
/// `&Database`:
///
/// ```no_run
/// # use sqlrite::Connection;
/// # fn use_db(_d: &sqlrite::Database) {}
/// let conn = Connection::open_in_memory()?;
/// let db = conn.database();
/// use_db(&db);
/// # Ok::<(), sqlrite::SQLRiteError>(())
/// ```
#[doc(hidden)]
pub fn database(&self) -> MutexGuard<'_, Database> {
self.lock()
}
#[doc(hidden)]
pub fn database_mut(&mut self) -> MutexGuard<'_, Database> {
self.lock()
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let db = self.lock();
f.debug_struct("Connection")
.field("in_transaction", &db.in_transaction())
.field("read_only", &db.is_read_only())
.field("tables", &db.tables.len())
.field("prep_cache_len", &self.prep_cache.len())
.field("handles", &Arc::strong_count(&self.inner))
.finish()
}
}
/// SQLR-23 — the parse-once-execute-many representation. Built by
/// `CachedPlan::compile` (sqlparser walk + placeholder rewriting +
/// SELECT narrowing) and shared between every `Statement` that hits
/// the same SQL string in `prepare_cached`.
#[derive(Debug)]
struct CachedPlan {
/// Original SQL — kept for diagnostic output.
#[allow(dead_code)]
sql: String,
/// AST after `?` → `?N` placeholder rewriting. Cloned per execute
/// so the substitution pass leaves the cached copy intact.
ast: AstStatement,
/// Total `?` placeholder count in the source SQL. Strict bind
/// validation in `query_with_params` / `execute_with_params`
/// uses this.
param_count: usize,
/// SELECT narrowing — cached so `query()` doesn't redo the
/// `SelectQuery::new` walk for unbound SELECTs. `None` for
/// non-SELECT statements.
select: Option<SelectQuery>,
}
impl CachedPlan {
fn compile(sql: &str) -> Result<Self> {
let dialect = SqlriteDialect::new();
let mut ast = Parser::parse_sql(&dialect, sql).map_err(SQLRiteError::from)?;
let Some(mut stmt) = ast.pop() else {
return Err(SQLRiteError::General("no statement to prepare".to_string()));
};
if !ast.is_empty() {
return Err(SQLRiteError::General(
"prepare() accepts a single statement; found more than one".to_string(),
));
}
let param_count = rewrite_placeholders(&mut stmt);
let select = match &stmt {
AstStatement::Query(_) => Some(SelectQuery::new(&stmt)?),
_ => None,
};
Ok(Self {
sql: sql.to_string(),
ast: stmt,
param_count,
select,
})
}
}
/// A prepared statement bound to a specific connection lifetime.
///
/// SQLR-23 — `Statement` carries the parsed AST (parsed exactly once
/// at prepare time), not just the raw SQL. `query` / `run` execute
/// against the cached AST; `query_with_params` / `execute_with_params`
/// clone the AST and substitute `?` placeholders before dispatch.
pub struct Statement<'c> {
conn: &'c mut Connection,
plan: Arc<CachedPlan>,
}
impl std::fmt::Debug for Statement<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Statement")
.field("sql", &self.plan.sql)
.field("param_count", &self.plan.param_count)
.field(
"kind",
&match self.plan.select {
Some(_) => "Select",
None => "Other",
},
)
.finish()
}
}
impl<'c> Statement<'c> {
/// Number of `?` placeholders detected in the source SQL. Strict
/// arity validation: passing a slice of a different length to
/// `query_with_params` / `execute_with_params` returns a typed
/// error.
pub fn parameter_count(&self) -> usize {
self.plan.param_count
}
/// Executes a prepared non-query statement. Equivalent to
/// [`Connection::execute`] — included for parity with the
/// typed-row `query()` so callers who want `Statement::run` /
/// `Statement::query` symmetry get it.
///
/// Errors if the prepared SQL contains `?` placeholders — use
/// [`Statement::execute_with_params`] for those.
pub fn run(&mut self) -> Result<String> {
if self.plan.param_count > 0 {
return Err(SQLRiteError::General(format!(
"statement has {} `?` placeholder(s); call execute_with_params()",
self.plan.param_count
)));
}
let ast = self.plan.ast.clone();
let mut db = self.conn.lock();
process_ast_with_render(ast, &mut db).map(|o| o.status)
}
/// SQLR-23 — executes a prepared non-SELECT statement after binding
/// `?` placeholders to `params` (positional, in source order).
///
/// Use this for parameterized INSERT / UPDATE / DELETE — the
/// substitution clones the cached AST, fills in the `?` slots
/// from `params`, and dispatches without re-running sqlparser.
/// For SELECT, prefer [`Statement::query_with_params`].
pub fn execute_with_params(&mut self, params: &[Value]) -> Result<String> {
self.check_arity(params)?;
let mut ast = self.plan.ast.clone();
if !params.is_empty() {
substitute_params(&mut ast, params)?;
}
let mut db = self.conn.lock();
process_ast_with_render(ast, &mut db).map(|o| o.status)
}
/// Runs a SELECT and returns a [`Rows`] iterator over typed rows.
/// Errors if the prepared statement isn't a SELECT.
///
/// SQLR-23 — uses the SELECT narrowing cached at prepare time;
/// no per-call sqlparser walk. Errors if the prepared SQL
/// contains `?` placeholders — use [`Statement::query_with_params`]
/// for those.
pub fn query(&self) -> Result<Rows> {
if self.plan.param_count > 0 {
return Err(SQLRiteError::General(format!(
"statement has {} `?` placeholder(s); call query_with_params()",
self.plan.param_count
)));
}
let Some(sq) = self.plan.select.as_ref() else {
return Err(SQLRiteError::General(
"query() only works on SELECT statements; use run() for DDL/DML".to_string(),
));
};
let db = self.conn.lock();
let result = execute_select_rows(sq.clone(), &db)?;
Ok(Rows {
columns: result.columns,
rows: result.rows.into_iter(),
})
}
/// SQLR-23 — runs a SELECT and returns a [`Rows`] iterator after
/// binding `?` placeholders to `params`. Positional, source-order
/// indexing — `params[0]` is `?1`, `params[1]` is `?2`, etc.
///
/// Vector parameters (`Value::Vector(...)`) substitute as the
/// in-band bracket-array shape the executor recognizes, so a
/// bound query vector still triggers the HNSW probe optimizer
/// (Phase 7d.2 KNN shortcut).
pub fn query_with_params(&self, params: &[Value]) -> Result<Rows> {
self.check_arity(params)?;
if self.plan.select.is_none() {
return Err(SQLRiteError::General(
"query_with_params() only works on SELECT statements; use execute_with_params() \
for DDL/DML"
.to_string(),
));
}
// Re-narrow against the substituted AST. The narrow walk is
// cheap (it pulls projection/WHERE/ORDER BY into typed
// structs), and rerunning it ensures the substituted literals
// (e.g. a bracket-array vector) flow through `SelectQuery`.
let mut ast = self.plan.ast.clone();
if !params.is_empty() {
substitute_params(&mut ast, params)?;
}
let sq = SelectQuery::new(&ast)?;
let db = self.conn.lock();
let result = execute_select_rows(sq, &db)?;
Ok(Rows {
columns: result.columns,
rows: result.rows.into_iter(),
})
}
fn check_arity(&self, params: &[Value]) -> Result<()> {
if params.len() != self.plan.param_count {
return Err(SQLRiteError::General(format!(
"expected {} parameter{}, got {}",
self.plan.param_count,
if self.plan.param_count == 1 { "" } else { "s" },
params.len()
)));
}
Ok(())
}
/// Column names this statement will produce, in projection order.
/// `None` for non-SELECT statements.
pub fn column_names(&self) -> Option<Vec<String>> {
match &self.plan.select {
Some(_) => {
// We can't know the concrete column list without
// running the query (it depends on the table schema
// and the projection). Callers who need it up front
// should call query() and inspect Rows::columns.
None
}
None => None,
}
}
}
/// Iterator of typed [`Row`] values produced by a `SELECT` query.
///
/// Today `Rows` is backed by an eager `Vec<Vec<Value>>` — the cursor
/// abstraction in Phase 5a's follow-up will swap this for a lazy
/// walker that streams rows off the B-Tree without materializing
/// them upfront. The `Rows::next` API is designed for that: it
/// returns `Result<Option<Row>>` rather than `Option<Result<Row>>`,
/// so a mid-stream I/O error surfaces cleanly.
pub struct Rows {
columns: Vec<String>,
rows: std::vec::IntoIter<Vec<Value>>,
}
impl std::fmt::Debug for Rows {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Rows")
.field("columns", &self.columns)
.field("remaining", &self.rows.len())
.finish()
}
}
impl Rows {
/// Column names in projection order.
pub fn columns(&self) -> &[String] {
&self.columns
}
/// Advances to the next row. Returns `Ok(None)` when the query is
/// exhausted, `Ok(Some(row))` otherwise, `Err(_)` on an I/O or
/// decode failure (relevant once Phase 5a's cursor work lands —
/// today this is always `Ok(_)`).
pub fn next(&mut self) -> Result<Option<Row<'_>>> {
Ok(self.rows.next().map(|values| Row {
columns: &self.columns,
values,
}))
}
/// Collects every remaining row into a `Vec<Row>`. Convenient for
/// small result sets; avoid on large queries — that's what the
/// streaming [`Rows::next`] API is for.
pub fn collect_all(mut self) -> Result<Vec<OwnedRow>> {
let mut out = Vec::new();
while let Some(r) = self.next()? {
out.push(r.to_owned_row());
}
Ok(out)
}
}
/// A single row borrowed from a [`Rows`] iterator. Lives only as long
/// as the iterator; call `Row::to_owned_row` to detach it if you need
/// to keep it past the next `next()` call.
pub struct Row<'r> {
columns: &'r [String],
values: Vec<Value>,
}
impl<'r> Row<'r> {
/// Value at column index `idx`. Returns a clean error if out of
/// bounds or the type conversion fails.
pub fn get<T: FromValue>(&self, idx: usize) -> Result<T> {
let v = self.values.get(idx).ok_or_else(|| {
SQLRiteError::General(format!(
"column index {idx} out of bounds (row has {} columns)",
self.values.len()
))
})?;
T::from_value(v)
}
/// Value at column named `name`. Case-sensitive.
pub fn get_by_name<T: FromValue>(&self, name: &str) -> Result<T> {
let idx = self
.columns
.iter()
.position(|c| c == name)
.ok_or_else(|| SQLRiteError::General(format!("no column named '{name}' in row")))?;
self.get(idx)
}
/// Column names for this row.
pub fn columns(&self) -> &[String] {
self.columns
}
/// Detaches from the parent `Rows` iterator. Useful when you want
/// to keep rows past the next `Rows::next()` call.
pub fn to_owned_row(&self) -> OwnedRow {
OwnedRow {
columns: self.columns.to_vec(),
values: self.values.clone(),
}
}
}
/// A row detached from the `Rows` iterator — owns its data, no
/// borrow ties it to the parent iterator.
#[derive(Debug, Clone)]
pub struct OwnedRow {
pub columns: Vec<String>,
pub values: Vec<Value>,
}
impl OwnedRow {
pub fn get<T: FromValue>(&self, idx: usize) -> Result<T> {
let v = self.values.get(idx).ok_or_else(|| {
SQLRiteError::General(format!(
"column index {idx} out of bounds (row has {} columns)",
self.values.len()
))
})?;
T::from_value(v)
}
pub fn get_by_name<T: FromValue>(&self, name: &str) -> Result<T> {
let idx = self
.columns
.iter()
.position(|c| c == name)
.ok_or_else(|| SQLRiteError::General(format!("no column named '{name}' in row")))?;
self.get(idx)
}
}
/// Conversion from SQLRite's internal [`Value`] enum into a typed Rust
/// value. Implementations cover the common built-ins — `i64`, `f64`,
/// `String`, `bool`, and `Option<T>` for nullable columns. Extend on
/// demand.
pub trait FromValue: Sized {
fn from_value(v: &Value) -> Result<Self>;
}
impl FromValue for i64 {
fn from_value(v: &Value) -> Result<Self> {
match v {
Value::Integer(n) => Ok(*n),
Value::Null => Err(SQLRiteError::General(
"expected Integer, got NULL".to_string(),
)),
other => Err(SQLRiteError::General(format!(
"cannot convert {other:?} to i64"
))),
}
}
}
impl FromValue for f64 {
fn from_value(v: &Value) -> Result<Self> {
match v {
Value::Real(f) => Ok(*f),
Value::Integer(n) => Ok(*n as f64),
Value::Null => Err(SQLRiteError::General("expected Real, got NULL".to_string())),
other => Err(SQLRiteError::General(format!(
"cannot convert {other:?} to f64"
))),
}
}
}
impl FromValue for String {
fn from_value(v: &Value) -> Result<Self> {
match v {
Value::Text(s) => Ok(s.clone()),
Value::Null => Err(SQLRiteError::General("expected Text, got NULL".to_string())),
other => Err(SQLRiteError::General(format!(
"cannot convert {other:?} to String"
))),
}
}
}
impl FromValue for bool {
fn from_value(v: &Value) -> Result<Self> {
match v {
Value::Bool(b) => Ok(*b),
Value::Integer(n) => Ok(*n != 0),
Value::Null => Err(SQLRiteError::General("expected Bool, got NULL".to_string())),
other => Err(SQLRiteError::General(format!(
"cannot convert {other:?} to bool"
))),
}
}
}
/// Nullable columns: `Option<T>` maps `NULL → None` and everything else
/// through the inner type's `FromValue` impl.
impl<T: FromValue> FromValue for Option<T> {
fn from_value(v: &Value) -> Result<Self> {
match v {
Value::Null => Ok(None),
other => Ok(Some(T::from_value(other)?)),
}
}
}
/// Identity impl so `row.get::<_, Value>(0)` works when you want
/// untyped access.
impl FromValue for Value {
fn from_value(v: &Value) -> Result<Self> {
Ok(v.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tmp_path(name: &str) -> std::path::PathBuf {
let mut p = std::env::temp_dir();
let pid = std::process::id();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
p.push(format!("sqlrite-conn-{pid}-{nanos}-{name}.sqlrite"));
p
}
fn cleanup(path: &std::path::Path) {
let _ = std::fs::remove_file(path);
let mut wal = path.as_os_str().to_owned();
wal.push("-wal");
let _ = std::fs::remove_file(std::path::PathBuf::from(wal));
}
#[test]
fn in_memory_roundtrip() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);")
.unwrap();
conn.execute("INSERT INTO users (name, age) VALUES ('alice', 30);")
.unwrap();
conn.execute("INSERT INTO users (name, age) VALUES ('bob', 25);")
.unwrap();
let stmt = conn.prepare("SELECT id, name, age FROM users;").unwrap();
let mut rows = stmt.query().unwrap();
assert_eq!(rows.columns(), &["id", "name", "age"]);
let mut collected: Vec<(i64, String, i64)> = Vec::new();
while let Some(row) = rows.next().unwrap() {
collected.push((
row.get::<i64>(0).unwrap(),
row.get::<String>(1).unwrap(),
row.get::<i64>(2).unwrap(),
));
}
assert_eq!(collected.len(), 2);
assert!(collected.iter().any(|(_, n, a)| n == "alice" && *a == 30));
assert!(collected.iter().any(|(_, n, a)| n == "bob" && *a == 25));
}
#[test]
fn file_backed_persists_across_connections() {
let path = tmp_path("persist");
{
let mut c1 = Connection::open(&path).unwrap();
c1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, label TEXT);")
.unwrap();
c1.execute("INSERT INTO items (label) VALUES ('one');")
.unwrap();
}
{
let mut c2 = Connection::open(&path).unwrap();
let stmt = c2.prepare("SELECT label FROM items;").unwrap();
let mut rows = stmt.query().unwrap();
let first = rows.next().unwrap().expect("one row");
assert_eq!(first.get::<String>(0).unwrap(), "one");
assert!(rows.next().unwrap().is_none());
}
cleanup(&path);
}
#[test]
fn read_only_connection_rejects_writes() {
let path = tmp_path("ro_reject");
{
let mut c = Connection::open(&path).unwrap();
c.execute("CREATE TABLE t (id INTEGER PRIMARY KEY);")
.unwrap();
c.execute("INSERT INTO t (id) VALUES (1);").unwrap();
} // writer drops → releases exclusive lock
let mut ro = Connection::open_read_only(&path).unwrap();
assert!(ro.is_read_only());
let err = ro.execute("INSERT INTO t (id) VALUES (2);").unwrap_err();
assert!(format!("{err}").contains("read-only"));
cleanup(&path);
}
#[test]
fn transactions_work_through_connection() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, x INTEGER);")
.unwrap();
conn.execute("INSERT INTO t (x) VALUES (1);").unwrap();
conn.execute("BEGIN;").unwrap();
assert!(conn.in_transaction());
conn.execute("INSERT INTO t (x) VALUES (2);").unwrap();
conn.execute("ROLLBACK;").unwrap();
assert!(!conn.in_transaction());
let stmt = conn.prepare("SELECT x FROM t;").unwrap();
let rows = stmt.query().unwrap().collect_all().unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].get::<i64>(0).unwrap(), 1);
}
#[test]
fn get_by_name_works() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE t (a INTEGER, b TEXT);").unwrap();
conn.execute("INSERT INTO t (a, b) VALUES (42, 'hello');")
.unwrap();
let stmt = conn.prepare("SELECT a, b FROM t;").unwrap();
let mut rows = stmt.query().unwrap();
let row = rows.next().unwrap().unwrap();
assert_eq!(row.get_by_name::<i64>("a").unwrap(), 42);
assert_eq!(row.get_by_name::<String>("b").unwrap(), "hello");
}
#[test]
fn null_column_maps_to_none() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, note TEXT);")
.unwrap();
// id INTEGER PRIMARY KEY autoincrements; `note` is left unspecified.
conn.execute("INSERT INTO t (id) VALUES (1);").unwrap();
let stmt = conn.prepare("SELECT id, note FROM t;").unwrap();
let mut rows = stmt.query().unwrap();
let row = rows.next().unwrap().unwrap();
assert_eq!(row.get::<i64>(0).unwrap(), 1);
// note is NULL → Option<String> resolves to None.
assert_eq!(row.get::<Option<String>>(1).unwrap(), None);
}
#[test]
fn prepare_rejects_multiple_statements() {
let mut conn = Connection::open_in_memory().unwrap();
let err = conn.prepare("SELECT 1; SELECT 2;").unwrap_err();
assert!(format!("{err}").contains("single statement"));
}
#[test]
fn query_on_non_select_errors() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY);")
.unwrap();
let stmt = conn.prepare("INSERT INTO t VALUES (1);").unwrap();
let err = stmt.query().unwrap_err();
assert!(format!("{err}").contains("SELECT"));
}
/// SQLR-10: fresh connections expose the SQLite-parity 25% default,
/// the setter validates its input, and `None` opts out cleanly.
#[test]
fn auto_vacuum_threshold_default_and_setter() {
let mut conn = Connection::open_in_memory().unwrap();
assert_eq!(
conn.auto_vacuum_threshold(),
Some(0.25),
"fresh connection should ship with the SQLite-parity default"
);
conn.set_auto_vacuum_threshold(None).unwrap();
assert_eq!(conn.auto_vacuum_threshold(), None);
conn.set_auto_vacuum_threshold(Some(0.5)).unwrap();
assert_eq!(conn.auto_vacuum_threshold(), Some(0.5));
// Out-of-range values must be rejected with a typed error and
// must not stomp the previously-set value.
let err = conn.set_auto_vacuum_threshold(Some(1.5)).unwrap_err();
assert!(
format!("{err}").contains("auto_vacuum_threshold"),
"expected typed range error, got: {err}"
);
assert_eq!(
conn.auto_vacuum_threshold(),
Some(0.5),
"rejected setter call must not mutate the threshold"
);
}
#[test]
fn index_out_of_bounds_errors_cleanly() {
let mut conn = Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE t (a INTEGER PRIMARY KEY);")
.unwrap();
conn.execute("INSERT INTO t (a) VALUES (1);").unwrap();
let stmt = conn.prepare("SELECT a FROM t;").unwrap();
let mut rows = stmt.query().unwrap();
let row = rows.next().unwrap().unwrap();
let err = row.get::<i64>(99).unwrap_err();
assert!(format!("{err}").contains("out of bounds"));
}
// -----------------------------------------------------------------
// SQLR-23 — prepared-statement plan cache + parameter binding