std.db
Databases: a Database opens one, a Connection runs statements and transactions on it, and a Statement has parameters and gives rows. The text that opens the database says which one it is: the name of a file is a database of SQLite, which is inside the program, made if it is missing, ":memory:" one in memory, and "postgresql://user:password@host:5432/name" one of a server of PostgreSQL.
import std.db
db.Database data = db.Database("notes.db")
db.Connection c = data.connect()
c.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, title TEXT)")
db.Statement insert = c.prepare("INSERT INTO notes (title) VALUES (?)")
insert.setText(1, "Buy the bread")
insert.exec()
db.Statement all = c.prepare("SELECT id, title FROM notes ORDER BY id")
for (all.next()) {
println("{} {}", all.getInt(0), all.getText(1))
}A wrong use of the module, as a column that the row does not have, is a panic. An error of the database, as a statement that is not SQL or a table that is missing, is an Error with the message of the database.
The guide: Databases.
Generata dalla documentazione nei sorgenti della libreria, che è in inglese.
#Tipi
#Database
struct DatabaseA database, opened by its text. It is a handle: its copies are the same database, and the threads and the tasks capture it. It keeps the connections that are given back, to give them again, so connect() costs little: a request of a server takes a connection, uses it and lets it end.
db.Database data = db.Database("notes.db") // a file of SQLite, made if it is missing
db.Database quick = db.Database(":memory:") // a database in memory, gone with the program
db.Database shared = db.Database("postgresql://notes:secret@db.example.com/notes?sslmode=require")An address of PostgreSQL is postgresql://user:password@host:port/name: the port is 5432 without one, the host this computer, and the name the one of the user. A character of the user or of the password that an address cannot have is written with its code, as %40 for @. With ?sslmode=require at the end the connection is encrypted with TLS, and the certificate of the server is verified as net.connectTls does; without it, or with ?sslmode=disable, it is not encrypted.
Database(string text)Opens the database: an Error when it cannot, as for a folder that is missing, a server that does not answer or a wrong password. A database in memory has one connection, so connect() waits for it while another part of the program has it.
#Database.setMaxIdle
void setMaxIdle(i64 count) constHow many connections the database keeps when they are given back, 4 by default: the others are closed.
#Database.setTimeout
void setTimeout(i64 milliseconds) constHow long a statement waits for a lock that another connection or another program holds, in milliseconds, 5000 by default, before it is an Error. For the connections made from now on; with PostgreSQL, for the ones opened from now on, not for those that the database kept.
#Database.connect
Connection connect() constA connection to the database: one that was given back, or a new one. It goes back to the database when its variable ends.
#Connection
struct ConnectionA connection to a database, from Database.connect(): it runs statements, one after the other. It cannot be copied; at the end of its variable a transaction still open is rolled back, and the connection goes back to its database.
#Connection.exec
i64 exec(string sql)Runs the statements of sql, separated by ;, which have no parameters, and gives how many rows they inserted, changed and deleted.
c.exec("CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT); CREATE INDEX byTitle ON notes (title)")
i64 gone = c.exec("DELETE FROM notes WHERE title = ''")#Connection.begin
void begin()Starts a transaction: the statements that follow are all kept by commit(), or all undone by rollback(), and by the end of the connection without a commit.
c.begin()
c.exec("UPDATE accounts SET balance = balance - 30 WHERE id = 1")
c.exec("UPDATE accounts SET balance = balance + 30 WHERE id = 2")
c.commit()#Connection.commit
void commit()Keeps what the transaction did.
#Connection.rollback
void rollback()Undoes what the transaction did.
#Connection.prepare
Statement prepare(string sql)A statement to run more than once, and with parameters, each written ? in sql and set by number, from 1. A value is never written inside the text of a statement: a parameter cannot be taken for SQL, whatever it holds. With PostgreSQL, whose operators can have a ?, ?? is a ? of the statement.
#Connection.hasTable
bool hasTable(string name)Whether the database has a table, or a view, with this name.
#Connection.hasColumn
bool hasColumn(string table, string name)Whether a table has a column with this name.
#Connection.backup
void backup(string file)Copies the whole database into another file, also while it is used: the file is made, and what it held is replaced. Only for SQLite: a database of PostgreSQL is copied with the tools of its server, and this throws an Error.
#Statement
struct StatementA statement of a connection, from Connection.prepare(): its parameters are set by number, from 1, then exec() runs it, or next() reads its rows one at a time, with the columns by number, from 0. It cannot be copied.
db.Statement find = c.prepare("SELECT title, done FROM notes WHERE id > ? ORDER BY id")
find.setInt(1, 10)
for (find.next()) {
println("{} {}", find.getText(0), find.getBool(1))
}#Statement.setInt
void setInt(i64 index, i64 value)Sets the parameter index, from 1, to an integer.
#Statement.setFloat
void setFloat(i64 index, f64 value)Sets the parameter index to a number with a fraction.
#Statement.setText
void setText(i64 index, string value)Sets the parameter index to a text.
#Statement.setBytes
void setBytes(i64 index, list<u8> value)Sets the parameter index to bytes, as an image.
#Statement.setBool
void setBool(i64 index, bool value)Sets the parameter index to true or false, kept as 1 or 0.
#Statement.setNull
void setNull(i64 index)Sets the parameter index to no value, the NULL of SQL.
#Statement.exec
i64 exec()Runs the statement to its end and gives how many rows it inserted, changed or deleted. Then it is ready to run again: the parameters keep their values until they are set again.
db.Statement insert = c.prepare("INSERT INTO notes (title) VALUES (?)")
for (string title in titles) {
insert.setText(1, title)
insert.exec()
}#Statement.next
bool next()Goes to the next row of the statement, the first one the first time: false when there are no more. The columns are then read with getInt, getText and the others. A statement that is on a row keeps reading the database as it was at its first row, and keeps the others from writing some of it: reset(), or its end, lets it go.
#Statement.reset
void reset()Makes the statement ready to run again from its first row. The parameters keep their values.
#Statement.columnCount
i64 columnCount() constHow many columns the rows of the statement have: 0 for one that gives no rows.
#Statement.columnName
string columnName(i64 index) constThe name of the column index, from 0.
#Statement.isNull
bool isNull(i64 index) constWhether the column index of the row, from 0, has no value, the NULL of SQL.
#Statement.getInt
i64 getInt(i64 index) constThe column index of the row as an integer: 0 without a value.
#Statement.getFloat
f64 getFloat(i64 index) constThe column index of the row as a number with a fraction: 0 without a value.
#Statement.getText
string getText(i64 index) constThe column index of the row as a text: "" without a value.
#Statement.getBytes
list<u8> getBytes(i64 index) constThe column index of the row as bytes: none without a value.
#Statement.getBool
bool getBool(i64 index) constThe column index of the row as true or false: false for 0 and without a value.