numbox.core.bindings.sqlite

The numbox.core.bindings.sqlite subpackage holds the bindings to SQLite’s C API and the helpers built on them, one module for each group. Import a function from its module, as in from numbox.core.bindings.sqlite.conn import sqlite3_open. The package’s __init__ is empty, so importing a module imports and compiles only that module and the sibling modules it uses. A binding module such as conn uses none. The helper modules query, tvf, vtable and udf_helpers import the binding modules they call.

numbox.core.bindings.sqlite.conn

Bindings that open and close a SQLite connection and report its state.

The module binds sqlite3_open, sqlite3_open_v2 and sqlite3_close, and the functions that report the library’s version, the error of the most recent failed call, a database’s file name and read-only state, and the counts of changed rows. SQLite added sqlite3_changes64 and sqlite3_total_changes64 in version 3.37, released in November 2021. Older libraries lack them, such as the SQLite 3.34 that CPython 3.10 ships on Windows, or a system SQLite on Linux or macOS older than 3.37. Each of the two bindings is a stub if the loaded library lacks its function, as its docstring describes.

numbox.core.bindings.sqlite.conn.sqlite3_changes(db_p)[source]

Return the number of rows that the most recent completed INSERT, UPDATE or DELETE on db_p changed.

C reference: sqlite3_changes.

The count excludes the rows that triggers, foreign key actions and REPLACE conflict resolution changed. Above the int32 range the value is undefined; sqlite3_changes64() returns it as an int64.

numbox.core.bindings.sqlite.conn.sqlite3_changes64(db_p)[source]

Return the count of sqlite3_changes() as an int64.

C reference: sqlite3_changes64.

SQLite added the function in version 3.37. If the loaded library is older, this binding is a stub: a call from Python raises NotImplementedError, and a jitted call fails to compile with a TypingError. A stub has no as_func, so hasattr(sqlite3_changes64, "as_func") is true only when the binding is present.

numbox.core.bindings.sqlite.conn.sqlite3_close(db_p)[source]

Close the connection db_p and free its resources, and return SQLITE_OK.

C reference: sqlite3_close.

SQLite returns SQLITE_BUSY and leaves the connection open while a prepared statement on it is not finalized or a BLOB handle is not closed. It rolls back a transaction that is still open. A call with a handle of 0 does nothing.

numbox.core.bindings.sqlite.conn.sqlite3_db_filename(db_p, name_p)[source]

Return the address of the absolute file name of the database named at name_p on the connection db_p.

C reference: sqlite3_db_filename.

name_p is the address of the database’s name: "main", "temp" or the name of an attached database. Returns 0 or an empty string for a temporary or in-memory database, and for a name that the connection lacks. The connection owns the text, which stays valid until the database is detached or the connection closes.

numbox.core.bindings.sqlite.conn.sqlite3_db_handle(stmt_p)[source]

Return the handle of the connection on which the statement stmt_p was prepared.

C reference: sqlite3_db_handle.

numbox.core.bindings.sqlite.conn.sqlite3_db_readonly(db_p, name_p)[source]

Return 1 if the database named at name_p is read-only, 0 if it is writable, and -1 if db_p lacks it.

C reference: sqlite3_db_readonly.

name_p is the address of the database’s name, as for sqlite3_db_filename().

numbox.core.bindings.sqlite.conn.sqlite3_errcode(db_p)[source]

Return the result code of the most recent failed call on the connection db_p.

C reference: sqlite3_errcode.

The code is a primary one, such as SQLITE_CONSTRAINT, unless the connection uses extended result codes. Any later call on the connection may change it.

numbox.core.bindings.sqlite.conn.sqlite3_errmsg(db_p)[source]

Return the address of SQLite’s English message, in UTF-8, for the most recent error on the connection db_p.

C reference: sqlite3_errmsg.

SQLite owns the text, and the next call on the connection may overwrite or free it, so copy it at once, as get_str_from_p_as_int() does. Returns 0 when no message is available.

numbox.core.bindings.sqlite.conn.sqlite3_extended_errcode(db_p)[source]

Return the extended result code of the most recent failed call on the connection db_p.

C reference: sqlite3_extended_errcode.

The low 8 bits of an extended code are its primary code, one of the result codes of constants.

numbox.core.bindings.sqlite.conn.sqlite3_last_insert_rowid(db_p)[source]

Return the rowid of the most recent successful INSERT into a rowid table on db_p, or 0 if there was none.

C reference: sqlite3_last_insert_rowid.

numbox.core.bindings.sqlite.conn.sqlite3_libversion()[source]

Return the address of the loaded library’s version string, such as "3.45.1".

C reference: sqlite3_libversion.

The string is a constant of the library, valid for the life of the process. Python code reads it with get_str_from_p_as_int().

numbox.core.bindings.sqlite.conn.sqlite3_libversion_number()[source]

Return the loaded library’s version as an integer, such as 3045001 for version 3.45.1.

C reference: sqlite3_libversion_number.

numbox.core.bindings.sqlite.conn.sqlite3_open(filename_p, db_pp)[source]

Open the database file named at filename_p and write the new connection’s handle to db_pp.

C reference: sqlite3_open.

filename_p is the address of a NUL-terminated UTF-8 file name, and ":memory:" opens a private in-memory database. SQLite opens the file for reading and writing and creates it if it does not exist. db_pp is the address of an intp that receives the handle, such as ctypes.addressof of a ctypes.c_int64. Returns SQLITE_OK, or an error code that sqlite3_errmsg() explains. SQLite writes a handle even when the open fails, unless it cannot allocate one, and the caller closes it with sqlite3_close() in either case.

numbox.core.bindings.sqlite.conn.sqlite3_open_v2(filename_p, db_pp, flags, vfs_p)[source]

Open the database file named at filename_p in the mode that flags sets; write the handle to db_pp.

C reference: sqlite3_open_v2.

flags holds SQLITE_OPEN_READONLY, SQLITE_OPEN_READWRITE, or SQLITE_OPEN_READWRITE with SQLITE_OPEN_CREATE, and may add other SQLITE_OPEN_* flags of constants with a bitwise OR. vfs_p is the address of the name of a VFS, or 0 for the default one. The file name, the handle and the result code have the meaning that sqlite3_open() describes.

numbox.core.bindings.sqlite.conn.sqlite3_threadsafe()[source]

Return 0 if the loaded library was compiled without its mutexes, and a nonzero value otherwise.

C reference: sqlite3_threadsafe.

The value reports the compile-time setting SQLITE_THREADSAFE, not a threading mode set later at run time.

numbox.core.bindings.sqlite.conn.sqlite3_total_changes(db_p)[source]

Return the number of rows changed by every INSERT, UPDATE and DELETE on db_p since the connection opened.

C reference: sqlite3_total_changes.

The count includes the rows that triggers and foreign key actions changed, and it excludes the rows that REPLACE conflict resolution changed. Above the int32 range the value is undefined; sqlite3_total_changes64() returns it as an int64.

numbox.core.bindings.sqlite.conn.sqlite3_total_changes64(db_p)[source]

Return the count of sqlite3_total_changes() as an int64.

C reference: sqlite3_total_changes64.

SQLite added the function in version 3.37. If the loaded library is older, this binding is a stub, as sqlite3_changes64() describes.

numbox.core.bindings.sqlite.stmt

Bindings that prepare, step, reset and finalize a SQLite statement.

The module binds sqlite3_prepare_v2, sqlite3_step, sqlite3_reset and sqlite3_finalize, and sqlite3_sql, sqlite3_expanded_sql and sqlite3_stmt_busy, which report a statement’s text and state. sqlite3_expanded_sql returns a char * that the caller must free with sqlite3_free, which exec binds.

