DB

object

%DB

/phlo/resources/DB/DB.phlo

Database engine class

The shape every driver fills in, and the reason a model can move between MySQL, PostgreSQL, SQLite and a JSON file untouched. Reads come in named flavours, so ask for what you want back: record for one, records keyed by id, rows in order, column, pair and item. Anything you pass as an argument is bound, never pasted into the SQL, so a value from a visitor is safe by construction. A connection that went away is reconnected and the query is tried once more, which is what keeps a long-lived worker alive.

databasepdosql
prop

%DB -> PDO:\PDO

line 10
This function triggers an error if no PDO connector is defined for database operations.
error('No PDO connector defined')
prop

%DB -> fieldQuotes:string

line 11
Retrieves the field quotes for a specified database field, allowing for the correct formatting of SQL queries.
bt
prop

%DB -> savepoint:int

line 12
Creates a savepoint in the current database transaction, allowing for partial rollbacks.
prop

%DB -> insertIgnore:string

line 13
Inserts a new record into the database while ignoring any duplicate entries that would cause a conflict.
' IGNORE'
prop

%DB -> insertOnConflict:string

line 14
Inserts a new record into the database, and in case of a conflict, it updates the existing record instead.
void
method

%DB -> load (string $table, string $columns = '*', string $where = void, string $joins = void, string $group = void, string $limit = void, string $order = void, array $whereArgs = [], ...$args)

line 18
The caller's where is wrapped in parentheses before anything joins it, so an OR in it cannot
$table = strpos($table, space) || strpos($table, dot) ? $table : "$this->fieldQuotes$table$this->fieldQuotes"
if ($args){
	[$named, $args] = $this->named($table, $args)
	$where = ($where !== void ? "($where) AND " : void).$named
}
$joins && $joins = " $joins"
$where && $where = " WHERE $where"
$group && $group = " GROUP BY $group"
$order && $order = " ORDER BY $order"
$limit && $limit = " LIMIT $limit"
$query = "SELECT $columns FROM $table$joins$where$group$order$limit"
return $this->query($query, ...array_values($whereArgs), ...$args)
method

%DB -> named (string $table, array $args):array

line 37
Named arguments as conditions with their bindings: a value is equality and a list is IN. An
$parts = $bindings = []
foreach ($args AS $column => $value){
	$col = $table.dot.$this->quoteId($column)
	if ($value === null || $value === []) $parts[] = '1 = 0'
	elseif (!is_array($value)) [$parts[] = "$col = ?", $bindings[] = $value]
	elseif (array_filter(array_keys($value), 'is_string')) error("$column can be matched with a value or a list, not a map")
	else [$parts[] = $col.' IN ('.implode(comma, array_fill(0, count($value), qm)).')', array_push($bindings, ...array_values($value))]
}
return [implode(' AND ', $parts), $bindings]
method

%DB -> query ($query, ...$args)

line 49
Executes a database query with the specified SQL statement and arguments, returning the result set.
$this->queryRun($query, $args, true)
method

%DB -> queryRun ($query, $args, $retry):\PDOStatement

line 56
Runs a statement, retrying once when the connection was lost.
try {
	if (!$args) $stmt = $this->PDO->query($query)
	else {
		$stmt = $this->PDO->prepare($query)
		$stmt->execute($args)
	}
	if (debug){
		$match = regex('/\b(UPDATE|INSERT INTO|DELETE FROM|FROM)\b\s+([`"\[]?\w+[`"\]]?)/i', strtr($query, [$this->fieldQuotes => void]))
		$where = strtr(regex('/\bWHERE (\b.+)/is', $query)[1] ?? void, [' ORDER BY' => void])
		$match && debug("Q: $match[1] $match[2]".strtr(rtrim(" $where "), [dq => void])." (".$stmt->rowCount().")")
	}
	return $stmt
}
catch (\PDOException $e){
	// Retry only idempotent read statements outside a transaction. WITH is excluded: a `WITH ... UPDATE`
	// or `WITH ... DELETE` CTE is a mutation that may already have run before the connection dropped
	// (error 2013), and a reconnect would start a fresh, transaction-less session.
	if (!$retry || !$this->goneAway($e) || $this->PDO->inTransaction() || !preg_match('/^\s*\(*\s*(SELECT|SHOW|EXPLAIN|DESCRIBE|DESC)\b/i', $query)) error('Database error'.colon.lf.$query.lf.lf.$e->getMessage())
	unset($this->PDO)
	return $this->queryRun($query, $args, false)
}
method

%DB -> goneAway ($e):bool

line 80
Checks if a database connection error indicates that the connection has been lost or the server is unavailable.
in_array((int)($e->errorInfo[1] ?? 0), [2006, 2013], true) || stripos($e->getMessage(), 'gone away') !== false || stripos($e->getMessage(), 'lost connection') !== false
method

%DB -> column (...$args):array

line 82
Fetches a single column from the result set of a database query, using the provided arguments to load the data.
$this->load(...$args)->fetchAll(\PDO::FETCH_COLUMN)
method

%DB -> item (...$args)

line 83
Loads an item from the database using the provided arguments and returns it as a single column value, or null if not found.
($v = $this->load(...$args)->fetch(\PDO::FETCH_COLUMN)) === false ? null : $v
method

%DB -> pair (...$args):array

line 84
Fetches all rows from the database as a key-value pair array using the provided arguments.
$this->load(...$args)->fetchAll(\PDO::FETCH_KEY_PAIR)
method

%DB -> group (...$args):array

line 85
Fetches all records from the database grouped by a specified column or columns, returning the results as an array of objects of the specified class.
$this->load(...$args)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_CLASS, obj::class)
method

%DB -> records (...$args):array

line 86
Fetches all records from the database as objects of the specified class, using the provided arguments for the query.
$this->load(...$args)->fetchAll(\PDO::FETCH_CLASS|\PDO::FETCH_UNIQUE, obj::class)
method

%DB -> rows (...$args):array

line 87
Fetches all rows from the database as instances of the specified class using the provided arguments.
$this->load(...$args)->fetchAll(\PDO::FETCH_CLASS, obj::class)
method

%DB -> record (...$args):?obj

line 88
Fetches a single record from the database as an object of the specified class, returning null if no record is found.
$this->load(...$args)->fetchObject(obj::class) ?: null
method

%DB -> quoteList (array $ids):string

line 89
Quotes each element in the provided array of IDs for safe use in SQL queries, returning a comma-separated string.
loop($ids, fn($id) => $this->PDO->quote((string)$id), comma)
method

%DB -> quoteId ($id):string

line 94
Safely quotes a SQL identifier such as a column or table name.
$this->fieldQuotes.str_replace($this->fieldQuotes, $this->fieldQuotes.$this->fieldQuotes, (string)$id).$this->fieldQuotes
method

%DB -> create (string $table, ...$data)

line 96
Inserts a new record into the specified table with the provided data, optionally ignoring conflicts based on the 'ignore' flag.
if ($ignore = $data['ignore'] ?? false) unset($data['ignore'])
$columns = implode(comma, loop(array_keys($data), fn($k) => $this->quoteId($k)))
$values = implode(comma, array_fill(0, count($data), qm))
$query = "INSERT".($ignore ? $this->insertIgnore : void)." INTO $table ($columns) VALUES ($values)".($ignore ? $this->insertOnConflict : void)
$this->query($query, ...array_values(loop($data, fn($value) => is_a($value, obj::class) ? $value->id : $value)))
return $this->lastId() ?: ($data['id'] ?? null)
method

%DB -> lastId

line 105
Returns the ID of the last inserted row in the database.
$this->PDO->lastInsertId()
method

%DB -> upsert (string $table, array $objKey, ...$data):int

line 108
Creates the row, or changes the one with the same key, in one statement.
$key = $objKey
array_diff($key, array_keys($data)) && error('An upsert needs its key in the data: '.implode(comma, $key))
$columns = implode(comma, loop(array_keys($data), fn($k) => $this->quoteId($k)))
$values = implode(comma, array_fill(0, count($data), qm))
$query = "INSERT INTO $table ($columns) VALUES ($values) ".$this->upsertClause($key, array_values(array_diff(array_keys($data), $key)))
return $this->query($query, ...array_values(loop($data, fn($value) => is_a($value, obj::class) ? $value->id : $value)))->rowCount()
method

%DB -> upsertClause (array $key, array $update):string

