Skip to content
Connect > Client Libraries > Python Client

Python DB-API and SQLAlchemy

The pyami-3forge package includes a DB-API 2.0 driver and a SQLAlchemy dialect, so a Python program can query 3forge Enterprise with standard database code and pandas.read_sql.

Overview

Both are part of the Python client package and run over its SQL connection:

  • The DB-API driver: pyami.db.ami_dbapi.ami_dbapi gives connections and cursors.
  • The SQLAlchemy dialect: ami+jdbc sits on the DB-API driver and is registered when the package is installed.

Both need a client certificate the server accepts; see Connecting and Securing a Client.

Connecting with the DB-API driver

connect() opens a connection and checks it with SELECT 1.

from pyami.db.ami_dbapi import ami_dbapi

con = ami_dbapi.connect(host="localhost", port=3280,
                        username="demo", password="demo123",
                        trusted_server_pub_file="3forge.pub",
                        client_cert_file="client.crt.pem",
                        client_key_file="client.key.pem")
cur = con.cursor()
cur.execute("SELECT sym, px FROM Quotes WHERE sym == :sym", {"sym": "IBM"})
print(cur.fetchall())
con.close()

The module is imported as shown: from pyami.db import ami_dbapi gives the package, which has no connect.

Argument Default What it sets
host "localhost" The server
port 3280 The Center's JDBC listener
username, password "demo", "demo123" The login
timeout_ms 60000 The query timeout sent to the server
limit 10000 The most rows a query returns. More are dropped without notice
use_ssl True TLS
failover_endpoints None (host, port) pairs to try if the connection drops
trusted_server_pub_file, client_cert_file, client_key_file, client_key_password "" The TLS settings, as in Server pinning and TLS settings

A connection that cannot be checked raises OperationError:

OperationError: failed to connect to AMI server at 'localhost:3280': no response to validation query ...

Using a connection and cursor

The driver follows DB-API 2.0, with paramstyle = "named" and threadsafety = 1.

  • Parameters are substituted into the text: a statement names them as :name and takes a dictionary, and the driver writes the values into the statement before sending it, quoting strings and writing None or a missing name as NULL.
  • Results come back as tuples: fetchone(), fetchmany(size), and fetchall() return rows; description names the columns, rowcount counts the rows, and lastrowid holds the last id an AUTOGEN index assigned, or None.
  • Numbers come back as numpy scalars: a value is a numpy scalar of the column's own width, such as np.int32 for an Integer column or np.float64 for a Double column, not a Python float or int. Convert them before passing rows to json.dumps or similar.
  • Statements commit on their own: commit() and rollback() do nothing.
  • Connections and cursors are closed explicitly: a connection is not a context manager and a cursor cannot be iterated, so a program calls close() and reads rows with fetchall().
  • A failed statement raises DatabaseError: the error carries the server's message, e.g: [shard 0] 009-EXCEPTION: Unknown table: Quotes.

Connect errors and imports

  • The connect error class is OperationError: the module has no OperationalError, the usual DB-API name, so code that names it fails with AttributeError. Catch DatabaseError, the parent class, instead.

Connecting with SQLAlchemy

The dialect's URL is ami+jdbc://user:password@host:port/, and every query parameter in the URL is passed to the DB-API connect().

from urllib.parse import quote
import pandas as pd
import sqlalchemy as sa

url = ("ami+jdbc://demo:demo123@localhost:3280/"
       f"?trusted_server_pub_file={quote('3forge.pub')}"
       f"&client_cert_file={quote('client.crt.pem')}"
       f"&client_key_file={quote('client.key.pem')}")
engine = sa.create_engine(url)

with engine.connect() as conn:
    frame = pd.read_sql_query("SELECT * FROM Quotes", conn)
    table = pd.read_sql_table("Quotes", conn)
    print(sa.inspect(conn).get_table_names())

The URL takes the same arguments as connect():

  • File paths are quoted: urllib.parse.quote escapes them for the URL.
  • Only the DB-API argument names are accepted: timeout_ms, limit, use_ssl, and the 4 TLS settings. Any other name, such as timeout, raises TypeError: connect() got an unexpected keyword argument 'timeout'. Did you mean 'timeout_ms'?.
  • TLS is on by default: use_ssl=false is for a listener with no keystore.

How SQL is translated

The dialect writes 3forge Enterprise SQL for SQLAlchemy expressions:

SQLAlchemy Becomes
a == b a == b
.like("p%"), .ilike(), .startswith(), .contains() ~~ with a regular expression
.limit(n).offset(m) LIMIT m, n. An offset without a limit raises AMI SQL requires LIMIT when OFFSET is specified.
func.now() timestamp()
distinct() with no group_by GROUP BY on the selected columns
Identifiers Quoted with backticks

LIKE against another column, rather than a value, cannot be translated and raises a CompileError.

Creating tables

metadata.create_all() creates PUBLIC tables with these column types:

SQLAlchemy type Column type
Integer INT
BigInteger LONG
SmallInteger SHORT
Float DOUBLE
REAL FLOAT
String, Text, Unicode STRING
Boolean BOOLEAN
DateTime UTC
LargeBinary Binary
  • Constraints are dropped from the table definition: NOT NULL, defaults, primary keys, and foreign keys are left out.
  • A single primary key becomes an index: the index is named idx_<table>_pk and has a primary-key constraint.
  • A composite primary key gets no index: no error says so.
  • unique=True on a column fails: the generated statement is rejected with 009-EXCEPTION: Variable required.
  • Date, Numeric, and JSON columns cannot be created: Date raises CompileError: ... can't render element of type DATE.

The primary-key index comes from a listener that runs after every table is created in the program, on any dialect: a SQLite table with a primary key, created in the same program, also gets an index named idx_<table>_pk.

Indexes take options through Index(..., info={...}) or the ami dialect options: use_constraint (NONE, UNIQUE, PRIMARY), autogen (RAND, INC), and per-column HASH, SORT, or SERIES, e.g: info={"ami_columns": {"b": "HASH"}}:

  • Pass options through info: a dialect option such as ami_use_constraint="UNIQUE" works, but SQLAlchemy warns Can't validate argument 'ami_use_constraint'; can't locate any SQLAlchemy dialect named 'ami'.
  • Create one index per column and type: a second index on the same columns, with the same type, fails with Duplicate index not allowed. The type is SORT unless set.
  • Expect INC to start at 0: with autogen INC, the first generated value is 0.

Reading table structure

sa.inspect() reads tables, columns, and indexes from the system tables __TABLE, __COLUMN, and __INDEX. Views and foreign keys come back empty. On a connection that has dropped, a reflection call returns an empty result rather than raising: get_table_names() returns [] and has_table() returns False, so the dropped connection looks like a missing table. An engine that cannot connect at all raises OperationError.

What this does not support

  • Transactions: commit() and rollback() do nothing.
  • Foreign keys and views: foreign keys are left out of table definitions, and reflection returns none.
  • LIKE against a column: only a value can be matched.
  • Date, Numeric, and JSON columns: create_all() cannot create them.