A DB-API 2.0 (PEP 249) driver for
vsql, a single file or in-memory SQL
database. libvsql (the vsql library) is compiled into the package, so there's
nothing else to install.
pip install vsql-python
import vsql
with vsql.connect("test.vsql") as conn:
cur = conn.cursor()
cur.execute("CREATE TABLE foo (x INTEGER)")
cur.execute("INSERT INTO foo (x) VALUES (?)", [123])
conn.commit()
cur.execute("SELECT x FROM foo")
print(cur.fetchall()) # [(123,)]
The database is the path of the file (it's created if it doesn't exist), or
:memory: for a database that only exists for the life of the connection.
Leaving the with block commits (or rolls back if there was an exception) and
closes the connection.
As PEP 249 requires, autocommit is off: the first statement starts a
transaction, which is ended by conn.commit() or conn.rollback() (closing
the connection rolls it back). With vsql.connect(..., autocommit=True) (or
conn.autocommit = True), each statement is committed when it finishes, or
when all the rows of a query have been fetched. START TRANSACTION, COMMIT
and ROLLBACK can't be executed as statements.
With autocommit on, a query's transaction lasts until all of its rows have
been fetched (or its cursor is closed, or executes another statement), so a
cursor that's left part way through a query can block other connections that
write to the database file.
A query's cursor stays open after conn.commit() (vsql's cursors are
holdable), so its rows can still be fetched, but conn.rollback() closes it.
isolation_level is (the default, as in vsql and the SQL
standard), , (which vsql runs as
) or (which vsql runs as ,
and is always read only), in any case. It's the isolation level of the
transactions that the driver starts when autocommit is off, and of each
statement when it's on. starts transactions,
where a change is .
"SERIALIZABLE"
"READ COMMITTED"
"REPEATABLE READ"
SERIALIZABLE
"READ UNCOMMITTED"
READ COMMITTED
read_only=True
READ ONLY
25006
With one connection, nothing ever waits. vsql allows one READ WRITESERIALIZABLE transaction on a file at a time, so another connection's waits
for it to finish (for up to lock_timeout, 5 seconds by default, then it's
40001). Connections in separate threads or processes take turns, but two
connections in one thread always time out while one of them holds a write
transaction.
With autocommit off (the DB-API default), a connection is in a transaction
from its first statement until commit() or rollback(), so after a change
it holds up the other connections' changes until it commits: commit promptly.
An app that shares a file with long transactions can use "READ COMMITTED",
which never waits, but its commit fails fast with 40001 while a
SERIALIZABLE transaction is changing the file, so it should retry on
40001.
"READ UNCOMMITTED" can't create a new file or open :memory: yet (08001,
vsql#1947).
Connection options
vsql's connection options are keyword arguments of vsql.connect:
How long (in seconds, or a datetime.timedelta) a SERIALIZABLE transaction waits for another connection before 40001. 0 doesn't wait.
5 seconds
create_index_timeout
How long CREATE INDEX waits before 55P03.
60 seconds
cache_size
The number of pages of the file that are kept in memory. 0 keeps none.
2000
page_size
The size of a page (17 to 65535 octets) of a new file or :memory:.
4096
full_fsync
True to sync with F_FULLFSYNC on macOS.
False
An option that isn't given (or is None) is vsql's default. A value that vsql
doesn't allow, such as a negative timeout, is an InterfaceError (HY024).
Statements
Each execute is one statement (a ; between statements is 42601), and vsql
doesn't allow -- comments (42000), but /* ... */ comments work.
Savepoints
A savepoint is made by executing SAVEPOINT, and released by executing
RELEASE SAVEPOINT. Like ROLLBACK, ROLLBACK TO SAVEPOINT can't be executed
as a statement, so it's conn.rollback_to_savepoint(name) instead:
cur.execute("INSERT INTO foo (x) VALUES (1)")
cur.execute("SAVEPOINT before_two")
cur.execute("INSERT INTO foo (x) VALUES (2)")
conn.rollback_to_savepoint("before_two")
conn.commit() # only 1 is inserted
The name is an identifier, so "before_two" is BEFORE_TWO, and a name that
must stay lower case is quoted, such as '"b"'.
Parameters
Parameters are ? (paramstyle is "qmark"), given as a sequence. Each
Python type is sent as an SQL type, which is cast to the type it's used as:
Python
SQL
None
NULL
bool
BOOLEAN
int
BIGINT (NUMERIC if it's out of range)
float
DOUBLE PRECISION (it must be finite)
str
CHARACTER VARYING
decimal.Decimal
NUMERIC (it must be finite)
datetime.datetime
TIMESTAMP(6) (WITH TIME ZONE if aware)
datetime.date
DATE
datetime.time
TIME(6) (WITH TIME ZONE if aware)
bytes, bytearray, memoryview
BINARY VARYING
datetime.timedelta
INTERVAL DAY TO SECOND(6)
vsql.YearMonthInterval
INTERVAL YEAR TO MONTH
A string can't be a binary string (or the other way around), and a
year-month interval can't be a day-time interval (07006). A
datetime.timedelta can have up to 99,999,999 days (DAY(8)). A float
that's NaN or infinity is a DataError (22003), as is a custom function's
result or a virtual table's value that isn't finite.
Scrolling
cursor.rownumber is the index of the next row of a query (from 0). The rows
of a cursor from conn.cursor(scrollable=True) can be fetched in any order
with cursor.scroll(value, mode), where mode is "relative" (the default)
or "absolute":
cur = conn.cursor(scrollable=True)
cur.execute("SELECT x FROM foo ORDER BY x")
cur.fetchmany(2)
cur.scroll(-2) # back to the first row
cur.scroll(5, "absolute") # the sixth row
Scrolling outside of the rows is an IndexError. A cursor that isn't
scrollable can only scroll forward. A scrollable cursor stays open after its
last row has been fetched (so, with autocommit on, the query isn't committed
until the cursor is closed, or executes another statement).
Columns
SQL
Python
SMALLINT, INTEGER, BIGINT
int
REAL, DOUBLE PRECISION
float
DECIMAL, NUMERIC, DECFLOAT
decimal.Decimal
CHARACTER, VARCHAR, CLOB
str
BINARY, VARBINARY, BLOB
bytes
BOOLEAN
bool
DATE
datetime.date
TIME (WITH TIME ZONE)
datetime.time
TIMESTAMP (WITH TIME ZONE)
datetime.datetime
INTERVAL YEAR, INTERVAL MONTH, INTERVAL YEAR TO MONTH
vsql.YearMonthInterval
any other INTERVAL (DAY to SECOND)
datetime.timedelta
A NULL is None. A value WITH TIME ZONE is aware (with a fixed offset),
otherwise it's naive.
A year-month interval isn't a datetime.timedelta, since a month doesn't have
a fixed length. vsql.YearMonthInterval(years=1, months=2) is a number of
months (total_months), which is also years and months (with the same
sign):
cur.execute("VALUES INTERVAL -'1-02' YEAR TO MONTH")
i = cur.fetchone()[0] # YearMonthInterval(years=-1, months=-2)
print(i.total_months) # -14
The type_code in cursor.description is the name of the type (such as
"INTEGER" or "INTERVAL DAY TO SECOND"), which compares equal to
vsql.NUMBER, vsql.STRING, vsql.BINARY or vsql.DATETIME (which includes
the intervals). The internal_size is the length of a string (in octets, 4 for
each character) or a binary string, the precision of a number, or the length of
a datetime or interval (which is also its display_size). The precision and
scale are those of a DECIMAL or NUMERIC, the precision of a DECFLOAT
(16 or 34), or the leading field precision and the fractional seconds
precision of an interval. The scale of a TIME or TIMESTAMP is its
fractional seconds precision.
Errors
An error from vsql is the PEP 249 exception for its SQLSTATE, with the
SQLSTATE as sqlstate:
try:
cur.execute("SELECT * FROM nope")
except vsql.ProgrammingError as e:
print(e.sqlstate) # 42P01
print(e.table_name) # NOPE
The object that the error is about is in these attributes (or None):
e.diagnostics is a tuple of (sqlstate, message) for every condition that
vsql raised, starting with the error itself.
Warnings
A statement that completes with a warning (an SQLSTATE of class 01) issues a
vsql.Warning with warnings.warn, so it's printed once by default, and can be
filtered or turned into an error like any other warning:
cur.execute("SELECT COUNT(x) FROM foo")
# Warning: null value eliminated in set function (SQLSTATE 01003)
warnings.simplefilter("error", vsql.Warning) # raise them instead
vsql.Warning is a subclass of Python's Warning (which PEP 249 requires to
be an Exception), with the sqlstate and message.
Custom functions
conn.create_function(create_function, func) registers a Python function as
the body of an SQL function, until the connection is closed. create_function
is a CREATE FUNCTION statement with LANGUAGE C, NO SQL and an EXTERNAL
body (the Python function is called through vsql's C API):
def no_pennies(amount):
if amount is None:
return None
if amount < 0:
raise vsql.DataError("amount is negative", "22003")
return round(amount / 0.05) * 0.05
conn.create_function(
"CREATE FUNCTION no_pennies(amount DOUBLE PRECISION) "
"RETURNS DOUBLE PRECISION LANGUAGE C NO SQL EXTERNAL",
no_pennies)
cur.execute("SELECT product_name, no_pennies(price) AS total FROM products")
The other characteristics are optional, and can be in any order: CALLED ON NULL INPUT (the default) or RETURNS NULL ON NULL INPUT (the function isn't
called when an argument is NULL, and the result is NULL),
NOT DETERMINISTIC, PARAMETER STYLE SQL, EXTERNAL NAME and
EXTERNAL SECURITY. A characteristic that vsql doesn't support (such as
DETERMINISTIC) is a NotSupportedError (0A000), and a statement that isn't
valid (such as one without NO SQL) is a ProgrammingError (42601).
The function is called with an argument for each parameter (NULL is None),
as the Python value of its type (see Columns). It
returns the result, which is cast to the return type like a parameter (see
Parameters), or None for NULL. A datetime.datetime is its date or time
for a DATE or TIME, and a datetime.date is midnight for a TIMESTAMP. A
datetime.timedelta or vsql.YearMonthInterval is cast to the fields of an
INTERVAL return type (like a CAST, so 1 hour 30 minutes is 1 hour for an
INTERVAL HOUR), and a string is the value of the interval (such as "1-2"
for an INTERVAL YEAR TO MONTH) or its literal ("INTERVAL '1-2' YEAR TO MONTH"). If
it raises a vsql.Error with an SQLSTATE, the statement fails with that
SQLSTATE, and any other exception is 38000 (external routine exception). The
exception is the __cause__ of the statement's error. A function with the same
name and parameter types as one that already exists is a ProgrammingError
(42723).
The function is chosen by the types of its arguments, which aren't made
narrower (an INTEGER doesn't match a SMALLINT parameter), and a ?
argument needs a CAST, such as no_pennies(CAST(? AS DOUBLE PRECISION)). A
CLOB parameter takes any character string, and a BLOB parameter any binary
string.
Parameters and results can be intervals, with any fields and precisions:
def overtime(worked):
return max(worked - datetime.timedelta(hours=8), datetime.timedelta())
conn.create_function(
"CREATE FUNCTION overtime(worked INTERVAL HOUR TO MINUTE) "
"RETURNS INTERVAL HOUR TO MINUTE LANGUAGE C NO SQL EXTERNAL",
overtime)
cur.execute("VALUES overtime(INTERVAL '9:45' HOUR TO MINUTE)")
cur.fetchone() # (datetime.timedelta(seconds=6300),)
conn.create_function(
"CREATE FUNCTION half(i INTERVAL YEAR TO MONTH) "
"RETURNS INTERVAL YEAR TO MONTH LANGUAGE C NO SQL EXTERNAL",
lambda i: vsql.YearMonthInterval(months=i.total_months // 2))
cur.execute("VALUES half(INTERVAL '1-03' YEAR TO MONTH)")
cur.fetchone() # (YearMonthInterval(years=0, months=7),)
Virtual tables
conn.create_virtual_table(create_table, rows) registers a table whose rows
come from Python, until the connection is closed. create_table is a
CREATE VIRTUAL TABLE statement, which only has the name of the table and the
name and type of each column (a constraint or DEFAULT is a
ProgrammingError, 42601). Each time the table is read, rows is called,
and returns an iterable of rows (each a sequence of the values of the columns,
which are cast to the type of each column like a parameter):
def produce():
yield "Apple", "0.42", True, datetime.date(2026, 11, 20)
yield "Banana", "0.28", False, datetime.date(2026, 11, 25)
yield "Avocado", "1.67", True, None
conn.create_virtual_table(
"CREATE VIRTUAL TABLE produce (name VARCHAR(50), price NUMERIC(5, 2), "
"organic BOOLEAN, picked DATE)",
produce)
cur.execute("SELECT name, price, picked FROM produce WHERE organic ORDER BY price")
cur.fetchall()
# [('Apple', Decimal('0.42'), datetime.date(2026, 11, 20)),
# ('Avocado', Decimal('1.67'), None)]
A price is a string, so it has exactly the decimal places of the NUMERIC (a
decimal.Decimal works too). A row with fewer values than columns has NULL
for the rest, and datetimes are converted for their column in the same way as a
function's result. Every row is read before the statement goes on, so the
iterable must end. An exception fails the statement in the same way as for a
custom function. A table that already exists is a ProgrammingError (42P07).
While a custom function or virtual table runs, the statement that called it is
still running, so it can't use its connection or the connection's cursors
(that's a ProgrammingError). It can use another connection.
Versions
vsql.vsql_version is the version of vsql that's compiled into the package
(such as "1.7.58"), and vsql.vsql_version_info is the same as a tuple
((1, 7, 58)). vsql.build_info is a dict of how it was built:
conn.file_version is the (read, write) version of the database file's
format ((0, 0) for :memory:).
Threads
Each connection has its own libvsql environment, so different connections can
be used from different threads at the same time (threadsafety is 1: threads
can share the module, but not connections). The GIL is released while libvsql
runs, and on free-threaded Python (such as 3.14t) the module doesn't turn the
GIL back on.
On musl (such as Alpine), a thread only has 128 KiB of stack, which isn't
enough for libvsql, so importing vsql sets threading.stack_size to 1 MiB
(unless it was set already). A thread that was started before vsql was
imported, or that wasn't started by Python, still has the smaller stack.
Type hints
The package has type hints (vsql/__init__.pyi), so type checkers such as
mypy and pyright know the types of the module, Connection, Cursor, the
parameters and the rows.
Requirements
Python 3.9 or later. Wheels are built for macOS, Linux (glibc and musl, such as
Alpine) and Windows, each for ARM64 and x86-64, so pip doesn't need to compile
anything.
Building from the source distribution needs a C compiler, and takes a minute or
two. On Windows, it needs clang-cl (from LLVM, or the
"C++ Clang tools for Windows" component of Visual Studio) as well as MSVC, since
the C that V generates doesn't compile with MSVC. clang-cl is found on the
PATH (or in C:\Program Files\LLVM\bin), or set CC to its path.
Tests
pip install -e . pytest && pytest tests
The tests must cover every line and branch of the Python modules, and every
line of the extension module (src/vsql/_libvsql.c), which CI checks with:
tests/test_libvsql.py calls the extension module directly, for the errors
that the rest of the package never causes, and runs it out of memory (with
_testcapi.set_nomemory).
Updating vsql
internal/amalgamation is the libvsql C from a vsql release
(vsql-VERSION-amalgamation.zip). To update it to the latest release: