.. Automatically generated by code2rst.py
   Edit src/connection.c not this file!

.. currentmodule:: apsw

.. _connections:

Connections to a database
*************************

A :class:`Connection` encapsulates access to a database.  You can have
multiple :class:`Connections <Connection>` open against the same
database file in the same process, across threads and in other
processes.

Connection class
================

.. index:: sqlite3_open_v2

.. class:: Connection(filename: str, flags: int = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, vfs: str | None = None, statementcachesize: int = 100)

  This object wraps a `sqlite3 pointer
  <https://sqlite.org/c3ref/sqlite3.html>`_.

  Opens the named database.  You can use ``:memory:`` to get a private temporary
  in-memory database that is not shared with any other connections.

  :param flags: One or more of the `open flags <https://sqlite.org/c3ref/c_open_autoproxy.html>`_ orred together
  :param vfs: The name of the `vfs <https://sqlite.org/c3ref/vfs.html>`_ to use.  If *None* then the default
     vfs will be used.

  :param statementcachesize: Use zero to disable the statement cache,
    or a number larger than the total distinct SQL statements you
    execute frequently.

  .. seealso::

    * :attr:`apsw.connection_hooks`
    * :ref:`statementcache`
    * :ref:`vfs`

  Calls: `sqlite3_open_v2 <https://sqlite.org/c3ref/open.html>`__

.. method:: Connection.__aenter__() -> Self

  |badge-async-async|

  Async version of :meth:`__enter__` context manager.

.. method:: Connection.__aexit__(etype: type[BaseException] | None, evalue: BaseException | None, etraceback: types.TracebackType | None) -> bool | None

  |badge-async-async|

  Async version of :meth:`__exit__` context manager.

.. method:: Connection.__enter__() -> Connection

  |badge-async-sync|

  You can use the database as a `context manager
  <https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers>`_
  as defined in :pep:`0343`.  When you use *with* a transaction is
  started.  If the block finishes with an exception then the
  transaction is rolled back, otherwise it is committed.  For example::

    with connection:
        connection.execute("....")
        with connection:
            # nested is supported
            call_function(connection)
            connection.execute("...")
            with connection as db:
                # You can also use 'as'
                call_function2(db)
                db.execute("...")

  If starting an `outermost transaction
  <https://sqlite.org/lang_transaction.html>`__ then ``BEGIN`` uses
  :attr:`transaction_mode` (default ``DEFERRED``).  Nested statements
  use `savepoints <https://sqlite.org/lang_savepoint.html>`__.

.. method:: Connection.__exit__(etype: type[BaseException] | None, evalue: BaseException | None, etraceback: types.TracebackType | None) -> bool

  |badge-async-sync|

  Implements context manager in conjunction with
  :meth:`~Connection.__enter__`.  If no exception happened then
  the pending transaction is committed, while an exception results in a
  rollback.

.. method:: Connection.aclose(force: bool = False) -> None

  |badge-close|

  The async version of :meth:`close`

.. method:: Connection.as_async(filename: str, flags: int = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, vfs: str | None = None, statementcachesize: int = 100) -> Awaitable[AsyncConnection]
  :classmethod:

  Uses the :attr:`async_controller` to start a :class:`Connection`
  with the parameters in a background worker thread.  The resulting
  :class:`AsyncConnection` is the same as regular :class:`Connection`
  but with most methods and attributes and related objects configured
  for async operation.

  See :mod:`apsw.aio` for some controller implementations and :doc:`async`
  for more details.

  .. note:: Inheritance

    If you inherit from :class:`Connection` then this still works without
    having to write your own.  The returned object will be of your
    Connection subclass.  The parameters can be any positional and keyword
    arguments, and will be passed to your ``__init__`` method in the
    worker thread first.  ``super().__init__`` should be called
    from it as normal for inheritance.

.. attribute:: Connection.async_controller
  :type: AsyncConnectionController

  |badge-async-value|

  The controller in effect in async mode.

.. method:: Connection.async_run(call: typing.Callable, /, *args, **kwargs) -> typing.Any

  |badge-async-async|

  Calls ``call`` with the provided arguments in the async worker thread for this
  connection.

.. index:: sqlite3_set_authorizer

.. attribute:: Connection.authorizer
  :type: Authorizer | None

  |badge-async-value|

  While `preparing <https://sqlite.org/c3ref/prepare.html>`_
  statements, SQLite will call any defined authorizer to see if a
  particular action is ok to be part of the statement.

  Typical usage would be if you are running user supplied SQL and want
  to prevent harmful operations.

  The authorizer callback has 5 parameters:

    * An `operation code <https://sqlite.org/c3ref/c_alter_table.html>`_
    * A string (or None) dependent on the operation `(listed as 3rd) <https://sqlite.org/c3ref/c_alter_table.html>`_
    * A string (or None) dependent on the operation `(listed as 4th) <https://sqlite.org/c3ref/c_alter_table.html>`_
    * A string name of the database (or None)
    * Name of the innermost trigger or view doing the access (or None)

  The authorizer callback should return one of *SQLITE_OK*,
  *SQLITE_DENY* or *SQLITE_IGNORE*.
  (*SQLITE_DENY* is returned if there is an error in your
  Python code).

  Changing the authorizer (including setting to :code:`None`) will not
  affect currently executing statements.  Any cached statements
  or currently executing ones will be prepared again on their
  next use.

  .. seealso::

    * :ref:`Example <example_authorizer>`

  Calls: `sqlite3_set_authorizer <https://sqlite.org/c3ref/set_authorizer.html>`__

.. index:: sqlite3_autovacuum_pages

.. method:: Connection.autovacuum_pages(callable: typing.Callable[[str, int, int, int], int] | None) -> None

  |badge-async-dual|

  Calls `callable` to find out how many pages to autovacuum.  The callback has 4 parameters:

  * Database name: str. `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__
  * Database pages: int (how many pages make up the database now)
  * Free pages: int (how many pages could be freed)
  * Page size: int (page size in bytes)

  Return how many pages should be freed.  Values less than zero or more than the free pages are
  treated as zero or free page count.  On error zero is returned.

  .. warning:: READ THE NOTE IN THE SQLITE DOCUMENTATION.

    Calling back into SQLite can result in crashes, corrupt
    databases, or worse.

  Calls: `sqlite3_autovacuum_pages <https://sqlite.org/c3ref/autovacuum_pages.html>`__

.. index:: sqlite3_backup_init

.. method:: Connection.backup(databasename: str, sourceconnection: Connection | AsyncConnection, sourcedatabasename: str)  -> Backup

   |badge-async-dual|

   Opens a :ref:`backup object <Backup>`.  All data will be copied from source
   database to this database.

   :param databasename: Name of the database. `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__
   :param sourceconnection: The :class:`Connection` to copy a database from.
   :param sourcedatabasename: Name of the database in the source (eg ``main``).

   :rtype: :class:`Backup`

   .. seealso::

     * :doc:`Backup reference <backup>`
     * :ref:`Backup example <example_backup>`

   Calls: `sqlite3_backup_init <https://sqlite.org/c3ref/backup_finish.html#sqlite3backupinit>`__

.. index:: sqlite3_blob_open

