NAME DBIx::QuickORM - An ORM that quickly gives you what you need with minimal boilerplate, and easily extends to more complex use cases. DESCRIPTION Quickly get a usable ORM that scans the database for everything it needs. Start operating on rows, using transactions, and making complicated queries right away. Minimal at first, but easy to extend and configure for more complex codebases. EXPERIMENTAL STATUS This distribution is still considered experimental and may change significantly without warning. Once we release version 1.x, we will have a settled final shape and will be careful about breaking public APIs. Until then there is no guarantee of compatibility between releases. QUICKSTART See DBIx::QuickORM::Manual::DocSchema for the schema this project's documentation uses. CONNECTING A database is scanned once per process, whichever way you connect. After changing its tables, pass rescan => 1 to new(). For more details see new. CREDENTIALS use DBIx::QuickORM; my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, ); CONNECT SUB my $orm = DBIx::QuickORM->new( connect => sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1, AutoCommit => 1}); }, ); NOTES: 1. The sub must return a new handle each time it is called. EXISTING DBH my $dbh = DBI->connect($dsn, $user, $pass, {RaiseError => 1, AutoCommit => 1}); my $orm = DBIx::QuickORM->new(dbh => $dbh); NOTES: 1. Nothing that needs a second connection, such as forking or reconnecting, will work. 2. The ORM assumes control of the handle and may change its properties at will. Do not keep using the handle outside the ORM. BASIC ROW OPERATIONS INSERTING my $alice = $orm->insert(users => {name => 'Alice', email => 'alice@example.com'}); my $id = $alice->field('id'); # generated by the database my $post = $orm->insert(posts => {user_id => $id, title => 'Hello'}); my $status = $post->field('status'); # 'draft', the column default FETCHING my $user = $orm->find(users => $id); # by primary key, returns undef when no row has that key my $name = $user->field('name'); my $bob = $orm->handle('users')->where({email => 'bob@example.com'})->only; # undef, because there is no Bob UPDATING $alice->update({name => 'Alice Smith'}); $alice->refresh; # read it again from the database NOTES: 1. Rows have no setters. Change them with update(). 2. Never edit a row's data hash directly. The ORM would not know about it. COMPARE AND SWAP # Writes only if the fields being changed still match what we last fetched until ($post->cas_update({views => $post->field('views') + 1})) { $post->refresh; } NOTES: 1. To compare fields other than the ones being changed, pass cas => \@fields. 2. The comparison uses =, so it does not suit floats or JSON. For more details see DBIx::QuickORM::Manual::Caching. DELETING my $draft = $orm->insert(posts => {user_id => $id, title => 'Draft'}); $draft->delete; my $gone = $draft->was_deleted; # true INFLATION # JSON my $carol = $orm->insert(users => {name => 'Carol', prefs => {theme => 'dark'}}); my $theme = $carol->field('prefs')->{theme}; # 'dark' my $json = $carol->raw_field('prefs'); # the JSON text, as stored # DateTime use DateTime; my $dan = $orm->insert( users => { name => 'Dan', created => DateTime->new(year => 2024, month => 2, day => 3), }, ); my $created = $dan->field('created'); # a lazy DateTime my $year = $created->datetime_ref->year; # 2024 my $later = $created->datetime->add(days => 1); # a copy, safe to change # UUID my $erin = $orm->insert(users => {name => 'Erin', uuid => '0190a6e8-1d2c-7c3b-9f00-123456789abc'}); my $uuid = $erin->field('uuid'); # the 36-character string NOTES: 1. The scan gives JSON, UUID, boolean, and date and time fields their types. 2. field() returns the inflated value. raw_field() returns the value as stored. 3. A lazy DateTime builds the DateTime on first use. Treat the object datetime_ref() returns as read only. 4. If a UUID is stored as 16 bytes (MySQL's binary(16)), it still comes back as the string. 5. raw() from DBIx::QuickORM::Value sends a value as given, without deflating it. 6. A UUID string, a DateTime, or a boolean such as 'true' given to where() is deflated as an insert deflates it. For more details see DBIx::QuickORM::Manual::Values. OVERRIDING SCAN SPECIFY TYPES my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, types => { users => {prefs => undef}, # no type, so JSON text goes in and out posts => {title => '+My::Type::Trimmed'}, # a type class of your own }, ); AUTOTYPE # JSON only, so created comes back as the database's text, not a DateTime my $json_only = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, autotype => ['JSON'], ); # the default types, then your own my $more = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, append_autotype => ['+My::Type::Trimmed'], ); NOTES: 1. The default list is UUID, JSON, DateTime, then Boolean. When several types claim a field, the first one is used. 2. With autotype => undef, no field gets a type. TIME ZONES my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, time_zone => 'America/New_York', ); my $nell = $orm->insert(users => {name => 'Nell'}); my $offset = $nell->field('created')->datetime_ref->offset; # New York's, not UTC's NOTES: 1. The default is UTC, not the server's zone or your machine's. 2. time_zone sets the session time zone. SQLite has none. 3. If you write a floating DateTime to a timestamp with time zone, it is taken to be in this zone. 4. On MySQL and MariaDB, TIMESTAMP values are read and written in this zone. 5. tz is an alias for time_zone. For more details see DBIx::QuickORM::Manual::ScanOverrides. TRANSACTIONS $orm->txn(sub { my $fay = $orm->insert(users => {name => 'Fay'}); $orm->insert(posts => {user_id => $fay->field('id'), title => 'First'}); }); $orm->txn(sub { my $txn = shift; $orm->insert(users => {name => 'Gus'}); $txn->rollback; # Gus is never written }); NOTES: 1. The block commits when it returns. 2. If the block throws an exception, the transaction rolls back and the exception is rethrown. 3. The block may end the transaction early with $txn->commit or $txn->rollback. 4. A transaction started inside another is a savepoint. DuckDB has no savepoints, so nesting a transaction croaks there. 5. Rows read before the transaction are not canonical inside it. Call refresh() on such a row before writing it. RETRY my $views = $orm->txn( retry => 3, sub { my ($post) = $orm->handle('posts')->where({title => 'Hello'})->all; $post->update({views => $post->field('views') + 1}); return $post->field('views'); }, ); NOTES: 1. txn() runs the block up to 3 more times after a deadlock, a serialization failure, or a lock timeout. 2. Other errors are rethrown at once. 3. The block must be safe to run again. 4. Only an outermost transaction with a block can retry. Croaks if given retry anywhere else. For more details see DBIx::QuickORM::Manual::Transactions. HANDLES (QUERIES) See DBIx::QuickORM::Handle for more. Every source and query modifier returns a new handle and leaves the original unchanged. The first read of results sends the query, and the handle keeps the results along with its iteration state. The handle sends the query only once. Call $h->clear to send it again. A SIMPLE FETCH AND ITERATE my $posts = $orm->handle('posts')->where({user_id => $id})->order_by('id'); for my $post ($posts->all) { my $title = $post->field('title'); } while (my $post = $posts->next) { my $views = $post->field('views'); } BULK UPDATE my $count = $orm->handle('posts') ->where({status => 'draft'}) ->update({status => 'published'}); # how many rows changed JOINS my @pairs = $orm->handle('posts') ->join('users') ->where({'users.name' => 'Alice Smith'}) ->all; for my $pair (@pairs) { my $title = $pair->row('posts')->field('title'); my $author = $pair->row('users')->field('name'); } For more details see DBIx::QuickORM::Manual::Joins. AGGREGATES my @stats = $orm->handle('posts') ->group_by('user_id') ->fields({ user_id => 'user_id', posts => [count => '*'], views => [sum => 'views'], }) ->order_by('user_id') ->all; my $count = $stats[0]->field('posts'); For more details see DBIx::QuickORM::Manual::Aggregates, and DBIx::QuickORM::Handle for every handle method. TEMP TABLES AND VIEWS TEMP TABLE use DBIx::QuickORM::DSL ':temp'; my $scores = $orm->temp_table(sub { column user_id => sub { db_type 'integer'; primary_key }; column score => sub { db_type 'integer'; not_null }; }); $scores->handle->insert({user_id => $id, score => 10}); Or using a hashref: my $points = $orm->temp_table({ user_id => {db_type => 'integer', primary_key => 1}, score => {db_type => 'integer', not_null => 1}, }); $points->handle->insert({user_id => $id, score => 10}); POPULATED TEMP TABLE my $popular = $orm->temp_table(pk => ['id'], $orm->handle('posts')->where({views => {'>' => 100}})); my @titles = map { $_->field('title') } $popular->handle->all; TEMP VIEW my $drafts = $orm->temp_view(pk => ['id'], $orm->handle('posts')->where({status => 'draft'})); my $count = $drafts->handle->count; Or from the handle: my $published = $orm->handle('posts')->where({status => 'published'})->temp_view(pk => ['id']); my $total = $published->handle->count; NOTES: 1. A temporary view lasts until you drop it, until the transaction that made it rolls back, or until the connection ends. 2. MySQL and MariaDB have no temporary views. For more details see DBIx::QuickORM::Manual::TempTables. ASYNC AND RELATED ASYNC my $it = $orm->handle('posts')->async->iter; # sends the query, returns at once do_other_work() until $it->ready; my @posts = $it->all; # waits for the rows when they are not there yet maybe_async() is async where the database supports it, and an ordinary query where it does not. The calls are the same either way: my $it = $orm->handle('posts')->maybe_async->iter; do_other_work() until $it->ready; # true at once when it ran as an ordinary query my @posts = $it->all; NOTES: 1. An async query runs on the ORM's connection. Until its rows are read, any other query on that connection croaks. 2. async() currently works on PostgreSQL, MySQL, and MariaDB. Other dialects may add support later. ASIDE my $it = $orm->handle('users')->aside->iter; # on a second connection my $count = $orm->handle('posts')->count; # the ORM's connection is free my @users = $it->all; NOTES: 1. aside() opens a second connection, so it cannot read a temporary table or view. 2. aside() currently works on PostgreSQL, MySQL, and MariaDB, and not when the ORM was given a dbh. Other dialects may add support later. 3. Croaks if started or read inside a transaction. FORKED my $it = $orm->handle('users')->forked->iter; # in a child process my @users = $it->all; NOTES: 1. The child runs the query on a new connection of its own. 2. forked() does not work on DuckDB or an in-memory SQLite database, or when the ORM was given a dbh. 3. A forked query cannot read a temporary table or view. 4. Croaks if started or read inside a transaction. For more details see DBIx::QuickORM::Manual::Background. MANUALS See DBIx::QuickORM::Manual for the manual's index. ATTRIBUTES AND METHODS $orm = DBIx::QuickORM->new(credentials => \%credentials, %OPTS) $orm = DBIx::QuickORM->new(connect => sub { ... }, %OPTS) $orm = DBIx::QuickORM->new(%OPTS) Connects, scans the database, applies the options to what the scan found, and returns the ORM. Arguments: * credentials => {dsn => $dsn, user => $user, pass => $pass, attrs => \%attrs} - Required, or connect or dbh: Arguments for DBI->connect. * connect => sub { ... } - Required, or credentials or dbh: Returns a new DBI handle each time it is called. * dbh => $dbh - Required, or credentials or connect: A DBI handle the ORM takes over (see "EXISTING DBH"). * db_map => $map - Optional: A DBIx::QuickORM::Map, or its data, used instead of a scan. * rescan => $bool - Optional: Scan again even when this process scanned the database before. * autotype => \@types - Optional: The types tried on each field. Pass undef for none. * append_autotype => \@types - Optional: More types, tried after autotype. * types => {$table => {$field => $type}} - Optional: Set a field's type, or remove it with undef. * type_options => {$type => \%hints} - Optional: Field hints for every field of a type. * time_zone => $zone - Optional: The session time zone, UTC by default. Alias: tz. * datetime_parsers => \@parsers - Optional: More parsers for date and time text. * fks => {$table => {$other_table => [\%link, ...]}} - Optional: Foreign keys the database does not declare. * pks => {$table => \@fields} - Optional: Primary keys for views, and tables without one. * elective => \@tables - Optional: Tables the database may lack. * omit => {$table => \@fields} - Optional: Fields left out of default selects. * default_fields => {$table => \@fields} - Optional: The only fields selected by default, plus the primary key. * auto_omit => {types => \@types, db_types => \@db_types} - Optional: Leave fields of these types out of default selects. * row_class => $class - Optional: The default row class, DBIx::QuickORM::Row. Pass undef for hashrefs. * row_classes => {$table => $class} - Optional: Row classes for single tables. Pass undef for hashrefs. * row_namespace => $namespace - Optional: Each table gets the row class named after it under this namespace, when one exists. * row_class_name => sub { my ($table) = @_; ... } - Optional: Returns a table's class name under row_namespace. * lookup => $class - Optional: The lookup table class, Identity by default (see DBIx::QuickORM::LookupTable). * retain_cache => $bool - Optional: Keep cached rows until you call clear_cache(). * enforce_canon => $bool - Optional: Refuse writes of rows that are not canonical. Default 1. * debug => $bool - Optional: Record which call made a row stop being canonical. * isolation => $level - Optional: The isolation level of outermost transactions. * dialect => $class_or_object - Optional: A DBIx::QuickORM::Dialect class (loaded when missing) or object to use in place of the driver's, such as a subclass with your changes. * sql_builder => $builder - Optional: A DBIx::QuickORM::Role::SQLBuilder class or object. * where_builders => \@builders - Optional: DBIx::QuickORM::Role::WhereBuilder classes or objects, tried in order. * like_aggregates => \@names - Optional: Aggregate functions whose result keeps the field's type, like min and max. my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, omit => {users => ['prefs']}, # selected only when asked for row_classes => {posts => undef}, # posts come back as hashrefs retain_cache => 1, ); This example uses most of the options. The My::... classes are your own: my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, attrs => {pg_enable_utf8 => 1}, }, rescan => 1, # scan again, even if this process did dialect => 'DBIx::QuickORM::Dialect::PostgreSQL', # or a subclass of your own autotype => ['JSON', 'UUID', 'DateTime', 'Boolean'], # the types tried on each field append_autotype => ['+My::Type::Trimmed'], # tried after those types => {users => {prefs => undef}}, # prefs stays JSON text type_options => {DateTime => {format => sub { $_[0] =~ s/\.\d+//r }}}, # no fractional seconds time_zone => 'America/New_York', datetime_parsers => ['My::DateParser'], # any class with parse_datetime elective => ['audit_log'], # the database may lack it omit => {users => ['prefs']}, # selected only when asked for default_fields => {posts => ['title', 'status']}, # plus the primary key auto_omit => {types => ['JSON']}, # every JSON field omitted row_class => 'My::Row', # the default row class row_classes => {posts => undef}, # posts come back as hashrefs row_namespace => 'My::App::Row', # My::App::Row::Users, if it exists lookup => 'Identity', # the default, needed by retain_cache retain_cache => 1, enforce_canon => 1, debug => 1, isolation => 'repeatable read', sql_builder => 'DBIx::QuickORM::SQLBuilder::SQLAbstract', where_builders => ['DBIx::QuickORM::WhereBuilder::Simple', 'DBIx::QuickORM::WhereBuilder::SQLAbstract'], like_aggregates => ['any_value'], ); NOTES: 1. Croaks if given an unknown argument, or a table or field the database lacks. 2. The first scan of a database is reused by later new() calls in the process. Pass rescan after you change its tables. 3. Every DBI handle needs AutoCommit on and no open transaction. For more details see DBIx::QuickORM::Manual::ScanOverrides. $conn = $orm->connection Returns the current DBIx::QuickORM::Connection, making a new connection if there is no current one for this process. NOTES: 1. In a forked child it croaks if the ORM was given a dbh, or on DuckDB or an in-memory SQLite database. $map = $orm->db_map Returns the DBIx::QuickORM::Map of the current connection, including its temporary tables and views. $class = $orm->lookup_class Returns the full name of the lookup table class as a string, DBIx::QuickORM::LookupTable::Identity by default. $bool = $orm->retain_cache Returns true if cached rows are kept until you call clear_cache(). $bool = $orm->enforce_canon Returns true if writing row data that is not canonical croaks outside a transaction. Inside a transaction it always croaks. $orm->set_enforce_canon($bool) Sets whether writing row data that is not canonical croaks outside a transaction. $debug = $orm->debug Returns the DBIx::QuickORM::Debug object if you passed debug => 1 to new(), or undef if you did not. $level = $orm->isolation Returns the isolation level of outermost transactions as a lowercase string, or undef if none was given. $zone = $orm->time_zone Returns the session time zone name as a string, UTC by default. \@parsers = $orm->datetime_parsers Returns an arrayref of the extra parsers the DateTime type tries, empty by default. $orm->set_datetime_parsers(\@parsers) Replaces the extra parsers the DateTime type tries with a copy of \@parsers, loading each class and croaking on a bad parser. NOTES: 1. A value read before the call keeps the parsers it was read with. $bool = $orm->is_canon($table, $row_or_data) Returns true when the row data is the ORM's canonical copy of that row. Arguments: 1. $table - Required: Table name. 2. $row_or_data - Required: A row object, or row data (a hashref). my $found = $orm->find(users => $id); my $yes = $orm->is_canon(users => $found); # true NOTES: 1. The lookup table decides which copy is canonical (see DBIx::QuickORM::LookupTable). $orm->clear_cache $orm->clear_cache($table) $orm->clear_cache($table => $pk) Forgets the cached rows: all of them, one table's, or one row's. Arguments: 1. $table - Optional: Table name. 2. $pk - Optional: A primary key, in any form find() takes. $orm->clear_cache(users => $id); my $held = $orm->is_canon(users => $found); # false $found->refresh; # canonical again NOTES: 1. If the handle already ran, it keeps its rows. Call clear() to run the query again. canon_status $status = $orm->canon_status($table, $row_or_data) Returns undef while the row data is canonical. Otherwise it returns a hashref whose cause says why it is not. Arguments: 1. $table - Required: Table name. 2. $row_or_data - Required: A row object, or row data (a hashref). my $one = $orm->find(users => $id); my $two = $orm->handle('users')->fields(['name'])->where({id => $id})->only; my $why = $orm->canon_status(users => $one); # {cause => 'replaced', ...} NOTES: 1. replaced - Another copy took its place: a read of changed data or of fewer fields, a write, or a key change. 2. cache_cleared - The cached copy of this one row was cleared, with clear_cache($table => $pk). 3. txn - The row data was read before the open transaction began. 4. deleted - The row was deleted, or found gone. 5. not_in_db - The row data came from vivify(), or its insert was rolled back. 6. not_cached - The cache holds no copy of the row. It was read around the cache or rolled back, or its table or the whole cache was cleared. 7. rolled_back - With lookup => 'Scoped', the row data was read or written in a transaction that rolled back. 8. With debug => 1, by (or last_clear for not_cached) names the call that did it. For more details see DBIx::QuickORM::Manual::Caching. CRUD operations my $row = $orm->insert(users => {name => 'Hal'}); # a row object my $data = $orm->insert(users => {name => 'Ida'}, data => 1); # row data, a hashref my $hash = $orm->find(users => $id, row_class => undef); # row data too my $own = $orm->find(users => $id, data => 1, canonical => 1); # the row cache's own hash $orm->insert(users => {name => 'Jan'}); # in void context nothing is read back use DBIx::QuickORM::Value qw/raw/; $orm->insert(users => {name => 'Kay', prefs => {theme => 'dark'}}); # deflated to JSON text $orm->insert(users => {name => 'Lee', prefs => raw('{"theme":"dark"}')}); # sent as given $orm->insert(users => {name => 'Mo', prefs => '{"theme":"dark"}'}, raw => 1); # sent as given NOTES: 1. These rules hold for insert(), insert_many(), update_row(), refresh_row(), find(), find_or_insert(), insert_fk(), and insert_many_fk(). 2. In void context these methods do the work and return nothing. 3. With data => 1, they return row data instead of a row, even when row_class is given. 4. With row_class => $class, that call builds its rows with $class. If $class is undef, it returns row data. 5. The row data from data => 1 or row_class => undef is a shallow copy of the row cache's hash, so you may change it. A copy is not canonical, so the write methods croak on it under enforce_canon. 6. With canonical => 1 as well, they return the row cache's own hash, which the write methods accept. Never change it. Croaks if given canonical without row data. 7. Without data or row_class, the rows use the table's row class, or the ORM's row_class when the table has none. If that class is undef, they return the row cache's own hashes. 8. If given a row object, update_row() and refresh_row() return that same object, holding the new data. 9. Row data is a plain hashref. See DBIx::QuickORM::Manual::RowData. 10. The values sent are deflated by their field's type. Croaks if given a reference for a field without a type. 11. With raw => 1, every value is sent as given. The markers of DBIx::QuickORM::Value (raw(), inflated(), binary(), sql()) override that for one value. 12. A row written with RETURNING holds the default fields, the fields written, and for an update the fields it held. 13. Without RETURNING (MySQL, and MariaDB for updates) the row holds only the primary key. 14. Writes replace the cached canonical copy of the row. 15. Single-row operations use prepare_cached(). Behind a pooler in transaction mode, turn off server-side prepares. $row = $orm->insert($table => \%fields) \%data = $orm->insert($table => \%fields, data => 1) $row = $orm->insert($table => \%fields, %OPTS) Inserts one row and returns it. Arguments: 1. $table - Required: Table name. 2. \%fields - Required: The values, at least one. * raw => $bool - Optional: The values are in database form already. Nothing is deflated. * data => $bool - Optional: Return a copy of the row data (a hashref), not a row. * canonical => $bool - Optional: With row data, return the row cache's own hash instead of a copy. * row_class => $class - Optional: Build the row with this class. Pass undef for the row data. * as_given => $bool - Optional: Return the values as sent, plus the new key, without reading the row back. my $ann = $orm->insert(users => {name => 'Ann', prefs => {theme => 'dark'}}); $orm->insert(users => {name => 'Cy'}); # in void context nothing is read back NOTES: 1. If the insert leaves out the primary key, its type may supply one (a UUID key gets a version 7 UUID). For more details see DBIx::QuickORM::Manual::Values. \@rows = $orm->insert_many($table => \@rows) $count = $orm->insert_many($table => \@rows, count => 1) \@rows = $orm->insert_many($table => \@rows, %OPTS) Inserts many rows and returns an arrayref of the new rows. Arguments: 1. $table - Required: Table name. 2. \@rows - Required: Hashrefs of values, every one with the same fields. * count => $bool - Optional: Return how many rows went in. Nothing is read back. * raw => $bool - Optional: The values are in database form already. * data => $bool - Optional: Return copies of the row data (hashrefs), not rows. * canonical => $bool - Optional: With row data, return the row cache's own hashes instead of copies. * row_class => $class - Optional: Build the rows with this class. Pass undef for the row data. my $rows = $orm->insert_many(users => [{name => 'Ola'}, {name => 'Pia'}]); my $count = $orm->insert_many(users => [{name => 'Rae'}, {name => 'Sol'}], count => 1); # 2 NOTES: 1. When the insert takes more than one statement, either every row goes in or none does. 2. Without RETURNING (MySQL), every row needs its whole primary key, unless you pass count or call it in void context. For more details see DBIx::QuickORM::Manual::BulkInsert. $row = $orm->update_row($table, $row_or_data, \%changes) $row = $orm->update_row($table, $row_or_data, \%changes, %OPTS) Updates the row with that primary key and returns it. Returns undef when no row matched. Arguments: 1. $table - Required: Table name. 2. $row_or_data - Required: A row object (which takes the new data), or row data. 3. \%changes - Required: The new values, at least one. * cas => \@fields - Optional: Write only if these fields still hold the row data's values. Otherwise return undef. * auto_cas => $bool - Optional: Use cas on every changed field the row data holds. * enforce_canon => $bool - Optional: Croak unless the row data is canonical. 0 skips the check. * raw => $bool - Optional: The values are in database form already. * data => $bool - Optional: Return a copy of the row data, not a row. * canonical => $bool - Optional: With row data, return the row cache's own hash instead of a copy. * row_class => $class - Optional: Build the row with this class. $orm->update_row(users => $ann, {name => 'Anne'}); # writes only if email still holds what $ann read my $done = $orm->update_row(users => $ann, {email => 'anne@example.com'}, auto_cas => 1); NOTES: 1. update() on a row calls this method. 2. Inside a transaction enforce_canon defaults to true. Outside one it defaults to the ORM's enforce_canon. \%data = $orm->cas_update($table, \%data, \%changes) $row = $orm->cas_update($table, $row, \%changes, cas => \@fields) Writes the changes only while the database still holds the row data's values for the changed fields (or the cas fields). Returns undef otherwise. Arguments: 1. $table - Required: Table name. 2. $row_or_data - Required: A row object, or any hashref holding the primary key and the compared fields. 3. \%changes - Required: The new values. * cas => \@fields - Optional: The fields to compare, instead of the changed ones. * raw => $bool - Optional: The changes are in database form already. * row_class => $class - Optional: Build the row with this class. * canonical => $bool - Optional: Given a hashref, return the row cache's own hash instead of a copy. my ($cy) = $orm->handle('users')->where({name => 'Cy'})->bare->all; my $renamed = $orm->cas_update(users => $cy, {name => 'Cyrus'}, canonical => 1); # undef if the name changed NOTES: 1. The row data need not be canonical. 2. The row data's values are compared as the database returned them, without deflating them. $count = $orm->delete_row($table, $row_or_data) $count = $orm->delete_row($table, $row_or_data, enforce_canon => $bool, raw => $bool) Deletes the row with that primary key and returns how many rows it deleted (0 or 1). Arguments: 1. $table - Required: Table name. 2. $row_or_data - Required: A row object, or row data. * enforce_canon => $bool - Optional: As for update_row(). * raw => $bool - Optional: The key is in database form already. my $gone = $orm->delete_row(users => $renamed); # 1 NOTES: 1. The row data is marked deleted, even when no row matched. $row = $orm->refresh_row($table, $row_or_pk) $row = $orm->refresh_row($table, $row_or_pk, %OPTS) Returns the canonical row for that primary key, reading the database when the row is not in the cache. Returns undef when there is no such row. Arguments: 1. $table - Required: Table name. 2. $row_or_pk - Required: A row object (which takes the new data), row data, or a primary key. * cache => $bool - Optional: Pass 0 to always read the database. * db => $bool - Optional: Pass 0 to never read the database. * fields => \@fields - Optional: The fields to read, plus the primary key. * raw => $bool - Optional: The key is in database form already. * data => $bool - Optional: Return a copy of the row data, not a row. * canonical => $bool - Optional: With row data, return the row cache's own hash instead of a copy. * row_class => $class - Optional: Build the row with this class. my $fresh = $orm->refresh_row(users => $id, cache => 0); # always a query my $cached = $orm->refresh_row(users => $id, db => 0); # never a query $row = $orm->find($table, $pk) \%data = $orm->find($table, $pk, data => 1) $row = $orm->find($table, $pk, %OPTS) Returns the row with that primary key, or undef. Arguments: 1. $table - Required: Table name. 2. $pk - Required: A primary key in any form (see DBIx::QuickORM::Manual::Keys). 3. %OPTS - Optional: The options of refresh_row(). my $user = $orm->find(users => $id); my $none = $orm->find(users => -1); # undef $row = $orm->find_or_insert($table => \%fields) $row = $orm->find_or_insert($table => \%fields, by => \@fields) $row = $orm->find_or_insert($table => \%fields, %OPTS) Returns the row whose by fields hold these values, inserting it when there is none. Arguments: 1. $table - Required: Table name. 2. \%fields - Required: The values to insert. They hold every by field. * by => \@fields - Optional: The fields to find by. Default: the primary key. * raw => $bool - Optional: The values are in database form already, by values included. * data => $bool - Optional: Return a copy of the row data, not a row. * canonical => $bool - Optional: With row data, return the row cache's own hash instead of a copy. * row_class => $class - Optional: Build the row with this class. # Gil keeps the name Gil the second time, because only the by fields are compared my $gil = $orm->find_or_insert( users => {name => 'Gil', email => 'gil@example.com'}, by => ['email'], ); my $same = $orm->find_or_insert( users => {name => 'Someone', email => 'gil@example.com'}, by => ['email'], ); NOTES: 1. If another process inserts the row first, find_or_insert() finds that row. For that to work, the by fields need a unique key. 2. Croaks if more than one row matches, or if a by value is undef. $row = $orm->vivify($table => \%fields) $row = $orm->vivify($table => \%fields, row_class => $class) Returns a new row that is not in the database yet. Call insert() on the row to write it. Arguments: 1. $table - Required: Table name. 2. \%fields - Required: The values. May be empty. * row_class => $class - Optional: Build the row with this class. Pass undef for the row data. my $ivy = $orm->vivify(users => {name => 'Ivy'}); $ivy->modify({email => 'ivy@example.com'}); # still nothing written $ivy->insert; # now in the database $h = $orm->follow_fk($table, $row_or_data, $other_table) $h = $orm->follow_fk($table, $row_or_data, $other_table, link => \%link) $h = $orm->follow_fk($table, $row_or_data, $other_table, via => \%via) Returns a handle on $other_table for the rows linked to this row by a foreign key, in either direction. Arguments: 1. $table - Required: The row's table. 2. $row_or_data - Required: A row object, or row data. 3. $other_table - Required: The table to follow to. * link => {$our_field => $their_field} - Optional: Picks the key when there is more than one. * via => {$our_field => $their_field} - Optional: Follows fields no declared key links. my $author = $orm->follow_fk(posts => $post, 'users')->only; my @posts = $orm->follow_fk(users => $author, 'posts')->all; NOTES: 1. Narrow the handle with and(). where() would replace the link. For more details see DBIx::QuickORM::Manual::ForeignKeys. $row = $orm->insert_fk($table, $row_or_data, $other_table, \%fields) \@rows = $orm->insert_many_fk($table, $row_or_data, $other_table, @fields) $row = $orm->insert_fk($table, $row_or_data, $other_table, %OPTS, \%fields) Inserts rows into $other_table that point at this row, filling in their foreign key fields. insert_fk() inserts one row, as insert() does. insert_many_fk() inserts many, as insert_many() does. Arguments: 1. $table - Required: The row's table. 2. $row_or_data - Required: A row object, or row data. 3. $other_table - Required: The table to insert into. 4. \%fields - Required: The new row's values, without the linked fields. 5. %OPTS - Optional: link and via as for follow_fk(), and the options of insert() or insert_many(). my $one = $orm->insert_fk(users => $author, 'posts', {title => 'One'}); my $more = $orm->insert_many_fk(users => $author, 'posts', {title => 'A'}, {title => 'B'}); $h = $orm->handle($table) $h = $orm->handle(\[$sql, @binds]) $h = $orm->handle($source) Returns a DBIx::QuickORM::Handle over a table, an SQL query, or a source object. Arguments: 1. $table - Required, or one of the others: Table name. 2. \$sql or \[$sql, @binds] - Required, or one of the others: An SQL query. 3. $source - Required, or one of the others: A DBIx::QuickORM::Role::Source, such as a temporary table. my @drafts = $orm->handle('posts')->where({status => 'draft'})->all; my @named = $orm->handle(\['SELECT id, name FROM users WHERE id > ?', 0])->all; NOTES: 1. The binds of an SQL query are not deflated, and its rows can never be written through the ORM. @result = $orm->txn(sub { my $txn = shift; ... }) $txn = $orm->txn @result = $orm->txn(retry => $n, isolation => $level, sub { ... }) Opens a transaction, or a savepoint inside one, as a DBIx::QuickORM::Txn. Given a block, it runs the block and returns what the block returns. Arguments: 1. sub { ... } - Optional: The block. The transaction commits when it returns and rolls back on an exception. Pass it first or last. * retry => $n - Optional: Run the block up to $n more times after a retriable error. * isolation => $level - Optional: 'read committed' (default), 'repeatable read', 'serializable', 'read uncommitted', or 'server'. my $txn = $orm->txn; $orm->insert(users => {name => 'Kim'}); $txn->commit; my $count = $orm->txn( isolation => 'serializable', sub { $orm->handle('users')->count }, ); NOTES: 1. Croaks if given retry or isolation for a nested transaction. 2. SQLite and DuckDB cannot set an isolation level. DuckDB has no savepoints. For more details see DBIx::QuickORM::Manual::Transactions. $temp = $orm->temp_table(%OPTS, sub { ... }) $temp = $orm->temp_table(%OPTS, \%columns) $temp = $orm->temp_table(%OPTS, $what) Creates a temporary table and returns its DBIx::QuickORM::Source::Table::Temp. Given only options, it returns a DBIx::QuickORM::SchemaBuilder::Table::Temp instead. Call build() on that to create the table. Arguments: 1. $what - Optional, first or last: A block describing the table, \%columns, a handle or \[$select, @binds] to fill it from, or \$create_sql. \%columns maps each column name to the arguments add_column() in DBIx::QuickORM::SchemaBuilder::Table takes, so no DSL is needed. * name => $name - Optional: The table name. One is made up when not given. Required with \$create_sql. * pk => \@fields - Optional: The primary key. With \%columns the table is created with it. With a handle or a SELECT only the ORM uses it. Croaks if given with a block or \$create_sql. my $pairs = $orm->temp_table( pk => ['user_id', 'post_id'], { user_id => {db_type => 'integer', not_null => 1}, post_id => {db_type => 'integer', not_null => 1}, }, ); my $mine = $orm->temp_table(name => 'mine', pk => ['id'], \['SELECT id, title FROM posts WHERE user_id = ?', $id]); my $scratch = $orm->temp_table(name => 'scratch', \'CREATE TEMPORARY TABLE scratch (k TEXT PRIMARY KEY, v TEXT)'); NOTES: 1. When the table is filled from a query, the database picks the column types and copies no key. 2. With \%columns, the columns are created in name order. Use a block for another order. 3. With \%columns, give the key with pk or with primary_key on its columns, not both. $temp = $orm->temp_view(%OPTS, $handle) $temp = $orm->temp_view(%OPTS, \[$select, @binds]) Creates a temporary view and returns its DBIx::QuickORM::Source::Table::Temp. Arguments: 1. $handle or \$select or \[$select, @binds] - Required, first or last: The view's query. * name => $name - Optional: The view name. One is made up when not given. * pk => \@fields - Optional: The fields that identify a row. my $popular = $orm->temp_view(name => 'popular', pk => ['id'], \['SELECT id, title FROM posts WHERE views > ?', 100]); NOTES: 1. The binds are written into the view as literals. 2. Croaks on MySQL and MariaDB, which have no temporary views. @names = $orm->temp_tables Returns the names of the current connection's temporary tables and views, sorted. my @names = $orm->temp_tables; $temp = $orm->temp($name) Returns the DBIx::QuickORM::Source::Table::Temp of a temporary table or view. Croaks for any other name. Arguments: 1. $name - Required: The table or view name. $orm->temp('popular')->drop; For more details see DBIx::QuickORM::Manual::TempTables. $class = $orm->require_type($type) $class = $orm->require_type($type, $context) Returns the class for a type name, loading it when needed. Arguments: 1. $type - Required: A type name: JSON, or +My::Type for a full class name. 2. $context - Optional: What asked for it, for the error. my $class = $orm->require_type('JSON'); # 'DBIx::QuickORM::Type::JSON' $orm->load_row_class($class) Loads a row class unless it already has new(). Croaks if it cannot be loaded. Arguments: 1. $class - Required: Class name. $orm->load_row_class('DBIx::QuickORM::Row'); $class = $orm->row_class Returns the default row class name as a string, DBIx::QuickORM::Row unless new() was given another, or undef when rows are hashrefs by default. \%classes = $orm->row_classes Returns the row_classes hashref given to new(), mapping table names to row classes, or undef if it was not given. $namespace = $orm->row_namespace Returns the row_namespace package name given to new() as a string, or undef if none was given. $code = $orm->row_class_name Returns the row_class_name code reference given to new(), or undef if none was given. \%omit = $orm->omit Returns the omit hashref given to new(), mapping table names to the fields left out of default selects, or undef if it was not given. \%fields = $orm->default_fields Returns the default_fields hashref given to new(), mapping table names to the fields selected by default, or undef if it was not given. \%auto_omit = $orm->auto_omit Returns the auto_omit hashref given to new(), holding the types and db_types lists, or undef if it was not given. \%types = $orm->types Returns the types hashref given to new(), mapping table names to field types, or undef if it was not given. \%options = $orm->type_options Returns the type_options hashref given to new(), mapping type names to field hints, or undef if it was not given. \@types = $orm->autotype Returns the autotype arrayref of type names given to new(), or undef if it was not given, even though a default list applies. \@types = $orm->append_autotype Returns the append_autotype arrayref of type names given to new(), or undef if it was not given. \%fks = $orm->fks Returns the fks hashref of extra foreign keys given to new(), or undef if it was not given. \%pks = $orm->pks Returns the pks hashref of extra primary keys given to new(), or undef if it was not given. \@tables = $orm->elective Returns the elective arrayref of table names given to new(), or undef if it was not given. $builder = $orm->sql_builder Returns the DBIx::QuickORM::Role::SQLBuilder object, built from the sql_builder given to new() or from DBIx::QuickORM::SQLBuilder::SQLAbstract by default. \@builders = $orm->where_builders Returns an arrayref of the DBIx::QuickORM::Role::WhereBuilder classes or objects, in the order they are tried. $code = $orm->connector Returns the code reference that returns a new DBI handle each time it is called, built from credentials or connect. With dbh, it returns that handle once and croaks after. \@names = $orm->like_aggregates Returns the like_aggregates arrayref of function names given to new(), or undef if it was not given. SOURCE The source code repository for DBIx-QuickORM can be found at https://github.com/exodist/DBIx-QuickORM. AI/LLM POLICY AND INFORMATION This project does allow the use of AI/LLM in contributions. However, it is not a low-effort "slop" project. The project was originally entirely hand-coded without AI/LLM, and its intended audience is humans writing code, not bots. It has since been reworked several times and AI/LLM tools have been used to shuffle around and restructure much of the code. It was never unreviewed or low-effort. I cannot promise some hard to read AI documentation will not slip through, and I cannot promise the AI/LLM portions of the code are bug free. But I can say they have been held to the same standard as any human contribution, including my own. Humans can also write bugs and bad documentation. I do review what agents produce, and I have caught many cases of terrible documentation wording, terrible code, and bugs where the agent was a moron. I am sure plenty of others have slipped through despite my thorough review. If you want to avoid AI/LLM code completely, use another distribution. If you want to send me slop or unreviewed and terrible low-effort PRs then use another distribution. Responsible and vetted AI use is perfectly acceptable. Discussions, PRs and bug reports should remain civil, and must not become a place to debate if or when AI/LLM should be used. That said, we absolutely can call out low-effort slop, and reject it for that reason. But AI/LLM being involved is not in itself enough to reject submissions, so long as the quality is good, and the person submitting it understands it, reviews it, and stands by it. The full AI/LLM policy is covered in the AI_AND_LLM_POLICY.md file included with this distribution. MAINTAINERS Chad Granum AUTHORS Chad Granum COPYRIGHT Copyright Chad Granum . This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See https://dev.perl.org/licenses/