Python Driver: Cursor

A Cursor executes statements and reads their results. Create it with Connection.cursor(). A cursor reads one result at a time. Each new execution discards the previous result on that cursor.

Execute

Method Behavior
execute(query, params=None, *, fetch_size=None) Executes one SQL statement.
executemany(query, params) Executes a SQL statement once per parameter set. It sends each execution separately, leaves the final execution’s result and row count, and leaves transaction control to the caller.
executeany(lang, query, params=None, *, fetch_size=None, namespace=None) Runs a statement in an enabled Polypheny query language. Use "sql" for SQL, "mongo" for MQL, or "cypher" for Cypher. namespace selects the default namespace for that statement.

These methods update the cursor and return None. Pass params=None for an unparameterized statement. For SQL positional parameters use ? and pass a list or tuple of values. For SQL named parameters use :name and pass a dictionary with keys such as "name". The available placeholder syntax depends on the query language. Supply identifiers separately from parameter values and use trusted names when constructing query text.

fetch_size requests a server frame size. A positive value bounds the number of source rows in a frame. A graph row can expand into several streamed elements. Omit fetch_size to use the server default. The number passed to fetchmany() limits the results returned by that call and can span frames.

Read results

Method Behavior
fetchone() Returns the next tabular row as a list, or the next document or flat graph element as a dictionary. Returns None at exhaustion.
fetchmany(size=None) Reads up to size results and returns a list. Uses arraysize when size is omitted. Returns an empty list when exhausted.
fetchall() Returns all remaining results as a list. For large results, use iteration or fetchmany() to limit how much you keep in memory.
iter(cursor) and next(cursor) Iterate over the current results.

Fetch only after executing a statement that produced a result set. An individual cell can contain None even when the row itself is a list. The connector fetches additional tabular, document, and graph frames as needed. Cypher and Graph Results

Result attributes

Attribute Value
arraysize Default maximum results returned by fetchmany(). It starts at 1 and resets to 1 on each execution. Assign a new value after executing a statement.
rowcount The server’s scalar result for a statement without a result set. Returns -1 before execution and for statements with result sets.
description None before execution and for document, flat graph, or scalar results. A relational result, including mixed graph and scalar projections, supplies a list with one tuple per column.

Each description tuple is (column_label, None, None, None, None, precision, scale, is_nullable). The label is the first item and the type code is always None. The tuple includes an extra placeholder before precision, so its shape differs from the seven-item DB-API tuple.

Reset and close

  • reset() closes the current result and restores rowcount, description and arraysize to their initial values. The next execution also resets the cursor.
  • close() closes the current result and releases the cursor. The connection remains open. Repeated calls to close() return without effect.
  • setinputsizes(sizes) and setoutputsize(sizes, column=None) are no-ops.
  • Stored-procedure calls through callproc() and multiple result sets through nextset() are unavailable.

Example

The example connects to the plain Prism listener, creates a temporary test table by name, and demonstrates named parameters, relational paging and the column metadata.

import os
from uuid import uuid4

import polypheny

connection = polypheny.connect(
    (os.getenv("POLYPHENY_HOST", "127.0.0.1"), int(os.getenv("POLYPHENY_PORT", "20590"))),
    username=os.getenv("POLYPHENY_USER", "pa"),
    password=os.getenv("POLYPHENY_PASSWORD", ""),
    transport="plain",
)
table = f"py_cursor_{uuid4().hex[:12]}"
cursor = connection.cursor()
try:
    cursor.execute(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY)")
    cursor.executemany(f"INSERT INTO {table} VALUES (?)", [(1,), (2,), (3,)])
    connection.commit()

    cursor.execute(
        f"SELECT id AS n FROM {table} WHERE id >= :minimum ORDER BY id",
        {"minimum": 1},
        fetch_size=2,
    )
    cursor.arraysize = 2
    print([column[0] for column in cursor.description])
    print(cursor.fetchmany())
    print(cursor.fetchall())
finally:
    try:
        connection.rollback()
        cursor.execute(f"DROP TABLE IF EXISTS {table}")
    finally:
        connection.close()
© Polypheny GmbH. All Rights Reserved.