numbox.core.bindings.sqlite.stmt.sqlite3_expanded_sql(stmt_p)[source]

Return the address of the SQL text of the statement stmt_p, with the bound parameter values written in.

C reference: sqlite3_expanded_sql.

SQLite allocates the text, and the caller frees it with sqlite3_free. Returns 0 when an allocation fails, when the text would exceed SQLite’s length limit, and in a SQLite built with SQLITE_OMIT_TRACE.

numbox.core.bindings.sqlite.stmt.sqlite3_finalize(stmt_p)[source]

Delete the prepared statement stmt_p, and return SQLITE_OK or the error code of its last failed step.

C reference: sqlite3_finalize.

A call with a handle of 0 does nothing. Any use of the statement after this call is undefined, and can crash the process.

numbox.core.bindings.sqlite.stmt.sqlite3_prepare_v2(db_p, sql_p, n_byte, stmt_pp, tail_pp)[source]

Compile the first SQL statement of the text at sql_p on db_p and write its handle to stmt_pp.

C reference: sqlite3_prepare_v2.

sql_p is the address of UTF-8 SQL text, and n_byte its length in bytes, or -1 to read up to the first NUL. stmt_pp is the address of an intp that receives the statement’s handle, or 0 after an error or for text that holds no statement. Unless tail_pp is 0, it receives the address of the text after the first statement. Returns SQLITE_OK or an error code. The caller finalizes the statement with sqlite3_finalize().

numbox.core.bindings.sqlite.stmt.sqlite3_reset(stmt_p)[source]

Reset the statement stmt_p to run again from the start, and return SQLITE_OK or an error code.

C reference: sqlite3_reset.

The parameters keep their bound values. The code is the error of the most recent step, if it failed. The reset itself can fail too, for example with SQLITE_BUSY when a statement stepped only once cannot commit, so check the code even when every step succeeded.

numbox.core.bindings.sqlite.stmt.sqlite3_sql(stmt_p)[source]

Return the address of the UTF-8 SQL text from which the statement stmt_p was prepared.

C reference: sqlite3_sql.

The statement owns the text, and SQLite frees it when the statement is finalized.

numbox.core.bindings.sqlite.stmt.sqlite3_step(stmt_p)[source]

Run the statement stmt_p to its next result row, and return SQLITE_ROW, SQLITE_DONE or an error code.

C reference: sqlite3_step.

After SQLITE_ROW, the bindings of column read the row. After SQLITE_DONE or an error, the statement must be reset before it is stepped again. SQLITE_BUSY means that SQLite could not take a lock that it needs.

numbox.core.bindings.sqlite.stmt.sqlite3_stmt_busy(stmt_p)[source]

Return a nonzero value if stmt_p has been stepped but has neither finished nor been reset, and 0 otherwise.

C reference: sqlite3_stmt_busy.

numbox.core.bindings.sqlite.bind

Bindings that bind values to the parameters of a prepared SQLite statement.

Each binding takes the statement’s handle and the parameter’s index, which counts from 1, and returns SQLITE_OK, SQLITE_RANGE for an index out of range, or SQLITE_MISUSE for a statement that has been stepped since its last reset. sqlite3_bind_text and sqlite3_bind_blob take a destructor as their last argument, an intp that sets how SQLite manages the lifetime of the buffer:

  • SQLITE_STATIC (0): SQLite reads the buffer in place until the statement is finalized or the parameter is bound again, so the caller keeps the buffer alive and unchanged until then.

  • SQLITE_TRANSIENT (-1): SQLite copies the buffer before the call returns.

  • Any other value: the address of a C function that SQLite calls to free the buffer when SQLite no longer needs it.

For a NumPy array passed through array_data_p, pass SQLITE_TRANSIENT unless the array outlives the prepared statement.

numbox.core.bindings.sqlite.bind.sqlite3_bind_blob(stmt_p, idx, data_p, n, destructor)[source]

Bind the n bytes at data_p as a BLOB to the parameter idx of the statement stmt_p.

C reference: sqlite3_bind_blob.

n must not be negative, and numba converts it to int32 without a check. A destructor of SQLITE_TRANSIENT makes SQLite copy the bytes before the call returns. With SQLITE_STATIC, SQLite reads the bytes in place, and the caller keeps them alive and unchanged until the statement is finalized or the parameter is bound again. Any other value is the address of a C function that SQLite calls to free the bytes. A data_p of 0 binds NULL. Returns SQLITE_OK, SQLITE_RANGE for an index out of range, SQLITE_MISUSE if the statement has been stepped since its last reset, or SQLITE_TOOBIG for a BLOB longer than SQLite’s limit.

numbox.core.bindings.sqlite.bind.sqlite3_bind_double(stmt_p, idx, val)[source]

Bind the float64 val to the parameter idx of the statement stmt_p, counted from 1.

C reference: sqlite3_bind_double.

Returns SQLITE_OK, SQLITE_RANGE for an index out of range, or SQLITE_MISUSE if the statement has been stepped since its last reset.

numbox.core.bindings.sqlite.bind.sqlite3_bind_int(stmt_p, idx, val)[source]

Bind the int32 val to the parameter idx of the statement stmt_p, counted from 1.

C reference: sqlite3_bind_int.

numba converts val to int32 without a check, so a wider value is truncated to its low 32 bits; bind it with sqlite3_bind_int64() instead. Returns SQLITE_OK, SQLITE_RANGE for an index out of range, or SQLITE_MISUSE if the statement has been stepped since its last reset.

numbox.core.bindings.sqlite.bind.sqlite3_bind_int64(stmt_p, idx, val)[source]

Bind the int64 val to the parameter idx of the statement stmt_p, counted from 1.

C reference: sqlite3_bind_int64.

Returns SQLITE_OK, SQLITE_RANGE for an index out of range, or SQLITE_MISUSE if the statement has been stepped since its last reset.

numbox.core.bindings.sqlite.bind.sqlite3_bind_null(stmt_p, idx)[source]

Bind SQL NULL to the parameter idx of the statement stmt_p, counted from 1.

C reference: sqlite3_bind_null.

A parameter that is never bound is NULL as well. Returns SQLITE_OK, SQLITE_RANGE for an index out of range, or SQLITE_MISUSE if the statement has been stepped since its last reset.

numbox.core.bindings.sqlite.bind.sqlite3_bind_parameter_count(stmt_p)[source]

Return the largest parameter index of the statement stmt_p, 0 if it has no parameters.

C reference: sqlite3_bind_parameter_count.

The index equals the number of parameters unless parameters of the form ?NNN leave gaps between indexes.

numbox.core.bindings.sqlite.bind.sqlite3_bind_parameter_index(stmt_p, name_p)[source]

Return the index of the parameter of stmt_p named by the UTF-8 text at name_p, or 0 if there is none.

C reference: sqlite3_bind_parameter_index.

The name includes its first character, as in ":rate" or "$rate".

numbox.core.bindings.sqlite.bind.sqlite3_bind_parameter_name(stmt_p, idx)[source]

Return the address of the UTF-8 name of the parameter idx of the statement stmt_p, counted from 1.

C reference: sqlite3_bind_parameter_name.

The name includes its first character, as in ":rate". Returns 0 for a nameless ? parameter and for an index out of range.

numbox.core.bindings.sqlite.bind.sqlite3_bind_text(stmt_p, idx, text_p, n, destructor)[source]

