​
Query a DataFrame with SQL

Pass a SQL query and its input tables to DataFrame.from_sql. Each keyword names a table in the query. Its value can be a ChalkDF DataFrame, an Arrow table, or an Arrow record batch.

from chalkdf import DataFrame

orders = DataFrame({"customer": ["a", "a", "b"], "amount": [12, 8, 30]})
totals = DataFrame.from_sql(
    """
    SELECT customer, SUM(amount) AS total
    FROM orders
    GROUP BY customer
    ORDER BY customer
    """,
    orders=orders,
)
totals.run()
#
customerstring
totalint64
1a20
2b30

The result is a DataFrame you can use in another query or join to another frame. See Chalk SQL for the dialect and SELECT for query syntax.

​
Read from a PostgreSQL data source

To query a database directly, use its Arrow Database Connectivity (ADBC) driver. Install adbc-driver-postgresql and set DATABASE_URL to your PostgreSQL connection URI. This example reads an orders table with the same three rows as above. PostgreSQL computes the totals, and DataFrame.from_arrow wraps the two result rows.

import os

from adbc_driver_postgresql import dbapi
from chalkdf import DataFrame

with dbapi.connect(os.environ["DATABASE_URL"]) as connection:
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT customer, SUM(amount)::bigint AS total
            FROM orders
            GROUP BY customer
            ORDER BY customer
        """)
        totals = DataFrame.from_arrow(cursor.fetch_arrow_table())

totals
#
customerstring
totalint64
1a20
2b30

​
Use a configured Chalk source

If your project already defines a SQL source, pass that object to DataFrame.from_datasource with a query in the database’s dialect and its expected result schema. Here sources.warehouse is the project’s PostgreSQL source. Replace that import with your own source. Running the frame executes the query using the source’s configured connection.

import pyarrow as pa
from chalkdf import DataFrame
from sources import warehouse

totals = DataFrame.from_datasource(
    warehouse,
    """
    SELECT customer, SUM(amount)::bigint AS total
    FROM orders
    GROUP BY customer
    ORDER BY customer
    """,
    pa.schema([("customer", pa.string()), ("total", pa.int64())]),
)
totals.run()
#
customerstring
totalint64
1a20
2b30