Package tsurugi_dbapi

Tsurugi Python DB-API.

Examples

import tsurugi_dbapi as tsurugi

with tsurugi.connect(
    endpoint="tcp://localhost:12345",
    user="tsurugi",
    password="password",
    default_timeout=30,  # seconds
) as connection:
    with connection.cursor() as cursor:
        cursor.execute("insert into example values (1, 100, 'abc')")
        print("insert rowcount:", cursor.rowcount)
        connection.commit()

        cursor.execute("select * from example")
        for row in cursor:
            print("row:", row)
        connection.commit()

Note

See Config, connect(), Connection, and Cursor for more details.

Sub-modules

tsurugi_dbapi.error
tsurugi_dbapi.type_code

Functions

def connect(*args, **kwargs)

Constructor for creating a connection to the Tsurugi.

Args

*args : Config, optional
configuration object.
**kwargs : dict, optional
e.g. endpoint="tcp://localhost:12345", user="tsurugi"

Returns

Connection
Connection object.

Examples

import tsurugi_dbapi as tsurugi

config = tsurugi.Config()
config.endpoint = "tcp://localhost:12345"
config.user = "tsurugi"
config.password = "password"
config.default_timeout = 30  # seconds
with tsurugi.connect(config) as connection:
    pass
import tsurugi_dbapi as tsurugi

with tsurugi.connect(
    endpoint="tcp://localhost:12345",
    user="tsurugi",
    password="password",
    default_timeout=30,  # seconds
) as connection:
    pass
def env_logger_init(filters='tsubakuro_rust_python=info', file_path=None)

Initialize env_logger.

Args

filters : str, optional
filter string. If ommitted, "tsubakuro_rust_python=info" is used.
file_path : str, optional
log file path. If None, logs to stderr.

Examples

import tsurugi_dbapi as tsurugi

tsurugi.env_logger_init("tsubakuro_rust_python=trace")

Note

def logging_init()

Initialize logging.

Examples

import logging
import tsurugi_dbapi as tsurugi

logging.basicConfig()
logger = logging.getLogger("_tsubakuro_rust_python")
logger.setLevel(5)  # TRACE

tsurugi.logging_init()

Note

Classes

class Column

Column metadata.

Attributes

name : str
Column name. (read only)
description : Optional[str]
Column description. (read only)
type_code : str
Type code. (read only)
atom_type_code : int
AtomType code. -1 if unknown. (read only)
sql_type : str
SQL type. (read only)
sql_type_name : Optional[str]
SQL type name. (read only)
length : Optional[int]
Length for string types. (read only)
precision : Optional[int]
Precision for numeric types. (read only)
scale : Optional[int]
Scale for numeric types. (read only)
nullable : Optional[bool]
Nullable flag. (read only)

Instance variables

var atom_type_code

AtomType code.

var description

Column description.

var length

Length.

var name

Column name.

var nullable

Nullable.

var precision

Precision.

var scale

Scale.

var sql_type

SQL type.

var sql_type_name

SQL type name.

var type_code

type_code.

class CommitOption (commit_type=Ellipsis, auto_dispose=False, timeout=None)

Commit option for transaction.

Attributes

commit_type : CommitType
Commit type. Default is CommitType.DEFAULT.
auto_dispose : bool
Auto dispose flag. Default is False.
commit_timeout : int
Commit timeout in seconds.

Examples

import tsurugi_dbapi as tsurugi

commit_option = tsurugi.CommitOption(tsurugi.CommitType.DEFAULT, False, 60)

Instance variables

var auto_dispose

Auto dispose flag.

var commit_timeout

Commit timeout in seconds.

var commit_type

Commit type.

class CommitType

Commit type for transaction.

Attributes

DEFAULT
the default commit type (rely on the database settings).
ACCEPTED
commit operation has accepted, and the transaction will never abort except system errors.
AVAILABLE
commit data has been visible for others.
STORED
commit data has been saved on the local disk.
PROPAGATED
commit data has been propagated to the all suitable nodes.

Class variables

var ACCEPTED
var AVAILABLE
var DEFAULT
var PROPAGATED
var STORED
class Config (*args, **kwargs)

