NaviServer Programmable Web Server

ns_db(n)

NaviServer Module Commands – 5.2.0a


[ Main Table Of Contents | Table Of Contents | Keyword Index ]

Name

ns_db - Database access API

Table Of Contents

Synopsis

Description

These commands provides a mechanism to access databases.

COMMANDS

ns_db 1row handle ?-bindvars? ?-bindset setId? ?-binddict dictionary? ?-bindtypes types? ?-emptynull? ?--? sql

This command expects the SQL to be a select statement that returns exactly one row and returns that row as an ns_set. An error is returned if zero or more than one row is returned.

ns_db 0or1row handle ?-bindvars? ?-bindset setId? ?-binddict dictionary? ?-bindtypes types? ?-emptynull? ?--? sql

This command expects the provided SQL command to be a select statement that returns exactly zero or one row. On zero rows, a null string is returned. On one row, a newly allocated ns_set is returned. An error is thrown if more than one row is returned.

ns_db batchinfo ?-handle value? ?batch?

Without -handle, batch is required. With -handle, value is a checked-out database handle and batch is optional. Return immutable-batch metadata as a Tcl dictionary without materializing record values. Batches are opaque, interpreter-local values produced by registered C producers such as ns_accesslog scan. Metadata includes the shared schema, record count and producer-specific source/checkpoint information. Modifying the returned Tcl dictionary does not mutate the batch. A diagnostic string label is not a serializable or reconstructible batch handle.

With -handle, report the checked-out handle's batch capabilities. supported is false for a driver without registered batch callbacks. Registered drivers report their method, base types, supported refinements/representations and transaction requirements. The tclRows boolean reports support for prepared Tcl-row input on this handle. Older cores omit this key. With a batch, compatible reports schema/type compatibility; it does not validate individual values, a destination table's affinities or its constraints.

ns_db batchinsert handle -table table ?-columns mapping? ?-schema schema? ?-nulls nulls? batchOrRows

Insert synchronously through a driver's explicitly registered batch implementation using the existing checked-out connection and an active caller-owned transaction. A driver without callbacks raises NS_DB BATCH UNSUPPORTED before database work; there is no automatic SQL-text, JSON or other insertion fallback.

table is a Tcl list of one or two identifier components, each quoted by the backend. It is not an SQL fragment. mapping is a dictionary of source-field names to destination-column names. Omitted mapping uses all schema names unchanged. Omitted destination columns use database defaults. Empty mappings, unknown source fields, duplicate target names and unsupported types/refinements are rejected. Targets must already exist; there is no table creation, conflict policy, upsert, deduplication or automatic record transformation.

The batch remains unchanged and retained by its caller. Native sinks read borrowed lexical byte slices against the shared schema, with explicit nulls and conversion at the sink. No per-record Tcl dictionaries, triples or serialization are required. The initial shared provider ABI supports flat string, number, boolean and null columns; nested object/array schemas are explicitly rejected. JSON base types and optional schema refinements remain separate.

Prepared Tcl rows can be inserted directly with:

 ns_db dml $handle {BEGIN IMMEDIATE}
 
 ns_db batchinsert $handle -table events -schema {
     id event-rows version 1 columns {
         {name id type number refinement int64 representation integer_decimal}
         {name label type string nullable true}
     }
 } -nulls {{} {1}} \
 {{1 {a label}} {2 {}}}
 
 ns_db dml $handle COMMIT

With -schema, the final argument is a list of rows rather than an opaque C batch. Each row is a positional Tcl list with exactly one value per schema column. The schema uses the same flat descriptors and lexical values as C batches (for example, true/false for booleans and hexadecimal strings for encoded binary). -columns retains its source-name to destination-name mapping semantics. Optional -nulls is a parallel list containing zero-based NULL column indices for each row; it requires -schema. Omission means no explicit NULL values except columns of base type null. Empty strings remain values and are never interpreted as NULL. Explicit NULLs require nullable columns.

