On this page:
3.1 Statements
statement?
3.2 Simple queries
query-exec
query-rows
query-list
query-row
query-maybe-row
query-value
query-maybe-value
in-query
3.3 General query support
simple-result
recordset
query
query-fold
3.4 Prepared statements
prepare
prepared-statement?
prepared-statement-parameter-types
prepared-statement-result-types
bind-prepared-statement
statement-binding?
virtual-statement
virtual-statement?
statement-generator
statement-generator?
3.5 Transactions
start-transaction
commit-transaction
rollback-transaction
in-transaction?
needs-rollback?
call-with-transaction
3.6 Creating new kinds of statements
prop: statement

3 Queries

The database package implements a high-level functional query API, unlike many other database libraries, which present a stateful, iteration-based interface to queries. When a query function is invoked, it either returns a result or, if the query caused an error, raises an exception. Different query functions impose different constraints on the query results and offer different mechanisms for processing the results.

Errors In most cases, a query error does not cause the connection to be disconnected. Specifically, the following kinds of errors should never cause a connection to be disconnected:
  • SQL syntax errors, such as references to undefined tables, columns, or operations, etc

  • SQL runtime errors, such as integrity constraint violations

  • violations of a specialized query function’s expectations, such as using query-value with a query that returns multiple columns

  • supplying the wrong number or wrong types of parameters to a prepared query, executing a prepared query with the wrong connection, etc

The following kinds of errors may cause a connection to be disconnected:
  • changing communication settings, such as changing the connection’s character encoding

  • communication failures and internal errors in the library

See Transactions for information on how errors can affect the transaction status.

Character encoding This library is designed to interact with database systems using the UTF-8 character encoding. The connection functions attempt to negotiate UTF-8 communication at the beginning of every connection, but some systems also allow the character encoding to be changed via SQL commands (eg, SET NAMES). If this happens, the client might be unable to reliably communicate with the database, and data might get corrupted in transmission. Avoid changing a connection’s character encoding. When possible, the connection will observe the change and automatically disconnect with an error.

Synchronization Connections are internally synchronized: it is safe to perform concurrent queries on the same connection object from different threads. Connections are not kill-safe: killing a thread that is using a connection—or shutting down the connection’s managing custodian—may leave the connection locked, causing future operations to block indefinitely. See Connection utilities for a way to make kill-safe connections.

3.1 Statements

All queries require both a connection and a statement, which is one of the following:

(statement? x)  boolean?
  x : any/c
Returns #t if x is a statement, #f otherwise.

3.2 Simple queries

The simple query API consists of a set of functions specialized to various types of queries. For example, query-value is specialized to queries that return a recordset of exactly one column and exactly one row.

If a statement takes parameters, the parameter values are given as additional arguments immediately after the SQL statement. Only a statement given as a string, prepared statement, or virtual statement can be given “inline” parameters; if the statement is a statement-binding, no inline parameters are permitted.

The types of parameters and returned fields are described in SQL types and conversions.

(query-exec connection stmt arg ...)  void?
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a SQL statement for effect.

Examples:

  > (query-exec c "insert into some_table values (1, 'a')")
  > (query-exec pgc "delete from some_table where n = $1" 42)

(query-rows connection stmt arg ...)  (listof vector?)
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a SQL query, which must produce a recordset, and returns the list of rows (as vectors) from the query.

