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_dbapigives connections and cursors. - The SQLAlchemy dialect:
ami+jdbcsits 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.
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:
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
:nameand takes a dictionary, and the driver writes the values into the statement before sending it, quoting strings and writingNoneor a missing name asNULL. - Results come back as tuples:
fetchone(),fetchmany(size), andfetchall()return rows;descriptionnames the columns,rowcountcounts the rows, andlastrowidholds the last id anAUTOGENindex assigned, orNone. - Numbers come back as numpy scalars: a value is a numpy scalar of the column's own width, such as
np.int32for anIntegercolumn ornp.float64for aDoublecolumn, not a Pythonfloatorint. Convert them before passing rows tojson.dumpsor similar. - Statements commit on their own:
commit()androllback()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 withfetchall(). - 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 noOperationalError, the usual DB-API name, so code that names it fails withAttributeError. CatchDatabaseError, 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().
The URL takes the same arguments as connect():
- File paths are quoted:
urllib.parse.quoteescapes 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 astimeout, raisesTypeError: connect() got an unexpected keyword argument 'timeout'. Did you mean 'timeout_ms'?. - TLS is on by default:
use_ssl=falseis 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>_pkand has a primary-key constraint. - A composite primary key gets no index: no error says so.
unique=Trueon a column fails: the generated statement is rejected with009-EXCEPTION: Variable required.Date,Numeric, andJSONcolumns cannot be created:DateraisesCompileError: ... 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 asami_use_constraint="UNIQUE"works, but SQLAlchemy warnsCan'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 isSORTunless set. - Expect
INCto start at0: withautogenINC, the first generated value is0.
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()androllback()do nothing. - Foreign keys and views: foreign keys are left out of table definitions, and reflection returns none.
LIKEagainst a column: only a value can be matched.Date,Numeric, andJSONcolumns:create_all()cannot create them.