A higher level PostgreSQL database wrapper. This interface is implemented for other databases also.
Parameter substitution
All db_* modules support the same form of parameter substitution. That is, using the ? (question mark) to signify the place where a value should be placed. For example:
sql"INSERT INTO myTable (colA, colB, colC) VALUES (?, ?, ?)"
Note: There are two approaches to parameter substitution support by this module.
1. SqlQuery using ?, ?, ?, ... (same as all the db_* modules)
2. SqlPrepared using $1, $2, $3, ...
prepare(db, "myExampleInsert", sql"""INSERT INTO myTable (colA, colB, colC) VALUES ($1, $2, $3)""", 3)
Examples
Opening a connection to a database
import db_postgres let db = open("localhost", "user", "password", "dbname") db.close()
Creating a table
db.exec(sql"DROP TABLE IF EXISTS myTable") db.exec(sql("""CREATE TABLE myTable ( id integer, name varchar(50) not null)"""))
Inserting data
db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)", "Dominik")
Types
DbConn = PPGconn
- encapsulates a database connection Source
Row = seq[string]
- a row of a dataset. NULL database values will be transformed always to the empty string. Source
InstantRow = tuple[res: PPGresult, line: int32]
- a handle that can be used to get a row's column text on demand Source
EDb = object of IOError
- exception that is raised if a database error occurs Source
SqlQuery = distinct string
- an SQL query string Source
SqlPrepared = distinct string
- a identifier for the prepared queries Source
FDb = object of IOEffect
- effect that denotes a database operation Source
FReadDb = object of FDb
- effect that denotes a read operation Source
FWriteDb = object of FDb
- effect that denotes a write operation Source
Procs
proc sql(query: string): SqlQuery {.noSideEffect, inline, raises: [], tags: [].}
-
constructs a SqlQuery from the string query. This is supposed to be used as a raw-string-literal modifier: sql"update user set counter = counter + 1"
If assertions are turned off, it does nothing. If assertions are turned on, later versions will check the string for valid syntax.
Source proc dbError(db: DbConn) {.noreturn, raises: [EDb], tags: [].}
- raises an EDb exception. Source
proc dbError(msg: string) {.noreturn, raises: [EDb], tags: [].}
- raises an EDb exception with message msg. Source
proc dbQuote(s: string): string {.raises: [], tags: [].}
- DB quotes the string. Source
proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {. tags: [FReadDb, FWriteDb], raises: [EDb].}
- tries to execute the query and returns true if successful, false otherwise. Source
proc tryExec(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): bool {. tags: [FReadDb, FWriteDb], raises: [Exception].}
- tries to execute the query and returns true if successful, false otherwise. Source
proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {. tags: [FReadDb, FWriteDb], raises: [EDb].}
- executes the query and raises EDB if not successful. Source
proc exec(db: DbConn; stmtName: SqlPrepared; args: varargs[string]) {. tags: [FReadDb, FWriteDb], raises: [Exception, EDb].}
- Source
proc prepare(db: DbConn; stmtName: string; query: SqlQuery; nParams: int): SqlPrepared {. raises: [EDb], tags: [].}
- Source
proc `[]`(row: InstantRow; col: int32): string {.inline, raises: [], tags: [].}
- returns text for given column of the row Source
proc len(row: InstantRow): int32 {.inline, raises: [], tags: [].}
- returns number of columns in the row Source
proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {. tags: [FReadDb], raises: [EDb].}
- retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. Source
proc getRow(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {. tags: [FReadDb], raises: [Exception, EDb].}
- Source
proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[Row] {. tags: [FReadDb], raises: [EDb].}
- executes the query and returns the whole result dataset. Source
proc getAllRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): seq[Row] {. tags: [FReadDb], raises: [Exception, EDb].}
- executes the prepared query and returns the whole result dataset. Source
proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {. tags: [FReadDb], raises: [EDb].}
- executes the query and returns the first column of the first row of the result dataset. Returns "" if the dataset contains no rows or the database value is NULL. Source
proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {. tags: [FWriteDb], raises: [EDb, ValueError].}
- executes the query (typically "INSERT") and returns the generated ID for the row or -1 in case of an error. For Postgre this adds RETURNING id to the query, so it only works if your primary key is named id. Source
proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {. tags: [FWriteDb], raises: [EDb, ValueError].}
- executes the query (typically "INSERT") and returns the generated ID for the row. For Postgre this adds RETURNING id to the query, so it only works if your primary key is named id. Source
proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {. tags: [FReadDb, FWriteDb], raises: [EDb, ValueError].}
- executes the query (typically "UPDATE") and returns the number of affected rows. Source
proc execAffectedRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): int64 {. tags: [FReadDb, FWriteDb], raises: [Exception, EDb, ValueError].}
- executes the query (typically "UPDATE") and returns the number of affected rows. Source
proc close(db: DbConn) {.tags: [FDb], raises: [].}
- closes the database connection. Source
proc open(connection, user, password, database: string): DbConn {.tags: [FDb], raises: [EDb].}
-
opens a database connection. Raises EDb if the connection could not be established.
Clients can also use Postgres keyword/value connection strings to connect.
Example:
con = open("", "", "", "host=localhost port=5432 dbname=mydb")
See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING for more information.
Note that the connection parameter is not used but exists to maintain the nim db api.
Source proc setEncoding(connection: DbConn; encoding: string): bool {.tags: [FDb], raises: [].}
- sets the encoding of a database connection, returns true for success, false for failure. Source
Iterators
iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {. tags: [FReadDb], raises: [EDb].}
- executes the query and iterates over the result dataset. This is very fast, but potenially dangerous: If the for-loop-body executes another query, the results can be undefined. For Postgres it is safe though. Source
iterator fastRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {. tags: [FReadDb], raises: [Exception, EDb].}
- executes the prepared query and iterates over the result dataset. Source
iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {. tags: [FReadDb], raises: [EDb].}
- same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within interator body. Source
iterator instantRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): InstantRow {. tags: [FReadDb], raises: [Exception, EDb].}
- same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within interator body. Source
iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {. tags: [FReadDb], raises: [EDb].}
- same as fastRows, but slower and safe. Source
iterator rows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {. tags: [FReadDb], raises: [Exception, EDb].}
- same as fastRows, but slower and safe. Source