Note: In order to use this module, run nimble install db_connector.

A higher level PostgreSQL database wrapper. This interface is implemented for other databases also.

See also: db_odbc, db_sqlite, db_mysql.

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:

  1. 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, …
  1. prepare(db, "myExampleInsert",
  2. sql"""INSERT INTO myTable
  3. (colA, colB, colC)
  4. VALUES ($1, $2, $3)""",
  5. 3)

Unix Socket

Using Unix sockets instead of TCP connection can improve performance up to 30% ~ 175% for some operations.

To use Unix sockets with db_postgres, change the server address to the socket file path:

  1. import std/db_postgres ## Change "localhost" or "127.0.0.1" to the socket file path
  2. let db = db_postgres.open("/run/postgresql", "user", "password", "database")
  3. echo db.getAllRows(sql"SELECT version();")
  4. db.close()

The socket file path is operating system specific and distribution specific, additional configuration may or may not be needed on your postgresql.conf. The Postgres server must be on the same computer and only works for Unix-like operating systems.

Examples

Opening a connection to a database

  1. import db_connector/db_postgres
  2. let db = open("localhost", "user", "password", "dbname")
  3. db.close()

Creating a table

  1. db.exec(sql"DROP TABLE IF EXISTS myTable")
  2. db.exec(sql("""CREATE TABLE myTable (
  3. id integer,
  4. name varchar(50) not null)"""))

Inserting data

  1. db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
  2. "Dominik")

Imports

postgres, db_common, dbutils

Types

  1. DbConn = PPGconn

encapsulates a database connection

  1. InstantRow = object
  2. ## used to get a row's

a handle that can be

  1. Row = seq[string]

a row of a dataset. NULL database values will be converted to nil.

  1. SqlPrepared = distinct string

a identifier for the prepared queries

Procs

  1. proc `[]`(row: InstantRow; col: int): string {.inline, ...raises: [], tags: [],
  2. forbids: [].}

returns text for given column of the row

  1. proc close(db: DbConn) {....tags: [DbEffect], raises: [], forbids: [].}

closes the database connection.

  1. proc dbError(db: DbConn) {.noreturn, ...raises: [DbError], tags: [], forbids: [].}

raises a DbError exception.

  1. proc dbQuote(s: string): string {....raises: [], tags: [], forbids: [].}

DB quotes the string.

  1. proc exec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]) {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

executes the query and raises EDB if not successful.

  1. proc exec(db: DbConn; stmtName: SqlPrepared; args: varargs[string]) {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}
  1. proc execAffectedRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError, ValueError],
  3. forbids: [].}

executes the query (typically “UPDATE”) and returns the number of affected rows.

  1. proc execAffectedRows(db: DbConn; stmtName: SqlPrepared;
  2. args: varargs[string, `$`]): int64 {.
  3. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError, ValueError],
  4. forbids: [].}

executes the query (typically “UPDATE”) and returns the number of affected rows.

  1. proc getAllRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): seq[
  2. Row] {....tags: [ReadDbEffect], raises: [DbError], forbids: [].}

executes the query and returns the whole result dataset.

  1. proc getAllRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): seq[
  2. Row] {....tags: [ReadDbEffect], raises: [DbError], forbids: [].}

executes the prepared query and returns the whole result dataset.

  1. proc getRow(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

retrieves a single row. If the query doesn’t return any rows, this proc will return a Row with empty strings for each column.

  1. proc getRow(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
  1. proc getValue(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): string {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

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.

  1. proc getValue(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): string {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

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.

  1. proc insert(db: DbConn; query: SqlQuery; pkName: string;
  2. args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
  3. raises: [DbError, ValueError], forbids: [].}

executes the query (typically “INSERT”) and returns the generated ID

  1. proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
  2. ...tags: [WriteDbEffect], raises: [DbError, ValueError], forbids: [].}

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.

  1. proc len(row: InstantRow): int {.inline, ...raises: [], tags: [], forbids: [].}

returns number of columns in the row

  1. proc open(connection, user, password, database: string): DbConn {.
  2. ...tags: [DbEffect], raises: [DbError], forbids: [].}

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:

  1. con = open("", "", "", "host=localhost port=5432 dbname=mydb")

See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING for more information.

  1. proc prepare(db: DbConn; stmtName: string; query: SqlQuery; nParams: int): SqlPrepared {.
  2. ...raises: [DbError], tags: [], forbids: [].}

Creates a new SqlPrepared statement. Parameter substitution is done via $1, $2, $3, etc.

  1. proc setEncoding(connection: DbConn; encoding: string): bool {....tags: [DbEffect],
  2. raises: [], forbids: [].}

sets the encoding of a database connection, returns true for success, false for failure.

  1. proc tryExec(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): bool {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [DbError], forbids: [].}

tries to execute the query and returns true if successful, false otherwise.

  1. proc tryExec(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): bool {.
  2. ...tags: [ReadDbEffect, WriteDbEffect], raises: [], forbids: [].}

tries to execute the query and returns true if successful, false otherwise.

  1. proc tryInsert(db: DbConn; query: SqlQuery; pkName: string;
  2. args: varargs[string, `$`]): int64 {....tags: [WriteDbEffect],
  3. raises: [DbError, ValueError], forbids: [].}

executes the query (typically “INSERT”) and returns the generated ID for the row or -1 in case of an error.

  1. proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {.
  2. ...tags: [WriteDbEffect], raises: [DbError, ValueError], forbids: [].}

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.

  1. proc unsafeColumnAt(row: InstantRow; index: int): cstring {.inline, ...raises: [],
  2. tags: [], forbids: [].}

Return cstring of given column of the row

Iterators

  1. iterator fastRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

executes the query and iterates over the result dataset. This is very fast, but potentially dangerous: If the for-loop-body executes another query, the results can be undefined. For Postgres it is safe though.

  1. iterator fastRows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

executes the query and iterates over the result dataset. This is very fast, but potentially dangerous: If the for-loop-body executes another query, the results can be undefined. For Postgres it is safe though.

  1. iterator instantRows(db: DbConn; columns: var DbColumns; query: SqlQuery;
  2. args: varargs[string, `$`]): InstantRow {.
  3. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}
  1. iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within iterator body.

  1. iterator instantRows(db: DbConn; stmtName: SqlPrepared;
  2. args: varargs[string, `$`]): InstantRow {.
  3. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

same as fastRows but returns a handle that can be used to get column text on demand using []. Returned handle is valid only within iterator body.

  1. iterator rows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

same as fastRows, but slower and safe.

  1. iterator rows(db: DbConn; stmtName: SqlPrepared; args: varargs[string, `$`]): Row {.
  2. ...tags: [ReadDbEffect], raises: [DbError], forbids: [].}

same as fastRows, but slower and safe.

Exports

DbTypeKind, sql, DbType, SqlQuery, DbColumn, ReadDbEffect, DbError, WriteDbEffect, dbError, DbColumns, DbEffect