.. method:: Connection.blob_open(database: str, table: str, column: str, rowid: int, writeable: bool)  -> Blob

   |badge-async-dual|

   Opens a blob for :ref:`incremental I/O <blobio>`.

   :param database: Name of the database.  `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__.
   :param table: The name of the table
   :param column: The name of the column
   :param rowid: The id that uniquely identifies the row.
   :param writeable: If True then you can read and write the blob.  If False then you can only read it.

   :rtype: :class:`Blob`

   .. seealso::

     * :ref:`Blob I/O example <example_blob_io>`
     * `SQLite row ids <https://sqlite.org/autoinc.html>`_

   Calls: `sqlite3_blob_open <https://sqlite.org/c3ref/blob_open.html>`__

.. index:: sqlite3_db_cacheflush

.. method:: Connection.cache_flush() -> None

  |badge-async-dual|

  Flushes caches to disk mid-transaction.

  Calls: `sqlite3_db_cacheflush <https://sqlite.org/c3ref/db_cacheflush.html>`__

.. method:: Connection.cache_stats(include_entries: bool = False) -> dict[str, int]

|badge-async-value|

Returns information about the statement cache as dict.

.. note::

  Calling execute with "select a; select b; insert into c ..." will
  result in 3 cache entries corresponding to each of the 3 queries
  present.

The returned dictionary has the following information.

.. list-table::
  :header-rows: 1
  :widths: auto

  * - Key
    - Explanation
  * - size
    - Maximum number of entries in the cache
  * - evictions
    - How many entries were removed (expired) to make space for a newer
      entry
  * - no_cache
    - Queries that had can_cache parameter set to False
  * - hits
    - A match was found in the cache
  * - misses
    - No match was found in the cache, or the cache couldn't be used
  * - no_vdbe
    - The statement was empty (eg a comment) or SQLite took action
      during parsing (eg some pragmas).  These are not cached and also
      included in the misses count
  * - too_big
    - UTF8 query size was larger than considered for caching.  These are also included
      in the misses count.
  * - max_cacheable_bytes
    - Maximum size of query (in bytes of utf8) that will be considered for caching
  * - entries
    - (Only present if `include_entries` is True) A list of the cache entries

If `entries` is present, then each list entry is a dict with the following information.

.. list-table::
  :header-rows: 1
  :widths: auto

  * - Key
    - Explanation
  * - query
    - Text of the query itself (first statement only)
  * - prepare_flags
    - Flags passed to `sqlite3_prepare_v3 <https://sqlite.org/c3ref/prepare.html>`__
      for this query
  * - explain
    - The value passed to `sqlite3_stmt_explain <https://sqlite.org/c3ref/stmt_explain.html>`__
      if >= 0
  * - uses
    - How many times this entry has been (re)used
  * - has_more
    - Boolean indicating if there was more query text than
      the first statement

.. index:: sqlite3_changes64

.. method:: Connection.changes() -> int

  |badge-async-value|

  Returns the number of database rows that were changed (or inserted
  or deleted) by the most recently completed INSERT, UPDATE, or DELETE
  statement.

  Calls: `sqlite3_changes64 <https://sqlite.org/c3ref/changes.html>`__

.. index:: sqlite3_close

.. method:: Connection.close(force: bool = False) -> None

  |badge-close|

  Closes the database.  If there are any outstanding :class:`cursors
  <Cursor>`, :class:`blobs <Blob>` or :class:`backups <Backup>` then
  they are closed too.  It is normally not necessary to call this
  method as the database is automatically closed when there are no
  more references.  It is ok to call the method multiple times.

  If your user defined functions or collations have direct or indirect
  references to the Connection then it won't be automatically garbage
  collected because of circular referencing that can't be
  automatically broken.  Calling *close* will free all those objects
  and what they reference.

  SQLite is designed to survive power failures at even the most
  awkward moments.  Consequently it doesn't matter if it is closed
  when the process is exited, or even if the exit is graceful or
  abrupt.  In the worst case of having a transaction in progress, that
  transaction will be rolled back by the next program to open the
  database, reverting the database to a know good state.

  If *force* is *True* then any exceptions are ignored.

  Calls: `sqlite3_close <https://sqlite.org/c3ref/close.html>`__

.. index:: sqlite3_collation_needed

.. method:: Connection.collation_needed(callable: typing.Callable[[Connection, str], None] | None) -> None

  |badge-async-dual|

  *callable* will be called if a statement requires a `collation
  <https://en.wikipedia.org/wiki/Collation>`_ that hasn't been
  registered. Your callable will be passed two parameters. The first
  is the connection object. The second is the name of the
  collation. If you have the collation code available then call
  :meth:`Connection.create_collation`.

  This is useful for creating collations on demand.  For example you
  may include the `locale <https://en.wikipedia.org/wiki/Locale>`_ in
  the collation name, but since there are thousands of locales in
  popular use it would not be useful to :meth:`prereigster
  <Connection.create_collation>` them all.  Using
  :meth:`~Connection.collation_needed` tells you when you need to
  register them.

  .. seealso::

    * :meth:`~Connection.create_collation`

  Calls: `sqlite3_collation_needed <https://sqlite.org/c3ref/collation_needed.html>`__

.. index:: sqlite3_table_column_metadata

.. method:: Connection.column_metadata(dbname: str | None, table_name: str, column_name: str) -> tuple[str, str, bool, bool, bool]

  |badge-async-dual|

  `dbname` is `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__, or None to search
  all databases.

  The returned :class:`tuple` has these fields:

  0: str - declared data type

  1: str - name of default collation sequence

  2: bool - True if not null constraint

  3: bool - True if part of primary key

  4: bool - True if column is `autoincrement <https://www.sqlite.org/autoinc.html>`__

  Calls: `sqlite3_table_column_metadata <https://sqlite.org/c3ref/table_column_metadata.html>`__

.. index:: sqlite3_db_config

.. method:: Connection.config(op: int, *args: int) -> int

    |badge-async-dual|

    :param op: A `configuration operation
      <https://sqlite.org/c3ref/c_dbconfig_defensive.html>`__
    :param args: Zero or more arguments as appropriate for *op*

    This is how to get the fkey setting::

      val = db.config(apsw.SQLITE_DBCONFIG_ENABLE_FKEY, -1)

    A parameter of zero would turn it off, 1 turns on, and negative
    leaves unaltered.  The effective value is always returned.

    Calls: `sqlite3_db_config <https://sqlite.org/c3ref/db_config.html>`__

.. attribute:: Connection.convert_binding
  :type: ConvertBinding | None

  |badge-async-value|

  Called on a cursor when a binding is not a supported type.
  This connection value is used when the cursor does not set
  its own value.  See :attr:`Cursor.convert_binding`

.. attribute:: Connection.convert_jsonb
  :type: ConvertJSONB | None

  |badge-async-value|

  Called on a cursor when a blob being returned is valid JSONB.
  This connection value is used when the cursor does not set
  its own value.  See :attr:`Cursor.convert_jsonb`

.. index:: sqlite3_create_function_v2

.. method:: Connection.create_aggregate_function(name: str, factory: AggregateFactory | None, numargs: int = -1, *, flags: int = 0) -> None

  |badge-async-dual|

  Registers an aggregate function.  Aggregate functions operate on all
  the relevant rows such as counting how many there are.

  :param name: The string name of the function.  It should be less than 255 characters
  :param factory: The function that will be called.  Use None to delete the function.
  :param numargs: How many arguments the function takes, with -1 meaning any number
  :param flags: `Function flags <https://www.sqlite.org/c3ref/c_deterministic.html>`__

  When a query starts, the *factory* will be called.  It can return an object
  with a *step* function called for each matching row, and a *final* function
  to provide the final value.

  Alternatively a non-class approach can return a tuple of 3 items:

    a context object
       This can be of any type

    a step function
       This function is called once for each row.  The first parameter
       will be the context object and the remaining parameters will be
       from the SQL statement.  Any value returned will be ignored.

    a final function
       This function is called at the very end with the context object
       as a parameter.  The value returned is set as the return for
       the function. The final function is always called even if an
       exception was raised by the step function. This allows you to
       ensure any resources are cleaned up.

  .. note::

    You can register the same named function but with different
    callables and *numargs*.  See
    :meth:`~Connection.create_scalar_function` for an example.

  .. seealso::

     * :ref:`Example <example_aggregate>`
     * :meth:`~Connection.create_scalar_function`
     * :meth:`~Connection.create_window_function`

  Calls: `sqlite3_create_function_v2 <https://sqlite.org/c3ref/create_function.html>`__

