Binary values in the database

Bytes (a packed file, an image, a compressed document) go into a binary column (LONGBLOB on MySQL / MariaDB, BYTEA on PostgreSQL, BLOB on SQLite) through the driver's parameter binding, never inside the SQL text: NUL, 0xFF, quotes and backslashes need no escaping and come back byte-exact. The drivers mysqli, pgsql, pdo_mysql, pdo_pgsql and sqlite have it; clickhouse does not (the calls return false). The other APIs (insert_safe(), the query builder) are unchanged and do not take binary values.

$db = db();
// insert one row: binary() marks the bytes; the other values are bound as int, float, string or NULL (no _es() needed)
$ok = $db->insert_binary('files', ['id' => 7, 'name' => "it's.png", 'data' => $db->binary($bytes)]);
$ok || logger()->warning('insert failed: ' . $db->binary_error());

// update: the WHERE is SQL, escaped by you as for update_safe()
$db->update_binary('files', ['data' => $db->binary($new_bytes)], 'id = ' . (int) $id);

// read: from_binary() turns what the driver returns (PostgreSQL text output, a pdo_pgsql stream) into the bytes
$bytes = $db->from_binary($db->get_one('SELECT data FROM ' . $db->_real_name('files') . ' WHERE id = ' . (int) $id));
  • Column names must be letters, digits and _; anything else makes the call return false.
  • mysqli sends a binary value with send_long_data() in 1 MB parts; the whole value must still fit in the server's max_allowed_packet. PostgreSQL gets it as the bytea hex input form through pg_query_params(); PDO binds it as PDO::PARAM_LOB.
  • In DDL files (share/db/sql/*.sql.php) write longblob (or blob, mediumblob): the installer makes it BYTEA on PostgreSQL and BLOB on SQLite.
  • The statements count in NUM_QUERIES and show in the debug console with the binary values as their length.