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

.. currentmodule:: apsw

.. _cursors:

Cursors (executing SQL)
***********************

A cursor encapsulates a SQL query and returning results.  You only need an
explicit cursor if you want more information or control over execution.  Using
:meth:`Connection.execute` or :meth:`Connection.executemany` will automatically
obtain a cursor behind the scenes.

If you need a cursor you should call :meth:`~Connection.cursor` on your
database::

  db = apsw.Connection("databasefilename")
  cursor = db.cursor()

The :ref:`example <example_executing_sql>` shows how to execute SQL and
how to provide values used in queries (bindings).

Cursors are cheap.  Use as many as you need. Behind the scenes a
:class:`Cursor` maps to a `SQLite statement <https://sqlite.org/c3ref/stmt.html>`_.
APSW maintains a :ref:`cache <statementcache>` so that the mapping is very fast, and the
SQLite objects are reused when possible.

.. note::

  Cursors on the same :ref:`Connection <connections>` are not isolated
  from each other.  Anything done on one cursor is immediately visible
  to all other Cursors on the same connection.  This still applies if
  you start transactions.  Connections are isolated from each other
  with cursors on other connections not seeing changes until they are
  committed.

.. seealso::

  * `SQLite transactions <https://sqlite.org/lang_transaction.html>`_
  * `Atomic commit <https://sqlite.org/atomiccommit.html>`_
  * :ref:`Benchmarking`

Cursor class
============

.. class:: Cursor(connection: Connection)

 Use :meth:`Connection.cursor` to make a new cursor.

.. method:: Cursor.__aiter__() -> Self

    |badge-async-async|

    AsyncCursors are async iterators

.. method:: Cursor.__anext__() -> typing.Any

    |badge-async-async|

    Cursors are iterators

.. method:: Cursor.__iter__(self: Cursor) -> Cursor

    |badge-async-sync|

    Cursors are iterators

.. method:: Cursor.__next__() -> typing.Any

    |badge-async-sync|

    Cursors are iterators

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

  |badge-close|

  Async version of :meth:`close`

.. index:: sqlite3_bind_parameter_count

.. attribute:: Cursor.bindings_count
  :type: int

  |badge-async-value|

  How many bindings are in the statement.  The ``?`` form
  results in the largest number.  For example you could do
  ``SELECT ?123``` in which case the count will be ``123``.

  Calls: `sqlite3_bind_parameter_count <https://sqlite.org/c3ref/bind_parameter_count.html>`__

.. index:: sqlite3_bind_parameter_name

.. attribute:: Cursor.bindings_names
  :type: tuple[str | None]

  |badge-async-dual|

  A tuple of the name of each bind parameter, or None for no name.  The
  leading marker (``?:@$``) is omitted

  .. note::

    SQLite parameter numbering starts at ``1``, while Python
    indexing starts at ``0``.

  Calls: `sqlite3_bind_parameter_name <https://sqlite.org/c3ref/bind_parameter_name.html>`__

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

  |badge-close|

  It is very unlikely you will need to call this method.
  Cursors are automatically garbage collected and when there
  are none left will allow the connection to be garbage collected if
  it has no other references.

  It is safe to call the method multiple times.

  A cursor is open if there are remaining statements to execute (if
  your query included multiple statements), or if you called
  :meth:`~Cursor.executemany` and not all of the sequence of bindings
  have been used yet.

  :param force: If False then you will get exceptions if there is
   remaining work to do be in the Cursor such as more statements to
   execute, more data from the executemany binding sequence etc. If
   force is True then all remaining work and state information will be
   silently discarded.

.. attribute:: Cursor.connection
  :type: Connection

  |badge-async-value|

  :class:`Connection` this cursor is using

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

  |badge-async-value|

  Called with the :class:`Cursor`, parameter number, and value when
  an unsuppported type is used in a binding. Note that parameter
  numbers start at 1.

  If set to ``None`` then conversion is disabled for this cursor.

  .. seealso::

    * :attr:`bindings_count`
    * :attr:`bindings_names`

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

  |badge-async-value|

  Called with the :class:`Cursor`, column number, and bytes value
  when a blob value is valid JSONB.  The callback can :func:`decode the
  <jsonb_decode>` or return the bytes as is.

  If set to ``None`` then conversion is disabled for this cursor.

  .. seealso::

    You can consult the description to get further confirmation if
    the value is intended to be JSONB.

    * :attr:`Cursor.description_full`
    * :attr:`Cursor.description`