.. index:: sqlite3_create_collation_v2

.. method:: Connection.create_collation(name: str, callback: typing.Callable[[str, str], int] | None) -> None

  |badge-async-dual|

  You can control how SQLite sorts (termed `collation
  <https://en.wikipedia.org/wiki/Collation>`_) when giving the
  ``COLLATE`` term to a `SELECT
  <https://sqlite.org/lang_select.html>`_.  For example your
  collation could take into account locale or do numeric sorting.

  The *callback* will be called with two items.  It should return -1
  if the first is less then the second, 0 if they are equal, and 1 if
  first is greater::

     def mycollation(first: str, two: str) -> int:
         if first < second:
             return -1
         if first == second:
             return 0
         if first > second:
             return 1

  Passing None as the callback will unregister the collation.

  .. seealso::

    * :ref:`Example <example_collation>`
    * :meth:`Connection.collation_needed`

  Calls: `sqlite3_create_collation_v2 <https://sqlite.org/c3ref/create_collation.html>`__

.. index:: sqlite3_create_module_v2

.. method:: Connection.create_module(name: str, datasource: VTModule | None, *, use_bestindex_object: bool = False, use_no_change: bool = False, iVersion: int = 1, eponymous: bool=False, eponymous_only: bool = False, read_only: bool = False) -> None

    |badge-async-dual|

    Registers a virtual table, or drops it if *datasource* is *None*.
    See :ref:`virtualtables` for details.

    :param name: Module name (CREATE VIRTUAL TABLE table_name USING module_name...)
    :param datasource: Provides :class:`VTModule` methods
    :param use_bestindex_object: If True then BestIndexObject is used, else BestIndex
    :param use_no_change: Turn on understanding :meth:`VTCursor.ColumnNoChange` and using :attr:`apsw.no_change` to reduce :meth:`VTTable.UpdateChangeRow` work
    :param iVersion: iVersion field in `sqlite3_module <https://www.sqlite.org/c3ref/module.html>`__
    :param eponymous: Configures module to be `eponymous <https://www.sqlite.org/vtab.html#eponymous_virtual_tables>`__
    :param eponymous_only: Configures module to be `eponymous only <https://www.sqlite.org/vtab.html#eponymous_only_virtual_tables>`__
    :param read_only: Leaves `sqlite3_module <https://www.sqlite.org/c3ref/module.html>`__ methods that involve writing and transactions as NULL

    .. seealso::

       * :ref:`Example <example_virtual_tables>`

    Calls: `sqlite3_create_module_v2 <https://sqlite.org/c3ref/create_module.html>`__

.. index:: sqlite3_create_function_v2

.. method:: Connection.create_scalar_function(name: str, callable: ScalarProtocol | None, numargs: int = -1, *, deterministic: bool = False, flags: int = 0) -> None

  |badge-async-dual|

  Registers a scalar function.  Scalar functions operate on one set of parameters once.

  :param name: The string name of the function.  It should be less than 255 characters
  :param callable: The function that will be called.  Use None to unregister.
  :param numargs: How many arguments the function takes, with -1 meaning any number
  :param deterministic: When True this means the function always
           returns the same result for the same input arguments.
           SQLite's query planner can perform additional optimisations
           for deterministic functions.  For example a random()
           function is not deterministic while one that returns the
           length of a string is.
  :param flags: Additional `function flags <https://www.sqlite.org/c3ref/c_deterministic.html>`__

  .. note::

    You can register the same named function but with different
    *callable* and *numargs*.  For example::

      connection.create_scalar_function("toip", ipv4convert, 4)
      connection.create_scalar_function("toip", ipv6convert, 16)
      connection.create_scalar_function("toip", strconvert, -1)

    The one with the correct *numargs* will be called and only if that
    doesn't exist then the one with negative *numargs* will be called.

  .. seealso::

     * :ref:`Example <example_scalar>`
     * :meth:`~Connection.create_aggregate_function`
     * :meth:`~Connection.create_window_function`

  Calls: `sqlite3_create_function_v2 <https://sqlite.org/c3ref/create_function.html>`__

.. index:: sqlite3_create_window_function

.. method:: Connection.create_window_function(name:str, factory: WindowFactory | None, numargs: int =-1, *, flags: int = 0) -> None

    |badge-async-dual|

    Registers a `window function
    <https://sqlite.org/windowfunctions.html#user_defined_aggregate_window_functions>`__

    :param name: The string name of the function.  It should be less than 255 characters
    :param factory: Called to start a new window.  Use None to delete the function.
    :param numargs: How many arguments the function takes, with -1 meaning any number
    :param flags: `Function flags <https://www.sqlite.org/c3ref/c_deterministic.html>`__

    You need to provide callbacks for the ``step``, ``final``, ``value``
    and ``inverse`` methods.  This can be done by having `factory` as a
    class, returning an instance with the corresponding method names, or by having `factory`
    return a sequence of a first parameter, and then each of the 4
    functions.

    **Debugging note** SQlite always calls the ``final`` method to allow
    for cleanup.  If you have an exception in one of the other methods, then
    ``final`` will also be called, and you may see both methods in
    tracebacks.

    .. seealso::

     * :ref:`Example <example_window>`
     * :meth:`~Connection.create_scalar_function`
     * :meth:`~Connection.create_aggregate_function`

    Calls: `sqlite3_create_window_function <https://sqlite.org/c3ref/create_function.html>`__

.. method:: Connection.cursor() -> Cursor

  |badge-async-value|

  Creates a new :class:`Cursor` object on this database.

  :rtype: :class:`Cursor`

.. attribute:: Connection.cursor_factory
  :type: Callable[[Connection], Any]

  |badge-async-value|

  Defaults to :class:`Cursor`

  Called with a :class:`Connection` as the only parameter when a cursor
  is needed such as by the :meth:`cursor` method, or
  :meth:`Connection.execute`.

  Note that whatever is returned doesn't have to be an actual
  :class:`Cursor` instance, and just needs to have the methods present
  that are actually called.  These are likely to be `execute`,
  `executemany`, `close` etc.

.. index:: sqlite3_file_control

.. method:: Connection.data_version(schema: str | None = None) -> int

  |badge-async-dual|

  Unlike `pragma data_version
  <https://sqlite.org/pragma.html#pragma_data_version>`__ this value
  updates when changes are made by other connections, **AND** this one.

  :param schema: `schema` is `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__,
      defaulting to `main` if not supplied.

  See the :ref:`example <example_caching>`.

  Calls: `sqlite3_file_control <https://sqlite.org/c3ref/file_control.html>`__

.. index:: sqlite3_db_filename

.. method:: Connection.db_filename(name: str) -> str

  |badge-async-dual|

  Returns the full filename of the named (attached) database.  The
  main is `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__

  Calls: `sqlite3_db_filename <https://sqlite.org/c3ref/db_filename.html>`__

