# db_postgres

- マニュアル
- 標準ライブラリ
- 索引

検索
分類:

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:

    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")

# インポート

strutils, postgres, db_common

# 型

    DbConn = PPGconn

  encapsulates a database connection Source Edit

    Row = seq[string]

  a row of a dataset. NULL database values will be converted to nil. ソース 編集

    InstantRow = object
      res: PPGresult               ## used to get a row's
      line: int                    ## column text on demand

  a handle that can be Source Edit

    SqlPrepared = distinct string

  a identifier for the prepared queries Source Edit

# プロシージャ

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

  raises a DbError exception. ソース 編集

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

  DB quotes the string. ソース 編集

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

  tries to execute the query and returns true if successful, false otherwise. ソース 編集

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

  tries to execute the query and returns true if successful, false otherwise. ソース 編集

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

  executes the query and raises EDB if not successful. ソース 編集

    proc exec(db: DbConn; stmtName: SqlPrepared; args: varargs[string]) {...}{.
        tags: [ReadDbEffect, WriteDbEffect], raises: [DbError].}

  ソース 編集

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

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

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

  returns text for given column of the row Source Edit

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

  Return cstring of given column of the row Source Edit

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

  returns number of columns in the row Source Edit

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

  retrieves a single row. If the query doesn't return any rows, this proc will return a Row with empty strings for each column. ソース 編集

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

  ソース 編集

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

  executes the query and returns the whole result dataset. ソース 編集

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

  executes the prepared query and returns the whole result dataset. ソース 編集

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

  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. ソース 編集

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

  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. ソース 編集

    proc tryInsertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
        tags: [WriteDbEffect], raises: [DbError, 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`. ソース 編集

    proc insertID(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): int64 {...}{.
        tags: [WriteDbEffect], raises: [DbError, 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`. ソース 編集

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

  executes the query (typically "UPDATE") and returns the number of affected rows. ソース 編集

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

  executes the query (typically "UPDATE") and returns the number of affected rows. ソース 編集

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

  closes the database connection. ソース 編集

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

  opens a database connection. Raises `EDb` if the connection could not be established.

  Clients can also use Postgres keyword/value connection strings to connect.

  用例:

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

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

  ソース 編集

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

  sets the encoding of a database connection, returns true for success, false for failure. ソース 編集

# イテレータ

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

  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. ソース 編集

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

  executes the prepared query and iterates over the result dataset. ソース 編集

    iterator instantRows(db: DbConn; query: SqlQuery; args: varargs[string, `$`]): InstantRow {...}{.
        tags: [ReadDbEffect], raises: [DbError].}

  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. ソース 編集

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

  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. ソース 編集

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

  ソース 編集

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

  same as `fastRows`, but slower and safe. ソース 編集

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

  same as `fastRows`, but slower and safe. ソース 編集

# エクスポート

dbSerial, dbUser5, dbLine, dbBool, DbTypeKind, dbUInt, dbGeometry, dbInet, dbUser4, sql, dbUser3, dbPolygon, DbType, dbSet, dbFloat, dbMacAddress, dbVarchar, dbBit, dbArray, dbUser1, dbLseg, SqlQuery, db_common, DbColumn, dbBox, ReadDbEffect, dbNull, DbError, dbDate, dbUuid, dbJson, dbUrl, dbDecimal, dbXml, dbUnknown, WriteDbEffect, dbBlob, dbEnum, dbError, dbTime, DbColumns, dbPoint, DbEffect, dbTimeInterval, dbPath, dbTimestamp, dbCircle, dbInt, dbDatetime, dbComposite, dbFixedChar, dbUser2