All row widths and NULL indices are checked before insertion. Typed value conversion and destination compatibility remain with the driver. The input rows are retained synchronously and are not modified. No application C producer, opaque batch object or separate conversion command is required. The core borrows ASCII lexical values and converts non-ASCII Tcl strings to external UTF-8 when needed. Rows are not SQL fragments. Existing opaque C batch input remains unchanged when -schema is omitted.

Success reports a dictionary with rows and method. The count represents changes within the transaction, not a durable commit. The driver must finish all native readers/statements before returning. An empty batch still requires a supported driver, valid mapping/target and caller transaction, then reports zero rows. A disconnected handle, active result or conflicting prepared operation is rejected without discarding its result.

The command never commits, rolls back or consumes the batch. An error can leave earlier rows written in the outer transaction: the caller must roll back. Errors use NS_DB BATCH codes such as TYPE_MISMATCH, MAPPING, TRANSACTION_REQUIRED, CONVERSION or INSERT; native driver diagnostics can append zero-based row/field information and populate the ordinary nsdb exception. An application can atomically insert records, update rollups and save a producer checkpoint before committing the same transaction. Checkpoint serialization must preserve binary fields, for example by base64-encoding a UTF-8 Tcl-list envelope when storing the checkpoint as database text.

The SQLite implementation uses reusable prepared bindings on the same connection and checks its actual transaction state, including outer SAVEPOINTs. It enforces native int32/int64 ranges and exact integer-microsecond conversions without doubles. Access-log calendar/epoch timestamp strings can become UTC microseconds in INTEGER/NUMERIC targets, or remain lexical in TEXT targets. Generic JSON numbers can remain exact lexemes in explicit TEXT storage. Encoded-binary hex refinements map to BLOB. Unknown refinements fail explicitly.

SQLite target affinities are checked before row insertion to prevent silent numeric coercion or integer-to-REAL precision loss. Ordinary strings require TEXT or no-affinity/BLOB storage, native integers/booleans/microseconds require INTEGER/NUMERIC or no-affinity/BLOB storage, and encoded binary requires BLOB. Generated/hidden columns are rejected. Database constraints and triggers retain their normal semantics. SQLite rows counts direct changes, excluding trigger side effects, matching SQLite changes semantics. Exact conversion can reject a source spelling or value even when its base type is supported.

ns_db bindinfo handle ?-version|-types?

Reports whether the driver supports bind vars in SQL statements. Its optional -version returns Tcl binding API version 6 for native one-dimensional array metadata (5 denotes binary values and row column types; 4 denotes untyped rows; 3 denotes scalar/list types; 2 denotes the preceding scalar-only options), or 0 when unsupported. The default boolean result remains compatible with the earlier binding API.

With -types, returns the supported native parameter interpretations: scalar, binary, and optionally array. Core list/row expansions remain independent of native array capabilities.

ns_db bindrow handle

Returns an ns_set structure whose key names are the column names of the rows returned by the SQL command previously-executed with ns_db exec. If the database is not currently returning rows (i.e., a status other than NS_ROWS was returned by ns_db exec), an error is thrown. The handle argument is a database handle (obtained with ns_db gethandle).

ns_db bouncepool poolname

Marks all database handles for the specified database pool as stale. When any database handle currently open is put back into the pool, its connection to the database will be reset.

ns_db cancel handle

Cancel the current operation.

ns_db connected handle

Returns a boolean value indicating whether the connection to the database pool is made.

ns_db currenthandles

Returns information about handles currently allocated to the thread performing this call. The result contains a dict with the pools, from which handles were allocated, the names of the handles and their "active" state (a handle is active between a "ns_db select" and the last "ns_db getrow" statement). If no handles are allocated by this thread, empty is returned.

 # [ns_db currenthandles]
 main {nsdb0 1} subquery {nsdb1 0}

in the example above the result indicates that the current thread has allocated handles from pool main and subquery, but the handle from pool main (i.e. nsdb0) is currently active (e.g., during a select).

ns_db datasource handle

Returns the datasource for the database pool.

ns_db dbtype handle

Returns the database type for the database pool.

ns_db dml handle ?-bindvars? ?-bindset setId? ?-binddict dictionary? ?-bindtypes types? ?-emptynull? ?--? sql

Executes the provided SQL DML statement that should be data manipulation language such as an insert or update, or data definition language such as a create table.

ns_db driver handle

Returns the name of the driver of the handle.

ns_db exception handle

Returns the most recent exception for the database pool.

ns_db exec handle ?-bindvars? ?-bindset setId? ?-binddict dictionary? ?-bindtypes types? ?-emptynull? ?--? sql

Executes the specified SQL command. It returns either NS_DML (if the SQL command is a DML or DDL command) or NS_ROWS (if the SQL command returns rows, such as a SELECT). This function can be used for ad hoc querying, where you don't know what kind of SQL command will be executed.

ns_db flush handle

Flushes the results of an SQL select so you do not need to use ns_db getrow to get all the rows and throw them away.

ns_db gethandle ?-timeout time? ?--? ?poolname? ?nhandles?

Returns the specified number of handles from the specified pool. If poolname is not specified, the Defaultpool from the configuration file is used. If nhandles is not specified, 1 handle is returned. (Note that if you specify nhandles, you must also specify a poolname.) If not enough handles are available to fulfill the request, it waits until they are available. You must request all the handles you will need for a specific pool with one call to ns_db gethandle. You must release all your database handles explicitly (with ns_db releasehandle) before acquiring more. If you request multiple handles from the database, this function returns a Tcl list of database handles (space delimited). In this case, each handle must be released with a separate call to ns_db releasehandle.

If -timeout is not specified or timeout is zero, ns_db gethandle will wait indefinitely (perhaps forever) for the requested number of handles to become available. If timeout is greater than zero, ns_db gethandle will either return with the handles within that time period, or return "" if the time period was exceeded, or generate a Tcl error. See the examples below. The argument time can be specified in the form secs?:microsecs?, or secs.fraction, or as a number with the time units ms, s, m, d. These are valid uses of ns_db gethandle:

 ns_db gethandle
 # 1 handle from default pool
 
 ns_db gethandle -timeout 2.5s
 # 1 handle from default pool, 2.5 sec timeout
 
 ns_db gethandle -timeout -1 poolname
 # 1 handle from poolname, error if not available
 
 ns_db gethandle poolname
 # 1 handle from poolname
 
 ns_db gethandle -timeout 23 poolname
 # 1 handle from poolname, 23 sec timeout
 
 ns_db gethandle poolname 5
 # 5 handles from poolname
 
 ns_db gethandle -timeout 2.0s poolname 5
 # 5 handles from poolname, 2.0 sec timeout
ns_db getrow handle setId

Fetches the next row from the result of a prior ns_db select call, inserting its values into the ns_set identified by setId (the same set returned by the ns_db select). The command returns "1" if there are more rows waiting and returns "0" otherwise. Calling ns_db getrow again after receiving `0` will raise an error.

ns_db info handle