.. index:: sqlite3_db_name

.. method:: Connection.db_names() -> list[str]

 |badge-async-dual|

 Returns the list of database names.  For example the first database
 is named 'main', the next 'temp', and the rest with the name provided
 in `ATTACH <https://www.sqlite.org/lang_attach.html>`__

 Calls: `sqlite3_db_name <https://sqlite.org/c3ref/db_name.html>`__

.. index:: sqlite3_deserialize

.. method:: Connection.deserialize(name: str, contents: collections.abc.Buffer) -> None

   |badge-async-dual|

   Replaces the named database with an in-memory copy of *contents*.
   *name* is `main`, `temp`, the name in `ATTACH
   <https://sqlite.org/lang_attach.html>`__

   The resulting database is in-memory, read-write, and the memory is
   owned, resized, and freed by SQLite.

   .. seealso::

     * :meth:`Connection.serialize`

   Calls: `sqlite3_deserialize <https://sqlite.org/c3ref/deserialize.html>`__

.. method:: Connection.drop_modules(keep: Iterable[str] | None) -> None

  |badge-async-dual|

  If *keep* is *None* then all registered virtual tables are dropped.

  Otherwise *keep* is a sequence of strings, naming the virtual tables that
  are kept, dropping all others.

.. index:: sqlite3_enable_load_extension

.. method:: Connection.enable_load_extension(enable: bool) -> None

  |badge-async-dual|

  Enables/disables `extension loading
  <https://www.sqlite.org/loadext.html>`_
  which is disabled by default.

  :param enable: If True then extension loading is enabled, else it is disabled.

  .. seealso::

    * :meth:`~Connection.load_extension`

  Calls: `sqlite3_enable_load_extension <https://sqlite.org/c3ref/enable_load_extension.html>`__

.. attribute:: Connection.exec_trace
  :type: ExecTracer | None

  |badge-async-value|

  Called with the cursor, statement and bindings for
  each :meth:`~Cursor.execute` or :meth:`~Cursor.executemany` on this
  Connection, unless the :class:`Cursor` installed its own
  tracer. Your execution tracer can also abort execution of a
  statement.

  If *callable* is *None* then any existing execution tracer is
  removed.

  .. seealso::

    * :ref:`tracing`
    * :ref:`rowtracer`
    * :attr:`Cursor.exec_trace`

.. method:: Connection.execute(statements: str, bindings: Bindings | None = None, *, can_cache: bool = True, prepare_flags: int = 0, explain: int = -1) -> Cursor

    |badge-async-dual|

    Executes the statements using the supplied bindings.  Execution
    returns when the first row is available or all statements have
    completed.  (A cursor is automatically obtained).

    For pragmas you should use :meth:`pragma` which handles quoting and
    caching correctly.

    See :meth:`Cursor.execute` for more details, and the :ref:`example <example_executing_sql>`.

.. method:: Connection.executemany(statements: str, sequenceofbindings:Iterable[Bindings], *, can_cache: bool = True, prepare_flags: int = 0, explain: int = -1) -> Cursor

|badge-async-dual|

This method is for when you want to execute the same statements over a
sequence of bindings, such as inserting into a database.  (A cursor is
automatically obtained).

See :meth:`Cursor.executemany` for more details, and the :ref:`example <example_executemany>`.

.. index:: sqlite3_file_control

.. method:: Connection.file_control(dbname: str, op: int, pointer: int) -> bool

  |badge-async-dual|

  Calls the :meth:`~VFSFile.xFileControl` method on the :ref:`VFS`
  implementing :class:`file access <VFSFile>` for the database.

  :param dbname: The name of the database to affect.  `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__
  :param op: A `numeric code
    <https://sqlite.org/c3ref/c_fcntl_begin_atomic_write.html>`__ with values less
    than 100 reserved for SQLite internal use.
  :param pointer: A number which is treated as a ``void pointer`` at the C level.

  :returns: True or False indicating if the VFS understood the op.

  :meth:`reserve_bytes` does :code:`SQLITE_FCNTL_RESERVE_BYTES`.  The
  :ref:`example <example_filecontrol>` shows getting
  `SQLITE_FCNTL_DATA_VERSION
  <https://sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntldataversion>`__.
  You will find :meth:`data_version` more convenient.

  If you want data returned back then the *pointer* needs to point to
  something mutable.  Here is an example using :mod:`ctypes` of
  passing a Python dictionary to :meth:`~VFSFile.xFileControl` which
  can then modify the dictionary to set return values::

    obj={"foo": 1, 2: 3}                 # object we want to pass
    objwrap=ctypes.py_object(obj)        # objwrap must live before and after the call else
                                         # it gets garbage collected
    connection.file_control(
             "main",                     # which db
             123,                        # our op code
             ctypes.addressof(objwrap))  # get pointer

  The :meth:`~VFSFile.xFileControl` method then looks like this::

    def xFileControl(self, op, pointer):
        if op==123:                      # our op code
            obj=ctypes.py_object.from_address(pointer).value
            # play with obj - you can use id() to verify it is the same
            print(obj["foo"])
            obj["result"]="it worked"
            return True
        else:
            # pass to parent/superclass
            return super().xFileControl(op, pointer)

  This is how you set the chunk size by which the database grows.  Do
  not combine it into one line as the c_int would be garbage collected
  before the file control call is made::

     chunksize=ctypes.c_int(32768)
     connection.file_control("main", apsw.SQLITE_FCNTL_CHUNK_SIZE, ctypes.addressof(chunksize))

  Calls: `sqlite3_file_control <https://sqlite.org/c3ref/file_control.html>`__

.. index:: sqlite3_db_filename

.. attribute:: Connection.filename
  :type: str

  |badge-async-dual|

  The filename of the database.

  Calls: `sqlite3_db_filename <https://sqlite.org/c3ref/db_filename.html>`__

.. index:: sqlite3_filename_journal

.. attribute:: Connection.filename_journal
  :type: str

  |badge-async-dual|

  The journal filename of the database,

  Calls: `sqlite3_filename_journal <https://sqlite.org/c3ref/filename_database.html>`__

.. index:: sqlite3_filename_wal

.. attribute:: Connection.filename_wal
  :type: str

  |badge-async-dual|

  The WAL filename of the database,

  Calls: `sqlite3_filename_wal <https://sqlite.org/c3ref/filename_database.html>`__

.. method:: Connection.fts5_tokenizer(name: str, args: list[str] | None = None) -> apsw.FTS5Tokenizer

  |badge-async-dual|

  Returns the named tokenizer initialized with ``args``.  Names are case insensitive.

  .. seealso::

      * :meth:`register_fts5_tokenizer`
      * :doc:`textsearch`

.. method:: Connection.fts5_tokenizer_available(name: str) -> bool

  |badge-async-dual|

  Checks if the named tokenizer is registered.

  .. seealso::

      * :meth:`fts5_tokenizer`
      * :doc:`textsearch`
      * `FTS5 documentation <https://www.sqlite.org/fts5.html#custom_tokenizers>`__

.. index:: sqlite3_get_autocommit

.. method:: Connection.get_autocommit() -> bool

  |badge-async-value|

  Returns if the Connection is in auto commit mode (ie not in a transaction).

  Calls: `sqlite3_get_autocommit <https://sqlite.org/c3ref/get_autocommit.html>`__