Configuration options for connecting to Tsurugi.

Attributes

application_name : str
Application name.
endpoint : str
Endpoint URL of the Tsurugi server.
user : str
Username for authentication.
password : str
Password for authentication.
auth_token : str
Authentication token.
credentials : str
Path to credentials file.
session_label : str
Session label for the connection.
blob_relay_service_endpoint : str
Blob relay service endpoint. since 0.10.0
blob_relay_service_ca_cert_pem_file : str
Blob relay service CA certificate PEM file. since 0.10.0
lob_upload_timeout : int
Large object upload timeout in seconds. since 0.10.0
lob_download_timeout : int
Large object download timeout in seconds. since 0.10.0
transaction_option : TransactionOption
Transaction option.
commit_option : CommitOption
Commit option.
shutdown_option : ShutdownOption
Shutdown option.
default_timeout : int
Default timeout in seconds.

Examples

import tsurugi_dbapi as tsurugi

config = tsurugi.Config()
config.application_name = "tsurugi-dbapi example"
config.endpoint = "tcp://localhost:12345"
config.user = "tsurugi"
config.password = "password"
config.session_label = "tsurugi-dbapi session"
config.default_timeout = 30  # seconds
import tsurugi_dbapi as tsurugi

config = tsurugi.Config(
    application_name="tsurugi-dbapi example",
    endpoint="tcp://localhost:12345",
    user="tsurugi",
    password="password",
    session_label="tsurugi-dbapi session",
    default_timeout=30,  # seconds
)

Instance variables

var application_name

Application name.

var auth_token

Authentication token.

var blob_relay_service_ca_cert_pem_file

Blob relay service CA certificate PEM file.

since 0.10.0

var blob_relay_service_endpoint

Blob relay service endpoint.

since 0.10.0

var commit_option

Commit option.

var credentials

Path to credentials file.

var default_timeout

Default timeout in seconds.

var endpoint

Endpoint URL of the Tsurugi server.

var lob_download_timeout

Large object download timeout in seconds.

since 0.10.0

var lob_upload_timeout

Large object upload timeout in seconds.

since 0.10.0

var password

Password for authentication.

var session_label

Session label for the connection.

var shutdown_option

Shutdown option.

var transaction_option

Transaction option.

var user

Username for authentication.

Methods

def merge(self, /, other)

Merge another Config into this one.

Args

other : Config
other configuration object.
def set(self, /, *args, **kwargs)

Set configuration options.

Args

*args : Config | TransactionOption | CommitOption | ShutdownOption | str, optional
other configuration object.
**kwargs : dict, optional
e.g. endpoint="tcp://localhost:12345", user="tsurugi"
class Connection

Connection to Tsurugi.

Attributes

transaction_option : TransactionOption
Transaction option. (write only)
commit_option : CommitOption
Commit option. (write only)
shutdown_option : ShutdownOption
Shutdown option. (write only)
closed : bool
Whether the connection is closed. (read only)

Instance variables

var closed

Whether the connection is closed.

var commit_option

Commit option.

var shutdown_option

Shutdown option.

var transaction_option

Transaction option.

Methods

def close(self, /)

Close the connection.

def commit(self, /, option=None)

Commit the current transaction.

Args

option : CommitOption, optional
CommitOption object.

Examples

connection.commit()
def cursor(self, /)

Create a new cursor object using the connection.

Returns

Cursor
Cursor object.

Examples

with connection.cursor() as cursor:
   pass
def find_table_metadata(self, /, table_name)

Find table metadata.

Args

table_name : str
Table name.

Returns

Optional[TableMetadata]
Table metadata, or None if the table does not exist.

Examples

metadata = connection.find_table_metadata("my_table")
def get_table_metadata(self, /, table_name)

Get table metadata.

Args

table_name : str
Table name.

Returns

TableMetadata
Table metadata.

Raises

TargetNotFoundException
If the table does not exist.

Examples

import tsurugi_dbapi as tsurugi

try:
    metadata = connection.get_table_metadata("my_table")
except tsurugi.error.TargetNotFoundException:
    pass
def list_tables(self, /)