Bind the UTF-8 text at text_p, n bytes long, to the parameter idx of the statement stmt_p.

C reference: sqlite3_bind_text.

A negative n makes SQLite read up to the first NUL, and numba converts n to int32 without a check. A destructor of SQLITE_TRANSIENT makes SQLite copy the text before the call returns. With SQLITE_STATIC, SQLite reads the text in place, and the caller keeps it alive and unchanged until the statement is finalized or the parameter is bound again. Any other value is the address of a C function that SQLite calls to free the text. A text_p of 0 binds NULL. Returns SQLITE_OK, SQLITE_RANGE for an index out of range, SQLITE_MISUSE if the statement has been stepped since its last reset, or SQLITE_TOOBIG for text longer than SQLite’s limit.

numbox.core.bindings.sqlite.column

Bindings that read the current result row of a prepared SQLite statement and describe its columns.

Each binding takes the statement’s handle and a column index that counts from 0. A binding that reads a value may be called only after sqlite3_step returned SQLITE_ROW, and before the statement is stepped again, reset or finalized. sqlite3_column_database_name, sqlite3_column_table_name and sqlite3_column_origin_name exist only in a SQLite compiled with SQLITE_ENABLE_COLUMN_METADATA. CPython’s sqlite3.dll on Windows has them, and numbox loads only that DLL on Windows. On Linux and macOS, numbox loads the system’s SQLite, and whether that library has them depends on the distribution. If the loaded library lacks one of them, its binding is a stub, as its docstring describes. Every other binding of the module exists in every SQLite that numbox supports.

numbox.core.bindings.sqlite.column.sqlite3_column_blob(stmt_p, idx)[source]

Return the address of the bytes of column idx of the current row, or 0 for NULL and for an empty BLOB.

C reference: sqlite3_column_blob.

SQLite owns the bytes. They stay valid until the statement is stepped, reset or finalized, or until another accessor converts the same column. Call sqlite3_column_bytes() after this call for their number.

numbox.core.bindings.sqlite.column.sqlite3_column_bytes(stmt_p, idx)[source]

Return the length in bytes of column idx as a BLOB or as UTF-8 text, without a NUL, and 0 for NULL.

C reference: sqlite3_column_bytes.

Call it after sqlite3_column_text() or sqlite3_column_blob(), because either of them can convert the value and change its length.

numbox.core.bindings.sqlite.column.sqlite3_column_count(stmt_p)[source]

Return the number of columns in the result of the statement stmt_p, 0 for a statement that returns no data.

C reference: sqlite3_column_count.

A positive count does not mean that the statement returns any rows.

numbox.core.bindings.sqlite.column.sqlite3_column_database_name(stmt_p, idx)[source]

Return the address of the name of the database from which column idx of the statement stmt_p comes.

C reference: sqlite3_column_database_name.

Returns 0 for a column that is an expression or a subquery. The UTF-8 text is valid until the statement is finalized or prepared again. SQLite has the function only when it is compiled with SQLITE_ENABLE_COLUMN_METADATA. If the loaded library lacks it, this binding is a stub: a call from Python raises NotImplementedError, and a jitted call fails to compile with a TypingError. A stub has no as_func, so hasattr(sqlite3_column_database_name, "as_func") is true only when the binding is present.

numbox.core.bindings.sqlite.column.sqlite3_column_decltype(stmt_p, idx)[source]

Return the address of the declared type of column idx of the result, or 0 when the column is an expression.

C reference: sqlite3_column_decltype.

The UTF-8 text is the type in the table’s definition. SQLite assigns a type to each value, not to each column, so a value need not have the declared type of its column.

numbox.core.bindings.sqlite.column.sqlite3_column_double(stmt_p, idx)[source]

Return the value of column idx of the current row of stmt_p, counted from 0, as a float64.

C reference: sqlite3_column_double.

The binding returns 0.0 for NULL. SQLite converts an integer or a text value as SQL’s CAST to REAL does.

numbox.core.bindings.sqlite.column.sqlite3_column_int(stmt_p, idx)[source]

Return the value of column idx of the current row of stmt_p, counted from 0, as an int32.

C reference: sqlite3_column_int.

SQLite converts a value of another type, and the binding returns 0 for NULL. A value outside the int32 range is truncated to its low 32 bits; sqlite3_column_int64() reads all 64 bits.

numbox.core.bindings.sqlite.column.sqlite3_column_int64(stmt_p, idx)[source]

Return the value of column idx of the current row of stmt_p, counted from 0, as an int64.

C reference: sqlite3_column_int64.

The binding returns 0 for NULL. SQLite converts a REAL or a text value as SQL’s CAST to INTEGER does.

numbox.core.bindings.sqlite.column.sqlite3_column_name(stmt_p, idx)[source]

Return the address of the UTF-8 name of column idx of the result of the statement stmt_p.

C reference: sqlite3_column_name.

The name is the one that the column’s AS clause sets. If the column has no AS clause, SQLite does not specify its name. The text is valid until the statement is finalized, until its first step prepares it again, or until the next call for the same column. Returns 0 when an allocation fails.

numbox.core.bindings.sqlite.column.sqlite3_column_origin_name(stmt_p, idx)[source]

Return the address of the name of the table column from which column idx of the statement stmt_p comes.

C reference: sqlite3_column_origin_name.

Returns 0 for a column that is an expression or a subquery. The name is the column’s original name, not an alias. If the loaded library lacks the function, this binding is a stub, as sqlite3_column_database_name() describes.

numbox.core.bindings.sqlite.column.sqlite3_column_table_name(stmt_p, idx)[source]

Return the address of the name of the table from which column idx of the statement stmt_p comes.

C reference: sqlite3_column_table_name.

Returns 0 for a column that is an expression or a subquery. The name is the table’s original name, not an alias. If the loaded library lacks the function, this binding is a stub, as sqlite3_column_database_name() describes.

numbox.core.bindings.sqlite.column.sqlite3_column_text(stmt_p, idx)[source]

Return the address of the value of column idx as NUL-terminated UTF-8 text, or 0 for NULL.

C reference: sqlite3_column_text.

SQLite owns the text. It stays valid until the statement is stepped, reset or finalized, or until another accessor converts the same column. Call sqlite3_column_bytes() after this call for the length in bytes.

numbox.core.bindings.sqlite.column.sqlite3_column_type(stmt_p, idx)[source]

Return the type code of the value of column idx of the current row of stmt_p, counted from 0.

C reference: sqlite3_column_type.

The code is SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB or SQLITE_NULL, and it describes the value before any conversion. After another accessor converts the value, the result is undefined, so read the type first.

numbox.core.bindings.sqlite.exec

Bindings for sqlite3_exec, which runs SQL text in one call, and for SQLite’s memory allocator.

sqlite3_exec prepares, steps and finalizes each statement of a SQL text, which may hold several statements. It can call a C function once for each result row, with this type:

int (*callback)(void *ctx, int ncol, char **col_values, char **col_names)

ctx is the pointer that the caller passed to sqlite3_exec. col_values and col_names are arrays of ncol addresses of NUL-terminated UTF-8 strings, valid only during the call, and a NULL value has the address 0. The callback returns 0 to continue. Any other value stops sqlite3_exec, which then returns SQLITE_ABORT. numba’s cfunc compiles such a function, and its .address is the value to pass. Here the callback stores the number of rows in a NumPy array:

from ctypes import addressof, c_int64

import numpy as np
from numba import carray, cfunc, types

from numbox.core.bindings.sqlite.conn import sqlite3_close, sqlite3_open
from numbox.core.bindings.sqlite.exec import sqlite3_exec
from numbox.utils.cstrings import c_string