line 117
'ON CONFLICT ('.loop($key, fn($k) => $this->quoteId($k), comma).') DO '.($update ? 'UPDATE SET '.loop($update, fn($c) => $this->quoteId($c).' = excluded.'.$this->quoteId($c), comma) : 'NOTHING')
method

%DB -> change (string $table, string $where, ...$data):int

line 119
$whereCount = substr_count($where, qm)
$updates = $data['objUpdates'] ?? void
unset($data['objUpdates'])
$updates .= (($wheres = array_slice(array_keys($data), $whereCount)) && $updates ? comma : void).loop($wheres, fn($key) => $this->quoteId($key).'=?', comma)
$query = "UPDATE $table SET $updates WHERE $where"
$args = array_values([...array_slice($data, $whereCount), ...array_slice($data, 0, $whereCount)])
return $this->query($query, ...$args)->rowCount()
method

%DB -> script (string $sql):void

line 130
A file of statements, such as a migration, in order; a failing one throws and stops the rest.
$this->PDO->exec($sql)
method

%DB -> delete (string $table, string $where, ...$args):int

line 134
Deletes rows from the specified table based on the given condition. It returns the number of affected rows.
$this->query("DELETE FROM $table WHERE $where", ...$args)->rowCount()
method

%DB -> begin:?bool

line 135
Starts a new database transaction using PDO.
$this->PDO->beginTransaction()
method

%DB -> commit:?bool

line 136
$done = $this->PDO->commit()
$work = $this->objAfterCommit
$this->objAfterCommit = []
$error = null
foreach ($work AS $run){
	try {
		$run()
	}
	catch (\Throwable $e){
		$error ??= $e
	}
}
$error && throw $error
return $done
method

%DB -> rollback:?bool

line 152
$this->objAfterCommit = []
return $this->PDO->inTransaction() && $this->PDO->rollBack()
prop

%DB -> objAfterCommit

line 158
What others may only hear once they can see it: inside a transaction it waits for the commit, and a rollback drops it.
[]
method

%DB -> objOnCommit (callable $work):void

line 159
if ($this->objInTransaction()) $this->objAfterCommit[] = $work
else $work()
method

%DB -> objInTransaction:bool

line 163
(isset($this->objProps['PDO']) || $this->objHasData('PDO')) && $this->PDO->inTransaction()
method

%DB -> transaction ($callback)

line 165
if (!$this->PDO->inTransaction()){
	$this->begin
	try {
		$result = $callback()
		$this->commit
		return $result
	} catch (\Throwable $e){
		$this->rollback
		throw $e
	}
}
// Nested: a savepoint gives the inner unit its own rollback point, so its failure
// (e.g. an audit insert) is undone even when the outer transaction commits.
$sp = 'phlo_sp_'.(++$this->savepoint)
$kept = count($this->objAfterCommit)
$this->PDO->exec('SAVEPOINT '.$sp)
$released = false
try {
	$result = $callback()
	$this->PDO->exec('RELEASE SAVEPOINT '.$sp)
	$released = true
	return $result
} catch (\Throwable $e){
	$this->PDO->exec('ROLLBACK TO SAVEPOINT '.$sp)
	$this->PDO->exec('RELEASE SAVEPOINT '.$sp)
	throw $e
} finally {
	$this->savepoint--
	$released || $this->objAfterCommit = array_slice($this->objAfterCommit, 0, $kept)
}
object

%JSONDB

/phlo/resources/DB/JSONDB.phlo

JSON file database driver. One JSONDB instance = one JSON file = one model table. No joins, no transactions, no schema introspection.

A model in a JSON file, for a set of records that stays small and readable: no joins, no transactions, and every write rewrites the whole file. It understands comparisons, LIKE, IN, BETWEEN and IS NULL in a where, the same ones named arguments write, peels parentheses around a part, and refuses an OR or raw SQL rather than ignoring it, so keep the model plain. Move to SQLite the moment the file grows or two processes start writing.

jsondatabasefilestorage
static

JSONDB :: __handle

line 10
JSONDB::$__handle is a reference to the internal file handle used for accessing the JSON database specified by the $file path.
"JSONDB/$file"
method

%JSONDB -> __construct (private string $file)

line 11
The constructor initializes a JSONDB instance and ensures that the directory for the specified file exists, creating it if necessary.
$dir = dirname($this->file)
is_dir($dir) || mkdir($dir, 0755, true) || error("JSONDB: cannot create dir $dir")
prop

%JSONDB -> PDO:\PDO

line 15
This function triggers an error indicating that the JSONDB driver is not compatible with PDO.
error('JSONDB driver does not use PDO')
prop

%JSONDB -> fieldQuotes:string

line 16
Retrieves the quotes for a specified field in a JSONDB resource.
void
prop

%JSONDB -> lastInsertedId

line 17
Returns the ID of the last inserted record in the JSONDB.
null
method

%JSONDB -> quoteList (array $ids):string

line 24
Builds the quoted id list an IN clause expects.
dq.implode(dq.comma.dq, $ids).dq
method

%JSONDB -> objRead:array

line 26
Reads a JSON file and returns its contents as an associative array. If the file does not exist or is empty, it returns an empty array.
file_exists($this->file) ? json_decode(file_get_contents($this->file), true) ?: [] : []
method

%JSONDB -> objWrite (array $data):int|false

line 27
file_put_contents($this->file, json_encode(array_values($data), jsonPretty), LOCK_EX)
method

%JSONDB -> objNextId (array $data):int

line 28
Returns the next available ID for a new object in the given array of data by finding the maximum current ID and adding one, or returns 1 if the array is empty.
$data ? (int)max(array_column($data, 'id')) + 1 : 1
method

%JSONDB -> objConditions (string $where, array $args):array