List table names.

Returns

List[str]
List of table names.

Examples

table_names = connection.list_tables()
def lob_transfer_type(self, /)

Get the large object transfer type.

Returns

LobTransferType
Large object transfer type.

Examples

lob_transfer_type = connection.lob_transfer_type()

since 0.10.0

def rollback(self, /)

Rollback the current transaction.

Examples

connection.rollback()
class Cursor

Cursor object for executing SQL statements and fetching results.

Attributes

connection : Connection
Connection object associated with the cursor. (read only)
description : Optional[Sequence[Tuple[str, str, None, Optional[int], Optional[int], Optional[int], Optional[bool]]]]
Description of the query result set. (name, tsurugi_dbapi.type_code, display_size, internal_size, precision, scale, null_ok). (read only)
arraysize : int
Number of rows to fetch at a time with Cursor.fetchmany(). Default is 1.
rownumber : int
Current row number (0-based). (read only)
rowcount : int
Number of rows affected by the last Cursor.execute*() method. -1 if not applicable. (read only)
closed : bool
Whether the cursor is closed. (read only)

Instance variables

var arraysize

Number of rows to fetch at a time with Cursor.fetchmany().

var closed

Whether the cursor is closed.

var connection

Connection object associated with the cursor. (read only)

var description

Description of the query result set.

var executemany_async

Whether to execute Cursor.executemany() asynchronously. Default is True.

var rowcount

Number of rows affected by the last Cursor.execute*() method.

var rownumber

Current row number (0-based).

Methods

def callproc(self, /, _procname)

Not supported in this implementation.

def clear(self, /)

Closes the current result set and clears cached prepared statements.

def close(self, /)

Close the cursor.

def execute(self, /, operation, parameters=None)

Execute a SQL statement.

Args

operation : str
SQL statement to be executed.
parameters : Tuple[Any, ...] | dict[str, Any], optional
Parameters for the SQL statement.

Examples

cursor.execute("insert into example values (1, 'Hello')")
connection.commit()
cursor.execute("insert into example values (?, ?)", (1, "Hello"))
connection.commit()
cursor.execute("insert into example values (:id, :name)", {"id": 1, "name": "Hello"})
connection.commit()
def executemany(self, /, operation, seq_of_parameters)

Execute a prepared SQL statement multiple times.

Args

operation : str
SQL statement to be executed.
seq_of_parameters : Sequence[Tuple[Any, ...] | dict[str, Any]]
Sequence of parameters for the SQL statement.

Examples

cursor.executemany("insert into example values (?, ?)", [(1, "Hello"), (2, "World")])
connection.commit()
cursor.executemany("insert into example values (:id, :name)", [{"id": 1, "name": "Hello"}, {"id": 2, "name": "World"}])
connection.commit()
def fetchall(self, /)

Fetch all (remaining) rows of a query result set.

Returns

List[Tuple[Any, …]]
A list of sequences, each representing a row of the result set.

Examples

cursor.execute("select * from example")
rows = cursor.fetchall()
connection.commit()
def fetchmany(self, /, size=None)

Fetch the next set of rows of a query result set.

Args

size (int, optional) - Number of rows to fetch. If not specified, use the cursor's arraysize attribute.

Returns

List[Tuple[Any, …]]
A list of sequences, each representing a row of the result set.

Examples

cursor.execute("select * from example")
rows = cursor.fetchmany(10)
connection.commit()

Note

See also Cursor.arraysize for setting the default number of rows to fetch with fetchmany().

def fetchone(self, /)

Fetch the next row of a query result set.

Returns

Optional[Tuple[Any, …]]
A single sequence representing the next row of the result set, or None if no more data is available.

Examples

cursor.execute("select * from example where id = 1")
row = cursor.fetchone()
connection.commit()
def next(self, /)

Fetch the next row of a query result set.

Returns

Tuple[Any, …]
A single sequence representing the next row of the result set.

Raises

StopIteration
When no more data is available.
def nextset(self, /)

Not supported in this implementation.

def prepare(self, /, operation, parameters)

Prepare a SQL statement for execution.

Args