.. attribute:: Cursor.description
    :type: tuple[tuple[str, str, None, None, None, None, None], ...]

    |badge-async-dual|

    Based on the `DB-API cursor property
    <https://www.python.org/dev/peps/pep-0249/>`__, this returns the
    same as :meth:`get_description` but with 5 Nones appended because
    SQLite does not have the information.

.. index:: sqlite3_column_name, sqlite3_column_decltype, sqlite3_column_database_name, sqlite3_column_table_name, sqlite3_column_origin_name

.. attribute:: Cursor.description_full
  :type: tuple[tuple[str, str, str, str, str], ...]

  |badge-async-dual|

Only present if SQLITE_ENABLE_COLUMN_METADATA was defined at
compile time.

Returns all information about the query result columns. In
addition to the name and declared type, you also get the database
name, table name, and origin name.

Calls:
  * `sqlite3_column_name <https://sqlite.org/c3ref/column_name.html>`__
  * `sqlite3_column_decltype <https://sqlite.org/c3ref/column_decltype.html>`__
  * `sqlite3_column_database_name <https://sqlite.org/c3ref/column_database_name.html>`__
  * `sqlite3_column_table_name <https://sqlite.org/c3ref/column_database_name.html>`__
  * `sqlite3_column_origin_name <https://sqlite.org/c3ref/column_database_name.html>`__

.. attribute:: Cursor.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
  cursor.

  If *callable* is *None* then execution tracing is disabled for the cursor..

  .. seealso::

    * :ref:`tracing`
    * :ref:`executiontracer`
    * :attr:`Connection.exec_trace`

.. index:: sqlite3_prepare_v3, sqlite3_step, sqlite3_bind_int64, sqlite3_bind_null, sqlite3_bind_text64, sqlite3_bind_double, sqlite3_bind_blob64, sqlite3_bind_zeroblob64, sqlite3_stmt_explain

.. method:: Cursor.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.

    :param statements: One or more SQL statements such as ``select *
      from books`` or ``begin; insert into books ...; select
      last_insert_rowid(); end``.
    :param bindings: If supplied should either be a sequence or a dictionary.  Each item must be one of the :ref:`supported types <types>`,
      :class:`zeroblob`, or a wrapped :ref:`Python object <pyobject>`
    :param can_cache: If False then the statement cache will not be used to find an already prepared query, nor will it be
      placed in the cache after execution
    :param prepare_flags: `flags <https://sqlite.org/c3ref/c_prepare_dont_log.html>`__ passed to
      `sqlite_prepare_v3 <https://sqlite.org/c3ref/prepare.html>`__
    :param explain: If 0 or greater then the statement is passed to `sqlite3_stmt_explain <https://sqlite.org/c3ref/stmt_explain.html>`__
       where you can force it to not be an explain, or force explain or explain query plan.

    :raises TypeError: The bindings supplied were neither a dict nor a sequence
    :raises BindingsError: You supplied too many or too few bindings for the statements
    :raises IncompleteExecutionError: There are remaining unexecuted queries from your last execute

    .. seealso::

       * :ref:`Example <example_executing_sql>` showing how to use bindings
       * :ref:`executionmodel`

    Calls:
      * `sqlite3_prepare_v3 <https://sqlite.org/c3ref/prepare.html>`__
      * `sqlite3_step <https://sqlite.org/c3ref/step.html>`__
      * `sqlite3_bind_int64 <https://sqlite.org/c3ref/bind_blob.html>`__
      * `sqlite3_bind_null <https://sqlite.org/c3ref/bind_blob.html>`__
      * `sqlite3_bind_text64 <https://sqlite.org/c3ref/bind_blob.html>`__
      * `sqlite3_bind_double <https://sqlite.org/c3ref/bind_blob.html>`__
      * `sqlite3_bind_blob64 <https://sqlite.org/c3ref/bind_blob.html>`__
      * `sqlite3_bind_zeroblob64 <https://sqlite.org/c3ref/bind_blob.html>`__
      * `sqlite3_stmt_explain <https://sqlite.org/c3ref/stmt_explain.html>`__

.. method:: Cursor.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.  Conceptually it does this::

    for binding in sequenceofbindings:
        cursor.execute(statements, binding)

  The return is the cursor itself which acts as an iterator.  Your
  statements can return data.  See :meth:`~Cursor.execute` for more
  information, and the :ref:`example <example_executemany>`.

.. index:: sqlite3_expanded_sql