line 34
A where is a list of conditions joined by AND: a column compared with ? or a literal (=, !=,
$conditions = []
$next = 0
$col = '(?:\w+\.)?[`"]?(\w+)[`"]?'
// The AND inside BETWEEN ? AND ? is not a separator.
foreach (preg_split('/\s+AND\s+/i', preg_replace('/\bBETWEEN\s+\?\s+AND\s+\?/i', 'BETWEEN ?~?', $where)) AS $part){
	$part = trim($part)
	while (str_starts_with($part, '(')) $part = trim(substr($part, 1))
	while (str_ends_with($part, ')') && substr_count($part, ')') > substr_count($part, '(')) $part = trim(substr($part, 0, -1))
	if (in_array($part, ['1', '1 = 1'], true)) continue
	if (in_array($part, ['0', '1 = 0'], true)) $conditions[] = [null, 'none', null]
	elseif (preg_match("/^$col\s+(NOT\s+)?IN\s*\((.*)\)$/i", $part, $m)){
		$values = []
		foreach (explode(comma, $m[3]) AS $v) $values[] = trim($v) === qm ? $args[$next++] ?? null : trim($v, "\"' ")
		$conditions[] = [$m[1], $m[2] ? 'not in' : 'in', $values]
	}
	elseif (preg_match("/^$col\s+BETWEEN\s+\?~\?$/i", $part, $m)) $conditions[] = [$m[1], 'between', [$args[$next++] ?? null, $args[$next++] ?? null]]
	elseif (preg_match("/^$col\s+IS\s+(NOT\s+)?NULL$/i", $part, $m)) $conditions[] = [$m[1], ($m[2] ?? void) !== void ? 'set' : 'null', null]
	elseif (preg_match("/^$col\s*(=|!=|<>|<=|>=|<|>|NOT\s+LIKE|LIKE)\s*\?$/i", $part, $m)) $conditions[] = [$m[1], strtolower(preg_replace('/\s+/', space, $m[2])), $args[$next++] ?? null]
	elseif (preg_match("/^$col\s*=\s*('[^']*'|\"[^\"]*\"|[\w.-]+)$/", $part, $m)) $conditions[] = [$m[1], '=', trim($m[2], "\"'")]
	else error('JSONDB cannot filter on: '.$part)
}
return $conditions
method

%JSONDB -> objMatches (array $row, array $conditions):bool

line 60
Compares the way SQL does: a missing value matches no comparison, and LIKE ignores case.
foreach ($conditions AS [$column, $op, $value]){
	$have = $column === null ? null : ($row[$column] ?? null)
	$ok = match ($op) {
		'null' => $have === null,
		'set' => $have !== null,
		'none' => false,
		'in' => $have !== null && in_array($have, $value),
		'not in' => $have !== null && !in_array($have, $value),
		default => $have !== null && match ($op) {
			'=' => $have == $value,
			'!=', '<>' => $have != $value,
			'<' => $have < $value,
			'<=' => $have <= $value,
			'>' => $have > $value,
			'>=' => $have >= $value,
			'like' => (bool)preg_match(static::likePattern($value), (string)$have),
			'not like' => !preg_match(static::likePattern($value), (string)$have),
			'between' => $have >= $value[0] && $have <= $value[1],
		},
	};
	if (!$ok) return false
}
return true
static

JSONDB :: likePattern ($value):string

line 86
'/^'.strtr(preg_quote((string)$value, slash), ['%' => '.*', '_' => dot]).'$/is'
method

%JSONDB -> objFilter (array $data, string $where = void, ...$args):array

line 88
if (!$where) return $data
$conditions = $this->objConditions($where, $args)
return array_values(array_filter($data, fn($row) => $this->objMatches($row, $conditions)))
method

%JSONDB -> objSelect (string $where = void, string $limit = void, string $order = void, ...$args):array

line 94
$data = $this->objFilter($this->objRead(), $where, ...array_values($args))
if ($order){
	$desc = str_contains($order, 'DESC')
	$col = trim(preg_replace('/\s+(ASC|DESC)/i', void, $order), '` ')
	usort($data, fn($a, $b) => $desc ? ($b[$col] ?? 0) <=> ($a[$col] ?? 0) : ($a[$col] ?? 0) <=> ($b[$col] ?? 0))
}
// A limit is n, offset,n or n OFFSET offset, as the SQL drivers take it.
if ($limit && preg_match('/^\s*(\d+)\s*(?:(,)\s*(\d+)|OFFSET\s+(\d+))?\s*$/i', $limit, $m)) $data = ($m[2] ?? void) ? array_slice($data, (int)$m[1], (int)$m[3]) : array_slice($data, (int)($m[4] ?? 0), (int)$m[1])
elseif ($limit) error('JSONDB cannot limit with: '.$limit)
return $data
method

%JSONDB -> create (string $table, ...$data)

line 110
ignore compares ids loosely, so the string "7" and the number 7 count as one row.
if ($ignore = $data['ignore'] ?? false) unset($data['ignore'])
$all = $this->objRead()
$data['id'] ??= $this->objNextId($all)
foreach ($data AS $key => $value) is_a($value, 'obj') && $data[$key] = $value->id
if ($ignore){
	foreach ($all AS $row) if (($row['id'] ?? null) == $data['id']) return $data['id']
}
$all[] = $data
$this->objWrite($all)
$this->lastInsertedId = $data['id']
return $data['id']
method

%JSONDB -> change (string $table, string $where, ...$data):int

line 125
An update can add to a number (objUpdates: 'stock = stock + 1'), which is what objIncrement() writes.
$all = $this->objRead()
$adds = []
foreach (isset($data['objUpdates']) ? explode(comma, $data['objUpdates']) : [] AS $part) preg_match('/^\s*[`"]?(\w+)[`"]?\s*=\s*[`"]?\1[`"]?\s*([+-])\s*([\d.]+)\s*$/', $part, $m) ? $adds[$m[1]] = ($m[2] === dash ? -1 : 1) * (0 + $m[3]) : error('JSONDB cannot update with: '.$part)
unset($data['objUpdates'])
$whereCount = substr_count($where, qm)
$whereArgs = array_slice(array_values($data), 0, $whereCount)
$updates = array_slice($data, $whereCount, null, true)
$changed = 0
foreach ($all AS &$row){
	if ($this->objFilter([$row], $where, ...$whereArgs)){
		foreach ($updates AS $key => $value) $row[$key] = $value
		foreach ($adds AS $key => $by) $row[$key] = ($row[$key] ?? 0) + $by
		$changed++
	}
}
unset($row)
$this->objWrite($all)
return $changed
method

%JSONDB -> upsert (string $table, array $objKey, ...$data):int

line 146
$key = $objKey
array_diff($key, array_keys($data)) && error('An upsert needs its key in the data: '.implode(comma, $key))
$where = loop($key, fn($k) => "$k = ?", ' AND ')
$args = array_values(array_intersect_key($data, array_flip($key)))
if ($this->objFilter($this->objRead(), $where, ...$args)) return $this->change($table, $where, ...$args, ...array_diff_key($data, array_flip($key)))
$this->create($table, ...$data)
return 1
method

%JSONDB -> delete (string $table, string $where, ...$args):int

line 156
Deletes records from the specified table in the JSON database that match the given condition.
$all = $this->objRead()
$matching = $this->objFilter($all, $where, ...$args)
$matchIds = array_column($matching, 'id')
$remaining = array_values(array_filter($all, fn($row) => !in_array($row['id'] ?? null, $matchIds)))
$this->objWrite($remaining)
return count($matching)
method

%JSONDB -> load (string $table, string $columns = '*', string $where = void, string $joins = void, string $group = void, string $limit = void, string $order = void, array $whereArgs = [], ...$args):JSON_result

line 165
if ($args){
	[$named, $args] = $this->named($table, $args)
	$where = ($where !== void ? "($where) AND " : void).$named
}
$data = $this->objSelect($where, $limit, $order, ...array_values($whereArgs), ...array_values($args))
// A count, or the columns item(), column() and pair() read.
if (preg_match('/^\s*COUNT\s*\(/i', $columns)) return %JSON_result([['count' => count($data)]])
return %JSON_result($data, $columns)
method

%JSONDB -> query ($query, ...$args)

line 175
Executes a query against the JSONDB, but does not support raw SQL queries.
error('JSONDB driver does not support raw SQL queries')
method

%JSONDB -> begin:?bool

line 177
Begins a transaction in the JSONDB, allowing for multiple operations to be executed atomically.
null
method

%JSONDB -> transaction ($callback)

line 178
$callback()
method

%JSONDB -> objOnCommit (callable $work):void

line 179
$work()
method

%JSONDB -> objInTransaction:bool

line 182
false
method

%JSONDB -> commit:?bool

line 183
Commits the current transaction to the JSONDB, saving all changes made during the transaction.
null
method

%JSONDB -> rollback:?bool

line 184
Reverts the last transaction in the JSONDB, restoring the database to its previous state.
null
object

%JSON_result

/phlo/resources/DB/JSON.result.phlo

Minimal PDOStatement-like wrapper for JSONDB result arrays

Exists so JSONDB can hand back something that behaves like a PDO statement, which is what lets the ORM stay unaware of which driver answered. You do not build one yourself; you meet it as the return value of a JSONDB query.

jsondatabaseresult
static

JSON_result :: __handle

line 8
This property is used to access the internal handle of a JSON_result object.
null
prop

%JSON_result -> data:array

line 9
Accesses the `$data` property of the `JSON_result` object, which contains the parsed data from a JSON response.
[]
prop

%JSON_result -> columns:string

line 10
'*'
method

%JSON_result -> __construct (array $data, string $columns = '*')

line 11
$this->data = $data
$this->columns = $columns
method

%JSON_result -> values ($row):array

line 18
A row's values in the columns asked for, which is what column(), item() and pair() read; every
$row = (array)$row
if (str_contains($this->columns, '*')) return array_values($row)
return loop(explode(comma, $this->columns), fn($c) => preg_match('/^\s*(?:[`"]?\w+[`"]?\.)?[`"]?(\w+)[`"]?\s*$/', $c, $m) ? $row[$m[1]] ?? null : error('JSONDB cannot select: '.trim($c)))
method

%JSON_result -> fetchAll ($mode = 2, $class = 'obj'):array

line 24
if ($mode === \PDO::FETCH_COLUMN) return loop($this->data, fn($row) => $this->values($row)[0] ?? null)
if ($mode === \PDO::FETCH_KEY_PAIR){
	$out = []
	foreach ($this->data AS $row){
		$vals = $this->values($row)
		$out[$vals[0] ?? null] = $vals[1] ?? null
	}
	return $out
}
if (($mode & (\PDO::FETCH_CLASS | \PDO::FETCH_UNIQUE)) === (\PDO::FETCH_CLASS | \PDO::FETCH_UNIQUE)){
	$out = []
	foreach ($this->data AS $row){
		$o = new $class
		foreach ((array)$row AS $k => $v) $o->$k = $v
		$out[$row['id'] ?? count($out)] = $o
	}
	return $out
}
if (($mode & \PDO::FETCH_CLASS) === \PDO::FETCH_CLASS){
	$out = []
	foreach ($this->data AS $row){
		$o = new $class
		foreach ((array)$row AS $k => $v) $o->$k = $v
		$out[] = $o
	}
	return $out
}
return $this->data
method

%JSON_result -> fetchObject ($class = 'obj'):?obj

line 55
Fetches a single object of the specified class from the JSON result data, mapping the properties of the object to the values in the first row of the data.
if (!$this->data) return null
$row = reset($this->data)
$o = new $class
foreach ((array)$row AS $k => $v) $o->$k = $v
return $o
method

%JSON_result -> fetch ($mode = 2)

line 63
if (!$this->data) return null
$row = reset($this->data)
if ($mode === \PDO::FETCH_COLUMN) return $this->values($row)[0] ?? null
return $row
method

%JSON_result -> fetchColumn ($col = 0)

line 70
if (!$this->data) return false
$row = reset($this->data)
return $this->values($row)[$col] ?? false
method

%JSON_result -> rowCount:int

line 76
Returns the number of rows in the JSON result set.
count($this->data)
object

%migration

/phlo/resources/DB/migration.phlo

Schema migrations from numbered SQL files, run from the command line

One .sql file per change in migrations/ at the app root, named so they sort in order (001_users.sql). php www/app.php migration::run applies every file that has not run, each with its record in one transaction, and stops at the first that fails; migration::status lists what ran, what is open and what changed after it ran. A database with tables but no schema_migration is refused, so the chain is never laid over a schema it did not make; migration::adopt records the files as they are without running them, which also accepts a file that changed. A run holds a lock on the database (GET_LOCK on MySQL, an advisory lock on PostgreSQL, a .lock file beside the SQLite file), so a second one at the same time stops. A file that changed after it ran stops a run too. MySQL commits DDL as it goes, so there a failing file can leave the statements before it: keep one change per file, and take a dump first, because this does not. Set static %migration.prefix when several apps keep their chain in one database; a row another tool wrote without a hash is not checked until adopt, and a schema_migration from before the hash, made by an earlier version or a script of your own, gets that column on the next run or adopt.

migrationsschemadatabasecli
static

migration :: table

line 9
'schema_migration'
static

migration :: prefix

line 10
''
static

migration :: dir

line 11
app.'migrations/'
static

migration :: DB

line 12
model::DB()
static

migration :: files:array

line 14
array_map('basename', files(static::dir(), '[0-9]*.sql'))
static

migration :: sql (string $file):string

line 15
(string)file_get_contents(static::dir().$file)
static

migration :: hash (string $sql):string

line 16
hash('sha256', strtr($sql, ["\r\n" => lf]))
static

migration :: ran:array

line 18
if (!static::exists()) return []
return static::hashed() ? static::DB()->pair(table: static::$table, columns: 'name, hash') : array_fill_keys(static::DB()->column(table: static::$table, columns: 'name'), null)
static

migration :: open:array

line 23
$ran = static::ran()
return array_values(array_filter(static::files(), fn($file) => !array_key_exists(static::$prefix.$file, $ran)))
static

migration :: changed:array

line 28
$ran = static::ran()
return array_values(array_filter(static::files(), fn($file) => ($ran[static::$prefix.$file] ?? null) !== null && $ran[static::$prefix.$file] !== static::hash(static::sql($file))))
static

migration :: status:array

line 33
['ran' => array_keys(static::ran()), 'open' => static::open(), 'changed' => static::changed()]
static

migration :: run:array

line 35
%req->cli || error('Migrations run from the command line', 403)
return static::locked(function(){
	static::begin()
	($changed = static::changed()) && error('Changed after they ran: '.implode(', ', $changed).'. Put them back, or record them as they are with migration::adopt')
	return loop(static::open(), fn($file) => static::apply($file, true))
})
static

migration :: adopt:array

line 44
%req->cli || error('Migrations run from the command line', 403)
return static::locked(function(){
	static::begin(true)
	$ran = static::ran()
	$hashes = loop(array_combine(static::files(), static::files()), fn($file) => static::hash(static::sql($file)))
	$stale = array_keys(array_filter($hashes, fn($hash, $file) => array_key_exists(static::$prefix.$file, $ran) && $ran[static::$prefix.$file] !== $hash, ARRAY_FILTER_USE_BOTH))
	foreach ($stale AS $file) static::DB()->change(static::$table, 'name=?', static::$prefix.$file, hash: $hashes[$file])
	return [...$stale, ...loop(static::open(), fn($file) => static::apply($file, false))]
})
static

migration :: apply (string $file, bool $run):string

line 56
$db = static::DB()
$sql = static::sql($file)
$db->begin
try {
	$run && $db->script($sql)
	$db->create(static::$table, name: static::$prefix.$file, applied_at: time(), hash: static::hash($sql))
	$db->PDO->inTransaction() && $db->commit
}
catch (\Throwable $e){
	$db->rollback
	error($file.colon.space.$e->getMessage())
}
return $file
static

migration :: locked (callable $work)

line 72
$db = static::DB()
$driver = $db->PDO->getAttribute(\PDO::ATTR_DRIVER_NAME)
$path = $driver === 'sqlite' ? (string)$db->query('PRAGMA database_list')->fetch(\PDO::FETCH_ASSOC)['file'] : void
$lock = $path === void ? null : fopen($path.'-migration.lock', 'c')
$held = match ($driver) {
	'mysql' => (int)$db->query('SELECT GET_LOCK(MD5(CONCAT(DATABASE(), ?)), 0)', static::$table)->fetchColumn() === 1,
	'pgsql' => (bool)$db->query('SELECT pg_try_advisory_lock(hashtext(current_schema()::text || ?::text))', static::$table)->fetchColumn(),
	default => !$lock || flock($lock, LOCK_EX | LOCK_NB),
};
$held || error('Another migration run holds the lock on this database')
try {
	return $work()
}
finally {
	match ($driver) {
		'mysql' => $db->query('SELECT RELEASE_LOCK(MD5(CONCAT(DATABASE(), ?)))', static::$table),
		'pgsql' => $db->query('SELECT pg_advisory_unlock(hashtext(current_schema()::text || ?::text))', static::$table),
		default => $lock && flock($lock, LOCK_UN),
	};
}
static

migration :: begin (bool $adopt = false):void

line 97
The chain starts on an empty database, or on one that already carries it. Adopting is the one
if (static::exists()){
	static::hashed() || static::DB()->query('ALTER TABLE '.static::$table.' ADD hash CHAR(64) NULL')
	return
}
$adopt || !static::tables() || error('This database has tables but no '.static::$table.'; run migration::adopt to start the chain on it')
static::DB()->query('CREATE TABLE '.static::$table.' (name VARCHAR(190) NOT NULL PRIMARY KEY, applied_at INTEGER NOT NULL, hash CHAR(64) NULL)')
static

migration :: exists:bool

line 106
try {
	static::DB()->query('SELECT 1 FROM '.static::$table.' LIMIT 1')
	return true
}
catch (\Throwable $e){
	return false
}
static

migration :: hashed:bool

line 116
$stmt = static::DB()->query('SELECT * FROM '.static::$table.' LIMIT 0')
return in_array('hash', loop(range(0, $stmt->columnCount() - 1), fn($i) => $stmt->getColumnMeta($i)['name'] ?? void), true)
static

migration :: tables:int

line 121
$db = static::DB()
return (int)$db->query(match ($db->PDO->getAttribute(\PDO::ATTR_DRIVER_NAME)) {
	'sqlite' => "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
	'pgsql' => 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = current_schema()',
	default => 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE()',
})->fetchColumn()
object

%model

/phlo/resources/DB/model.phlo

Phlo ORM class with unified columns and schema

A model is a class with fields, and everything else follows from that: columns, form, validation and relations. Named arguments in a read are equality and a list is IN, so records(active: 1, id: [3, 5]) needs no SQL; a comparison goes in where: with ? placeholders and whereArgs:, as in records(where: 'price >= ?', whereArgs: [5]). Cast a value from the request to a scalar when a lookup must match one row, because a list there matches several. A static where scopes every read in its own parentheses, so no OR in a search reaches past it. A parent field gives back the record itself rather than an id, and children and many-relations are fetched once for a whole result set instead of per row. A save writes only the columns this request changed since the read, so it leaves another request's change alone; objUpsert() creates or changes a row in one statement, objIncrement() adds in the database itself, objRecordPage() gives one page with its total, and change() takes raw SQL for its SET as objUpdates:, a name no column can have. A column cannot be called after a part of the query (table, columns, where, joins, group, limit, order, whereArgs), the cache (cache, cacheKey) or ignore, because as a named argument it would become that part; objUpsert($objKey) and objRecordPage($objPage, $objSize) name their own parameters so key, page and size stay free for columns. A virtual field with sql: is a computed column. An app names its database with static %model.DB; nothing picks one for it. Set objValidate to have field rules enforced on save, objAudit to log every change, objCache to keep reads in APCu until the next write through the model is committed (a transaction reads past the cache, and cacheKey: only names the entry), and objLive to tell the open screens over the websocket that it changed.

ormmodeldatabaserecordsschema
static

model :: DB

line 10
error('No database for '.static::class.': the app names one with a model.DB modifier')
static

model :: objCache

line 11
The model::$objCache property holds a cache for model objects, allowing for improved performance by reducing the need to repeatedly fetch the same data.
false
static

model :: objRecordLimit

line 12
Sets the maximum number of records that can be retrieved by the model.
10000
static

model :: objAudit

line 13
The `model::$objAudit` property is used to access the audit object associated with the model, allowing for tracking changes and modifications.
false
static

model :: objValidate

line 14
The model::$objValidate property indicates whether the object validation is enabled or disabled, returning false if validation is not active.
false
static

model :: objLive

line 15
false
static

model :: idColumn

line 16
The model::$idColumn property specifies the name of the identifier column used in the model, defaulting to 'id'.
'id'
static

model :: idType

line 17
Defines the data type for the model's identifier as an integer.
'int'
static

model :: canView

line 19
This property indicates whether the current user has permission to view the model.
true
static

model :: canCreate

line 20
The model::$canCreate property indicates whether a new instance of the model can be created.
true
static

model :: canChange

line 21
This property indicates whether the model can be changed, returning true if changes are allowed.
true
static

model :: canDelete

line 22
The model::$canDelete property indicates whether the model instance can be deleted.
true
static

model :: state:obj

line 24
%req->model ??= obj(meta: [], records: [], errors: [], unscoped: [])
prop

%model -> objLoaded

line 29
The record as it was read, so a save can tell what this request changed. A read sets the
null
method

%model -> __construct (...$data)

line 30
parent::__construct(...$data)
$data || $this->objLoaded = $this->objData
static

model :: columns:string

line 34
Retrieves the columns defined in the model, either from the static::$columns property or by calling the schema method if it exists.
if (isset(static::$columns)) return static::$columns
if (!method_exists(static::class, 'schema')) return static::$table.'.*'
$state = static::state()
$key = spl_object_id(static::DB()).':'.static::DB()->fieldQuotes.':'.static::$table
return $state->meta[static::class]['columns'][$key] ??= static::_columns()
static

model :: _columns:string

line 41
$fq = static::DB()->fieldQuotes
$list = array_merge(...array_values(array_filter(loop(static::fields(), fn($field) => loop($field->objColumns, fn($col) => $fq.static::$table."$fq.$fq".$col.$fq)))))
// A virtual field with sql: is a computed column, read with the record and never written.
foreach (static::fields() AS $name => $field) $field->type === 'virtual' && $field->sql && $list[] = "($field->sql) AS $fq$name$fq"
return implode(comma, $list)
static

model :: fields:array

line 48
Returns the fields defined in the model's schema, or an empty array if no schema exists. If the schema is available, it retrieves the fields from the model's state metadata.
if (!method_exists(static::class, 'schema')) return static::$fields ?? []
$state = static::state()
return $state->meta[static::class]['fields'] ??= static::_fields()
static

model :: objReserved:array

line 53
['table','columns','where','joins','group','limit','order','whereArgs','cache','cacheKey','ignore','fields','create','change','delete','records','record','column','item','pair','DB','idColumn','idType']
static

model :: _fields:array

line 54
$reserved = static::objReserved()
$fields = loop(static::schema(), fn($field, $column) => last($field->name ??= $column, $field->type === 'parent' && $field->obj ??= $column, $field))
foreach (array_keys($fields) AS $name) (in_array($name, $reserved, true) || preg_match('/^obj[A-Z]/', $name)) && error("Reserved column name '$name' in ".static::class)
return $fields
static

model :: field ($name)

line 60
Accesses a specific field defined in the model's static fields array using the provided name.
static::fields()[$name]
static

model :: create (...$args):?static

line 62
Creates a new instance of the model, validating the input arguments and executing any defined lifecycle methods before saving the record to the database.
$class = static::class
if (static::objValidate() && !static::objRunValidation($args)) return null
$record = new $class(...$args)
method_exists(static::class, 'beforeSave') && $record->beforeSave()
method_exists(static::class, 'beforeCreate') && $record->beforeCreate()
$pk = static::idColumn()
return static::objAudit() ? static::transaction(fn() => static::objCreateCommit($record, $pk)) : static::objCreateCommit($record, $pk)
static

model :: objCreateCommit ($record, $pk):?static

line 72
Creates a new record in the model and triggers afterCreate and afterSave methods if they exist, while also logging the creation event for auditing purposes.
$id = static::createRecord(...$record)
$record = static::record(...[$pk => $record->$pk ?? $id])
method_exists(static::class, 'afterCreate') && $record->afterCreate()
method_exists(static::class, 'afterSave') && $record->afterSave()
static::objAudit() && audit::log($record, 'create', [], $record->objData)
return $record
static

model :: objRunValidation ($data):bool

line 81
Validates the provided data against the defined fields of the model, collecting any errors encountered during the validation process.
$errors = []
$fields = static::fields()
foreach ($data AS $column => $value){
	if (!($field = $fields[$column] ?? null) || !method_exists($field, 'objValidate')) continue
	if ($error = $field->objValidate($value)) $errors[$column] = $error
}
static::state()->errors[static::class] = $errors
return empty($errors)
static

model :: objErrors:array

line 92
Retrieves the error messages associated with the current model instance, returning an empty array if none are found.
static::state()->errors[static::class] ?? []
static

model :: createRecord (...$args)

line 93
first(static::DB()->create(static::$table, ...$args), static::objFlush())
static

model :: objFlush:void

line 97
Every write moves the model's cache generation on once it is committed, so a cached read never
static::DB()->objOnCommit(function(){
	function_exists('apcu_key') && apcu_inc(apcu_key(static::class.'/generation'))
	// Only that it changed: who looks at it asks again, with their own rights.
	static::objLive() && wsCast(live: static::class)
})
static

model :: objGeneration:int

line 104
function_exists('apcu_key') ? (int)apcu_fetch(apcu_key(static::class.'/generation')) : 0
static

model :: objScoped (string $where = void):string

line 108
A where inside the model's scope: a static where applies to every read, change and delete, each
if (!method_exists(static::class, 'where') || isset(static::state()->unscoped[static::class]) || ($scope = (string)static::where()) === void) return $where
return $where === void ? "($scope)" : "($scope) AND ($where)"
static

model :: objUnscoped (callable $work)

line 115
Runs $work without the model's scope, for the one place that must reach every row, such as a
$state = static::state()
$was = isset($state->unscoped[static::class])
$state->unscoped[static::class] = true
try {
	return $work()
}
finally {
	if (!$was) unset($state->unscoped[static::class])
}
static

model :: change ($where, ...$args):int

line 127
$where = static::objScoped($where)
if (!static::objAudit()) return first(static::DB()->change(static::$table, $where, ...$args), static::objFlush())
$pk = static::idColumn()
$bindings = array_values(array_filter($args, 'is_int', ARRAY_FILTER_USE_KEY))
return first(static::transaction(function() use ($where, $args, $bindings, $pk){
	$old = static::DB()->query('SELECT '.static::$table.'.* FROM '.static::$table.' WHERE '.$where, ...$bindings)->fetchAll(\PDO::FETCH_CLASS, static::class)
	$result = static::DB()->change(static::$table, $where, ...$args)
	foreach ($old AS $record){
		$fresh = static::record(...[$pk => $record->$pk])
		$fresh && audit::log($fresh, 'update', $record->objData, $fresh->objData)
	}
	return $result
}), static::objFlush())
static

model :: delete ($where, ...$args):int

line 143
$where = static::objScoped($where)
if (method_exists(static::class, 'beforeDelete') || method_exists(static::class, 'afterDelete') || static::objAudit()){
	$records = static::DB()->query('SELECT '.static::$table.'.* FROM '.static::$table.' WHERE '.$where, ...$args)->fetchAll(\PDO::FETCH_CLASS, static::class)
	foreach ($records AS $record) method_exists(static::class, 'beforeDelete') && $record->beforeDelete()
	return static::objAudit() ? static::transaction(fn() => static::objDeleteCommit($where, $args, $records)) : static::objDeleteCommit($where, $args, $records)
}
return first(static::DB()->delete(static::$table, $where, ...$args), static::objFlush())
static

model :: objDeleteCommit ($where, $args, $records):int

line 153
$result = static::DB()->delete(static::$table, $where, ...$args)
static::objFlush()
foreach ($records AS $record){
	method_exists(static::class, 'afterDelete') && $record->afterDelete()
	static::objAudit() && audit::log($record, 'delete', $record->objData, [])
}
return $result
static

model :: objLogChange ($where, ...$args):int

line 163
Logs changes to the specified model object, capturing the state before and after modifications.
static::change($where, ...$args)
static

model :: objUpsert (string|array $objKey = void, ...$data):?static

line 168
One statement that creates the row or, when one with the same key exists, changes it, so two
// A unique key can match a row outside the scope, and the statement would change it unseen.
static::objScoped() === void || error('objUpsert reaches past the scope of '.static::class.': call it in objUnscoped()')
$key = (array)($objKey ?: static::idColumn())
static::DB()->upsert(static::$table, $key, ...$data)
static::objFlush()
return static::record(...array_intersect_key($data, array_flip($key)))
method

%model -> objIncrement (string $column, int|float $by = 1):static

line 179
Adds to a number in the database itself, so two requests at once both count; the record gets
$pk = static::idColumn()
$q = static::DB()->quoteId($column)
static::change("$pk=?", $this->$pk, objUpdates: "$q = $q ".($by < 0 ? dash : '+').space.abs($by))
$this->$column = static::item(...[$pk => $this->$pk, 'columns' => $q])
$this->objLoaded === null || $this->objLoaded[$column] = $this->$column
return $this
method

%model -> objSave:?static

line 188
$pk = static::idColumn()
$pkValue = $this->$pk ?? $this->id ?? null
$pkValue || error('Can\'t save '.static::class.' record without '.$pk)
$old = static::record(...[$pk => $pkValue])
$isNew = !$old
method_exists(static::class, 'beforeSave') && $this->beforeSave($old)
if ($isNew){
	method_exists(static::class, 'beforeCreate') && $this->beforeCreate()
	$saved = static::objAudit() ? static::transaction(fn() => $this->objSaveCreate($pk, $pkValue)) : $this->objSaveCreate($pk, $pkValue)
}
else {
	method_exists(static::class, 'beforeChange') && $this->beforeChange($old)
	($changes = $this->objChanges($old)) && static::change($pk.'=?', $pkValue, ...$changes)
	$this->objLoaded = $this->objData
	$saved = static::record(...[$pk => $pkValue])
	method_exists(static::class, 'afterChange') && $saved->afterChange($old)
}
method_exists(static::class, 'afterSave') && $saved->afterSave($old)
return $saved
method

%model -> objChanges ($old = null):array

line 214
The columns this request changed since the record was read, so a save leaves a column another
$base = $this->objLoaded ?? $old?->objData
$own = method_exists(static::class, 'schema') ? array_flip(array_merge(...array_values(loop(static::fields(), fn($f) => $f->objColumns)))) : null
$changes = array_filter($this->objData, fn($value, $column) => (!$own || isset($own[$column])) && ($base === null || !array_key_exists($column, $base) || ($value === null) !== ($base[$column] === null) || (string)(is_a($value, obj::class) ? $value->id : $value) !== (string)$base[$column]), ARRAY_FILTER_USE_BOTH)
return loop($changes, fn($value) => is_a($value, obj::class) ? $value->id : $value)
method

%model -> objSaveCreate ($pk, $pkValue):?static

line 221
Creates a new record in the model and performs post-creation actions if defined, such as logging and auditing.
static::createRecord(...$this)
$saved = static::record(...[$pk => $pkValue])
method_exists(static::class, 'afterCreate') && $saved->afterCreate()
static::objAudit() && audit::log($saved, 'create', [], $saved->objData)
return $saved
static

model :: transaction ($callback)

line 229
Executes a database transaction using the provided callback function, ensuring that all operations within the transaction are completed successfully before committing.
static::DB()->transaction($callback)
static

model :: column (...$args):array

line 231
Accesses a specific column from the records loaded by the model, using the fetchAll method with PDO's FETCH_COLUMN option.
static::recordsLoad($args, 'fetchAll', [\PDO::FETCH_COLUMN])
static

model :: item (...$args)

line 232
Loads records from the database using the specified arguments and fetch mode, returning a single column of data.
static::recordsLoad($args, 'fetch', [\PDO::FETCH_COLUMN])
static

model :: pair (...$args):array

line 233
Loads records from the database as a key-value pair array using the specified fetch mode.
static::recordsLoad($args, 'fetchAll', [\PDO::FETCH_KEY_PAIR])
static

model :: records (...$args):array

line 234
Retrieves all records from the model, loading them as instances of the model class.
static::recordsLoad($args, 'fetchAll', [\PDO::FETCH_CLASS|\PDO::FETCH_UNIQUE, static::class], true)
static

model :: recordCount (...$args)

line 235
Returns the total number of records in the model's database table.
static::item(...$args, columns: 'COUNT('.static::idColumn().')')
static

model :: objRecordPage (int $objPage = 1, int $objSize = 25, ...$args):obj

line 239
One page of a read, with what a pager needs: records, total, page and pages. The page is
$size = $objSize
$total = (int)static::recordCount(...array_diff_key($args, ['order' => 1, 'limit' => 1, 'columns' => 1]))
$pages = max(1, (int)ceil($total / max(1, $size)))
$page = min(max(1, $objPage), $pages)
return obj(records: static::records(...array_replace($args, ['limit' => $size.' OFFSET '.(($page - 1) * $size)])), total: $total, page: $page, pages: $pages)
static

model :: record (...$args):?static

line 246
Retrieves a single record from the model's records based on the provided arguments, returning an error if multiple records are found.
count($records = static::records(...$args)) > 1 ? error('Multiple records for '.static::class) : (current($records) ?: null)
static

model :: recordsLoad ($args, $fetch, $fetchMode, $saveRelations = false)

line 253
Loads records and keeps a full record read on the request-local state for relation reuse.
$pk = static::idColumn()
$args['table'] ??= static::$table
$saveRelations && $args['columns'] ??= static::$table.'.'.$pk.' as _,'.static::columns()
($where = static::objScoped((string)($args['where'] ?? void))) !== void && $args['where'] = $where
isset(static::$group) && $args['group'] ??= static::$group
isset(static::$order) && $args['order'] ??= static::$order
$cacheKey = $args['cacheKey'] ?? null
$duration = $args['cache'] ?? static::objCache()
unset($args['cacheKey'], $args['cache'])
if ($duration && !static::DB()->objInTransaction()){
	$cacheArgs = $args
	ksort($cacheArgs)
	$records = apcu(static::class.slash.static::objGeneration().slash.($cacheKey ?? md5(json_encode($cacheArgs))), fn() => static::DB()->load(...$args)->$fetch(...$fetchMode), $duration === true ? 86400 : $duration)
}
else $records = static::DB()->load(...$args)->$fetch(...$fetchMode)
if ($saveRelations && $records){
	$state = static::state()
	$state->records[static::class] = array_replace($state->records[static::class] ?? [], array_column($records, null, $pk))
	count($state->records[static::class]) > static::objRecordLimit() && $state->records[static::class] = array_slice($state->records[static::class], -static::objRecordLimit(), preserve_keys: true)
}
return $records
static

model :: objRel ($key):array

line 277
Accesses the relationship object defined in the model, returning metadata or invoking a method if it exists.
$state = static::state()
return $state->meta[static::class][$key] ??= method_exists(static::class, $key) ? static::$key() : static::$$key ?? []
prop

%model -> objState:array

line 282
The `$objState` property of the model holds the state of the object, including its parents, children, and many relationships, initialized as empty arrays.
['parents' => [], 'children' => [], 'many' => []]
method

%model -> objGet ($key)

line 283
Retrieves an object associated with the specified key from the parent, children, or many relationships in the model.
$this->getParent($key) ?? $this->getChildren($key) ?? $this->getMany($key)
method

%model -> objIn ($ids, $db = null):string

line 284
Returns a quoted list of IDs from the database or 'NULL' if no IDs are provided.
$ids ? ($db ?? static::DB())->quoteList($ids) : 'NULL'
method

%model -> objMirror (string $bucket, $key)

line 290
Mirrors a freshly loaded relation onto a stale reference to the same record.
$pk = $this->objData[static::idColumn()] ?? null
if ($pk === null) return
$canonical = static::state()->records[static::class][$pk] ?? null
if (!$canonical || $canonical === $this) return
if (array_key_exists($key, $this->objState[$bucket] ?? [])) return
if (array_key_exists($key, $canonical->objState[$bucket] ?? [])) $this->objState[$bucket][$key] = $canonical->objState[$bucket][$key]
method

%model -> getParent ($key)

line 299
Retrieves the parent object associated with a given key from the model's state, loading it if necessary.
if (array_key_exists($key, $this->objState['parents'])) return $this->objState['parents'][$key]
$state = static::state()
$parents = self::objRel('objParents')
if (!$relation = $parents[$key] ?? null) return
$isArray = is_array($relation)
$class = $isArray ? $relation['obj'] : $relation
$column = $isArray ? $relation['key'] ?? $key : $key
if (!$parentId = $this->objData[$column] ?? null) return $this->objState['parents'][$key] = null
if (!isset($state->records[$class][$parentId])){
	$idsToLoad = [$parentId => true]
	$allObjData = array_map(fn($record) => $record->objData, $state->records[static::class] ?? [])
	foreach ($parents as $pKey => $pRelation){
		$pIsArray = is_array($pRelation)
		$pClass = $pIsArray ? $pRelation['obj'] : $pRelation
		if ($pClass === $class) foreach (array_column($allObjData, $pIsArray ? $pRelation['key'] ?? $pKey : $pKey) as $pId) $pId && !isset($state->records[$class][$pId]) && $idsToLoad[$pId] = true
	}
	if ($idsToLoad = array_keys($idsToLoad)) $class::records(where: $class::idColumn().' IN ('.$this->objIn($idsToLoad, $class::DB()).')')
}
$parentObject = $state->records[$class][$parentId] ?? null
return $this->objState['parents'][$key] = $parentObject
method

%model -> getChildren ($key)

line 322
Retrieves the child objects associated with a given key from the model's state, loading them if they are not already present.
if (array_key_exists($key, $this->objState['children'])) return $this->objState['children'][$key]
$state = static::state()
if (!$relation = self::objRel('objChildren')[$key] ?? null) return
$isArray = is_array($relation)
$class = $isArray ? $relation['obj'] : $relation
$column = $isArray ? $relation['key'] : static::objShortName()
$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['children']))
if ($toLoad){
	$fq = $class::DB()->fieldQuotes
	$children = $class::records(where: $fq.$column.$fq.' IN ('.$this->objIn(array_keys($toLoad), $class::DB()).')')
	foreach ($toLoad AS $parentRecord) $parentRecord->objState['children'][$key] = []
	foreach ($children AS $childId => $child) !is_null($pId = $child->objData[$column] ?? null) && isset($state->records[static::class][$pId]) && $state->records[static::class][$pId]->objState['children'][$key][$childId] = $child
}
$this->objMirror('children', $key)
return $this->objState['children'][$key] ?? []
method

