ahi-sql¶
Small, dependency-light SQL helpers — the fiddly bits people otherwise hand-roll and get subtly wrong. No database driver required.
uv add ahi-sql
quote_identifier¶
Safely quote a table or column name, escaping embedded quotes per the ANSI rule
(double them). Defaults to " (ANSI / Redshift); pass quote="\"` for MySQL.
from ahi.sql import quote_identifier
quote_identifier("users") # '"users"'
quote_identifier('we"ird') # '"we""ird"'
quote_identifier("col", quote="`") # '`col`'
Identifiers only
Use this for identifiers (table/column names). Never quote values this
way — pass values as bind parameters to your driver or to
ahi.aws's run_query(..., parameters=...).
placeholders¶
Generate the right number of bind placeholders for an IN clause, in the style
your engine expects:
from ahi.sql import placeholders
placeholders(3) # '?, ?, ?' (qmark — Athena)
placeholders(3, style="named") # ':1, :2, :3' (Redshift Data API)
placeholders(3, style="format") # '%s, %s, %s' (psycopg)
DDL for a staged ID table¶
The SQL behind ahi.aws.stage_id_table.
These build text only — they run nothing and know nothing about AWS, so they are
useful on their own when you want to see or adapt the statement.
from ahi.sql import create_external_id_table, drop_table
create_external_id_table(
"ahi_ids_a1b2c3d4",
"s3://my-bucket/scratch/ahi_ids_a1b2c3d4/",
"encounter_id",
database="scratch",
)
CREATE EXTERNAL TABLE `scratch`.`ahi_ids_a1b2c3d4` (
`encounter_id` bigint
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LOCATION 's3://my-bucket/scratch/ahi_ids_a1b2c3d4/'
TBLPROPERTIES ('skip.header.line.count' = '1')
ROW FORMAT DELIMITED selects Hive's LazySimpleSerDe. It doesn't understand
quoted fields, but with one integer column there is nothing to quote — and it
types the column natively, so a join against it needs no CAST.
drop_table builds the matching teardown:
drop_table("ahi_ids_a1b2c3d4", database="scratch")
DROP TABLE IF EXISTS `scratch`.`ahi_ids_a1b2c3d4`
IF EXISTS is included by default, so dropping a table that was never created
— or was already removed — succeeds rather than failing the cleanup. Pass
if_exists=False when an absent table should be an error.
Dropping the table removes only the Glue catalog entry. The data files in S3
are untouched, which is why
stage_id_table also deletes the
staged files it uploaded.
| Function | Returns |
|---|---|
create_external_id_table(table, location, column, *, database) |
The CREATE EXTERNAL TABLE statement. |
drop_table(table, *, database, if_exists=True) |
The DROP TABLE statement. |
qualify(table, *, database, quote=DML_QUOTE) |
"database"."table" for SELECT; pass DDL_QUOTE for backticks. |
validate_identifier(name, kind="identifier") |
Nothing; raises ValueError if unusable. |
validate_location(location) |
Nothing; raises ValueError if unusable. |
database is required throughout. A staged table usually lives in a scratch
database that isn't the one the query runs against, and relying on the session
default would silently put it in the wrong place.
Athena uses two different quote characters
DDL statements (CREATE, DROP, ALTER) are Hive-based, where double
quotes delimit a string literal — a double-quoted table name there is a parse error.
SELECT is Trino-based and wants double quotes. The builders
emit backticks (DDL_QUOTE) and qualify defaults to double quotes
(DML_QUOTE), which is why StagedTable.table_ref is safe to interpolate into
a query but is not the form that created the table.
LOCATION takes a SQL string literal, not an identifier, so a quote in the
value would end the literal early. validate_location closes that by requiring
a location that cannot contain one: an s3:// URI whose bucket follows S3's
naming rules and whose key has no quote, backslash, whitespace or control
character. S3 keys may technically hold those, but in a scratch location they
are a mistake, and failing at the call site beats creating a table pointing
somewhere unintended. It also catches typos the old s3:// prefix check let
through, such as s3:///key or an uppercase bucket.
Identifiers must be plain: lowercase letters, digits, underscore and hyphen, not starting with a digit. Hyphens are allowed because every identifier is quoted, and Glue database names often have them (lhi-owlsong-dq-poc-scratch).
Uppercase is not, because Athena lower-cases names as it executes the query, so a quoted mixed-case name rarely means what it looks like.