cromo La guida di Cromo
Scarica PDF EN

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.

cromo
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

cromo
struct Database

A 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.

cromo
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.

cromo
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

cromo
void setMaxIdle(i64 count) const

How many connections the database keeps when they are given back, 4 by default: the others are closed.

#Database.setTimeout

cromo
void setTimeout(i64 milliseconds) const

How 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

cromo
Connection connect() const

A connection to the database: one that was given back, or a new one. It goes back to the database when its variable ends.

#Connection

cromo
struct Connection

A 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

cromo
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.

cromo
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

cromo
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.

cromo
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

cromo
void commit()

Keeps what the transaction did.

#Connection.rollback

cromo
void rollback()

Undoes what the transaction did.

#Connection.prepare

cromo
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

cromo
bool hasTable(string name)

Whether the database has a table, or a view, with this name.

#Connection.hasColumn

cromo
bool hasColumn(string table, string name)

Whether a table has a column with this name.

#Connection.backup

cromo
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

cromo
struct Statement

A 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.

cromo
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

cromo
void setInt(i64 index, i64 value)

Sets the parameter index, from 1, to an integer.

#Statement.setFloat

cromo
void setFloat(i64 index, f64 value)

Sets the parameter index to a number with a fraction.

#Statement.setText

cromo
void setText(i64 index, string value)

Sets the parameter index to a text.

#Statement.setBytes

cromo
void setBytes(i64 index, list<u8> value)

Sets the parameter index to bytes, as an image.

#Statement.setBool

cromo
void setBool(i64 index, bool value)

Sets the parameter index to true or false, kept as 1 or 0.

#Statement.setNull

cromo
void setNull(i64 index)

Sets the parameter index to no value, the NULL of SQL.

#Statement.exec

cromo
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.

cromo
db.Statement insert = c.prepare("INSERT INTO notes (title) VALUES (?)")
for (string title in titles) {
    insert.setText(1, title)
    insert.exec()
}

#Statement.next

cromo
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

cromo
void reset()

Makes the statement ready to run again from its first row. The parameters keep their values.

#Statement.columnCount

cromo
i64 columnCount() const

How many columns the rows of the statement have: 0 for one that gives no rows.

#Statement.columnName

cromo
string columnName(i64 index) const

The name of the column index, from 0.

#Statement.isNull

cromo
bool isNull(i64 index) const

Whether the column index of the row, from 0, has no value, the NULL of SQL.

#Statement.getInt

cromo
i64 getInt(i64 index) const

The column index of the row as an integer: 0 without a value.

#Statement.getFloat

cromo
f64 getFloat(i64 index) const

The column index of the row as a number with a fraction: 0 without a value.

#Statement.getText

cromo
string getText(i64 index) const

The column index of the row as a text: "" without a value.

#Statement.getBytes

cromo
list<u8> getBytes(i64 index) const

The column index of the row as bytes: none without a value.

#Statement.getBool

cromo
bool getBool(i64 index) const

The column index of the row as true or false: false for 0 and without a value.