Grain
Grain is a programming language that can use ASQL two ways.
For more info on Grain, please contact us.
In-process: sql()
A program running on the ASQL server calls the machine's own database directly, with no connection:
let rows = sql("SELECT sku, price FROM store.items WHERE price < 100")
for r in rows {
print(r.sku + ": " + str(r.price))
}
sql() returns a list of maps, one per row, with integers, reals, strings and nil as the columns' types give. A statement that fails raises an error. It runs with the engine's full authority; there is no login.
sql_on(machine, statement) runs a statement on another machine in the same fleet.
Over the network: db_connect()
let c = db_connect("127.0.0.1", 3307, "app", read_file("/etc/app/db.pass"), "store")
if not c.ok { error(c.error) }
let db = c.conn
let r = db_query(db, "SELECT sku, stock FROM items WHERE stock < ?", [10])
for item in r.records { print(item.sku) }
db_query(db, "UPDATE items SET stock = stock - 1 WHERE sku = ?", ["TIRE-G1"])
db_close(db)
| Call | Returns |
|---|---|
db_connect(host, port, user, password, database?) | {ok, conn, error, server_version} |
db_query(conn, sql, params?, options?) | {ok, error, columns, rows, records, affected_rows, last_insert_id} |
db_transaction(conn, fn(tx) { ... }) | commits when fn returns, rolls back if it raises |
db_close(conn) |
? placeholders take values from params; a list value expands for IN (?). records is a list of maps, rows a list of lists.
A result that stays current: live()
let low = live(db, "SELECT sku, stock FROM items WHERE stock < 10", {every: 2})
live() returns a map with rows, records, columns and changes. Every every seconds (default 1) it asks the server whether the tables the query reads have changed, which reads no rows, and runs the query again only if they have. A screen built from low updates when the answer changes.