@cfunc(types.int32(types.voidptr, types.int32, types.intp, types.intp))
def count_rows(ctx, ncol, col_values, col_names):
    count = carray(ctx, 1, dtype=np.int64)
    count[0] += 1
    return 0


db_p = c_int64(0)
with c_string(":memory:") as path_p:
    sqlite3_open(path_p, addressof(db_p))
count = np.zeros(1, dtype=np.int64)
with c_string("SELECT 1 UNION ALL SELECT 2") as sql_p:
    rc = sqlite3_exec(db_p.value, sql_p, count_rows.address, count.ctypes.data, 0)
print(rc, count[0])   # 0 2
sqlite3_close(db_p.value)

sqlite3_free releases memory that SQLite allocated for the caller, such as the error message of sqlite3_exec and the text of sqlite3_expanded_sql. sqlite3_malloc allocates such memory; numbox’s virtual tables allocate their sqlite3_vtab and cursor structs with it.

numbox.core.bindings.sqlite.exec.sqlite3_exec(db_p, sql_p, cb_p, ctx_p, errmsg_pp)[source]

Run each SQL statement of the UTF-8 text at sql_p on the connection db_p, and return a result code.

C reference: sqlite3_exec.

cb_p is 0, or the address of a row callback of the type that the module docstring gives, and SQLite passes ctx_p to that callback. If a statement fails, SQLite stops and skips the statements after it. Unless errmsg_pp is 0, SQLite then writes to it the address of an error message, which the caller frees with sqlite3_free(). If every statement succeeds, SQLite writes 0 there. Returns SQLITE_OK, SQLITE_ABORT when the callback returned a nonzero value, or the error code of the statement that failed.

numbox.core.bindings.sqlite.exec.sqlite3_free(mem_p)[source]

Free memory that SQLite allocated, such as the error message of sqlite3_exec().

C reference: sqlite3_free.

A call with a pointer of 0 does nothing. Freeing a pointer that SQLite’s allocator did not return can corrupt memory or crash the process. Reading the memory after it is freed can have the same effect.

numbox.core.bindings.sqlite.exec.sqlite3_malloc(n)[source]

Allocate at least n bytes with SQLite’s allocator and return their address, or 0 if the allocation fails.

C reference: sqlite3_malloc.

Returns 0 as well for an n of 0 or less, and numba converts n to int32 without a check. The memory is not zeroed. It is aligned to at least 8 bytes unless SQLite was built with SQLITE_4_BYTE_ALIGNED_MALLOC, and the caller frees it with sqlite3_free().

numbox.core.bindings.sqlite.blob

Bindings for SQLite’s incremental BLOB I/O, which reads and writes part of a stored value without loading the rest.

The module binds sqlite3_blob_open, sqlite3_blob_close, sqlite3_blob_bytes, sqlite3_blob_read, sqlite3_blob_write and sqlite3_blob_reopen. Each of them exists in SQLite from version 3.4.0, released in 2007, except sqlite3_blob_reopen, which SQLite added in version 3.7.4, released in 2010. Both versions are older than 3.34, the oldest SQLite in numbox’s test matrix, so every binding of the module is present.

numbox.core.bindings.sqlite.blob.sqlite3_blob_bytes(blob_p)[source]

Return the size in bytes of the value open on the BLOB handle blob_p.

C reference: sqlite3_blob_bytes.

Incremental I/O cannot change the size; an UPDATE statement can.

numbox.core.bindings.sqlite.blob.sqlite3_blob_close(blob_p)[source]

Close the BLOB handle blob_p, and return SQLITE_OK or an error code.

C reference: sqlite3_blob_close.

The handle is closed even when the call returns an error. If the handle was writable and the connection is in autocommit mode, the close can commit the transaction. A call with a handle of 0 does nothing.

numbox.core.bindings.sqlite.blob.sqlite3_blob_open(db_p, db_name_p, table_p, col_p, rowid, flags, blob_pp)[source]

Open the value in column col_p of row rowid for incremental I/O, and write the handle to blob_pp.

C reference: sqlite3_blob_open.

db_name_p, table_p and col_p are the addresses of UTF-8 names. The database’s name is "main", "temp" or the name of an attached database, not a file name. flags is SQLITE_BLOB_READONLY (0) or SQLITE_BLOB_READWRITE (1). Returns SQLITE_OK, or SQLITE_ERROR when the database, the table, the column or the row does not exist, or when the value is neither a BLOB nor text. After any error but SQLITE_MISUSE, blob_pp holds 0. The caller closes the handle with sqlite3_blob_close().

numbox.core.bindings.sqlite.blob.sqlite3_blob_read(blob_p, buf_p, n, offset)[source]

Copy n bytes of the value open on blob_p, from byte offset, into the buffer at buf_p.

C reference: sqlite3_blob_read.

Returns SQLITE_OK, or SQLITE_ERROR with nothing read when offset + n exceeds the size or either is negative. Returns SQLITE_ABORT when a change to the row has expired the handle. numba converts n and offset to int32 without a check.

numbox.core.bindings.sqlite.blob.sqlite3_blob_reopen(blob_p, new_rowid)[source]

Move the BLOB handle blob_p to row new_rowid of the same table and column, and return a result code.

C reference: sqlite3_blob_reopen.

The new row must exist and hold a BLOB or text in the column. An error aborts the handle: every later read, write or move returns SQLITE_ABORT, and sqlite3_blob_bytes() returns 0.

numbox.core.bindings.sqlite.blob.sqlite3_blob_write(blob_p, buf_p, n, offset)[source]

Copy n bytes from the buffer at buf_p into the value open on blob_p, from byte offset.

C reference: sqlite3_blob_write.

Returns SQLITE_OK, SQLITE_READONLY for a handle opened read-only, SQLITE_ERROR with nothing written when offset + n exceeds the size or either is negative, or SQLITE_ABORT when a change to the row has expired the handle. The write cannot increase the size of the value. numba converts n and offset to int32 without a check.

numbox.core.bindings.sqlite.hooks

Bindings that install SQLite’s callback hooks on a connection.

The module binds sqlite3_update_hook, sqlite3_progress_handler, sqlite3_busy_handler, sqlite3_commit_hook, sqlite3_rollback_hook and sqlite3_trace_v2. Each takes the callback as the intp address of a C function, such as the .address of a function that numba’s cfunc compiles. Each binding’s docstring gives the C type that its callback must have, and neither numbox nor SQLite checks that type. A connection has at most one callback of each kind, and installing a callback replaces the previous one. Keep the cfunc object referenced for as long as its hook is installed, for example at module level in the caller’s code. numba keeps a cfunc’s compiled code for the life of the process even after the object is collected, but it does not document that behavior.

numbox.core.bindings.sqlite.hooks.sqlite3_busy_handler(db_p, cb_p, ctx_p)[source]

Install cb_p to be called when db_p tries to access a table that another thread or process has locked.

C reference: sqlite3_busy_handler.

The callback has the C type int (*)(void *ctx, int count). It receives ctx_p and the number of earlier calls for the same lock. A return value of 0 makes the waiting call fail with SQLITE_BUSY, and a nonzero return value makes SQLite try again. A cb_p of 0 removes the handler, and sqlite3_busy_timeout or PRAGMA busy_timeout replaces it. The callback must neither change the connection nor close it. Keep the cfunc whose address is cb_p referenced while the handler is installed. Returns a result code.

numbox.core.bindings.sqlite.hooks.sqlite3_commit_hook(db_p, cb_p, ctx_p)[source]

