sqlite
SQLite databases: open a file (or an in-memory database), run SQL, and read rows back.
Values always go into SQL through ? placeholders and a Vec<sqlite.Value>, never by pasting text into the SQL string, so user input cannot change the query. query runs exactly one statement; extra statements after it are an error. Every call that touches the database returns ! sqlite.SqlError.
Opening needs an fs.Files permission, made by fs.files() in the program’s main file. ":memory:" gives a fresh database that disappears when the Db is dropped.
Create a table, insert, and query:
import fsimport sqlite
let files = fs.files()let mut db = try sqlite.open(&files, &":memory:")try db.exec(&"CREATE TABLE people (id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER)")for (name, age) in [("ann", 31), ("bob", 27), ("cy", 45)] { let _ = try db.run(&"INSERT INTO people (name, age) VALUES (?, ?)", &[.Text(name), .Int(age)])}print(db.last_id())let rows = try db.query(&"SELECT name, age FROM people WHERE age > ? ORDER BY age", &[.Int(30)])for r in &rows { print(f"{r.text(&"name").unwrap()} {r.int(&"age").unwrap()}")}3ann 31cy 45Update rows and see how many changed:
import fsimport sqlite
let files = fs.files()let mut db = try sqlite.open(&files, &":memory:")try db.exec(&"CREATE TABLE items (name TEXT, done INTEGER); INSERT INTO items VALUES ('a', 0), ('b', 0), ('c', 1)")let changed = try db.run(&"UPDATE items SET done = 1 WHERE done = ?", &[.Int(0)])print(changed)2Use a database file, and handle errors:
import fsimport sqlite
let files = fs.files()let dir = try fs.temp_dir()let mut db = try sqlite.open(&files, &dir.join(&"app.db"))try db.exec(&"CREATE TABLE IF NOT EXISTS notes (body TEXT)")let rows = db.query(&"SELECT body FROM missing_table", &[]) catch { sqlite.SqlError(e) => { print(e.message) [] }}print(rows.len())no such table: missing_table0Changes that belong together go into transaction: the function runs between BEGIN and COMMIT, and if it fails, everything it changed is rolled back. Many inserts are also much faster inside one transaction.
import fsimport sqlite
fn add_all(db: &mut sqlite.Db, names: &Vec<Str>) ! sqlite.SqlError { try db.transaction(&fn(tx: &mut sqlite.Db) ! sqlite.SqlError [names] { for n in names { if n.len() == 0 { return sqlite.SqlError { message: "an empty name" } } let _ = try tx.run(&"INSERT INTO people (name) VALUES (?)", &[.Text(n.clone())]) } })}
let mut db = try sqlite.open(&fs.files(), &":memory:")try db.exec(&"CREATE TABLE people (name TEXT)")try add_all(&mut db, &["ada", "grace"])add_all(&mut db, &["linus", ""]) catch { sqlite.SqlError(e) => print("not added: " + e.message)}print((try db.query(&"SELECT count(*) AS n FROM people", &[]))[0].int(&"n"))not added: an empty nameSome(2)Reference
Section titled “Reference”import sqliteFunctions
Section titled “Functions”pub fn open(files: &fs.Files, path: &Str) -> Db ! SqlErrorOpens (or creates) a database file the given file permission allows; “:memory:” is a fresh one.
The path is checked against the fs.Files permission, so a library handed files.within(&dir) cannot open a database outside dir. The file is created if it does not exist. When another connection holds a write lock, a write waits up to 5 seconds before failing with “database is locked”; set_busy_timeout changes that.
Running SQL needs &mut Db, and threads cannot hold &mut, so two threads never use one connection at once. A Db can be moved into one thread (fn() [db] => ...); for parallel work, open one connection per thread.
SqlError
Section titled “SqlError”pub struct SqlError { pub message: Str}pub enum Value { Null Int(i64) Real(f64) Text(Str) Blob(Str)}A value going into a query (bound to a ?, never pasted into the SQL) or coming out of one.
Null, Int, Real, Text and Blob (raw bytes). In a Vec<Value> the type is known, so write the variants with a leading dot: &[.Text(name), .Int(age), .Null]. Use an empty &[] when the SQL has no placeholders.
Binary data goes in as .Blob(bytes) and a BLOB column comes back as Blob; row.blob(&"col") reads it.
pub struct Row { pub columns: Vec<Str> pub values: Vec<Value>}columns holds the column names (as SQL names them; use AS to rename an expression) and values the values in the same order. The helper methods look a column up by name; for the raw value use get and match on it:
import fsimport sqlite
let files = fs.files()let mut db = try sqlite.open(&files, &":memory:")let rows = try db.query(&"SELECT 2.5 AS price, NULL AS note", &[])match rows[0].get(&"price") { Some(v) => { match v { .Real(x) => print(*x * 2.0) _ => print("not a real") } } None => print("no such column")}print(rows[0].text(&"note").is_none())5.0trueRow.get
Section titled “Row.get”pub fn get(&self, column: &Str) -> Option<&Value>Row.text
Section titled “Row.text”pub fn text(&self, column: &Str) -> Option<Str>The column as text: Some for text and numbers, None for NULL or an unknown column.
Numbers are turned into text, so text works on any non-NULL column. A misspelled column name gives None, the same as NULL.
Row.real
Section titled “Row.real”pub fn real(&self, column: &Str) -> Option<f64>The column as a float: Some for real and integer values, None otherwise.
Row.blob
Section titled “Row.blob”pub fn blob(&self, column: &Str) -> Option<Str>The raw bytes of a BLOB column; None for other kinds of value.
Row.int
Section titled “Row.int”pub fn int(&self, column: &Str) -> Option<i64>Only an Int value gives Some. A REAL column, text that looks like a number, NULL and an unknown column name all give None. real reads REAL and integer values as f64.
pub struct Db {}An open database; dropping it closes it.
It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Db.exec
Section titled “Db.exec”pub fn exec(&mut self, sql: &Str) ! SqlErrorRuns SQL with no values in it, like CREATE TABLE; several statements may follow each other.
For SQL without values: schema changes, BEGIN/COMMIT, setup scripts. It may hold several statements separated by ;. Never build exec SQL from user input; use run or query with placeholders.
Db.query
Section titled “Db.query”pub fn query(&mut self, sql: &Str, values: &Vec<Value>) -> Vec<Row> ! SqlErrorOne statement with ? placeholders, one value for each, in order; returns the rows it gives.
Exactly one statement. The number of values must match the number of ? placeholders, or the call fails before running. All rows are read into memory, so add LIMIT for large tables.
Db.run
Section titled “Db.run”pub fn run(&mut self, sql: &Str, values: &Vec<Value>) -> i64 ! SqlErrorLike query for a statement that returns no rows; gives how many rows it changed.
Same as query but returns the number of rows changed instead of rows. After an INSERT, last_id gives the new row’s id.
Db.last_id
Section titled “Db.last_id”pub fn last_id(&self) -> i64The row id of the last INSERT.
Db.set_busy_timeout
Section titled “Db.set_busy_timeout”pub fn set_busy_timeout(&mut self, wait: time.Duration)How long to wait for another connection’s lock before failing (5 seconds unless changed).
Db.transaction
Section titled “Db.transaction”pub fn transaction(&mut self, work: &fn(&mut Db) ! SqlError) ! SqlErrorRuns work as one transaction: committed if it succeeds, rolled back if it fails.