operation : str
SQL statement to be prepared.
parameters : Tuple[Any, ...] | dict[str, Any]
Parameters for the SQL statement.

Examples

import tsurugi_dbapi as tsurugi

sql = "insert into example values (?, ?)"
cursor.prepare(sql, (tsurugi.type_code.Int64, tsurugi.type_code.Str))
cursor.execute(sql, (1, "Hello"))
connection.commit()
import tsurugi_dbapi as tsurugi

sql = "insert into example values (:id, :name)"
cursor.prepare(sql, {"id": tsurugi.type_code.Int64, "name": tsurugi.type_code.Str})
cursor.execute(sql, {"id": 1, "name": "Hello"})
connection.commit()
def setinputsizes(self, /, _sizes)

This method is a no-op in this implementation.

def setoutputsize(self, /, _size)

This method is a no-op in this implementation.

def upload_blob(self, /, value, timeout=None)

Upload a blob value.

Args

value : bytes | None
Blob value to be uploaded.
timeout : int, optional
Timeout for the blob upload operation in seconds. If not specified, use the connection's default LOB upload timeout.

Returns

Blob
Uploaded blob.

Examples

blob = cursor.upload_blob(b"\x01\x02\x03", 10)
cursor.execute("insert into blob_example values (?, ?)", (1, blob))
connection.commit()

since 0.10.0

def upload_clob(self, /, value, timeout=None)

Upload a clob value.

Args

value : str | None
Clob value to be uploaded.
timeout : int, optional
Timeout for the clob upload operation in seconds. If not specified, use the connection's default LOB upload timeout.

Returns

Clob
Uploaded clob.

Examples

clob = cursor.upload_clob("Hello, World!", 10)
cursor.execute("insert into clob_example values (?, ?)", (1, clob))
connection.commit()

since 0.10.0

class DataError (*args, **kwargs)

data error (PEP 249)

Ancestors

Subclasses

class DatabaseError (*args, **kwargs)

database error (PEP 249)

Ancestors

  • Error
  • builtins.Exception
  • builtins.BaseException

Subclasses

class Error (*args, **kwargs)

base class of all other exceptions (PEP 249)

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

class IntegrityError (*args, **kwargs)

integrity error (PEP 249)

Ancestors

Subclasses

class InterfaceError (*args, **kwargs)

interface error (PEP 249)

Ancestors

  • Error
  • builtins.Exception
  • builtins.BaseException
class InternalError (*args, **kwargs)

internal error (PEP 249)

Ancestors

Subclasses

class LobTransferType

Large object transfer type.

Attributes

NOT_USE
does not use transfer type.
RELAY
Blob Relay transfer type.

since 0.10.0

Class variables

var NOT_USE
var RELAY
class NotSupportedError (*args, **kwargs)

not supported error (PEP 249)

Ancestors

Subclasses

class OperationalError (*args, **kwargs)

operation error (PEP 249)

Ancestors

Subclasses

class ProgrammingError (*args, **kwargs)

programming error (PEP 249)

Ancestors

Subclasses

class ShutdownOption (shutdown_type=Ellipsis, timeout=None)

Shutdown option for connection.

Attributes

shutdown_type : ShutdownType
Shutdown type. Default is ShutdownType.GRACEFUL.
shutdown_timeout : int
Shutdown timeout in seconds.

Examples

import tsurugi_dbapi as tsurugi

shutdown_option = tsurugi.ShutdownOption(tsurugi.ShutdownType.GRACEFUL, 30)

Instance variables

var shutdown_timeout

Shutdown timeout in seconds.

var shutdown_type

Shutdown type.

class ShutdownType

Shutdown type for connection.

Attributes

NOTHING
Do nothing special during shutdown.
GRACEFUL
Waits for the ongoing requests and safely shutdown the session.
FORCEFUL
Cancelling the ongoing requests and safely shutdown the session.

Class variables

var FORCEFUL
var GRACEFUL
var NOTHING
class TableMetadata

Table metadata.

Attributes