.. attribute:: Cursor.expanded_sql
  :type: str

  |badge-async-dual|

  The SQL text with bound parameters expanded.  For example::

     execute("select ?, ?", (3, "three"))

  would return::

     select 3, 'three'

  Note that while SQLite supports nulls in strings, their implementation
  of sqlite3_expanded_sql stops at the first null.

  You will get :exc:`MemoryError` if SQLite ran out of memory, or if
  the expanded string would exceed `SQLITE_LIMIT_LENGTH
  <https://www.sqlite.org/c3ref/c_limit_attached.html>`__.

  Calls: `sqlite3_expanded_sql <https://sqlite.org/c3ref/expanded_sql.html>`__

.. method:: Cursor.fetchall() -> list[SQLiteValues]

  |badge-async-dual|

  Returns all remaining result rows as a list.  This method is defined
  in DBAPI.  See :meth:`get` which does the same thing, but with the least
  amount of structure to unpack.

.. method:: Cursor.fetchone() -> typing.Any | None

  |badge-async-dual|

  Returns the next row of data or None if there are no more rows.

.. attribute:: Cursor.get
 :type: Any

 |badge-async-dual|

 Like :meth:`fetchall` but returns the data with the least amount of structure
 possible.

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

    * - Query
      - Result
    * - select 3
      - 3
    * - select 3,4
      - (3, 4)
    * - select 3; select 4
      - [3, 4]
    * - select 3,4; select 4,5
      - [(3, 4), (4, 5)]
    * - select 3,4; select 5
      - [(3, 4), 5]

 Row tracers are not called when using this method.

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

  |badge-async-value|

  Returns the :attr:`connection` this cursor is part of

.. index:: sqlite3_column_name, sqlite3_column_decltype

.. method:: Cursor.get_description() -> tuple[tuple[str, str], ...]

   |badge-async-dual|

   If you are trying to get information about a table or view,
   then `pragma table_info <https://sqlite.org/pragma.html#pragma_table_info>`__
   is better.  If you want to know up front what columns and other
   details a query does then :func:`apsw.ext.query_info` is useful.

   Returns a tuple describing each column in the result row.  The
   return is identical for every row of the results.

   The information about each column is a tuple of ``(column_name,
   declared_column_type)``.  The type is what was declared in the
   ``CREATE TABLE`` statement - the value returned in the row will be
   whatever type you put in for that row and column.

   See the :ref:`query_info example <example_query_details>`.

   Calls:
     * `sqlite3_column_name <https://sqlite.org/c3ref/column_name.html>`__
     * `sqlite3_column_decltype <https://sqlite.org/c3ref/column_decltype.html>`__

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

  |badge-async-value|

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

  .. seealso::

    * :ref:`tracing`

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

  |badge-async-value|

  Returns the currently installed (via :meth:`~Cursor.set_row_trace`)
  row tracer.

  .. seealso::

    * :ref:`tracing`

.. attribute:: Cursor.has_vdbe
  :type: bool

  |badge-async-value|

  ``True`` if the SQL does anything.  Comments have nothing to
  evaluate, and so are ``False``.

.. index:: sqlite3_stmt_isexplain

.. attribute:: Cursor.is_explain
  :type: int

  |badge-async-value|

  Returns 0 if executing a normal query, 1 if it is an EXPLAIN query,
  and 2 if an EXPLAIN QUERY PLAN query.

  Calls: `sqlite3_stmt_isexplain <https://sqlite.org/c3ref/stmt_isexplain.html>`__

.. index:: sqlite3_stmt_readonly

.. attribute:: Cursor.is_readonly
  :type: bool

  |badge-async-value|

  Returns True if the current query does not change the database.

  Note that called functions, virtual tables etc could make changes though.

  Calls: `sqlite3_stmt_readonly <https://sqlite.org/c3ref/stmt_readonly.html>`__

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

  |badge-async-value|

  Called with cursor and row being returned.  You can
  change the data that is returned or cause the row to be skipped
  altogether.

  If ``None`` then row tracing is disabled for this cursor.

  .. seealso::

    * :ref:`tracing`
    * :ref:`rowtracer`
    * :attr:`Connection.row_trace`

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

  |badge-async-value|

  Sets the :attr:`execution tracer <Cursor.exec_trace>`

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

  |badge-async-value|

  Sets the :attr:`row tracer <Cursor.row_trace>`.  If ``None``
  then row tracing is disabled for this cursor.

.. index:: sqlite3_sql

.. attribute:: Cursor.sql
  :type: str

  |badge-async-dual|

  The SQL being executed

  Calls: `sqlite3_sql <https://sqlite.org/c3ref/expanded_sql.html>`__