.. method:: Connection.get_exec_trace() -> ExecTracer | None

  |badge-async-value|

  Returns the currently installed :attr:`execution tracer
  <Connection.exec_trace>`

.. method:: Connection.get_row_trace() -> RowTracer | None

  |badge-async-value|

  Returns the currently installed :attr:`row tracer
  <Connection.row_trace>`

.. index:: sqlite3_get_autocommit

.. attribute:: Connection.in_transaction
  :type: bool

  |badge-async-value|

  It is recommended to use :meth:`txn_state` instead which is more reliable.

  Calls: `sqlite3_get_autocommit <https://sqlite.org/c3ref/get_autocommit.html>`__

.. index:: sqlite3_interrupt

.. method:: Connection.interrupt() -> None

  |badge-async-value|

  Causes all pending operations on the database to abort at the
  earliest opportunity. You can call this from any thread.  For
  example you may have a long running query when the user presses the
  stop button in your user interface.  :exc:`InterruptError`
  will be raised in the queries that got interrupted.

  Calls: `sqlite3_interrupt <https://sqlite.org/c3ref/interrupt.html>`__

.. attribute:: Connection.is_async
  :type: bool

  |badge-async-value|

  `True` if this connection is operating in async mode.

.. index:: sqlite3_is_interrupted

.. attribute:: Connection.is_interrupted
   :type: bool

   |badge-async-value|

   Indicates if this connection has been interrupted.

   Calls: `sqlite3_is_interrupted <https://sqlite.org/c3ref/interrupt.html>`__

.. index:: sqlite3_last_insert_rowid

.. method:: Connection.last_insert_rowid() -> int

  |badge-async-value|

  Returns the integer key of the most recent insert in the database.

  Calls: `sqlite3_last_insert_rowid <https://sqlite.org/c3ref/last_insert_rowid.html>`__

.. index:: sqlite3_limit

.. method:: Connection.limit(id: int, newval: int = -1) -> int

  |badge-async-value|

  If called with one parameter then the current limit for that *id* is
  returned.  If called with two then the limit is set to *newval*.

  :param id: One of the `runtime limit ids <https://sqlite.org/c3ref/c_limit_attached.html>`_
  :param newval: The new limit.  This is a 32 bit signed integer even on 64 bit platforms.

  :returns: The limit in place on entry to the call.

  .. seealso::

    * :ref:`Example <example_limits>`

  Calls: `sqlite3_limit <https://sqlite.org/c3ref/limit.html>`__

.. index:: sqlite3_load_extension

.. method:: Connection.load_extension(filename: str, entrypoint: str | None = None) -> None

  |badge-async-dual|

  Loads *filename* as an `extension <https://www.sqlite.org/loadext.html>`_

  :param filename: The file to load, the extension is optional

  :param entrypoint: The initialization method to call.  If this
    parameter is not supplied, then SQLite tries :code:`sqlite3_extension_init`
    and a name derived from the filename.

  :raises ExtensionLoadingError: If the extension could not be
    loaded.  The exception string includes more details.

  .. seealso::

    * :meth:`~Connection.enable_load_extension`
    * :func:`apsw.sqlite_extra.load`

  Calls: `sqlite3_load_extension <https://sqlite.org/c3ref/load_extension.html>`__

.. attribute:: Connection.open_flags
  :type: int

  |badge-async-value|

  The combination of :attr:`flags <apsw.mapping_open_flags>` used to open the database.

.. attribute:: Connection.open_vfs
  :type: str

  |badge-async-value|

  The string name of the vfs used to open the database.

.. index:: sqlite3_overload_function

.. method:: Connection.overload_function(name: str, nargs: int) -> None

  |badge-async-dual|

  Registers a placeholder function so that a virtual table can provide an implementation via
  :meth:`VTTable.FindFunction`.

  :param name: Function name
  :param nargs: How many arguments the function takes

  Calls: `sqlite3_overload_function <https://sqlite.org/c3ref/overload_function.html>`__

.. method:: Connection.pragma(name: str, value: SQLiteValue | None = None, *, schema: str | None = None) -> typing.Any

  |badge-async-dual|

  Issues the pragma (with the value if supplied) and returns the result with
  :attr:`the least amount of structure <Cursor.get>`.  For example
  :code:`pragma("user_version")` will return just the number, while
  :code:`pragma("journal_mode", "WAL")` will return the journal mode
  now in effect.

  Pragmas do not support bindings, so this method is a convenient
  alternative to composing SQL text.  Pragmas are often executed
  while being prepared, instead of when run like regular SQL.  They
  may also contain encryption keys.  This method ensures they are
  not cached to avoid problems.

  Use the `schema` parameter to run the pragma against a different
  attached database (eg ``temp``).

  * :ref:`Example <example_pragma>`

.. index:: sqlite3_preupdate_hook

.. method:: Connection.preupdate_hook(callback: PreupdateHook | None, *, id: typing.Any = None) -> None

 |badge-async-dual|

 A callback just after a database row is updated.  You can have multiple hooks at once
 (managed by APSW) by specifying different ``id`` for each.  Using :class:`None` for
 ``callback`` will remove it.

 SQLite provides no way to report errors from the callback.  The SQLite level update
 will always succeed, with Python exceptions reported when control returns to Python
 code.

 .. important::

    The :doc:`session` extension uses the preupdate hook, and will **CRASH
    THE PROCESS** if you register a hook via this method, and then create
    a :class:`Session`.

 SQLlite must be compiled with ``SQLITE_ENABLE_PREUPDATE_HOOK`` and this must be known
 to APSW at compile time.  If not, this API and :class:`PreUpdate` will not be present.

 You do not get calls undoing changes when a transaction is
 aborted/rolled back.  Consequently you can't use this hook to track
 the current state of the database.  The approach taken by the
 :doc:`session` is to note the rowid (or primary keys for without rowid
 tables), and initial values the first time that a row is seen.  When a
 changeset is requested, it compares the contents of the row now to the row
 then, and generates the appropriate changeset entry.

 Calls: `sqlite3_preupdate_hook <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__

.. index:: sqlite3_file_control

.. method:: Connection.read(schema: str, which: int, offset: int, amount: int) -> tuple[bool, bytes]

  |badge-async-dual|

  Invokes the underlying VFS method to read data from the database.  It
  is strongly recommended to read aligned complete pages, since that is
  only what SQLite does.

  `schema` is `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__

  `which` is 0 for the database file, 1 for the journal.

  The return value is a tuple of a boolean indicating a complete read if
  True, and the bytes read which will always be the amount requested
  in size.

  `SQLITE_IOERR_SHORT_READ` will give a `False` value for the boolean,
  and there is no way of knowing how much was read.

  Implemented using `SQLITE_FCNTL_FILE_POINTER` and `SQLITE_FCNTL_JOURNAL_POINTER`.
  Errors will usually be generic `SQLITE_ERROR` with no message.

  Calls: `sqlite3_file_control <https://sqlite.org/c3ref/file_control.html>`__

.. index:: sqlite3_db_readonly

.. method:: Connection.readonly(name: str) -> bool

  |badge-async-dual|

  True or False if the named (attached) database was opened readonly or file
  permissions don't allow writing.  The name is `main`, `temp`, the
  name in `ATTACH <https://sqlite.org/lang_attach.html>`__

  An exception is raised if the database doesn't exist.

  Calls: `sqlite3_db_readonly <https://sqlite.org/c3ref/db_readonly.html>`__