Returns a Tcl dictionary with metadata about the database connection associated with handle. The dictionary may include: clientversion (version of the client library), serverversion (version of the connected database server) type (the database type (e.g., PostgreSQL, Oracle) pool (the connection pool name from which this handle was allocated). Note: not all drivers supply every field; for instance, some may omit version numbers.

ns_db logminduration ?poolname? ?minduration?

Queries or sets the minimum execution time threshold for SQL statement logging. When SQL debug logging is enabled (for example via "ns_logctl severity Debug(sql) ..."), only statements that take at least the specified duration will be emitted to the system log. If poolname is omitted, the operation is applied on all database pools. The minduration can be specified in the form secs?:microsecs?, or secs.fraction, or as a number with the time units ms, s, m, d. Change the verbosity level to show all SQL commands or only these taking longer:

 #
 # Increase verbosity of SQL
 #
 ns_logctl debug(sql) on
 
 #
 # Set for every pool the longminduration to 0 to show all
 # SQL commands (or e.g. to 10ms, meaning: show SQL commands
 # taking longer than 10 milliseconds).
 #
 foreach pool [ns_db pools] {ns_db logminduration $pool 0}
ns_db password handle

Returns the password of the user for the database pool.

ns_db poolname handle

Returns the database pool that this handle came from.

ns_db pools

Returns a list of all database pools.

ns_db releasehandle handle

Puts the handle back in the pool. The server will automatically return any open handles to the pool after a page has finished executing.

ns_db rowcount handle

Returns number of processed records by the last SQL statements, this is useful with INSERT/UPDATE/DELETE statements to know how many records updated.

ns_db select handle ?-bindvars? ?-bindset setId? ?-binddict dictionary? ?-bindtypes types? ?-emptynull? ?--? sql

Executes the SQL statement on the database server. It returns an ns_set with the keys set to the column names that were selected. Use ns_db getrow to retrieve rows. You cannot perform nested select statements. Before you start a new select statement, you must first either retrieve all the rows from the first select or use the ns_db flush statement to flush any rows not yet retrieved.

ns_db setexception handle code message

Returns the specified status code and message to the client.

ns_db sp_exec handle

Executes a stored procedure that has been initialized with ns_db sp_start and ns_db sp_setparam. It returns "NS_DML" if the command was successfully executed but did not return rows, or it returns "NS_ROWS" if the command was successfully executed and did return rows (which can then be fetched with ns_db bindrow and ns_db getrow). It throws an error if the command failed. This function is implemented only for the Sybase database driver. See ns_db sp_start for an example.

ns_db sp_getparams handle

] Returns any output parameters set after executing a stored procedure with ns_db sp_exec. It returns an ns_set or throws an error on failure.

ns_db sp_returncode handle

ns_db sp_returncode gets the return code from a stored procedure. It must be called after ns_db sp_exec. This function is implemented only for the Sybase database driver. See ns_db sp_start for an example.

ns_db sp_setparam handle paramname type in|out value

Sets a parameter for a call to a stored procedure. paramname is the name of the parameter, for example @name. type is the data type of this parameter, for example varchar. The nextg argument denotes the direction, whether it is an input or output parameter. It must be set to either in or out. value denotes the parameter value to send. This function returns 1 on success and throws an error on failure. This function is implemented only for the Sybase database driver. See ns_db sp_start for an example.

ns_db sp_start handle procname

Begins execution of the stored procedure called procname. It returns 0 on success and throws an error on failure. This function is implemented only for the Sybase database driver. See the example below.

 set db [ns_db gethandle $pool]
 set ret [ns_db sp_start $db "p_TestProc"]
 
 #
 # Set the parameters for this stored procedure.  The SQL definition of this
 # procedure is:
 #
 #   CREATE PROCEDURE p_TestProc(@x int, @y varchar(16) out, @z int out)
 #
 # The arguments to ns_db sp_setparam are like this:
 #
 #   ns_db sp_setparam $handle $paramname $type in|out $value
 #
 set ret [ns_db sp_setparam $db "@x" int in 4]
 set ret [ns_db sp_setparam $db "@y" varchar out "varchar val"]
 set ret [ns_db sp_setparam $db "@z" int out 231]
 
 #
 # Execute the stored procedure now
 #
 set ret [ns_db sp_exec $db]
ns_db stats ?handle ?-database name??

Without handle, returns a Tcl dictionary of statistics for all pools. The statistics contain the number of SQL statements executed, the number of get-handle operations, the number of currently connected database connections, the total and used handles, and the aggregated wait time for handles from each pool (including connection setup time to the database server).

