DOCUMENTATION / REFERENCE

API reference

This reference combines the application patterns used in the tutorials with the exact public database transaction methods.

HTTP application

from mojara import App, Request, Response

def hello(req: Request) -> Response:
    return Response.html("<h1>Hello</h1>")

def main() raises:
    var app = App()
    app.get("/", hello)
    app.run(port=8000)

The App object holds registered routes. app.get(path, handler) and app.post(path, handler) associate HTTP methods with handlers. Each handler receives a request and returns a response.

HTTP response examples

Response.html("<h1>Hi</h1>")
Response.json('{"ok":true}')
Response.json('{"error":"Invalid"}', status=422)
Response.redirect("/", status=302)

See Routes, Requests, and HTTP API for complete applications and test requests.

PostgreSQL and MySQL public Mojo API

Import the transaction classes:

from mojara.dbclient import PooledDatabase, DbLease, DbResult

PooledDatabase constructors

PostgreSQL

var db = PooledDatabase(
    "host=127.0.0.1 port=5432 dbname=mydb user=myuser",
    capacity=4,
)

MySQL

var db = PooledDatabase(
    "127.0.0.1", 3306, "myuser", "password", "mydb",
    capacity=4,
)

PooledDatabase methods

Method Meaning
acquire(timeout_ms: Int = 3000) raises -> DbLease Borrow a connection
capacity() raises -> Int Maximum pool connections
active_leases() raises -> Int Connections currently borrowed
close(mut self) raises Close an idle pool

Pool capacity must be from 1 to 16. The pool must remain alive as long as any lease exists.

DbLease methods

Method Meaning
begin() raises Start transaction
commit() raises Commit transaction
rollback() raises Abort transaction
query(sql: String) raises -> DbResult Execute unparameterized SQL
query1(sql, a) raises -> DbResult Bind one string parameter
query2(sql, a, b) raises -> DbResult Bind two string parameters
query3(sql, a, b, c) raises -> DbResult Bind three string parameters
release(mut self) raises Return connection to pool

DbLease is thread-affine. Releasing a lease with an open transaction automatically rolls it back.

DbResult methods

Method Meaning
rows() -> Int Number of result rows
columns() -> Int Number of columns
affected() -> UInt64 Rows affected for relevant SQL statements
column_name(col: Int) raises -> String Column name
is_null(row, col) raises -> Bool Whether a value is SQL NULL
cell(row, col) raises -> String Value represented as a UTF-8 string

Complete result example

var lease = db.acquire()
var result = lease.query("SELECT 7 AS number")
print(result.rows())        # 1
print(result.column_name(0)) # number
print(result.cell(0, 0))    # 7
lease.release()
db.close()

See PostgreSQL and MySQL for complete connection examples.