Examples:

  > (query-rows pgc "select * from the_numbers where n = $1" 2)

  (#(2 "company"))

  > (query-rows c "select 17")

  (#(17))

(query-list connection stmt arg ...)  list?
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a SQL query, which must produce a recordset of exactly one column, and returns the list of values from the query.

Examples:

  > (query-list c "select n from the_numbers where n < 2")

  (0 1)

  > (query-list c "select 'hello'")

  ("hello")

(query-row connection stmt arg ...)  vector?
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a SQL query, which must produce a recordset of exactly one row, and returns its (single) row result as a vector.

Examples:

  > (query-row myc "select * from the_numbers where n = ?" 2)

  #(2 "company")

  > (query-row c "select 17")

  #(17)

(query-maybe-row connection stmt arg ...)  (or/c vector? #f)
  connection : connection?
  stmt : statement?
  arg : any/c
Like query-row, but the query may produce zero rows; in that case, #f is returned.

Examples:

  > (query-maybe-row pgc "select * from the_numbers where n = $1" 100)
  > (query-maybe-row c "select 17")

  #(17)

(query-value connection stmt arg ...)  any/c
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a SQL query, which must produce a recordset of exactly one column and exactly one row, and returns its single value result.

Examples:

  > (query-value pgc "select timestamp 'epoch'")

  #(struct:sql-timestamp 1970 1 1 0 0 0 0 #f)

  > (query-value pgc "select s from the_numbers where n = $1" 3)

  "a crowd"

(query-maybe-value connection stmt arg ...)  (or/c any/c #f)
  connection : connection?
  stmt : statement?
  arg : any/c
Like query-value, but the query may produce zero rows; in that case, #f is returned.

Examples:

  > (query-value myc "select s from some_table where n = ?" 100)
  > (query-value c "select 17")

  17

(in-query connection stmt arg ...)  sequence?
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a SQL query, which must produce a recordset, and returns a sequence. Each step in the sequence produces as many values as the recordset has columns.

Examples:

  > (for/list ([n (in-query pgc "select n from the_numbers where n < 2")])
      n)

  (0 1)

  > (for ([(n d)
           (in-query pgc "select * from the_numbers where n < $1" 4)])
      (printf "~a is ~a\n" n d))

  0: nothing

  1: the loneliest number

  2: company

  3: a crowd

An in-query application can provide better performance when it appears directly in a for clause. In addition, it may perform stricter checks on the number of columns returned by the query based on the number of variables in the clause’s left-hand side:

Example:

  > (for ([n (in-query pgc "select * from the_numbers")])
      (displayln n))

  in-query: query returned 2 columns (expected 1): "select *

  from the_numbers"

3.3 General query support

A general query result is either a simple-result or a recordset.

(struct simple-result (info))
  info : any/c
Represents the result of a SQL statement that does not return a relation, such as an INSERT or DELETE statement.

The info field is usually an association list, but do not rely on its contents; it varies based on database system and may change in future versions of this library (even new minor versions).

(struct recordset (headers rows))
  headers : (listof any/c)
  rows : (listof vector?)
Represents the result of SQL statement that results in a relation, such as a SELECT query.

The headers field is a list whose length is the number of columns in the result rows. Each header is usually an association list containing information about the column, but do not rely on its contents; it varies based on the database system and may change in future version of this library (even new minor versions).

(query connection stmt arg ...)  (or/c simple-result? recordset?)
  connection : connection?
  stmt : statement?
  arg : any/c
Executes a query, returning a structure that describes the results. Unlike the more specialized query functions, query supports both recordset-returning and effect-only queries.

(query-fold connection stmt fold-proc init)  alpha
  connection : connection?
  stmt : (or/c string? statement-binding?)
  fold-proc : (alpha field ... -> alpha)
  init : alpha
Left fold over the results of the query. The arity of fold-proc must include a number one greater than the number of columns returned by the query. Inline parameter arguments are not supported; parameter binding must be done explicitly with bind-prepared-statement.

This function is deprecated; use for/fold with in-query instead.

3.4 Prepared statements

A prepared statement is the result of a call to prepare.

The syntax of parameterized queries varies depending on the database system. For example:

PostgreSQL:

    

select * from the_numbers where num > $1;

MySQL, ODBC:

select * from the_numbers where num > ?;

SQLite:

supports both syntaxes (plus others)

Any server-side or native-library resources associated with a prepared statement are released when the prepared statement is garbage-collected or when the connection that owns it is closed; prepared statements do not need to be (and cannot be) explicitly closed.

(prepare connection stmt)  prepared-statement?
  connection : connection?
  stmt : (or/c string? virtual-statement?)
Prepares a (possibly parameterized) statement. The resulting prepared statement is tied to the connection that prepared it; attempting to execute it with another connection will trigger an exception. (The prepared statement holds its connection link weakly; a reference to a prepared statement will not keep a connection from being garbage collected.)

(prepared-statement? x)  boolean?
  x : any/c
Returns #t if x is a prepared statement created by prepare, #f otherwise.

Returns a list with one element for each of the prepared statement’s parameters. Each element is itself a list of the following form:

  (list supported? type typeid)

The supported? field is #t if the type is supported by this library; the type field is a symbol corresponding to one of the tables in SQL type conversions, and the typeid field is a system-specific type identifier. The type description list format may be extended with additional information in future versions of this library.

If pst is a recordset-producing statement (eg, SELECT), returns a list of type descriptions as described above, identifying the SQL types (or pseudotypes) of the result columns. If pst does not produce a recordset, the function returns the empty list.

(bind-prepared-statement pst params)  statement-binding?
  pst : prepared-statement?
  params : (listof any/c)
Creates a statement-binding value pairing pst with params, a list of parameter arguments. The result can be executed with query or any of the other query functions, but it must be used with the same connection that created pst.

Example:

  > (let* ([get-name-pst
           (prepare pgc "select d from the_numbers where n = $1")]
           [get-name2
            (bind-prepared-statement get-name-pst (list 2))]
           [get-name3
            (bind-prepared-statement get-name-pst (list 3))])
      (list (query-value pgc get-name2)
            (query-value pgc get-name3)))

  ("company" "a crowd")

Most query functions perform the binding step implicitly, but there are functions such as query-fold that do not accept query parameters; bind-prepared-statement is neccessary to use a parameterized query with such functions.

(statement-binding? x)  boolean?
  x : any/c
Returns #t if x is a statement created by bind-prepared-statement, #f otherwise.

Creates a virtual statement stmt, which encapsulates a weak mapping of connections to prepared statements. When a query function is called with stmt and a connection, the weak hash is consulted to see if the statement has already been prepared for that connection. If so, the prepared statement is used; otherwise, the statement is prepared and stored in the table.

The gen argument must be either a SQL string or a function that accepts a databse system object and produces a SQL string. The function variant allows the SQL syntax to be dynamically customized for the database system in use.

Examples:

  > (define pst
      (virtual-statement
       (lambda (dbsys)
         (case (dbsystem-name dbsys)
           ((postgresql) "select n from the_numbers where n < $1")
           ((sqlite3) "select n from the_numbers where n < ?")
           (else (error "unknown system"))))))
  > (query-list pgc pst 3)

  (1 2)

  > (query-list slc pst 3)

  (1 2)

(virtual-statement? x)  boolean?
  x : any/c
Returns #t if x is a virtual statement created by virtual-statement, #f otherwise.

Deprecated. Equivalents of virtual-statement and virtual-statement?.

3.5 Transactions

The functions described in this section provide a consistent interface to transactions.

ODBC connections should use these functions exclusively instead of transaction-changing SQL statements such as START TRANSACTION and COMMIT. Using transaction-changing SQL may cause these functions to behave incorrectly and may cause additional problems in the ODBC driver.

PostgreSQL, MySQL, and SQLite connections are discouraged from using transaction-changing SQL statements, but the consequences are less dire. The functions below will behave correctly, but the syntax and behavior of the SQL statements is idiosyncratic. For example, in MySQL START TRANSACTION commits the current transaction, if one is active; in PostgreSQL COMMIT silently rolls back the current transaction if an error occurred in a previous statement.

Errors Query errors may affect an open transaction in one of three ways:
  1. the transaction remains open and unchanged

  2. the transaction is automatically rolled back

  3. the transaction becomes an invalid transaction; all subsequent queries will fail until the transaction is explicitly rolled back

To avoid the silent loss of information, this library attempts to avoid behavior (2) completely by marking transactions as invalid instead (3). Invalid transactions can be identified using the needs-rollback? function. The following list is a rough guide to what errors cause which behaviors:
  • All errors raised by checks performed by this library, such as parameter arity and type errors, leave the transaction open and unchanged (1).

  • All errors originating from PostgreSQL cause the transaction to become invalid (3).

  • Most errors originating from MySQL leave the transaction open and unchanged (1), but a few cause the transaction to become invalid (3). In the latter cases, the underlying behavior of MySQL is to roll back the transaction but leave it open (see the MySQL documentation). This library detects those cases and marks the transaction invalid instead.

  • Most errors originating from SQLite leave the transaction open and unchanged (1), but a few cause the transaction to become invalid (3). In the latter cases, the underlying behavior of SQLite is to roll back the transaction (see the SQLite documentation). This library detects those cases and marks the transaction invalid instead.

  • All errors originating from an ODBC driver cause the transaction to become invalid (3). The underlying behavior of ODBC drivers varies widely, and ODBC provides no mechanism to detect when an existing transaction has been rolled back, so this library intercepts all errors and marks the transaction invalid instead.

Future versions of this library may refine the set of errors that invalidate a transaction (for example, by identifying innocuous ODBC errors by SQLSTATE) and may provide an option to automatically rollback invalid transactions.

(start-transaction c    
  [#:isolation isolation-level])  void?
  c : connection?
  isolation-level : 
(or/c 'serializable
      'repeatable-read
      'read-committed
      'read-uncommitted
      #f)
 = #f
Starts a transaction with isolation isolation-level. If isolation-level is #f, the isolation is database-dependent; it may be a default isolation level or it may be the isolation level of the previous transaction.

If c is already in a transaction, an exception is raised.

Attempts to commit the current transaction, if one is active. If the transaction cannot be commited, an exception is raised.

If no transaction is active, has no effect.

Rolls back the current transaction, if one is active.

If no transaction is active, has no effect.

Returns #t if c has a transaction is active, #f otherwise.

Returns #t if c is in an invalid transaction. All queries executed using c will fail until the transaction is explicitly rolled back using rollback-transaction.

(call-with-transaction c    
  proc    
  [#:isolation isolation-level])  any
  c : connection?
  proc : (-> any)
  isolation-level : 
(or/c 'serializable
      'repeatable-read
      'read-committed
      'read-uncommitted
      #f)
 = #f
Calls proc in the context of a new transaction with isolation level isolation-level. If proc completes normally, the transaction is committed and proc’s results are returned. If proc raises an exception, the transaction is rolled back.

3.6 Creating new kinds of statements

A struct type property for creating new kinds of statements. The value associated with this property should satisfy the contract
The property value is applied to the struct instance and a connection, and it must return a statement.