%model -> getMany ($key)

line 340
Retrieves multiple related records based on a specified key from the model's state, loading them if they are not already present.
if (array_key_exists($key, $this->objState['many'])) return $this->objState['many'][$key]
$state = static::state()
if (!$relation = self::objRel('objMany')[$key] ?? null) return
$class = $relation['obj']
$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['many']))
if ($toLoad){
	$fq = static::DB()->fieldQuotes
	$lk = $relation['localKey']
	$fk = $relation['foreignKey']
	$pivotRows = static::DB()->rows(table: $relation['table'], columns: $fq.$lk.$fq.comma.$fq.$fk.$fq, where: $fq.$lk.$fq.' IN ('.$this->objIn(array_keys($toLoad)).')')
	$targetIds = array_unique(array_map(fn($row) => $row->{$relation['foreignKey']}, $pivotRows ?: []))
	$targetRecords = $targetIds ? $class::records(where: $class::idColumn().' IN ('.$this->objIn($targetIds, $class::DB()).')') : []
	foreach ($toLoad AS $parentRecord) $parentRecord->objState['many'][$key] = []
	foreach ($pivotRows ?: [] AS $row){
		$parentId = $row->$lk
		$foreignId = $row->$fk
		if (isset($state->records[static::class][$parentId]) && isset($targetRecords[$foreignId])) $state->records[static::class][$parentId]->objState['many'][$key][$foreignId] = $targetRecords[$foreignId]
	}
}
$this->objMirror('many', $key)
return $this->objState['many'][$key] ?? []
method