Install cb_p to be called whenever a transaction on db_p commits.

C reference: sqlite3_commit_hook.

The callback has the C type int (*)(void *ctx) and receives ctx_p. A nonzero return value converts the commit into a rollback. The callback must not change the connection, and running any statement counts as a change. A cb_p of 0 removes the hook. Keep the cfunc whose address is cb_p referenced while the hook is installed. Returns the ctx_p of the previous call on the connection, or 0 for the first call.

numbox.core.bindings.sqlite.hooks.sqlite3_progress_handler(db_p, n_ops, cb_p, ctx_p)[source]

Install cb_p to be called about every n_ops virtual machine instructions during long calls on db_p.

C reference: sqlite3_progress_handler.

The callback has the C type int (*)(void *ctx) and receives ctx_p. A nonzero return value interrupts the operation. An n_ops below 1 or a cb_p of 0 removes the handler. The callback must not change the connection. Keep the cfunc whose address is cb_p referenced while the handler is installed.

numbox.core.bindings.sqlite.hooks.sqlite3_rollback_hook(db_p, cb_p, ctx_p)[source]

Install cb_p to be called whenever a transaction on db_p rolls back.

C reference: sqlite3_rollback_hook.

The callback has the C type void (*)(void *ctx) and receives ctx_p. SQLite does not call it for the rollback that closing the connection causes. The callback must not change the connection. A cb_p of 0 removes the hook. Keep the cfunc whose address is cb_p referenced while the hook is installed. Returns the ctx_p of the previous call on the connection, or 0 for the first call.

numbox.core.bindings.sqlite.hooks.sqlite3_trace_v2(db_p, mask, cb_p, ctx_p)[source]

Install cb_p to be called for the trace events in mask on db_p, and return a result code.

C reference: sqlite3_trace_v2.

mask combines SQLITE_TRACE_STMT, SQLITE_TRACE_PROFILE, SQLITE_TRACE_ROW and SQLITE_TRACE_CLOSE with a bitwise OR. The callback has the C type int (*)(unsigned event, void *ctx, void *p, void *x). It receives the event, ctx_p and two pointers whose meaning depends on the event, and it should return 0. A mask of 0 or a cb_p of 0 disables tracing. Keep the cfunc whose address is cb_p referenced while tracing is enabled.

numbox.core.bindings.sqlite.hooks.sqlite3_update_hook(db_p, cb_p, ctx_p)[source]

Install cb_p to be called for every row inserted, updated or deleted in a rowid table on db_p.

C reference: sqlite3_update_hook.

The callback has the C type void (*)(void *ctx, int op, const char *db, const char *table, sqlite3_int64). It receives ctx_p, the operation, the addresses of the database’s and the table’s names, and the rowid. The operation is SQLITE_INSERT (18), SQLITE_DELETE (9) or SQLITE_UPDATE (23), three codes that constants does not define. The callback must not change the connection, and preparing or stepping a statement counts as a change. A cb_p of 0 removes the hook. Keep the cfunc whose address is cb_p referenced while the hook is installed. Returns the ctx_p of the previous call on the connection, or 0 for the first call.

numbox.core.bindings.sqlite.constants

SQLite’s integer constants under their C names, for Python code and jitted code alike.

The module holds the result codes, the column type codes, the flags of sqlite3_open_v2, sqlite3_blob_open and sqlite3_trace_v2, the destructor values SQLITE_STATIC and SQLITE_TRANSIENT, the flags that register a SQL function, and the constraint operators of a virtual table’s xBestIndex. Import a constant by name, as in from numbox.core.bindings.sqlite.constants import SQLITE_OK. The names are the C names, in capitals, so they do not collide with the bindings, which use the lowercase names of SQLite’s functions. numba reads a module-level integer as a constant, so jitted code can use these names directly. SQLite has not changed these values between 3.34.0, the oldest version in numbox’s test matrix, and the current release.

numbox.core.bindings.sqlite.value

Bindings that read a sqlite3_value, such as an argument of a SQL function or a value of a virtual table’s filter.

A SQL function’s xFunc, xStep and xInverse callbacks receive their arguments as argv_pp, the address of an array of sqlite3_value *, and a virtual table’s xFilter receives its values the same way. Each binding of this module takes one element of that array, the intp at the argument’s index. A value is valid while the callback that received it runs, and it must be read in that callback’s thread.

numbox.core.bindings.sqlite.value.sqlite3_value_blob(value_p)[source]

Return the address of the bytes of the sqlite3_value at value_p, or 0 for NULL and for an empty BLOB.

C reference: sqlite3_value_blob.

SQLite owns the bytes. A later call that converts the same value can free them, so call sqlite3_value_bytes() after this call for their number, and use the bytes in the same callback.

numbox.core.bindings.sqlite.value.sqlite3_value_bytes(value_p)[source]

Return the length in bytes of the sqlite3_value at value_p as a BLOB or as UTF-8 text, 0 for NULL.

C reference: sqlite3_value_bytes.

Call it after sqlite3_value_text() or sqlite3_value_blob(), because either of them can convert the value and change its length.

numbox.core.bindings.sqlite.value.sqlite3_value_double(value_p)[source]

Return the sqlite3_value at value_p as a float64.

C reference: sqlite3_value_double.

The binding returns 0.0 for NULL. SQLite converts an integer or a text value as SQL’s CAST to REAL does.

numbox.core.bindings.sqlite.value.sqlite3_value_dup(value_p)[source]

Return the address of a copy of the sqlite3_value at value_p, or 0 if value_p is 0 or the copy fails.

C reference: sqlite3_value_dup.

The copy outlives the callback, and the caller frees it with sqlite3_value_free().

numbox.core.bindings.sqlite.value.sqlite3_value_free(value_p)[source]

Free a sqlite3_value that sqlite3_value_dup() returned; a call with a value_p of 0 does nothing.

C reference: sqlite3_value_free.

numbox.core.bindings.sqlite.value.sqlite3_value_frombind(value_p)[source]

Return a nonzero value if the sqlite3_value at value_p came from a bound parameter, and 0 otherwise.

C reference: sqlite3_value_frombind.

The binding returns 0 for a value from a SQL literal, a table column or an expression. SQLite added the function in version 3.28. If the loaded library is older, this binding is a stub: a call from Python raises NotImplementedError, and a jitted call fails to compile with a TypingError.

numbox.core.bindings.sqlite.value.sqlite3_value_int(value_p)[source]

Return the sqlite3_value at value_p as an int32.

C reference: sqlite3_value_int.

SQLite converts a value of another type, and the binding returns 0 for NULL. A value outside the int32 range is truncated to its low 32 bits; sqlite3_value_int64() reads all 64 bits.

numbox.core.bindings.sqlite.value.sqlite3_value_int64(value_p)[source]

Return the sqlite3_value at value_p as an int64.

C reference: sqlite3_value_int64.

The binding returns 0 for NULL. SQLite converts a REAL or a text value as SQL’s CAST to INTEGER does.

numbox.core.bindings.sqlite.value.sqlite3_value_nochange(value_p)[source]

Return a nonzero value if, in a virtual table’s xUpdate, the UPDATE leaves the value’s column unchanged.

C reference: sqlite3_value_nochange.

In every other respect, such a value appears to be NULL. Outside an xUpdate call, the result is arbitrary.

numbox.core.bindings.sqlite.value.sqlite3_value_numeric_type(value_p)[source]

Apply numeric affinity to the sqlite3_value at value_p, and return its type code after the conversion.

C reference: sqlite3_value_numeric_type.

