Runo

Runo — Builder & transactions

The Sql builder produces SQL strings and bindings but does not execute queries. Bindings use generated names like :p0, :p1...

Using Sql

use Runo\DB;
use Runo\Support\Sql;

$query = Sql::table('posts');
$sql = $query->toString();
$args = $query->args();

$result = DB::prepare($sql)->args($args)->execute();

SELECT

$query = Sql::table('posts')
    ->select(['id', 'title', 'status'])
    ->where('status', '=', 'published')
    ->orderBy('id', 'DESC')
    ->limit(10)
    ->offset(20);
SELECT id, title, status FROM posts WHERE status = :p0 ORDER BY id DESC LIMIT 10 OFFSET 20

select() accepts column expressions; default is ['*'].

INSERT

$query = Sql::table('posts')->insert([
    'title'      => 'Hello from the builder',
    'status'     => 'draft',
    'created_at' => Sql::raw('NOW()'),
]);
INSERT INTO posts (title, status, created_at) VALUES (:p0, :p1, NOW())

Sql::raw() inserts the value verbatim (never pass untrusted input). Multiple insert() calls merge columns; the builder inserts one row per statement.

UPDATE

$query = Sql::table('posts')
    ->update('title', 'Updated title')
    ->update('status', 'published')
    ->where('id', '=', 1);
UPDATE posts SET title = :p0, status = :p1 WHERE id = :p2

DELETE

$query = Sql::table('posts')->delete()->where('id', '=', 1);
DELETE FROM posts WHERE id = :p0
Safety

update() and delete() have no built-in safety guard. Calling them without where() affects every row in the table.

WHERE conditions

where(string|callable $column, ?string $operator = null, mixed $value = null), orWhere() require an explicit operator:

$query = Sql::table('posts')
    ->where('status', '=', 'published')
    ->where('views', '>', 100)
    ->orWhere('status', '=', 'featured');
SELECT * FROM posts WHERE status = :p0 AND views > :p1 OR status = :p2

WHERE IN

$query = Sql::table('posts')->whereIn('id', [1, 2, 3]);
SELECT * FROM posts WHERE id IN (:p0, :p1, :p2)

whereIn() always joins with AND. An empty array produces IN () (invalid SQL) — guard against it.

Nested WHERE groups

$query = Sql::table('posts')
    ->where(function (Sql $query) {
        $query->where('status', '=', 'draft')
            ->where('user_id', '=', 1);
    });

Nested groups are syntactically supported but placeholder numbering can collide when combined with outer bindings (each Sql starts at :p0). Prefer flat conditions or raw SQL until this is addressed.

JOIN

$query = Sql::table('posts')
    ->select(['posts.id', 'posts.title', 'users.name AS author'])
    ->join('users', 'users.id', '=', 'posts.user_id')
    ->where('posts.status', '=', 'published');
SELECT posts.id, posts.title, users.name AS author FROM posts JOIN users ON users.id = posts.user_id WHERE posts.status = :p0

Only inner JOIN is supported.

ORDER BY, LIMIT, OFFSET

$query = Sql::table('posts')
    ->select(['id', 'title'])
    ->orderBy('id', 'DESC')
    ->orderBy('title', 'ASC')
    ->limit(25)
    ->offset(50);

orderBy() can be called multiple times; limit()/offset() accept integers. Using offset() without limit() may fail on MySQL.

Builder method summary

MethodDescriptionReturns
Sql::table(string $table)Start a querySql
Sql::raw(string $value)Create a raw SQL fragmentRaw
select(array $columns)Set select columns (default ['*'])Sql
insert(array $data)Add insert valuesSql
update(string $column, mixed $value)Add an update assignmentSql
delete()Mark as deleteSql
where(...)Add an AND condition or nested groupSql
orWhere(...)Add an OR condition or nested groupSql
whereIn(string $column, array $values)Add an AND ... IN (...) conditionSql
join(string $table, string $first, string $operator, string $second)Add an inner joinSql
orderBy(string $column, string $direction = 'ASC')Add an order clauseSql
limit(int $limit)Set the row limitSql
offset(int $offset)Set the row offsetSql
toString()Build the SQL stringstring
args()Get the bound valuesarray

Transactions

Closure-based

use Runo\DB;

$postId = DB::transaction(function () {
    $post = DB::prepare(
        'INSERT INTO posts (title, status) VALUES (:title, :status)'
    )->args([
        ':title'  => 'Transactional post',
        ':status' => 'draft',
    ])->execute();

    DB::prepare('UPDATE stats SET post_count = post_count + 1 WHERE id = 1')->execute();

    return $post->meta()->id;
});

Commits on success, rolls back on any Throwable and rethrows it.

Manual

use Runo\DB;

DB::beginTransaction();

try {
    DB::prepare('INSERT INTO posts (title) VALUES (:title)')->args([':title' => 'Manual'])->execute();
    DB::prepare('UPDATE stats SET post_count = post_count + 1 WHERE id = 1')->execute();
    DB::commit();
} catch (Throwable $e) {
    DB::rollback();
    throw $e;
}

beginTransaction() does nothing if already active; commit()/rollback() check inTransaction(). No nested transactions/savepoints.

Error handling and security

  • DB::prepare() before DB::init() throws Exception("Database not initialized.").
  • Passing a record class that does not extend Record throws Exception("Invalid record class.").
  • Building an unknown query type in Sql throws Exception("Invalid query type").
  • SQL errors/constraint violations/connection failures surface as PDOException (PDO is in ERRMODE_EXCEPTION).
  • Always use prepared statements/bindings for user input.
  • SQL passed to DB::prepare(), table/column names, join/order clauses, and Sql::raw() values are not escaped/quoted — validate/whitelist and never pass untrusted input to raw().
  • Load credentials from environment variables, not inline in production.

API reference

ClassNotes
Runo\DBinit(), prepare(), transaction(), beginTransaction(), commit(), rollback()
Runo\Database\Statementargs(), cast(), as(), execute(), $id
Runo\Database\Queryabstract sql(), run(), static execute($args=[]), $args, $casts, protected static $recordClass
Runo\Support\SqlBuilder (table/select/insert/update/delete/where/orWhere/whereIn/join/orderBy/limit/offset/toString/args), raw()
Runo\Support\Resultmeta(), getIterator(), count(), first(), toArray(), pluck()
Runo\Support\Record__construct($attrs=[], $casts=[]), toArray(), __get/__set/__isset
Runo\Support\Attributesid (int), affected (int), time (float)
Runo\Support\Raw__construct(string $value), public $value
Runo\Support\HydratorInternal hydration component

Part of the Lunaris documentation · Source on Codeberg · MIT License

Part of the Lunaris documentation · Source on Codeberg · MIT License