%model -> getCount ($key):int

line 364
Retrieves the count of related records for a given key, loading data if necessary from the database and caching the result in the object's state.
if (array_key_exists($key, $this->objState['counts'] ?? [])) return $this->objState['counts'][$key]
$state = static::state()
if ($relation = self::objRel('objChildren')[$key] ?? null){
	$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['counts'] ?? []))
	if ($toLoad){
		$isArray = is_array($relation)
		$class = $isArray ? $relation['obj'] : $relation
		$column = $isArray ? $relation['key'] : static::objShortName()
		$fq = $class::DB()->fieldQuotes
		$counts = $class::pair(columns: $fq.$column.$fq.', COUNT(*)', where: $fq.$column.$fq.' IN ('.$this->objIn(array_keys($toLoad), $class::DB()).')', group: $fq.$column.$fq)
		foreach ($toLoad as $id => $record) $record->objState['counts'][$key] = (int)($counts[$id] ?? 0)
	}
	$this->objMirror('counts', $key)
	return $this->objState['counts'][$key] ?? 0
}
if ($relation = self::objRel('objMany')[$key] ?? null){
	$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['counts'] ?? []))
	if ($toLoad){
		$fq = static::DB()->fieldQuotes
		$localKey = $relation['localKey']
		$counts = static::DB()->load(table: $relation['table'], columns: $fq.$localKey.$fq.',COUNT(*)', where: $fq.$localKey.$fq.' IN ('.$this->objIn(array_keys($toLoad)).')', group: $fq.$localKey.$fq)->fetchAll(\PDO::FETCH_KEY_PAIR)
		foreach ($toLoad as $id => $record) $record->objState['counts'][$key] = (int)($counts[$id] ?? 0)
	}
	$this->objMirror('counts', $key)
	return $this->objState['counts'][$key] ?? 0
}
return 0
method