SQLite converts the value only if no information is lost. Text that represents a number becomes SQLITE_INTEGER or SQLITE_FLOAT, and any other value keeps its type.

numbox.core.bindings.sqlite.value.sqlite3_value_subtype(value_p)[source]

Return the subtype of the SQL function argument at value_p, or 0 if it has none.

C reference: sqlite3_value_subtype.

Register the function that reads it with SQLITE_SUBTYPE. Without that flag, the call may return 0 in some cases where the argument has a subtype.

numbox.core.bindings.sqlite.value.sqlite3_value_text(value_p)[source]

Return the address of the sqlite3_value at value_p as NUL-terminated UTF-8 text, or 0 for NULL.

C reference: sqlite3_value_text.

SQLite owns the text. A later call that converts the same value can free it, so call sqlite3_value_bytes() after this call for the length in bytes, and use the text in the same callback.

numbox.core.bindings.sqlite.value.sqlite3_value_type(value_p)[source]

Return the type code of the sqlite3_value at value_p, such as SQLITE_INTEGER or SQLITE_NULL.

C reference: sqlite3_value_type.

The code is SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB or SQLITE_NULL, and it describes the value before any conversion. A later call that converts the value may change the code that this binding returns, so read the type first.

numbox.core.bindings.sqlite.result

Bindings that set the result of a SQL function, or the value of a virtual table’s column.

A SQL function’s xFunc, xFinal and xValue callbacks report their result through these bindings, and a virtual table’s xColumn reports a cell’s value the same way. Each binding takes, as its first argument, the sqlite3_context * that SQLite passed to the callback, and it must be called in that callback’s thread. The text and BLOB setters take a destructor after the byte count, an intp that sets how SQLite manages the buffer:

  • SQLITE_STATIC (0): SQLite uses the buffer in place, without a copy, and never frees it, so the buffer must stay valid and unchanged until SQLite has finished with the result.

  • SQLITE_TRANSIENT (-1): SQLite copies the buffer before the call returns.

  • Any other value: the address of a C function that SQLite calls to free the buffer when SQLite no longer needs it.

numbox.core.bindings.sqlite.result.sqlite3_result_blob(ctx, data_p, n_bytes, destructor)[source]

Set the result of the SQL function on ctx to a BLOB of the n_bytes bytes at data_p.

C reference: sqlite3_result_blob.

n_bytes must not be negative, and numba converts it to int32 without a check. destructor is as for sqlite3_result_text(): with SQLITE_STATIC the caller keeps the bytes alive and unchanged until SQLite has finished with the result.

numbox.core.bindings.sqlite.result.sqlite3_result_blob64(ctx, data_p, n_bytes, destructor)[source]

Set the result of the SQL function on ctx to a BLOB of the n_bytes bytes at data_p.

C reference: sqlite3_result_blob64.

n_bytes is a uint64, and a length above 2**31 - 1 makes the function fail with SQLITE_TOOBIG. destructor is as for sqlite3_result_text().

numbox.core.bindings.sqlite.result.sqlite3_result_double(ctx, val)[source]

Set the result of the SQL function on ctx to the float64 val.

C reference: sqlite3_result_double.

SQLite converts a NaN to SQL NULL, and an infinity remains a REAL.

numbox.core.bindings.sqlite.result.sqlite3_result_error(ctx, msg_p, n_bytes)[source]

Make the SQL function on ctx fail with the UTF-8 error message at msg_p, n_bytes long.

C reference: sqlite3_result_error.

A negative n_bytes makes SQLite read the message up to the first NUL. SQLite copies the message before the call returns. The error code is SQLITE_ERROR unless a later call of sqlite3_result_error_code() sets another code.

numbox.core.bindings.sqlite.result.sqlite3_result_error_code(ctx, errcode)[source]

Make the SQL function on ctx fail with the result code errcode.

C reference: sqlite3_result_error_code.

If no message was set, SQLite uses its standard message for the code. A later call of sqlite3_result_error() resets the code to SQLITE_ERROR, so call this binding after that call.

numbox.core.bindings.sqlite.result.sqlite3_result_error_nomem(ctx)[source]

Make the SQL function on ctx fail with SQLITE_NOMEM, the error of a failed memory allocation.

C reference: sqlite3_result_error_nomem.

numbox.core.bindings.sqlite.result.sqlite3_result_error_toobig(ctx)[source]

Make the SQL function on ctx fail with SQLITE_TOOBIG, the error of a string or BLOB that is too long.

C reference: sqlite3_result_error_toobig.

numbox.core.bindings.sqlite.result.sqlite3_result_int(ctx, val)[source]

Set the result of the SQL function on ctx to the int32 val.

C reference: sqlite3_result_int.

numba converts val to int32 without a check, so a wider value is truncated to its low 32 bits; sqlite3_result_int64() sets the whole value.

numbox.core.bindings.sqlite.result.sqlite3_result_int64(ctx, val)[source]

Set the result of the SQL function on ctx to the int64 val.

C reference: sqlite3_result_int64.

numbox.core.bindings.sqlite.result.sqlite3_result_null(ctx)[source]

Set the result of the SQL function on ctx to SQL NULL.

C reference: sqlite3_result_null.

numbox.core.bindings.sqlite.result.sqlite3_result_subtype(ctx, subtype)[source]

Set the subtype of the result of the SQL function on ctx to the low 8 bits of subtype.

C reference: sqlite3_result_subtype.

Register the function with SQLITE_RESULT_SUBTYPE. If the flag is missing, the call can have no effect, and a SQLite built with -DSQLITE_STRICT_SUBTYPE=1 makes the function fail with an error.

numbox.core.bindings.sqlite.result.sqlite3_result_text(ctx, text_p, n_bytes, destructor)[source]

Set the result of the SQL function on ctx to the UTF-8 text at text_p, n_bytes long.

C reference: sqlite3_result_text.

A negative n_bytes makes SQLite read up to the first NUL, and numba converts n_bytes to int32 without a check. A destructor of SQLITE_TRANSIENT makes SQLite copy the text before the call returns. With SQLITE_STATIC, SQLite reads the text in place, and the caller keeps it alive and unchanged until SQLite has finished with the result. Any other value is the address of a C function that SQLite calls to free the text. A NUL before byte n_bytes remains part of the text, and the result of a SQL expression on such text is undefined.

numbox.core.bindings.sqlite.result.sqlite3_result_text64(ctx, text_p, n_bytes, destructor, encoding)[source]

Set the result of the SQL function on ctx to the text at text_p, n_bytes long, in encoding.

C reference: sqlite3_result_text64.

encoding is SQLITE_UTF8 for UTF-8 text. n_bytes is a uint64, so it must be the length itself: numba converts -1 to the largest uint64, and a length above 2**31 - 1 makes the function fail with SQLITE_TOOBIG. destructor is as for sqlite3_result_text().

numbox.core.bindings.sqlite.result.sqlite3_result_value(ctx, value_p)[source]

Set the result of the SQL function on ctx to a copy of the sqlite3_value at value_p.

C reference: sqlite3_result_value.

SQLite copies the value, so the value at value_p may change or be freed after the call.

numbox.core.bindings.sqlite.result.sqlite3_result_zeroblob(ctx, n)[source]

Set the result of the SQL function on ctx to a BLOB of n zero bytes.

C reference: sqlite3_result_zeroblob.

numba converts n to int32 without a check.

numbox.core.bindings.sqlite.result.sqlite3_result_zeroblob64(ctx, n)[source]

Set the result of the SQL function on ctx to a BLOB of n zero bytes, and return a result code.

