Skip to content
Connect > Client Libraries > Python Client

Python Query Builder

The query builder is a feature of the Python client that builds and runs a SELECT from Python values and expressions, so a program can query 3forge Enterprise without writing SQL text.

Overview

Column and table names are always quoted, and values are always written as literals, so neither can change the shape of the statement. The query runs over the SQL connection, so the client needs one configured; see Connecting.

The module, pyami.query, adds 2 methods to AmiClient when the Python client is imported:

  • select: runs a simple query from arguments.
  • run: runs a query composed with Select, or SQL text.

Simple queries with select

select(cluster, columns, table, ...) runs one SELECT and returns the same dictionary as sql().

1
2
3
4
5
6
from pyami.query import col, desc

client.select("N1", ["sym", "px"], "Quotes")
client.select("N1", ["sym", "px"], "Quotes",
              where=(col("px") > 10) & col("sym").isin(["AAPL", "IBM"]),
              order_by=desc("px"), limit=100, as_frame=True)
Argument What it takes
cols A column name, a list of names or expressions, or None or "*" for every column
table The table name
where, having An expression, a {column: value} dictionary, or SQL text, which is used unchanged
group_by, order_by Column names or expressions; desc(column) and asc(column) set the order
limit, offset Row counts. An offset needs a limit. Select has no .offset(): pass .limit(n, offset=m), or offset= to select
as_frame True returns a pandas DataFrame instead of a dictionary

A {column: value} condition joins its entries with AND. A None value matches nulls, and a list matches any of its values.

Composed queries with Select

Select builds a query step by step, and run(cluster, query) runs it. Each step returns a new Select. The example queries a table Trades (sym String, qty Long, venue String).

from pyami.query import Select, F, desc

query = (Select(["sym", F.sum("qty").as_("total")])
         .from_("Trades")
         .where({"venue": "NYSE"})
         .group_by("sym")
         .having(F.sum("qty") > 1000)
         .order_by(desc("total"))
         .limit(10))
client.run("N1", query)

query.to_sql() returns the statement without running it:

SELECT `sym`, SUM(`qty`) AS `total` FROM `Trades` WHERE (`venue` == "NYSE") GROUP BY `sym` HAVING (SUM(`qty`) > 1000) ORDER BY `total` DESC LIMIT 10

Calling .where() or .having() again adds a condition with AND. run also accepts SQL text, e.g: client.run("N1", "SELECT sym FROM Trades"), and runs any statement passed as text, not only a query.

Expressions

Write For
col("px") A column
col("px") > 10, ==, !=, <, <=, >= A comparison
+, -, *, / Arithmetic
a & b, a \| b, ~a AND, OR, NOT
col("sym").isin([...]) Any of a list of values
col("px").between(low, high) A range, inclusive
col("sym").is_null(), .is_not_null(), or == None A null check
col("sym").like("A%"), like(pattern, case_insensitive=True) A pattern, with % for any text and _ for one character
F.count(), F.sum(c), F.avg(c), F.min(c), F.max(c), F.call(name, ...) Aggregates and other functions. A string argument to F.call is a column name
expr.as_("name") A column alias
raw("...") SQL text, used unchanged
  • Conditions combine with &, |, and ~: Python's and, or, and chained comparisons such as 1 < col("px") < 5 raise an error.
  • A datetime becomes milliseconds since the epoch: a datetime with no time zone is taken as UTC.
  • F.count() returns a column named COUNT_: .as_() gives it another name. A hand-written count(*) run with sql() returns count_, in lower case.

Results

select and run return the sql() dictionary, or a DataFrame with as_frame=True. They raise on a server error, where sql() returns {'error': ...}:

RuntimeError: [shard 0] 009-EXCEPTION: Unknown table: Quotes

In a DataFrame, a Boolean column is uint8 and a UTC column is int64, as in Column types.

Errors the query builder raises

The query builder checks a value when it enters an expression, so a value error is raised by the line that builds the expression, not by select or run. The other errors come from the call named in the table:

Message Cause Raised by
AMI SQL has no literal for nan A NaN or infinite value The line that builds the expression
cannot render date value datetime.date(2026, 1, 1) as an AMI SQL literal A date, bytes, or Decimal value The line that builds the expression
a pyami.query expression has no truth value; combine conditions with &, \| and ~ and, or, if, or a chained comparison on an expression The line that builds the expression
AMI SQL requires a limit when an offset is given offset without limit select
Select has no table; call .from_(table) A Select run without .from_() run or to_sql()

What this does not support

  • Building statements other than SELECT: Select builds queries only. Use sql() for inserts, updates, and DDL.
  • DISTINCT: Select has no distinct option. A group_by on the selected columns gives the same rows.
  • date, bytes, and Decimal values: they are refused, as above; a datetime is accepted in place of a date.