%model -> getLast ($key)

line 394
Retrieves the last child object associated with the specified key from the model's state, loading it if necessary.
if (array_key_exists($key, $this->objState['last_child'] ?? [])) return $this->objState['last_child'][$key]
$state = static::state()
if ($relation = self::objRel('objChildren')[$key] ?? null){
	$toLoad = array_filter($state->records[static::class] ?? [], fn($p) => !array_key_exists($key, $p->objState['last_child'] ?? []))
	if ($toLoad){
		$isArray = is_array($relation)
		$class = $isArray ? $relation['obj'] : $relation
		$column = $isArray ? $relation['key'] : static::objShortName()
		$childTable = $class::$table
		$fq = $class::DB()->fieldQuotes
		$qt = $fq.$childTable.$fq
		$qc = $fq.$column.$fq
		$ids = $this->objIn(array_keys($toLoad), $class::DB())
		$childPk = $class::idColumn()
		$joins = ' INNER JOIN (SELECT MAX('.$fq.$childPk.$fq.') AS last_id, '.$qc.' AS parent_id FROM '.$qt.' WHERE '.$qc.' IN ('.$ids.') GROUP BY '.$qc.') AS lcmax ON '.$qt.'.'.$fq.$childPk.$fq.' = lcmax.last_id'
		$lastChildren = $class::records(joins: $joins)
		foreach ($toLoad as $record) $record->objState['last_child'][$key] = null
		foreach ($lastChildren as $child) if (isset($state->records[static::class][$parentId = $child->objData[$column]])) $state->records[static::class][$parentId]->objState['last_child'][$key] = $child
	}
	$this->objMirror('last_child', $key)
	return $this->objState['last_child'][$key] ?? null
}
return null
static