C reference: sqlite3_result_zeroblob64.

Returns SQLITE_OK, or SQLITE_TOOBIG for an n above SQLite’s length limit, which also makes the function fail.

numbox.core.bindings.sqlite.udf

Bindings that register SQL functions on a SQLite connection, and bindings that their callbacks call.

sqlite3_create_function_v2 registers a scalar or an aggregate function, and sqlite3_create_window_function registers a window function. The callbacks of such a function call sqlite3_aggregate_context for an aggregate’s state, sqlite3_user_data for the pointer that the registration passed, and sqlite3_context_db_handle for the connection. Each callback is the intp address of a C function, such as the .address of a function that numba’s cfunc compiles, and 0 stands for an unused callback or pointer. register_aggregate() and register_window() generate the callbacks of an aggregate or a window function whose state is a numba structref.

numbox.core.bindings.sqlite.udf.sqlite3_aggregate_context(ctx, n_bytes)[source]

Return the address of the memory that holds the state of the current aggregate group on ctx.

C reference: sqlite3_aggregate_context.

The first call of a group with a positive n_bytes allocates that many bytes and zeroes them, and later calls return the same memory regardless of their n_bytes. A first call with an n_bytes of 0 or less returns 0, and a failed allocation also returns 0. xFinal usually passes 0, because SQLite calls it once without any xStep when no row matches. SQLite frees the memory when the aggregate query ends.

numbox.core.bindings.sqlite.udf.sqlite3_context_db_handle(ctx)[source]

Return the handle of the connection on which the SQL function on ctx was registered.

C reference: sqlite3_context_db_handle.

numbox.core.bindings.sqlite.udf.sqlite3_create_function_v2(db, name_p, n_arg, e_text_rep, p_app, x_func, x_step, x_final, x_destroy)[source]

Register the scalar or aggregate SQL function named at name_p on the connection db.

C reference: sqlite3_create_function_v2.

A scalar function passes x_func and 0 for x_step and x_final, and an aggregate passes x_step and x_final and 0 for x_func; passing 0 for all three deletes the function. x_func and x_step have the C type void (*)(sqlite3_context *, int argc, sqlite3_value **argv), and x_final has the type void (*)(sqlite3_context *). n_arg is the number of SQL arguments, from 0 to 127, or -1 for any number. e_text_rep is SQLITE_UTF8, combined with flags such as SQLITE_DETERMINISTIC by a bitwise OR. SQLite returns p_app from sqlite3_user_data(). Unless x_destroy is 0, SQLite calls it with p_app when the function is deleted or replaced, when the connection closes, and when the registration fails. Keep each cfunc referenced while the function is registered. Returns SQLITE_OK, or an error code such as SQLITE_MISUSE for a name longer than 255 bytes.

numbox.core.bindings.sqlite.udf.sqlite3_create_window_function(db, name_p, n_arg, e_text_rep, p_app, x_step, x_final, x_value, x_inverse, x_destroy)[source]

Register the aggregate window SQL function named at name_p on the connection db.

C reference: sqlite3_create_window_function.

x_step and x_final are required. x_value and x_inverse are both set for a window function, and both are 0 for a plain aggregate. x_step and x_inverse have the C type void (*)(sqlite3_context *, int argc, sqlite3_value **argv), and x_final and x_value have the type void (*)(sqlite3_context *). The other arguments and the result codes are as for sqlite3_create_function_v2().

numbox.core.bindings.sqlite.udf.sqlite3_user_data(ctx)[source]

Return the p_app pointer that the registration of the SQL function on ctx passed.

C reference: sqlite3_user_data.

numbox.core.bindings.sqlite.udf_helpers

Register SQLite aggregate and window functions whose state is a numba structref.

register_aggregate() and register_window() take a state type and the functions that create, update and finalize the state. They generate and compile the C callbacks that SQLite calls. The callbacks keep each group’s state alive between rows, release it at the end of the group, and convert an exception in one of the functions into a SQL error. The caller writes only the logic of the state, as plain Python functions or jitted ones.

numbox.core.bindings.sqlite.udf_helpers.register_aggregate(db, name, n_arg, state_type, init, step, finalize, *, deterministic=False)[source]

Register the aggregate SQL function name on the connection db, with a state of state_type per group.

For each group of rows, SQLite calls init once to create the state, step once for each row, and finalize once to write the result. Each of the three is a plain Python function, which numbox compiles with njit, or a jitted one, such as an @njit or @proxy function. numbox generates the C callbacks that SQLite calls. They keep the group’s state alive between rows and release it after finalize.

Parameters:
  • db – the connection’s sqlite3 * handle, an intp.

  • name – the SQL name of the function, a str, which numbox passes to SQLite as a C string.

  • n_arg – the number of SQL arguments, or -1 for any number.

  • state_type – the numba StructRef instance type of the state.

  • init – init() returns a new state.

  • step – step(state, ctx, argc, argv_pp) updates the state with one row. ctx is the sqlite3_context *, argc the number of SQL arguments, and argv_pp the address of SQLite’s array of pointers to the argument values, which the bindings of value read.

  • finalize – finalize(state, ctx) writes the result with a binding of result. If no row reaches the function, as in an aggregate over an empty table, finalize receives a new state from init.

  • deterministic – if true, the function is registered with SQLITE_DETERMINISTIC.

If one of the functions raises, the SQL statement fails with an error such as “error in user step callback”. numba compiles the generated code and the functions during this call, so numba raises a typing error in a function from this call. The generated functions compile under numbox’s jit options, and numbox names their cache after a digest of the state type and of the functions. The state type and the functions may be defined in a script’s __main__. If a function reads a value without a fingerprint, such as numbox’s _cast_int_to_void_p, the digest misses some edits, as the section “If a SQLite function keeps returning old results” of numbox.utils explains. The digest also misses an edit to a method of the state type. After an edit that the digest misses, the registration can run code compiled before the edit.

Returns None, and the caller need not keep anything. numba keeps the compiled code of the callbacks for the life of the process, although it does not document that behavior. Raises TypeError when state_type is not a StructRef instance type or a function is not callable. Raises RuntimeError, with SQLite’s message, when SQLite refuses the registration.

numbox.core.bindings.sqlite.udf_helpers.register_window(db, name, n_arg, state_type, init, step, inverse, value, finalize, *, deterministic=False)[source]

Register the window SQL function name on the connection db, with a state of state_type per group.

The parameters are those of register_aggregate(), with two more functions. inverse(state, ctx, argc, argv_pp) removes from the state a row that leaves the window; SQLite calls it only for a row that step added, so the state exists. value(state, ctx) writes the current result of the window, as finalize does, but the state stays alive for the rows that follow. Only the call of finalize releases the state. The errors, the caching and its limits, the return value and the exceptions are those of register_aggregate().

numbox.core.bindings.sqlite.vtable

Expose a NumPy array, or a mapping of 1-D arrays, as a read-only SQLite virtual table.

register_table() registers the data under a name on a connection. A SQL statement can then query the name as a table, and numbox copies none of the data. tvf reuses the module’s NumPy layouts of SQLite’s virtual table structs, its function that sets a cell as a column’s result, and its registration. The registration keeps a table’s data alive while SQLite can read it.

numbox.core.bindings.sqlite.vtable.register_table(db, name, data, columns=None, *, text_as_blob=False)[source]

Register data on the connection db as the read-only SQLite virtual table name, without a copy.