With handle, returns statistics from the optional driver callback for that owned database handle. The result is a Tcl dictionary with driver (the driver's name) and supported (a boolean). Without a callback, supported is false; existing drivers require no modification. The -database option requires handle.

Statistics use a shared vocabulary where the scopes and units are comparable:

  • connection: memoryUsedBytes and cacheUsedBytes are current memory gauges in bytes. cacheHits and cacheMisses are cumulative cache-access counts for this connection. Backend documentation defines the cache coverage.

  • statement: executions counts execution starts of the currently retained statement; rowsReturned counts rows delivered to the caller by that statement. memoryUsedBytes is its current attributed memory in bytes. These are statement-instance metrics, not historical connection or server totals.

  • highwater: Meaningful peak gauges, nested at the same paths as their corresponding current metrics. Omit peaks that the engine does not measure. Cumulative counters are not peaks, even if an engine API returns them in an output called highwater.

  • backend: Driver-specific fields, nested under the driver's identifier. SQLite places its connection/statement details, pool policy and WAL snapshot under backend sqlite. These are not equated with PostgreSQL server-wide buffer, scan or checkpoint statistics.

Metric values are scalars, without per-metric available, current or highwater wrappers. Omit unsupported or unavailable metrics; zero means a measured zero. Omit empty groups. supported reports callback support only, not the availability of every metric. A backend may retain a reason/code when a supported measurement temporarily fails, without providing unavailable numerical values. SQLite, for example, omits WAL frame counts when its snapshot is locked and reports the reason under backend sqlite wal.

An explicit -database selects a database within the connection where supported; SQLite defaults to main and accepts attached database names. Unknown databases and unsupported explicit selection are errors. Connection counters still cover the connection; the selector chooses the SQLite WAL scope. ns_sqlite stats retains its legacy names, availability wrappers and sentinels for existing applications; it is a compatibility view of the same sampler rather than the shared result format.

A supported callback requires a connected handle. Statistics do not reconnect it, flush or consume pending rows, reset counters, commit or roll back work, or clear database error diagnostics. Callback errors propagate to the caller. Different drivers' counters need not be comparable; this command does not issue queries against PostgreSQL server statistics views.

Driver authors can implement the optional DbFn_Stats callback, declared by NS_DB_STATS_ABI in "nsdb.h". Existing callback IDs and the public handle layout are unchanged.

typedef int (Ns_DbStatsProc)(Tcl_Interp *interp, Ns_DbHandle *handle,
                           const char *database);

The callback returns TCL_OK with a dictionary as the interpreter result, or TCL_ERROR with its diagnostic. A NULL database selects the driver's default scope; an explicit name must be validated or rejected. The callback borrows the handle and database name only for the call. Core adds driver and supported to the result, and validates that successful results are dictionaries. Ns_DbStats is the corresponding C dispatch function.

Statistics callbacks are observational: preserve pending results, transactions, affected-row counts and database error diagnostics; do not reconnect, reset counters or run maintenance. Document scopes, units, unavailable counters and sampling costs per driver.

ns_db user handle

Returns the user (as specified for the User parameter of the configuration file) for the database pool.

ns_db withhandle ?-pool value? ?-handle value? ?-timeout value? ?--? handleVar script

Evaluate script in the caller's frame with a database handle temporarily assigned to handleVar. The variable may be a scalar or an array element. Its previous value is restored afterward; a previously absent variable is removed. The body's result and Tcl completion options, including errors, return, break, continue and custom completion codes, are preserved. A variable-restoration error is reported if the body succeeded; otherwise the body's original completion takes precedence. Variable traces can prevent assignment or restoration and should not reject these operations.

Without -handle, acquire one handle from the pool specified by -pool, or from the configured default pool when -pool is omitted. Release this owned handle on every exit, including assignment failure and script errors. -timeout has the same units and waiting semantics as ns_db gethandle, including indefinite waiting when omitted or zero. Unlike ns_db gethandle, a checkout timeout raises an error with NS DB TIMEOUT as its error code and does not execute the body. Pool permissions and the prohibition on acquiring more handles from an already-owned pool remain unchanged.

With -handle, borrow an existing handle owned by this interpreter. The borrowed handle is not released, flushed or reset on leaving the scope. This form can be nested and used within a caller-managed transaction. -handle cannot be combined with -pool or -timeout. There is no implicit reuse of other checked-out handles.

This command does not begin, commit or roll back a transaction itself. An owned handle follows the normal ns_db releasehandle cleanup path, including driver flush/reset. Finish transactions and consume results before leaving an owning scope; do not return its handle for later use or manually release it inside the body. Keep unrelated work outside the scope to avoid holding a connection unnecessarily. Borrowed handles retain their existing transaction and result-set state except for changes explicitly made by the body.

 ns_db withhandle -pool records -timeout 100ms db {
     ns_db dml $db -bindvars {
         UPDATE records SET value = :value WHERE id = :id
     }
 }
 # Use a caller-owned connection without returning it to the pool.
 ns_db withhandle -handle $transactionHandle db {
     update_records $db
 }
ns_dberrorcode handle

Returns the database error code for the specified database handle.

ns_dberrormsg handle

Returns the database error message for the specified database handle.

ns_dbconfigpath

Returns the database section name file for the nsdb module from the configuration file.

ns_dbpooldescription poolname

Returns the description of the provided database pool name from the [ns/db/pools] section in the configuration file.

COMMON BIND OPTIONS

The commands ns_db exec, ns_db dml, ns_db select, ns_db 1row and ns_db 0or1row accept these options after handle and before sql. Without binding options, their existing SQL execution behavior is unchanged. Binding requires a supporting driver; use ns_db bindinfo to check support.

-bindvars

Resolve colon-prefixed SQL parameters from Tcl variables in the caller's scope. For example, :id reads the variable id.

-bindset setId

Resolve parameters from the ns_set identified by setId. Keys are parameter names without the colon prefix.

-binddict dictionary

Resolve parameters from the Tcl dictionary. Keys are parameter names without the colon prefix.

-bindtypes types

Use the Tcl dictionary types to specify parameter interpretations. Keys are parameter names without the colon prefix; values specify scalar, binary, list, rows or array, with optional metadata as described in the bind variables section below. Parameters not listed use scalar. This option requires a binding source.

-emptynull

Map explicitly supplied empty scalar values and empty collection elements to SQL NULL. Without this option, empty text remains empty text. Empty native arrays remain empty arrays; empty list and row containers are errors. Explicit binary values are also mapped to NULL when empty. This option requires a binding source and does not permit missing bindings.

--

End option processing, for example when the SQL argument starts with a hyphen.

Exactly one of -bindvars, -bindset or -binddict selects the binding source. These sources are mutually exclusive. Missing bindings raise errors; explicit sources never fall back to caller variables.

BIND VARIABLES

Bind variables are named placeholders for values in an SQL statement. The SQL contains names such as :id, where the : denotes the begin of a bind variable and id is its name. The application supplies their values for the used names separately through Tcl variables, an ns_set or a dictionary.

Use binding instead of interpolating or quoting application values into SQL. A bound value is data, even when it contains quotes or SQL syntax. This prevents SQL injection through those values, reduces quoting mistakes and avoids repeated SQL string construction. Table names, column names and SQL fragments cannot be bound: keep these fixed or validate them separately. Binding does not make application-generated SQL fragments safe.

Scalar values

The simplest form uses -bindvars to read Tcl variables from the caller's scope. Brace the SQL so Tcl leaves its text unchanged:

 set id 42
 set row [ns_db 1row $handle -bindvars {
     SELECT label FROM items WHERE id = :id
 }]
 set label [ns_set get $row label]
 ns_set free $row

The same source works for writes. Quotes in label require no application escaping:

 set label "John's item"
 ns_db dml $handle -bindvars {
     UPDATE items SET label = :label WHERE id = :id
 }

Use -binddict when values already reside in a dictionary. Its keys omit the colon prefix; missing keys are errors rather than references to Tcl variables:

 set values [dict create id 42 label "John's item"]
 ns_db dml $handle -binddict $values {
     UPDATE items SET label = :label WHERE id = :id
 }

For an ns_set, use -bindset instead:

 set values [ns_set create bindings id 42 label "John's item"]
 ns_db dml $handle -bindset $values {
     UPDATE items SET label = :label WHERE id = :id
 }
 ns_set free $values

Scalar is the default interpretation, including for numeric Tcl objects and values whose internal representation happens to be a list or bytearray. The database applies its normal column conversions. Use -bindtypes only when a different interpretation of the supplied values is required.

Lists and rows

A list expands a Tcl list into separate parameters. SQL supplies the surrounding parentheses, as in an IN clause:

 set ids {42 57 91}
 set status active
 set rows [ns_db select $handle -bindvars -bindtypes {ids list} {
     SELECT id FROM items WHERE id IN (:ids) AND status = :status
 }]
 while {[ns_db getrow $handle $rows]} {
     # Consume each row using ns_set.
 }
 ns_db flush $handle
 ns_set free $rows

A rows value expands equal-width Tcl row lists into parenthesized rows of parameters. Do not add parentheses around its placeholder:

 set values {{42 first} {57 second}}
 ns_db dml $handle -bindvars -bindtypes {values rows} {
     INSERT INTO items (id, label) VALUES :values
 }

Lists and rows must be nonempty and well formed. Rows must have a nonzero, consistent width. Values remain parameters; no element is concatenated into SQL. Row cells use scalar semantics unless column types specify binary values.

Binary values

binary uses Tcl bytearray semantics, without decoding hex or base64. It supports embedded NUL and high bytes; SQLite stores these values as BLOBs:

 set payload [binary format H* 00ff0102]
 ns_db dml $handle -bindvars -bindtypes {payload binary} {
     INSERT INTO payloads (data) VALUES (:payload)
 }

For rows, specify one type per column. Only scalar and binary column types are supported, and the type list must match the row width:

 set key [binary format H* 00ff]
 set values [list [list $key 192.0.2.1 1700000000]]
 ns_db dml $handle -bindvars \
     -bindtypes {values {rows {binary scalar scalar}}} {
         INSERT INTO peers (k, address, seen) VALUES :values
     }

Drivers without binary support reject explicit binary values instead of silently converting them to text.

Native SQL arrays

array binds a Tcl list as one native one-dimensional SQL array parameter. Unlike list, it does not expand into separate SQL parameters. PostgreSQL supports this form; unsupported drivers reject it explicitly. A SQL cast or the target column determines the element type:

 set ids {42 57 91}
 set rows [ns_db select $handle -bindvars -bindtypes {ids array} {
     SELECT id FROM items WHERE id = ANY(:ids::integer[])
 }]
 while {[ns_db getrow $handle $rows]} {
     # Consume each row using ns_set.
 }
 ns_db flush $handle
 ns_set free $rows

Empty arrays are valid. Nested Tcl lists are text elements, not subarrays. Optional array delimiter metadata selects a printable, non-reserved ASCII delimiter; the default is a comma. Literal text such as NULL never acts as a special sentinel.

Empty values and SQL NULL

By default, an empty scalar is empty text and an empty binary value is a zero-length binary value. SQL NULL is different from both. Use -emptynull when explicitly supplied empty values should mean SQL NULL:

 set id 42
 set label {}
 ns_db dml $handle -bindvars -emptynull {
     UPDATE items SET label = :label WHERE id = :id
 }

This stores SQL NULL in label. Without -emptynull, it stores empty text. The option applies to all supplied empty scalar and binary values, list elements, row cells and native array elements in the call. It preserves an empty native array as an empty array; it does not make empty list or row containers valid. There is no magic string representing NULL. Missing bindings always raise errors, even with -emptynull.

Execution and parameter names

Each command retains its usual result and transaction behavior. Binding neither commits nor rolls back. One complete SQL statement is executed; additional SQL after it is rejected. Unsupported drivers raise errors when binding is requested. ns_db bindinfo checks support, and its -types form reports native parameter types. Malformed types, unused type metadata and missing bindings are errors before execution. SQL logging records the template rather than bound values. Text values and SQL containing NUL are rejected; use binary binding for binary data.

Parameter names follow ns_pg_bind: the first byte must be a letter (C isalpha) or underscore; subsequent bytes may be alphanumeric (C isalnum), underscore, dollar sign or number sign. Classification uses the current C locale, not Unicode character properties. For example, :phone# and :oracle$number each identify one parameter. Dollar signs continue names; use colon-prefixed names in application SQL.

SQL literals, quoted identifiers, doubled quote delimiters, SQLite bracket and backtick identifiers, and line/block comments do not introduce parameters. PostgreSQL casts are skipped. PostgreSQL escape-string and dollar-quoted bodies are not implemented by this lexer.

Caching and driver integration

The SQL Tcl object caches parsed parameter names and externally encoded SQL. Collection expansion caches one SQL shape; changing collection lengths rebuilds that shape without reparsing the original SQL. Every call resolves current values. This is not a connection-level prepared-statement cache.

Expanded parameters use driver markers that cannot collide with application names. Changes to SQL text, the expansion shape, marker factory or system encoding invalidate the corresponding cached representation. Shared plans and encoded buffers remain retained during nested driver calls.

Driver authors can implement DbFn_Bind for scalar text or DbFn_BindTyped for typed parameters. The typed callback is preferred; a NULL types array means all text, and registering only the typed callback is sufficient. Native arrays additionally require the corresponding driver support.

CONFIGURATION

The nsdb module is typically loaded per-server, where every server might use multiple database pools. Below is a sample configuration for PostgreSQL using the nsdbpg driver, using two database pools where pool1 is the default pool.

 ns_section "ns/db/drivers" {
   ns_param	postgres        ${bindir}/nsdbpg.so
 }
 
 ns_section ns/server/${server}/modules {
   ns_param	nsdb		${bindir}/nsdb.so
 }
 
 ns_section ns/server/${server}/db {
   ns_param	pools           pool1,pool2
   ns_param	defaultpool     pool1
 }
 
 ns_section ns/db/pools {
   ns_param	pool1           "Pool 1"
   ns_param	pool2           "Pool 2"
 }
 
 ns_section ns/db/pool/pool1 {
   ns_param	...
 }

For every pool the following configuration options might be used:

CheckInterval

Check after this time interval for stale connections. Default: 5m.

Connections

Integer: The maximum number of connections that can be established at any one time. The server automatically makes connections as needed up to this maximum number. If additional connections are requested during processing, the requests must wait. Default: 2

Datasource

Name specific to the database management system that might be necessary for opening database connections. For PostgreSQL, datasource has the form "${db_host}:${db_port}:${db_name}". See also: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS

Driver

Name of the driver for this pool as specified in ns/db/drivers.

LogMinDuration

Time interval for logging SQL statements. When SQL logging is turned on, log only SQL queries that take longer than the specified duration (similar to log_min_duration_statement in PostgreSQL). Setting LogMinDuration to 0 causes all SQL statements to be logged.

LogSQLErrors

Boolean value: If set to On, SQL errors are written to the server log along with the offending SQL statement(s).

MaxIdle

The maximum time interval that a database connection within this pool can remain open and idle. The default setting of "10m" causes connections that are idle for 10 minutes to be closed. Note that MaxIdle will not have an effect if it is equal to MaxOpen. Setting MaxIdle to 0 deactivates the automatic closing feature on idle connections. Default: 5m

MaxOpen

The maximum time interval that a database connection within this pool can remain open. The default setting of "60m" causes connections to keep open for one hour regardless of activity level. Database connections will then be opened again as needed up to the value of the Connections parameter. It is recommended that MaxOpen be a multiple of MaxIdle; otherwise, MaxOpen may be off by as much as (MaxOpen mod MaxIdle). Setting MaxOpen to 0 deactivates the automatic closing feature. Default: 60m

Password

Password to log in to the database.

User

Username to log in to the database.

All time intervals can be specified with and without a time unit suffix. Valid time units are "ms", "s", "m", "h", "d". If no time unit suffix is specified, seconds are assumed.

Below is a sample configuration for two pools. The referenced Tcl variables have to be set earlier to appropriate values.

 ns_section ns/db/pool/pool1 {
   ns_param	Connections        15
   ns_param     LogMinDuration     10ms
   ns_param	LogSQLerrors       $debug
   ns_param	driver             postgres
   ns_param	DataSource         ${db_host}:${db_port}:${db_name}
   ns_param	user               $db_user
   ns_param	password           ""
 }
 ns_section ns/db/pool/pool2 {
   ns_param	Connections        5
   ns_param     LogMinDuration     10ms
   ns_param	LogSQLerrors       $debug
   ns_param	driver             postgres
   ns_param	DataSource         ${db_host}:${db_port}:${db_name}
   ns_param	user               $db_user
   ns_param	password           ""
 }

See Also

ns_buildsqldate, ns_dbquotevalues

Keywords

SQL, database, module, nsdb, pools, server built-in