.. method:: Connection.register_fts5_function(name: str, function: FTS5Function) -> None

  |badge-async-dual|

  Registers the (case insensitive) named function used as an `auxiliary
  function  <https://www.sqlite.org/fts5.html#custom_auxiliary_functions>`__.

  The first parameter to the function will be :class:`FTS5ExtensionApi`
  and the rest will be the function arguments at the SQL level.

.. method:: Connection.register_fts5_tokenizer(name: str, tokenizer_factory: FTS5TokenizerFactory) -> None

  |badge-async-dual|

  Registers a tokenizer factory.  Names are case insensitive.  It is not possible to
  unregister a tokenizer.

  .. seealso::

      * :meth:`fts5_tokenizer`
      * :doc:`textsearch`
      * `FTS5 documentation <https://www.sqlite.org/fts5.html#custom_tokenizers>`__

.. index:: sqlite3_db_release_memory

.. method:: Connection.release_memory() -> None

  |badge-async-dual|

  Attempts to free as much heap memory as possible used by this connection.

  Calls: `sqlite3_db_release_memory <https://sqlite.org/c3ref/db_release_memory.html>`__

.. index:: sqlite3_file_control

.. method:: Connection.reserve_bytes(schema: str | None = None, reserve: int = -1) -> int

  |badge-async-dual|

  Each database page can have `some bytes at the end set aside for other
  use by the VFS
  <https://sqlite.org/fileformat.html#reserved_bytes_per_page>`__.  For
  example encryption will store signature information, and the `checksum
  VFS <https://sqlite.org/cksumvfs.html>`__ stores a checksum.

  It is recommended to do a :code:`VACUUM` after a change to ensure it
  takes effect.  You can use :func:`apsw.ext.dbinfo` to get the
  :class:`~apsw.ext.DatabaseFileInfo` to see what the database file
  is using right now.

  :param schema: `schema` is `main`, `temp`, the name in `ATTACH
      <https://sqlite.org/lang_attach.html>`__, defaulting to `main` if not
      supplied.
  :param reserve: The new value to apply.  SQLite only supports values
      between 0 and 255 inclusive.

  The current value is returned.  Note that it may be waiting for a
  :code:`VACUUM` before it gets applied.

  Calls: `sqlite3_file_control <https://sqlite.org/c3ref/file_control.html>`__

.. attribute:: Connection.row_trace
  :type: RowTracer | None

  |badge-async-value|

  Called with the cursor and row being returned for
  :class:`cursors <Cursor>` associated with this Connection, unless
  the Cursor installed its own tracer.  You can change the data that
  is returned or cause the row to be skipped altogether.

  If *callable* is *None* then any existing row tracer is
  removed.

  .. seealso::

    * :ref:`tracing`
    * :ref:`rowtracer`
    * :attr:`Cursor.exec_trace`

.. index:: sqlite3_serialize