model :: objResolveClass ($name):string

line 420
Resolves the class name for the specified model object, allowing dynamic class handling in Phlo.
$name
static

model :: objShortName ($class = null):string

line 421
This expression retrieves the class name of the current model or the specified class if it exists, using the static context.
$class ?? static::class
static

model :: objParents:array

line 423
Returns the parent objects associated with the current model, utilizing the defined schema and filtering fields of type 'parent'.
if (property_exists(static::class, 'objParents')) return static::$objParents
if (!method_exists(static::class, 'schema')) return []
return loop(array_filter(static::fields(), fn($f) => $f->type === 'parent'), fn($f, $c) => $f->key ? arr(obj: static::objResolveClass($f->obj), key: $f->key) : (static::objResolveClass($f->obj ?? $c)))
static

model :: objChildren:array

line 429
Returns the children objects associated with the current model, leveraging the defined schema and filtering fields of type 'child'.
if (property_exists(static::class, 'objChildren')) return static::$objChildren
if (!method_exists(static::class, 'schema')) return []
return loop(array_filter(static::fields(), fn($f) => $f->type === 'child'), fn($f, $c) => $f->key ? arr(obj: static::objResolveClass($f->obj), key: $f->key) : (static::objResolveClass($f->obj ?? $c)))
static

model :: objMany:array