database_name : str
Database name. (read only)
schema_name : str
Schema name. (read only)
table_name : str
Table name. (read only)
table_description : Optional[str]
Table description. (read only)
columns : List[Column]
Columns metadata. (read only)
description : Sequence[Tuple[str, str, None, Optional[int], Optional[int], Optional[int], Optional[bool]]]
Columns description. (name, tsurugi_dbapi.type_code, display_size, internal_size, precision, scale, null_ok). (read only)
primary_keys : List[str]
Primary keys. (read only)

Instance variables

var columns

Columns metadata.

var database_name

Database name.

var description

Columns description.

var primary_keys

Primary keys.

var schema_name

Schema name.

var table_description

Table description.

var table_name

Table name.

class TransactionOption (type=Ellipsis)

Transaction option.

Attributes

transaction_type : TransactionType
Transaction type. Default is TransactionType.OCC.
label : str
Transaction label.
include_ddl : bool
Whether the transaction modifies definitions (DDL). Default is False. Only applicable for TransactionType.LTX.
write_preserve : List[str]
List of table names to preserve for write operations. Only applicable for TransactionType.LTX.
inclusive_read_area : List[str]
List of table names to include in the read area. Only applicable for TransactionType.LTX.
exclusive_read_area : List[str]
List of table names to exclude from the read area. Only applicable for TransactionType.LTX.
scan_parallel : int
Degree of parallelism for scanning. Only applicable for TransactionType.RTX.
begin_timeout : int
Begin transaction timeout in seconds

Examples

import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption(tsurugi.TransactionType.OCC)
tx_option.label = "tsurugi-dbapi OCC example"
import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption(tsurugi.TransactionType.LTX)
tx_option.label = "tsurugi-dbapi LTX example"
tx_option.write_preserve = ["table1", "table2"]
import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption(tsurugi.TransactionType.RTX)
tx_option.label = "tsurugi-dbapi RTX example"
tx_option.scan_parallel = 4

Instance variables

var begin_timeout

Begin transaction timeout in seconds.

var exclusive_read_area

Exclusive read area.

var include_ddl

Include DDL flag.

var inclusive_read_area

Inclusive read area.

var label

Transaction label.

var scan_parallel

Scan parallel.

var transaction_type

Transaction type.

var write_preserve

Write preserve.

Methods

def ddl(label=None)

Create a new TransactionOption for LTX transaction for DDL.

Args

label : str, optional
Transaction label.

Returns

TransactionOption
A new TransactionOption instance for LTX transaction for DDL.

Examples

import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption.ddl(label="LTX transaction for DDL")
def ltx(label=None,
write_preserve=None,
inclusive_read_area=None,
exclusive_read_area=None)

Create a new TransactionOption for LTX transaction.

Args

label : str, optional
Transaction label.
write_preserve : List[str], optional
List of table names to preserve for write operations.
inclusive_read_area : List[str], optional
List of table names to include in the read area.
exclusive_read_area : List[str], optional
List of table names to exclude from the read area.

Returns

TransactionOption
A new TransactionOption instance for LTX transaction.

Examples

import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption.ltx(
    label="LTX transaction",
    write_preserve=["table1", "table2"],
)
def occ(label=None)

Create a new TransactionOption for OCC transaction.

Args

label : str, optional
Transaction label.

Returns

TransactionOption
A new TransactionOption instance for OCC transaction.

Examples

import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption.occ(label="OCC transaction")
def rtx(label=None, scan_parallel=None)

Create a new TransactionOption for RTX transaction.

Args

label : str, optional
Transaction label.
scan_parallel : int, optional
Degree of parallelism for scanning.

Returns

TransactionOption
A new TransactionOption instance for RTX transaction.

Examples

import tsurugi_dbapi as tsurugi

tx_option = tsurugi.TransactionOption.rtx(
    label="RTX transaction",
    scan_parallel=4,
)
class TransactionType

Transaction type.

Attributes

OCC
Optimistic concurrency control (OCC) transaction.
LTX
Long transaction (LTX).
RTX
Read-only transaction (RTX).

Class variables

var LTX
var OCC
var RTX
class Warning (*args, **kwargs)

important warning (PEP 249)

Ancestors

  • builtins.Exception
  • builtins.BaseException