.. method:: Connection.serialize(name: str) -> bytes

  |badge-async-dual|

  Returns a memory copy of the database. *name* is `main`, `temp`, the name
  in `ATTACH <https://sqlite.org/lang_attach.html>`__

  The memory copy is the same as if the database was backed up to
  disk.

  If the database name doesn't exist, then None is returned, not an
  exception (this is SQLite's behaviour).  One exception is than an
  empty temp will result in a None return.

   .. seealso::

     * :meth:`Connection.deserialize`

  Calls: `sqlite3_serialize <https://sqlite.org/c3ref/serialize.html>`__

.. method:: Connection.set_authorizer(callable: Authorizer | None) -> None

  |badge-async-dual|

  Sets the :attr:`authorizer`

.. index:: sqlite3_busy_handler

.. method:: Connection.set_busy_handler(callable: typing.Callable[[int], bool] | None) -> None

   |badge-async-dual|

   Sets the busy handler to callable. callable will be called with one
   integer argument which is the number of prior calls to the busy
   callback for the same lock. If the busy callback returns False,
   then SQLite returns *SQLITE_BUSY* to the calling code. If
   the callback returns True, then SQLite tries to open the table
   again and the cycle repeats.

   If you previously called :meth:`~Connection.set_busy_timeout` then
   calling this overrides that.

   Passing None unregisters the existing handler.

   .. seealso::

     * :meth:`Connection.set_busy_timeout`
     * :ref:`Busy handling <busyhandling>`

   Calls: `sqlite3_busy_handler <https://sqlite.org/c3ref/busy_handler.html>`__

.. index:: sqlite3_busy_timeout

.. method:: Connection.set_busy_timeout(milliseconds: int) -> None

  |badge-async-dual|

  If the database is locked such as when another connection is making
  changes, SQLite will keep retrying.  This sets the maximum amount of
  time SQLite will keep retrying before giving up.  If the database is
  still busy then :class:`apsw.BusyError` will be returned.

  :param milliseconds: Maximum thousandths of a second to wait.

  If you previously called :meth:`~Connection.set_busy_handler` then
  calling this overrides that.

  .. seealso::

     * :meth:`Connection.set_busy_handler`
     * :ref:`Busy handling <busyhandling>`

  Calls: `sqlite3_busy_timeout <https://sqlite.org/c3ref/busy_timeout.html>`__

.. index:: sqlite3_commit_hook

.. method:: Connection.set_commit_hook(callable: CommitHook | None, *, id: typing.Any = None) -> None

  |badge-async-dual|

  *callable* will be called just before a commit.  It should return
  False for the commit to go ahead and True for it to be turned
  into a rollback. In the case of an exception in your callable, a
  True (rollback) value is returned.  Pass None to unregister
  the existing hook.

  You can have multiple hooks at once (managed by APSW) by specifying
  different ``id`` for each one.

  .. seealso::

    * :ref:`Example <example_commit_hook>`

  Calls: `sqlite3_commit_hook <https://sqlite.org/c3ref/commit_hook.html>`__

.. method:: Connection.set_exec_trace(callable: ExecTracer | None) -> None

   |badge-async-value|

   Method to set :attr:`Connection.exec_trace`

.. index:: sqlite3_set_last_insert_rowid

.. method:: Connection.set_last_insert_rowid(rowid: int) -> None

  |badge-async-dual|

  Sets the value calls to :meth:`last_insert_rowid` will return.

  Calls: `sqlite3_set_last_insert_rowid <https://sqlite.org/c3ref/set_last_insert_rowid.html>`__

.. index:: sqlite3_trace_v2

.. method:: Connection.set_profile(callable: typing.Callable[[str, int], None] | None) -> None

  |badge-async-dual|

  Sets a callable which is invoked at the end of execution of each
  statement and passed the statement string and how long it took to
  execute. (The execution time is in nanoseconds.) Note that it is
  called only on completion. If for example you do a ``SELECT`` and only
  read the first result, then you won't reach the end of the statement.

  Calls: `sqlite3_trace_v2 <https://sqlite.org/c3ref/trace_v2.html>`__

.. index:: sqlite3_progress_handler

.. method:: Connection.set_progress_handler(callable: typing.Callable[[], bool] | None, nsteps: int = 100, *, id: typing.Any = None) -> None

  |badge-async-dual|

  Sets a callable which is invoked every *nsteps* SQLite inststructions.
  The callable should return True to abort or False to continue. (If
  there is an error in your Python *callable* then True/abort will be
  returned).  SQLite raises :exc:`InterruptError` for aborts.

  Use :class:`None` to cancel the progress handler.  Multiple handlers
  can be present at once (implemented by APSW). Registered callbacks are
  distinguished by their ``id`` - an equality test is done to match ids.

  You can use :class:`apsw.ext.Trace` to see how many steps are used for
  a representative statement, or :class:`apsw.ext.ShowResourceUsage` to
  see how many are used in a block.  It will generally be several million
  per second.

  .. seealso::

     * :ref:`Example <example_progress_handler>`

  Calls: `sqlite3_progress_handler <https://sqlite.org/c3ref/progress_handler.html>`__

.. index:: sqlite3_rollback_hook

.. method:: Connection.set_rollback_hook(callable: typing.Callable[[], None] | None, *, id: typing.Any = None) -> None

  |badge-async-dual|

  Sets a callable which is invoked during a rollback.  If *callable*
  is *None* then any existing rollback hook is unregistered.

  The *callable* is called with no parameters and the return value is ignored.

  You can have multiple hooks at once (managed by APSW) by specifying
  different ``id`` for each one.

  Calls: `sqlite3_rollback_hook <https://sqlite.org/c3ref/commit_hook.html>`__

.. method:: Connection.set_row_trace(callable: RowTracer | None) -> None

  |badge-async-value|

  Method to set :attr:`Connection.row_trace`

.. index:: sqlite3_update_hook

.. method:: Connection.set_update_hook(callable: typing.Callable[[int, str, str, int], None] | None) -> None

  |badge-async-dual|

  Calls *callable* whenever a row is updated, deleted or inserted.  If
  *callable* is *None* then any existing update hook is
  unregistered.  The update hook cannot make changes to the database while
  the query is still executing, but can record them for later use or
  apply them in a different connection.

  The update hook is called with 4 parameters:

    type (int)
      *SQLITE_INSERT*, *SQLITE_DELETE* or *SQLITE_UPDATE*
    database name (str)
      `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__
    table name (str)
      The table on which the update happened
    rowid (int)
      The affected row

  .. seealso::

      * :ref:`Example <example_update_hook>`

  Calls: `sqlite3_update_hook <https://sqlite.org/c3ref/update_hook.html>`__

.. index:: sqlite3_wal_hook

.. method:: Connection.set_wal_hook(callable: typing.Callable[[Connection, str, int], int] | None) -> None

 |badge-async-dual|

 *callable* will be called just after data is committed in :ref:`wal`
 mode.  It should return *SQLITE_OK* or an error code.  The
 callback is called with 3 parameters:

   * The Connection
   * The database name.  `main`, `temp`, the name in `ATTACH <https://sqlite.org/lang_attach.html>`__
   * The number of pages in the wal log

 You can pass in None in order to unregister an existing hook.

 Calls: `sqlite3_wal_hook <https://sqlite.org/c3ref/wal_hook.html>`__

.. index:: sqlite3_setlk_timeout

.. method:: Connection.setlk_timeout(ms: int, flags: int) -> None

  |badge-async-dual|

  Sets a VFS level timeout.

  Calls: `sqlite3_setlk_timeout <https://sqlite.org/c3ref/setlk_timeout.html>`__

.. method:: Connection.sqlite3_pointer() -> int

|badge-async-value|

Returns the underlying `sqlite3 *
<https://sqlite.org/c3ref/sqlite3.html>`_ for the connection. This
method is useful if there are other C level libraries in the same
process and you want them to use the APSW connection handle. The value
is returned as a number using `PyLong_FromVoidPtr
<https://docs.python.org/3/c-api/long.html?highlight=pylong_fromvoidptr#c.PyLong_FromVoidPtr>`__
under the hood. You should also ensure that you increment the
reference count on the :class:`Connection` for as long as the other
libraries are using the pointer.  It is also a very good idea to call
:meth:`sqlite_lib_version` and ensure it is the same as the other
libraries.

.. index:: sqlite3_db_status64

.. method:: Connection.status(op: int, reset: bool = False) -> tuple[int, int]

  |badge-async-dual|

  Returns current and highwater measurements for the database.

  :param op: A `status parameter <https://sqlite.org/c3ref/c_dbstatus_options.html>`_
  :param reset: If *True* then the highwater is set to the current value
  :returns: A tuple of current value and highwater value

  .. seealso::

    * :func:`apsw.status` which does the same for SQLite as a whole
    * :ref:`Example <example_status>`

  Calls: `sqlite3_db_status64 <https://sqlite.org/c3ref/db_status.html>`__

.. index:: sqlite3_system_errno

.. attribute:: Connection.system_errno
 :type: int

 |badge-async-value|

 The underlying system error code for the most recent I/O error.

 Calls: `sqlite3_system_errno <https://sqlite.org/c3ref/system_errno.html>`__

.. index:: sqlite3_table_column_metadata

.. method:: Connection.table_exists(dbname: str | None, table_name: str) -> bool

  |badge-async-dual|

  Returns True if the named table exists, else False.

  ``dbname`` is ``main``, ``temp``, the name in `ATTACH
  <https://sqlite.org/lang_attach.html>`__, or None to search  all
  databases

  Calls: `sqlite3_table_column_metadata <https://sqlite.org/c3ref/table_column_metadata.html>`__

.. index:: sqlite3_total_changes64

.. method:: Connection.total_changes() -> int

  |badge-async-value|

  Returns the total number of database rows that have be modified,
  inserted, or deleted since the database connection was opened.

  Calls: `sqlite3_total_changes64 <https://sqlite.org/c3ref/total_changes.html>`__

.. index:: sqlite3_trace_v2, sqlite3_stmt_status

.. method:: Connection.trace_v2(mask: int, callback: typing.Callable[[dict], None] | None = None, *, id: typing.Any = None) -> None

  |badge-async-dual|

  Registers a trace callback.  Multiple traces can be active at once
  (implemented by APSW).  A callback of :class:`None` unregisters a
  trace.  Registered callbacks are distinguished by their ``id`` - an
  equality test is done to match ids.

  The callback is called with a dict of relevant values based on the
  code.

  .. list-table::
    :header-rows: 1
    :widths: auto

    * - Key
      - Type
      - Explanation
    * - code
      - :class:`int`
      - One of the `trace event codes <https://www.sqlite.org/c3ref/c_trace.html>`__
    * - connection
      - :class:`Connection`
      - Connection this trace event belongs to
    * - sql
      - :class:`str`
      - SQL text (except SQLITE_TRACE_ROW and SQLITE_TRACE_CLOSE).
    * - id
      - :class:`int`
      - An opaque key to correlate events on the same statement.  The
        id can be reused after SQLITE_TRACE_PROFILE.
    * - trigger
      - :class:`bool`
      - If `trigger <https://www.sqlite.org/lang_createtrigger.html>`__
        SQL is executing then this is ``True`` and the SQL is of the trigger.
        Virtual table nested queries also come through as trigger activity.
    * - total_changes
      - :class:`int`
      - Value of :meth:`total_changes`  (SQLITE_TRACE_STMT and SQLITE_TRACE_PROFILE only)
    * - nanoseconds
      - :class:`int`
      - nanoseconds SQL took to execute (SQLITE_TRACE_PROFILE only)
    * - stmt_status
      - :class:`dict`
      - SQLITE_TRACE_PROFILE only: Keys are names from `status parameters
        <https://www.sqlite.org/c3ref/c_stmtstatus_counter.html>`__ - eg
        *"SQLITE_STMTSTATUS_VM_STEP"* and corresponding integer values.
        The counters are reset each time a statement
        starts execution.  This includes any changes made by triggers.

  Note that SQLite ignores any errors from the trace callbacks, so
  whatever was being traced will still proceed.  Exceptions will be
  delivered when your Python code resumes.

  If you register for all trace types, the following sequence will happen.

  * SQLITE_TRACE_STMT with `trigger` `False` and an `id` and `sql` of
    the statement.
  * Multiple times: SQLITE_TRACE_STMT with the same `id` and `trigger`
    `True` if a trigger is executed.  The first time the `sql` will be
    ``TRIGGER name`` and then subsequent calls will be lines of the
    trigger.  This also happens for virtual tables that make queries.
  * Multiple times: SQLITE_TRACE_ROW with the same `id` for each time
    execution stopped at a row. (Rows visited by triggers do not cause
    thie event)
  * SQLITE_TRACE_PROFILE with the same `id` for any virtual table
    queries - the ``sql`` will be of those queries
  * SQLITE_TRACE_PROFILE with the same `id` for the initial SQL.

  .. seealso::

    * :ref:`Example <example_trace_v2>`
    * :class:`apsw.ext.Trace`

  Calls:
    * `sqlite3_trace_v2 <https://sqlite.org/c3ref/trace_v2.html>`__
    * `sqlite3_stmt_status <https://sqlite.org/c3ref/stmt_status.html>`__

.. attribute:: Connection.transaction_mode
   :type: str

   |badge-async-value|

   The mode used for the outermost transaction when using the
   :meth:`context manager (with) <__enter__>`.

   The value will be one of ``DEFERRED`` (default), ``IMMEDIATE``,
   or ``EXCLUSIVE``.  When setting it must be one of those values
   in any case.

.. index:: sqlite3_txn_state

.. method:: Connection.txn_state(schema: str | None = None) -> int

  |badge-async-dual|

  Returns the current transaction state of the database, or a specific schema
  if provided.  :attr:`apsw.mapping_txn_state` contains the values returned.

  Calls: `sqlite3_txn_state <https://sqlite.org/c3ref/txn_state.html>`__

.. method:: Connection.vfsname(dbname: str) -> str | None

|badge-async-dual|

Issues the `SQLITE_FCNTL_VFSNAME
<https://sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlvfsname>`__
file control against the named database (`main`, `temp`, attached
name).

This is useful to see which VFS is in use, and if inheritance is used
then ``/`` will separate the names.  If you have a :class:`VFSFile` in
use then its fully qualified class name will also be included.

If ``SQLITE_FCNTL_VFSNAME`` is not implemented, ``dbname`` is not a
database name, or an error occurred then ``None`` is returned.

.. index:: sqlite3_vtab_config

.. method:: Connection.vtab_config(op: int, val: int = 0) -> None

 |badge-async-sync|

 Callable during virtual table :meth:`~VTModule.Connect`/:meth:`~VTModule.Create`.

 Calls: `sqlite3_vtab_config <https://sqlite.org/c3ref/vtab_config.html>`__

.. index:: sqlite3_vtab_on_conflict

.. method:: Connection.vtab_on_conflict() -> int

 |badge-async-sync|

 Callable during virtual table :meth:`insert <VTTable.UpdateInsertRow>` or
 :meth:`update <VTTable.UpdateChangeRow>`

 Calls: `sqlite3_vtab_on_conflict <https://sqlite.org/c3ref/vtab_on_conflict.html>`__

.. index:: sqlite3_wal_autocheckpoint

.. method:: Connection.wal_autocheckpoint(n: int) -> None

    |badge-async-dual|

    Sets how often the :ref:`wal` checkpointing is run.

    :param n: A number representing the checkpointing interval or
      zero/negative to disable auto checkpointing.

    Calls: `sqlite3_wal_autocheckpoint <https://sqlite.org/c3ref/wal_autocheckpoint.html>`__

.. index:: sqlite3_wal_checkpoint_v2

.. method:: Connection.wal_checkpoint(dbname: str | None = None, mode: int = apsw.SQLITE_CHECKPOINT_PASSIVE) -> tuple[int, int]

    |badge-async-dual|

    Does a WAL checkpoint.  Has no effect if the database(s) are not in WAL mode.

    :param dbname:  The name of the database or all databases if None

    :param mode: One of the `checkpoint modes <https://sqlite.org/c3ref/wal_checkpoint_v2.html>`__.

    :return: A tuple of the size of the WAL log in frames and the
       number of frames checkpointed as described in the
       `documentation
       <https://sqlite.org/c3ref/wal_checkpoint_v2.html>`__.

    Calls: `sqlite3_wal_checkpoint_v2 <https://sqlite.org/c3ref/wal_checkpoint_v2.html>`__

PreUpdate class
===============

.. class:: PreUpdate

  Provides the details of one update to the
  :meth:`Connection.preupdate_hook` callback.

  .. note::

     The object is only valid inside a the callback.
     Using it outside the hook gives :exc:`InvalidContextError`.
     You should copy all desired information in the callback.

.. index:: sqlite3_preupdate_blobwrite

.. attribute:: PreUpdate.blob_write
  :type: int

  Writes to blobs show up as `DELETE`, with this having the
  column number being rewritten.  The value is negative if
  no blob is being written.

  Only the old value is available.  To get the new value you have
  to query the database.

  Calls: `sqlite3_preupdate_blobwrite <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__

.. attribute:: PreUpdate.connection
  :type: Connection

  The :class:`Connection` the preupdate is called on.

.. attribute:: PreUpdate.database_name
  :type: str

  ``main``, ``temp``, the name of an attached database.

.. index:: sqlite3_preupdate_depth

.. attribute:: PreUpdate.depth
  :type: int

  0 for direct SQL, 1 for triggers, 2 and so on for triggers
  firing by a higher level trigger.

  Calls: `sqlite3_preupdate_depth <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__

.. index:: sqlite3_preupdate_new

.. attribute:: PreUpdate.new
  :type: SQLiteValues | None

  Row values for an INSERT, or after an UPDATE.  :class:`None` for
  DELETE.  See also :attr:`old` and :attr:`update`.

  Calls: `sqlite3_preupdate_new <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__

.. index:: sqlite3_preupdate_old

.. attribute:: PreUpdate.old
  :type: SQLiteValues | None

  Row values for a DELETE, or before an UPDATE. :class:`None` for
  INSERT.  See also :attr:`new` and :attr:`update`.

  Calls: `sqlite3_preupdate_old <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__

.. attribute:: PreUpdate.op
  :type: str

  The operation code as a string  ``INSERT``,
  ``DELETE``, or ``UPDATE``.  See :attr:`opcode`
  for this as a number.

.. attribute:: PreUpdate.opcode
  :type: int

  The operation code - ``apsw.SQLITE_INSERT``,
  ``apsw.SQLITE_DELETE``, or ``apsw.SQLITE_UPDATE``.
  See :attr:`op` for this as a string.

.. attribute:: PreUpdate.rowid
  :type: int

  The affected rowid.

.. attribute:: PreUpdate.rowid_new
  :type: int

  New rowid if changed via rowid UPDATE.

.. attribute:: PreUpdate.table_name
  :type: str

  Table name.

.. index:: sqlite3_preupdate_old, sqlite3_preupdate_new

.. attribute:: PreUpdate.update
  :type: tuple[SQLiteValue | Literal[no_change], ...] | None

  For UPDATE compares old and new values, providing the changed value,
  or :attr:`apsw.no_change` if that column was not changed.

  :class:`None` for INSERT and DELETE.  See also :attr:`old` and
  :attr:`new`.

  Calls:
    * `sqlite3_preupdate_old <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__
    * `sqlite3_preupdate_new <https://sqlite.org/c3ref/preupdate_blobwrite.html>`__