line 435
Returns the 'objMany' property if it exists; otherwise, it retrieves an array of related objects based on the schema definition.
if (property_exists(static::class, 'objMany')) return static::$objMany
if (!method_exists(static::class, 'schema')) return []
return loop(array_filter(static::fields(), fn($f) => $f->type === 'many'), fn($f) => arr(obj: static::objResolveClass($f->obj), table: $f->table, localKey: $f->localKey ?? static::objShortName(), foreignKey: $f->foreignKey ?? $f->obj))
object

%MySQL

/phlo/resources/DB/MySQL.phlo

MySQL handler via DB class

Reads host, database, user and password from the mysql section of %creds. A model reaches it through static %model.DB => %MySQL.

mysqlpdodatabasesql
method

%MySQL -> upsertClause (array $key, array $update):string

line 11
MySQL and MariaDB find the row by any unique key, so the key only says what stays as it is.
'ON DUPLICATE KEY UPDATE '.loop($update ?: [$key[0]], fn($c) => $this->quoteId($c).' = VALUES('.$this->quoteId($c).')', comma)
prop

%MySQL -> PDO:\PDO

line 13
Creates a new PDO instance for connecting to a MySQL database using the provided credentials.
new \PDO('mysql:host='.%creds->mysql->host.';dbname='.%creds->mysql->database, %creds->mysql->user, %creds->mysql->password)
object

%PostgreSQL

/phlo/resources/DB/PostgreSQL.phlo

PostgreSQL resource

Quotes identifiers with double quotes rather than backticks and has no INSERT IGNORE, so a duplicate is skipped with ON CONFLICT DO NOTHING. Postgres folds an unquoted name to lower case, so a column called createdAt in a schema is not the same one you get back unquoted.

postgresqlpdodatabasesql
prop

%PostgreSQL -> PDO:\PDO

line 10
Creates a new PDO instance for connecting to a PostgreSQL database using the provided credentials.
new PDO('pgsql:host='.%creds->postgresql->host.';dbname='.%creds->postgresql->database, %creds->postgresql->user, %creds->postgresql->password)
prop

%PostgreSQL -> fieldQuotes:string

line 11
Returns the field name wrapped in double quotes for PostgreSQL compatibility.
dq
prop

%PostgreSQL -> insertIgnore:string

line 12
Inserts a new record into a PostgreSQL database, ignoring the operation if a record with the same unique key already exists.
void
prop

%PostgreSQL -> insertOnConflict:string

line 13
Inserts a new record into a PostgreSQL database, and if a conflict occurs (e.g., a duplicate key), it does nothing instead of throwing an error.
' ON CONFLICT DO NOTHING'
method

%PostgreSQL -> lastId

line 19
Asks for the last id inside a savepoint, so a failed lastval() cannot abort the transaction.
$savepoint = $this->PDO->inTransaction()
$savepoint && $this->PDO->exec('SAVEPOINT phlo_lastid')
try {
	$id = $this->PDO->lastInsertId()
} catch (\Throwable $e){
	$id = false
}
if ($savepoint) $this->PDO->exec($id === false ? 'ROLLBACK TO SAVEPOINT phlo_lastid' : 'RELEASE SAVEPOINT phlo_lastid')
return $id
object

%Qdrant

/phlo/resources/DB/Qdrant.phlo

Embeddings resource with Qdrant

Embeddings are cached in APCu for four weeks per input and model, so repeating a search costs nothing at the AI end. create() opens a collection at 1536 dimensions, the length of an OpenAI vector, so state the size yourself when another engine fills it. search() without input sends a zero vector, which lists a collection rather than searching it.

qdrantembeddingsvectorsearchai
method

%Qdrant -> get (string $input, ?string $model = null):array

line 9
apcu('embedding/'.token(input: $model.lf.$input), fn() => %AI->embedding(input: $input, model: $model), 86400 * 28)
method

%Qdrant -> collections:array

line 11
Retrieves an array of collection names from the Qdrant API response.
array_column($this->request('collections')->result->collections, 'name')
method

%Qdrant -> create ($collection, $size = 1536, $distance = 'Cosine'):bool

line 12
Creates a new collection in Qdrant with specified vector size and distance metric.
$this->request("collections/$collection", PUT: arr(vectors: arr(size: $size, distance: $distance)))->status === 'ok'
method

%Qdrant -> upsert ($collection, $id, $input, ...$payload)

line 13
This function updates or inserts a point in a specified Qdrant collection using the provided ID and input vector, along with optional payload data.
$this->request("collections/$collection/points", PUT: arr(points: [arr(id: $id, vector: $this->get($input), payload: $payload ?: null)]))->result->operation_id
method

%Qdrant -> delete ($collection, ...$ids)

line 14
Deletes specified points from a Qdrant collection based on their IDs.
$this->request("collections/$collection/points/delete", POST: arr(points: $ids))->result
method

%Qdrant -> search ($collection, $input = null, $top = 100):array

line 15
Searches for points in the specified Qdrant collection based on the input vector and returns the top results.
create($this->request("collections/$collection/points/search", POST: arr(vector: is_null($input) ? array_fill(0, 1536, 0) : $this->get($input), top: $top, with_payload: true))->result, fn($record) => $record->id, fn($record) => last($record = array_merge(get_object_vars($record), get_object_vars($record->payload)), obj(...array_filter($record, fn($key) => $key !== 'payload', ARRAY_FILTER_USE_KEY))))
method

%Qdrant -> drop ($collection)

line 16
Drops the specified collection from Qdrant by sending a DELETE request to the appropriate endpoint.
$this->request("collections/$collection", DELETE: true)->result
method

%Qdrant -> request ($uri, ...$data)

line 18
Sends an HTTP request to the specified Qdrant server URI with optional data and returns the decoded JSON response.
json_decode(HTTP(%creds->qdrant->server.$uri, %creds->qdrant->key ? ['api-key: '.%creds->qdrant->key] : [], true, ...$data))
object

%SQLite

/phlo/resources/DB/SQLite.phlo

SQLite resource

One file, one database, given as a path: %SQLite('/path/db.sqlite'). It writes with a lock over the whole file, so it fits a single site or a worker but not a set of processes writing at once. Perfect where you want the ORM without a server.

sqlitepdodatabasesql
static

SQLite :: __handle

line 10
This property holds the handle to the SQLite database connection, allowing interaction with the database.
"SQLite/$file"
method

%SQLite -> __construct (private string $file)

line 11
Initializes a new SQLite instance with the specified database file.
prop

%SQLite -> PDO:\PDO

line 12
Creates a new PDO instance for SQLite using the specified file.
new PDO('sqlite:'.$this->file)
prop

%SQLite -> insertIgnore:string

line 13
Inserts a new record into the SQLite database, ignoring the operation if a record with the same primary key already exists.
' OR IGNORE'

Last updated on 3 November 2026

We use essential cookies to make this site work. With your permission we also use analytics to improve the site.