The table is eponymous: SQL queries it as name, with no CREATE VIRTUAL TABLE, because the module’s xCreate is its xConnect. data is one of:

  • a 1-D NumPy structured array, one row for each element, with the field names as column names. columns may rename the columns, but they keep the order of the fields; to reorder them, reorder the fields of the array or pass a mapping.

  • a 2-D NumPy array, one table row for each row of the array. columns is required and names each column.

  • a mapping, such as a dict, from column name to 1-D NumPy array. The arrays must all have the same length. The keys name the columns in their order, so passing columns raises ValueError. Each value must be a numpy.ndarray, because numbox converts nothing: another value raises TypeError, and an array that is not 1-D raises ValueError.

numbox keeps the data and the table’s descriptor alive until SQLite drops the module, when the connection closes or when the name is registered again. The caller must not change or resize the arrays while the table is registered, because each query reads the columns’ memory directly. 'S' and BLOB values reach SQLite as SQLITE_STATIC pointers into that memory.

Values:

  • A uint64 value of 2**63 or more becomes SQLite’s signed INTEGER, so it wraps to a negative value.

  • A float becomes a REAL, infinities included, except NaN: SQLite converts a NaN REAL to SQL NULL, so a query returns NULL for a NaN cell. A NumPy array has no missing values, so every other cell is non-NULL. Masked arrays are not supported, and the table ignores the mask.

String columns:

  • text_as_blob affects only bytes ('S') columns, and a unicode ('U') column is always TEXT. By default an 'S' column is TEXT, and its bytes reach SQLite without a check that they are UTF-8. Pass text_as_blob=True for bytes that are not UTF-8, so that they reach SQLite as a BLOB rather than as malformed TEXT.

  • NumPy pads a fixed-width 'S' or 'U' value with NULs. The table drops the trailing NULs of each value and keeps the interior ones.

  • SQLite receives the whole of a TEXT value with an interior NUL, because numbox passes its length in bytes. C string functions and most SQL text functions, however, stop at the first NUL. Read such a value with sqlite3_column_bytes and the text or BLOB pointer, or pass text_as_blob=True to keep every byte.

Raises TypeError for data of another type, for a column name that is not a string and for a dtype without a SQLite type. Raises ValueError for a shape, a length or a columns list that does not fit the data, and RuntimeError, with SQLite’s message, when SQLite refuses the registration.

numbox.core.bindings.sqlite.query

Collect the rows of a SQL query into a NumPy structured array.

query_to_array() runs one query on a connection and returns its rows, one field of the dtype for each result column. The jitted helpers that it calls step the statement and write the bytes of each cell into the array.

numbox.core.bindings.sqlite.query.query_to_array(db, sql_p, dtype)[source]

Run the SQL query at sql_p on db and return its rows as a 1-D NumPy structured array of dtype.

db is the connection’s sqlite3 * handle. sql_p is the address of NUL-terminated UTF-8 SQL text, not a Python str: c_string() provides one for any text, and get_unicode_data_p() provides one for ASCII text. Only the first statement of the text runs. The fields of dtype correspond to the result columns in order, one field for each column.

A SQL NULL becomes NaN in a float field, 0 in an integer or bool field, and an empty value in an 'S' or 'U' field. A value too wide for an integer field is truncated to the field’s low bits, and a bool field is true for any nonzero value. A string longer than its field is truncated to the field’s width, and the text for a 'U' field is decoded from UTF-8, with U+FFFD for malformed bytes.

Raises TypeError for a dtype without fields or with a field type that has no SQLite counterpart, such as a complex number. Raises ValueError when the number of fields differs from the number of result columns, and RuntimeError, with SQLite’s message, when the query fails to prepare or to run. Once the statement is prepared, the function finalizes it on every path.

numbox.core.bindings.sqlite.tvf

Register a SQLite table-valued function whose rows a Python or jitted function computes for each query.

register_tvf() registers fn under a name on a connection. SELECT * FROM name(2, 5) then calls fn(2, 5) and returns the rows of the structured array that fn returns. Each registration generates and compiles its own xFilter implementation, the code that calls fn, and builds its own sqlite3_module. The structs, the function that sets a cell as a column’s result, and the registration come from vtable.

numbox.core.bindings.sqlite.tvf.register_tvf(db, name, arg_types, out_dtype, fn)[source]

Register fn on the connection db as the eponymous table-valued function name.

SELECT * FROM name(a, b) calls fn(a, b) and returns the rows of the array that fn returns, a 1-D NumPy structured array of out_dtype. fn is a plain Python function, which numbox compiles with njit, or a jitted one. arg_types holds one integer, float or bool NumPy dtype for each argument. fn receives an integer or bool argument as an int64, and a float argument as a float64. Each argument is also a hidden column of the table, after the columns of out_dtype, and the hidden columns are named arg0, arg1, arg2, in the order of the arguments. Selecting a hidden column returns the value that fn received. A query must supply every argument: one that leaves an argument unbound, such as SELECT * FROM name, fails to prepare with SQLite’s error “no query solution”.

fn must return an array whose dtype is out_dtype. A slice, a strided view or an offset view is read correctly, because the row stride is honored. An array of another dtype is read through the layout of out_dtype and yields undefined values. A query returns SQL NULL for a NaN float cell, because SQLite converts a NaN REAL to NULL, as in register_table(). If fn raises, the query fails with SQLITE_ERROR.

numba compiles fn and the generated code that calls it during this call, so numba raises a typing error in fn from this call. The generated code compiles under numbox’s jit options, and numbox names its cache after a digest of out_dtype, the argument types and fn. If fn reads a value without a fingerprint, the digest misses some edits. The registration can then run code compiled before an edit, as the section “If a SQLite function keeps returning old results” of numbox.utils explains.

numbox keeps the registration’s objects, fn included, until SQLite drops the module, when the connection closes or when the name is registered again. Close the connection before the interpreter exits: if Python closes a sqlite3.Connection during its shutdown after a query of the function, the process can end with a segmentation fault.

Raises TypeError when out_dtype is not a structured dtype or has a field without a SQLite type, when an argument type is not an integer, float or bool dtype, and when fn is not callable. Raises RuntimeError, with SQLite’s message, when SQLite refuses the registration.

numbox.core.bindings.sqlite._typemap

Map NumPy dtypes to SQLite column types, and convert fixed-width strings between UTF-32 and UTF-8.

The read-only virtual tables of vtable, the table-valued functions of tvf and query_to_array() share this module. Each supported NumPy dtype has a tag, a small integer, and the tag alone decides the SQLite type of a NumPy column and how its bytes are read and written.

numbox.core.bindings.sqlite._typemap.utf32_to_utf8(src, n_codepoints, dst)[source]

Encode the UTF-32 code points at src as UTF-8 at dst, and return the number of bytes written.

src holds n_codepoints code points in the machine’s byte order, as a NumPy 'U' value stores them. The function ignores the trailing zero code points of the value’s padding and encodes the interior ones. A surrogate or a value above U+10FFFF is written as U+FFFD, and no NUL follows the bytes. dst must hold at least 4 * n_codepoints + 1 bytes.

numbox.core.bindings.sqlite._typemap.utf8_to_utf32(src, nbytes, dst, width_cp)[source]

Decode the UTF-8 bytes at src into at most width_cp code points at dst; return the number written.

nbytes is the length of the input. Each code point is written as a 4-byte unsigned integer in the machine’s byte order, which is little-endian on every platform that numbox supports, and the rest of the width_cp slots are set to 0. Malformed input, such as a stray continuation byte, a surrogate, an overlong encoding or a value above U+10FFFF, decodes to U+FFFD. dst may be unaligned, because every store is unaligned.