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_pchanged.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 aTypingError. A stub has noas_func, sohasattr(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_pand free its resources, and returnSQLITE_OK.C reference: sqlite3_close.
SQLite returns
SQLITE_BUSYand 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_pon the connectiondb_p.C reference: sqlite3_db_filename.
name_pis 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_pwas 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_pis read-only, 0 if it is writable, and -1 ifdb_placks it.C reference: sqlite3_db_readonly.
name_pis the address of the database’s name, as forsqlite3_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_pand write the new connection’s handle todb_pp.C reference: sqlite3_open.
filename_pis 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_ppis the address of anintpthat receives the handle, such asctypes.addressofof actypes.c_int64. ReturnsSQLITE_OK, or an error code thatsqlite3_errmsg()explains. SQLite writes a handle even when the open fails, unless it cannot allocate one, and the caller closes it withsqlite3_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_pin the mode thatflagssets; write the handle todb_pp.C reference: sqlite3_open_v2.
flagsholdsSQLITE_OPEN_READONLY,SQLITE_OPEN_READWRITE, orSQLITE_OPEN_READWRITEwithSQLITE_OPEN_CREATE, and may add otherSQLITE_OPEN_*flags ofconstantswith a bitwise OR.vfs_pis 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 thatsqlite3_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_psince 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 withSQLITE_OMIT_TRACE.
- numbox.core.bindings.sqlite.stmt.sqlite3_finalize(stmt_p)[source]
Delete the prepared statement
stmt_p, and returnSQLITE_OKor 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_pondb_pand write its handle tostmt_pp.C reference: sqlite3_prepare_v2.
sql_pis the address of UTF-8 SQL text, andn_byteits length in bytes, or -1 to read up to the first NUL.stmt_ppis the address of anintpthat receives the statement’s handle, or 0 after an error or for text that holds no statement. Unlesstail_ppis 0, it receives the address of the text after the first statement. ReturnsSQLITE_OKor an error code. The caller finalizes the statement withsqlite3_finalize().
- numbox.core.bindings.sqlite.stmt.sqlite3_reset(stmt_p)[source]
Reset the statement
stmt_pto run again from the start, and returnSQLITE_OKor 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_BUSYwhen 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_pwas 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_pto its next result row, and returnSQLITE_ROW,SQLITE_DONEor an error code.C reference: sqlite3_step.
After
SQLITE_ROW, the bindings ofcolumnread the row. AfterSQLITE_DONEor an error, the statement must be reset before it is stepped again.SQLITE_BUSYmeans 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_phas 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
nbytes atdata_pas a BLOB to the parameteridxof the statementstmt_p.C reference: sqlite3_bind_blob.
nmust not be negative, and numba converts it to int32 without a check. AdestructorofSQLITE_TRANSIENTmakes SQLite copy the bytes before the call returns. WithSQLITE_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. Adata_pof 0 binds NULL. ReturnsSQLITE_OK,SQLITE_RANGEfor an index out of range,SQLITE_MISUSEif the statement has been stepped since its last reset, orSQLITE_TOOBIGfor a BLOB longer than SQLite’s limit.
- numbox.core.bindings.sqlite.bind.sqlite3_bind_double(stmt_p, idx, val)[source]
Bind the float64
valto the parameteridxof the statementstmt_p, counted from 1.C reference: sqlite3_bind_double.
Returns
SQLITE_OK,SQLITE_RANGEfor an index out of range, orSQLITE_MISUSEif 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
valto the parameteridxof the statementstmt_p, counted from 1.C reference: sqlite3_bind_int.
numba converts
valto int32 without a check, so a wider value is truncated to its low 32 bits; bind it withsqlite3_bind_int64()instead. ReturnsSQLITE_OK,SQLITE_RANGEfor an index out of range, orSQLITE_MISUSEif 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
valto the parameteridxof the statementstmt_p, counted from 1.C reference: sqlite3_bind_int64.
Returns
SQLITE_OK,SQLITE_RANGEfor an index out of range, orSQLITE_MISUSEif 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
idxof the statementstmt_p, counted from 1.C reference: sqlite3_bind_null.
A parameter that is never bound is NULL as well. Returns
SQLITE_OK,SQLITE_RANGEfor an index out of range, orSQLITE_MISUSEif 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
?NNNleave 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_pnamed by the UTF-8 text atname_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
idxof the statementstmt_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,nbytes long, to the parameteridxof the statementstmt_p.C reference: sqlite3_bind_text.
A negative
nmakes SQLite read up to the first NUL, and numba convertsnto int32 without a check. AdestructorofSQLITE_TRANSIENTmakes SQLite copy the text before the call returns. WithSQLITE_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. Atext_pof 0 binds NULL. ReturnsSQLITE_OK,SQLITE_RANGEfor an index out of range,SQLITE_MISUSEif the statement has been stepped since its last reset, orSQLITE_TOOBIGfor 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
idxof 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
idxas 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()orsqlite3_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
idxof the statementstmt_pcomes.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 raisesNotImplementedError, and a jitted call fails to compile with aTypingError. A stub has noas_func, sohasattr(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
idxof 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
idxof the current row ofstmt_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
CASTtoREALdoes.
- numbox.core.bindings.sqlite.column.sqlite3_column_int(stmt_p, idx)[source]
Return the value of column
idxof the current row ofstmt_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
idxof the current row ofstmt_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
CASTtoINTEGERdoes.
- numbox.core.bindings.sqlite.column.sqlite3_column_name(stmt_p, idx)[source]
Return the address of the UTF-8 name of column
idxof the result of the statementstmt_p.C reference: sqlite3_column_name.
The name is the one that the column’s
ASclause sets. If the column has noASclause, 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
idxof the statementstmt_pcomes.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
idxof the statementstmt_pcomes.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
idxas 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
idxof the current row ofstmt_p, counted from 0.C reference: sqlite3_column_type.
The code is
SQLITE_INTEGER,SQLITE_FLOAT,SQLITE_TEXT,SQLITE_BLOBorSQLITE_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_pon the connectiondb_p, and return a result code.C reference: sqlite3_exec.
cb_pis 0, or the address of a row callback of the type that the module docstring gives, and SQLite passesctx_pto that callback. If a statement fails, SQLite stops and skips the statements after it. Unlesserrmsg_ppis 0, SQLite then writes to it the address of an error message, which the caller frees withsqlite3_free(). If every statement succeeds, SQLite writes 0 there. ReturnsSQLITE_OK,SQLITE_ABORTwhen 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
nbytes with SQLite’s allocator and return their address, or 0 if the allocation fails.C reference: sqlite3_malloc.
Returns 0 as well for an
nof 0 or less, and numba convertsnto int32 without a check. The memory is not zeroed. It is aligned to at least 8 bytes unless SQLite was built withSQLITE_4_BYTE_ALIGNED_MALLOC, and the caller frees it withsqlite3_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
UPDATEstatement can.
- numbox.core.bindings.sqlite.blob.sqlite3_blob_close(blob_p)[source]
Close the BLOB handle
blob_p, and returnSQLITE_OKor 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_pof rowrowidfor incremental I/O, and write the handle toblob_pp.C reference: sqlite3_blob_open.
db_name_p,table_pandcol_pare the addresses of UTF-8 names. The database’s name is"main","temp"or the name of an attached database, not a file name.flagsisSQLITE_BLOB_READONLY(0) orSQLITE_BLOB_READWRITE(1). ReturnsSQLITE_OK, orSQLITE_ERRORwhen 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 butSQLITE_MISUSE,blob_ppholds 0. The caller closes the handle withsqlite3_blob_close().
- numbox.core.bindings.sqlite.blob.sqlite3_blob_read(blob_p, buf_p, n, offset)[source]
Copy
nbytes of the value open onblob_p, from byteoffset, into the buffer atbuf_p.C reference: sqlite3_blob_read.
Returns
SQLITE_OK, orSQLITE_ERRORwith nothing read whenoffset + nexceeds the size or either is negative. ReturnsSQLITE_ABORTwhen a change to the row has expired the handle. numba convertsnandoffsetto int32 without a check.
- numbox.core.bindings.sqlite.blob.sqlite3_blob_reopen(blob_p, new_rowid)[source]
Move the BLOB handle
blob_pto rownew_rowidof 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, andsqlite3_blob_bytes()returns 0.
- numbox.core.bindings.sqlite.blob.sqlite3_blob_write(blob_p, buf_p, n, offset)[source]
Copy
nbytes from the buffer atbuf_pinto the value open onblob_p, from byteoffset.C reference: sqlite3_blob_write.
Returns
SQLITE_OK,SQLITE_READONLYfor a handle opened read-only,SQLITE_ERRORwith nothing written whenoffset + nexceeds the size or either is negative, orSQLITE_ABORTwhen a change to the row has expired the handle. The write cannot increase the size of the value. numba convertsnandoffsetto 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_pto be called whendb_ptries 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 receivesctx_pand the number of earlier calls for the same lock. A return value of 0 makes the waiting call fail withSQLITE_BUSY, and a nonzero return value makes SQLite try again. Acb_pof 0 removes the handler, andsqlite3_busy_timeoutorPRAGMA busy_timeoutreplaces it. The callback must neither change the connection nor close it. Keep thecfuncwhose address iscb_preferenced 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_pto be called whenever a transaction ondb_pcommits.C reference: sqlite3_commit_hook.
The callback has the C type
int (*)(void *ctx)and receivesctx_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. Acb_pof 0 removes the hook. Keep thecfuncwhose address iscb_preferenced while the hook is installed. Returns thectx_pof 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_pto be called about everyn_opsvirtual machine instructions during long calls ondb_p.C reference: sqlite3_progress_handler.
The callback has the C type
int (*)(void *ctx)and receivesctx_p. A nonzero return value interrupts the operation. Ann_opsbelow 1 or acb_pof 0 removes the handler. The callback must not change the connection. Keep thecfuncwhose address iscb_preferenced while the handler is installed.
- numbox.core.bindings.sqlite.hooks.sqlite3_rollback_hook(db_p, cb_p, ctx_p)[source]
Install
cb_pto be called whenever a transaction ondb_prolls back.C reference: sqlite3_rollback_hook.
The callback has the C type
void (*)(void *ctx)and receivesctx_p. SQLite does not call it for the rollback that closing the connection causes. The callback must not change the connection. Acb_pof 0 removes the hook. Keep thecfuncwhose address iscb_preferenced while the hook is installed. Returns thectx_pof 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_pto be called for the trace events inmaskondb_p, and return a result code.C reference: sqlite3_trace_v2.
maskcombinesSQLITE_TRACE_STMT,SQLITE_TRACE_PROFILE,SQLITE_TRACE_ROWandSQLITE_TRACE_CLOSEwith a bitwise OR. The callback has the C typeint (*)(unsigned event, void *ctx, void *p, void *x). It receives the event,ctx_pand two pointers whose meaning depends on the event, and it should return 0. Amaskof 0 or acb_pof 0 disables tracing. Keep thecfuncwhose address iscb_preferenced while tracing is enabled.
- numbox.core.bindings.sqlite.hooks.sqlite3_update_hook(db_p, cb_p, ctx_p)[source]
Install
cb_pto be called for every row inserted, updated or deleted in a rowid table ondb_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 receivesctx_p, the operation, the addresses of the database’s and the table’s names, and the rowid. The operation isSQLITE_INSERT(18),SQLITE_DELETE(9) orSQLITE_UPDATE(23), three codes thatconstantsdoes not define. The callback must not change the connection, and preparing or stepping a statement counts as a change. Acb_pof 0 removes the hook. Keep thecfuncwhose address iscb_preferenced while the hook is installed. Returns thectx_pof 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_valueatvalue_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_valueatvalue_pas a BLOB or as UTF-8 text, 0 for NULL.C reference: sqlite3_value_bytes.
Call it after
sqlite3_value_text()orsqlite3_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_valueatvalue_pas 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
CASTtoREALdoes.
- numbox.core.bindings.sqlite.value.sqlite3_value_dup(value_p)[source]
Return the address of a copy of the
sqlite3_valueatvalue_p, or 0 ifvalue_pis 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_valuethatsqlite3_value_dup()returned; a call with avalue_pof 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_valueatvalue_pcame 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 aTypingError.
- numbox.core.bindings.sqlite.value.sqlite3_value_int(value_p)[source]
Return the
sqlite3_valueatvalue_pas 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_valueatvalue_pas an int64.C reference: sqlite3_value_int64.
The binding returns 0 for NULL. SQLite converts a REAL or a text value as SQL’s
CASTtoINTEGERdoes.
- 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
xUpdatecall, the result is arbitrary.
- numbox.core.bindings.sqlite.value.sqlite3_value_numeric_type(value_p)[source]
Apply numeric affinity to the
sqlite3_valueatvalue_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_INTEGERorSQLITE_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_valueatvalue_pas 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_valueatvalue_p, such asSQLITE_INTEGERorSQLITE_NULL.C reference: sqlite3_value_type.
The code is
SQLITE_INTEGER,SQLITE_FLOAT,SQLITE_TEXT,SQLITE_BLOBorSQLITE_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
ctxto a BLOB of then_bytesbytes atdata_p.C reference: sqlite3_result_blob.
n_bytesmust not be negative, and numba converts it to int32 without a check.destructoris as forsqlite3_result_text(): withSQLITE_STATICthe 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
ctxto a BLOB of then_bytesbytes atdata_p.C reference: sqlite3_result_blob64.
n_bytesis a uint64, and a length above 2**31 - 1 makes the function fail withSQLITE_TOOBIG.destructoris as forsqlite3_result_text().
- numbox.core.bindings.sqlite.result.sqlite3_result_double(ctx, val)[source]
Set the result of the SQL function on
ctxto the float64val.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
ctxfail with the UTF-8 error message atmsg_p,n_byteslong.C reference: sqlite3_result_error.
A negative
n_bytesmakes SQLite read the message up to the first NUL. SQLite copies the message before the call returns. The error code isSQLITE_ERRORunless a later call ofsqlite3_result_error_code()sets another code.
- numbox.core.bindings.sqlite.result.sqlite3_result_error_code(ctx, errcode)[source]
Make the SQL function on
ctxfail with the result codeerrcode.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 toSQLITE_ERROR, so call this binding after that call.
- numbox.core.bindings.sqlite.result.sqlite3_result_error_nomem(ctx)[source]
Make the SQL function on
ctxfail withSQLITE_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
ctxfail withSQLITE_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
ctxto the int32val.C reference: sqlite3_result_int.
numba converts
valto 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
ctxto the int64val.C reference: sqlite3_result_int64.
- numbox.core.bindings.sqlite.result.sqlite3_result_null(ctx)[source]
Set the result of the SQL function on
ctxto 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
ctxto the low 8 bits ofsubtype.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=1makes 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
ctxto the UTF-8 text attext_p,n_byteslong.C reference: sqlite3_result_text.
A negative
n_bytesmakes SQLite read up to the first NUL, and numba convertsn_bytesto int32 without a check. AdestructorofSQLITE_TRANSIENTmakes SQLite copy the text before the call returns. WithSQLITE_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 byten_bytesremains 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
ctxto the text attext_p,n_byteslong, inencoding.C reference: sqlite3_result_text64.
encodingisSQLITE_UTF8for UTF-8 text.n_bytesis 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 withSQLITE_TOOBIG.destructoris as forsqlite3_result_text().
- numbox.core.bindings.sqlite.result.sqlite3_result_value(ctx, value_p)[source]
Set the result of the SQL function on
ctxto a copy of thesqlite3_valueatvalue_p.C reference: sqlite3_result_value.
SQLite copies the value, so the value at
value_pmay 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
ctxto a BLOB ofnzero bytes.C reference: sqlite3_result_zeroblob.
numba converts
nto int32 without a check.
- numbox.core.bindings.sqlite.result.sqlite3_result_zeroblob64(ctx, n)[source]
Set the result of the SQL function on
ctxto a BLOB ofnzero bytes, and return a result code.C reference: sqlite3_result_zeroblob64.
Returns
SQLITE_OK, orSQLITE_TOOBIGfor annabove 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_bytesallocates that many bytes and zeroes them, and later calls return the same memory regardless of theirn_bytes. A first call with ann_bytesof 0 or less returns 0, and a failed allocation also returns 0.xFinalusually passes 0, because SQLite calls it once without anyxStepwhen 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
ctxwas 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_pon the connectiondb.C reference: sqlite3_create_function_v2.
A scalar function passes
x_funcand 0 forx_stepandx_final, and an aggregate passesx_stepandx_finaland 0 forx_func; passing 0 for all three deletes the function.x_funcandx_stephave the C typevoid (*)(sqlite3_context *, int argc, sqlite3_value **argv), andx_finalhas the typevoid (*)(sqlite3_context *).n_argis the number of SQL arguments, from 0 to 127, or -1 for any number.e_text_repisSQLITE_UTF8, combined with flags such asSQLITE_DETERMINISTICby a bitwise OR. SQLite returnsp_appfromsqlite3_user_data(). Unlessx_destroyis 0, SQLite calls it withp_appwhen the function is deleted or replaced, when the connection closes, and when the registration fails. Keep eachcfuncreferenced while the function is registered. ReturnsSQLITE_OK, or an error code such asSQLITE_MISUSEfor 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_pon the connectiondb.C reference: sqlite3_create_window_function.
x_stepandx_finalare required.x_valueandx_inverseare both set for a window function, and both are 0 for a plain aggregate.x_stepandx_inversehave the C typevoid (*)(sqlite3_context *, int argc, sqlite3_value **argv), andx_finalandx_valuehave the typevoid (*)(sqlite3_context *). The other arguments and the result codes are as forsqlite3_create_function_v2().
- numbox.core.bindings.sqlite.udf.sqlite3_user_data(ctx)[source]
Return the
p_apppointer that the registration of the SQL function onctxpassed.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
nameon the connectiondb, with a state ofstate_typeper group.For each group of rows, SQLite calls
initonce to create the state,steponce for each row, andfinalizeonce to write the result. Each of the three is a plain Python function, which numbox compiles withnjit, or a jitted one, such as an@njitor@proxyfunction. numbox generates the C callbacks that SQLite calls. They keep the group’s state alive between rows and release it afterfinalize.- Parameters:
db – the connection’s
sqlite3 *handle, anintp.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
StructRefinstance type of the state.init –
init()returns a new state.step –
step(state, ctx, argc, argv_pp)updates the state with one row.ctxis thesqlite3_context *,argcthe number of SQL arguments, andargv_ppthe address of SQLite’s array of pointers to the argument values, which the bindings ofvalueread.finalize –
finalize(state, ctx)writes the result with a binding ofresult. If no row reaches the function, as in an aggregate over an empty table,finalizereceives a new state frominit.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. RaisesTypeErrorwhenstate_typeis not aStructRefinstance type or a function is not callable. RaisesRuntimeError, 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
nameon the connectiondb, with a state ofstate_typeper 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 thatstepadded, so the state exists.value(state, ctx)writes the current result of the window, asfinalizedoes, but the state stays alive for the rows that follow. Only the call offinalizereleases the state. The errors, the caching and its limits, the return value and the exceptions are those ofregister_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
dataon the connectiondbas the read-only SQLite virtual tablename, without a copy.The table is eponymous: SQL queries it as
name, with noCREATE VIRTUAL TABLE, because the module’sxCreateis itsxConnect.datais one of:a 1-D NumPy structured array, one row for each element, with the field names as column names.
columnsmay 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.
columnsis 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 passingcolumnsraisesValueError. Each value must be anumpy.ndarray, because numbox converts nothing: another value raisesTypeError, and an array that is not 1-D raisesValueError.
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 asSQLITE_STATICpointers into that memory.Values:
A
uint64value 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_blobaffects 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. Passtext_as_blob=Truefor 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_bytesand the text or BLOB pointer, or passtext_as_blob=Trueto keep every byte.
Raises
TypeErrorfordataof another type, for a column name that is not a string and for a dtype without a SQLite type. RaisesValueErrorfor a shape, a length or acolumnslist that does not fit the data, andRuntimeError, 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_pondband return its rows as a 1-D NumPy structured array ofdtype.dbis the connection’ssqlite3 *handle.sql_pis the address of NUL-terminated UTF-8 SQL text, not a Pythonstr:c_string()provides one for any text, andget_unicode_data_p()provides one for ASCII text. Only the first statement of the text runs. The fields ofdtypecorrespond 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
boolfield, 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 aboolfield 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
TypeErrorfor adtypewithout fields or with a field type that has no SQLite counterpart, such as a complex number. RaisesValueErrorwhen the number of fields differs from the number of result columns, andRuntimeError, 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
fnon the connectiondbas the eponymous table-valued functionname.SELECT * FROM name(a, b)callsfn(a, b)and returns the rows of the array thatfnreturns, a 1-D NumPy structured array ofout_dtype.fnis a plain Python function, which numbox compiles withnjit, or a jitted one.arg_typesholds one integer, float orboolNumPy dtype for each argument.fnreceives an integer orboolargument as an int64, and a float argument as a float64. Each argument is also a hidden column of the table, after the columns ofout_dtype, and the hidden columns are namedarg0,arg1,arg2, in the order of the arguments. Selecting a hidden column returns the value thatfnreceived. A query must supply every argument: one that leaves an argument unbound, such asSELECT * FROM name, fails to prepare with SQLite’s error “no query solution”.fnmust return an array whose dtype isout_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 ofout_dtypeand yields undefined values. A query returns SQL NULL for a NaN float cell, because SQLite converts a NaN REAL to NULL, as inregister_table(). Iffnraises, the query fails withSQLITE_ERROR.numba compiles
fnand the generated code that calls it during this call, so numba raises a typing error infnfrom this call. The generated code compiles under numbox’s jit options, and numbox names its cache after a digest ofout_dtype, the argument types andfn. Iffnreads 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,
fnincluded, 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 asqlite3.Connectionduring its shutdown after a query of the function, the process can end with a segmentation fault.Raises
TypeErrorwhenout_dtypeis not a structured dtype or has a field without a SQLite type, when an argument type is not an integer, float orbooldtype, and whenfnis not callable. RaisesRuntimeError, 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
srcas UTF-8 atdst, and return the number of bytes written.srcholdsn_codepointscode 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.dstmust hold at least4 * n_codepoints + 1bytes.
- numbox.core.bindings.sqlite._typemap.utf8_to_utf32(src, nbytes, dst, width_cp)[source]
Decode the UTF-8 bytes at
srcinto at mostwidth_cpcode points atdst; return the number written.nbytesis 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 thewidth_cpslots 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.dstmay be unaligned, because every store is unaligned.