A PostgreSQL client library for MoonBit using libpq.
{
"import": [
{
"path": "mattn/postgres"
}
],
"link": {
"native": {
"cc-link-flags": "-lpq"
}
}
}fn main {
let conn = mattn/postgres::connect("postgresql://user:password@localhost/dbname")?
// Simple query
let result = conn.query("SELECT * FROM users")?
let rows = result.rows()
result.free()
// Parameterized query with ToValue trait
let result2 = conn.execute(
"SELECT * FROM users WHERE id = $1",
[42]
)?
result2.free()
conn.close()
}// Direct values - recommended
conn.execute("SELECT * FROM users WHERE id = $1", [42])?
conn.execute("SELECT * FROM users WHERE name = $1", ["Alice"])?
conn.execute("SELECT * FROM users WHERE active = $1", [true])?
// Mixed types
conn.execute(
"INSERT INTO users (id, name, active) VALUES ($1, $2, $3)",
[42, "Alice", true]
)?pub enum PgError {
ConnectionError(String)
AuthError(String)
QueryError(String)
ProtocolError(String)
}
error.to_string() -> Stringfn main {
let conn = mattn/postgres::connect("postgresql://localhost/mydb")?
let result = conn.query("SELECT id, name FROM users")?
for row in result.rows() {
println(row[0] + ": " + row[1])
}
result.free()
conn.close()
}fn main {
let conn = mattn/postgres::connect("postgresql://localhost/mydb")?
// Direct value passing with ToValue trait
let result = conn.execute(
"SELECT * FROM users WHERE id = $1 AND active = $2",
[42, true]
)?
result.free()
conn.close()
}fn main {
let conn = mattn/postgres::connect("postgresql://localhost/mydb")?
let stmt = conn.prepare("get_user", "SELECT * FROM users WHERE id = $1")?
for i = 1; i <= 100; i = i + 1 {
let result = stmt.execute([i])?
result.free()
}
stmt.close()
conn.close()
}fn main {
let conn = mattn/postgres::connect("postgresql://localhost/mydb")?
let result = conn.execute(
"UPDATE users SET active = $1 WHERE id = $2",
[false, 123]
)?
println(result.affected_rows().to_string() + " rows updated")
result.free()
conn.close()
}fn main {
let host = mattn/postgres::pg_get_env("DB_HOST")
let user = mattn/postgres::pg_get_env("DB_USER")
let password = mattn/postgres::pg_get_env("DB_PASSWORD")
let conninfo = "postgresql://" + user + ":" + password + "@" + host
let conn = mattn/postgres::connect(conninfo)?
conn.close()
}type Connectionfn[T : ToValue] Connection::execute(self : Connection, sql : String, params : Array[T]) -> Result[QueryResult, PgError]fn Connection::prepare(self : Connection, name : String, sql : String) -> Result[PreparedStatement, PgError]pub enum PgError {
ConnectionError(String)
AuthError(String)
QueryError(String)
ProtocolError(String)
}type PreparedStatementfn[T : ToValue] PreparedStatement::execute(self : PreparedStatement, params : Array[T]) -> Result[QueryResult, PgError]type QueryResultpub(all) enum Value {
Null
Bool(Bool)
Int(Int)
Int64(Int64)
Float(Float)
String(String)
Bytes(Bytes)
}Install
Download zipA PostgreSQL client library for MoonBit using libpq.