Python SDK
Python SDK
Trilogy's reference implementation is pytrilogy, a Python package. It gives you:
- An API to evaluate Trilogy queries inline
- A fully programmatic way to construct environments and queries
- A CLI to run
.preqlfiles (see the CLI reference)
pip install pytrilogy
Core Objects
| Object | Role |
|---|---|
Environment | Defines available concepts, datasources, and grain — your semantic model |
Dialects | Enum of supported backends (DuckDB, BigQuery, Snowflake, Postgres, ...) |
| Executor | Created via Dialects.<BACKEND>.default_executor(...); parses and runs queries |
Executing Queries
Trilogy is easy to embed in Python. It returns SQLAlchemy result sets, which many tools integrate with:
from trilogy import Dialects, Environment
executor = Dialects.DUCK_DB.default_executor(environment=Environment())
results = executor.execute_text("SELECT 1 + 1 -> test;")
for rs in results:
for row in rs.fetchall():
print(row)
Building Environments
An Environment can be built inline, parsed from a string, or loaded from a .preql file.
From a file:
from trilogy import Environment, Dialects
from pathlib import Path
env = Environment.from_file(Path("./model.preql"))
executor = Dialects.DUCK_DB.default_executor(environment=env)
From a string, via parse:
from trilogy import Dialects, parse
env, _ = parse("""
key user_id int;
property user_id.name string;
""")
Environments are mutable — you can extend a model incrementally with env.parse(...), or remove bindings (for example, del env.datasources['dowjones']) and rebind concepts to new datasources without touching your queries. See Trilogy in Practice: Python Analytics for a full worked example.
Escaping to Raw SQL
The executor exposes the underlying connection for raw SQL when you need it — for example, registering pandas DataFrames with DuckDB:
executor.execute_raw_sql("register(:name, :df)", {"name": "healthexp", "df": healthexp})
Backend Configuration
Trilogy uses SQLAlchemy to connect to databases. DuckDB is the default backend and requires no additional configuration. Install drivers for other backends as extras:
pip install pytrilogy[bigquery]
pip install pytrilogy[snowflake]
Backends that require credentials take a config object:
from trilogy import Dialects
from trilogy.dialect.config import SnowflakeConfig
executor = Dialects.SNOWFLAKE.default_executor(
environment=env,
conf=SnowflakeConfig(
account="account", username="user", password="password"
),
)
from trilogy import Dialects
from trilogy.dialect.config import PostgresConfig
executor = Dialects.POSTGRES.default_executor(
environment=env,
conf=PostgresConfig(
host="host", port="port", username="user", password="password", database="db"
),
)