NAME DBIx::QuickORM - An ORM that quickly gives you what you need with minimal boilerplate, and easily extends to more complex use cases. 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. WHERE TO START New to the ORM? Read DBIx::QuickORM::Manual::Quickstart: short examples of everything most applications need. See DBIx::QuickORM::Manual for additional resources. 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. DESCRIPTION Connect and start working. DBIx::QuickORM scans the live database and uses what it finds as the schema. There is no schema, table, or column metadata to declare. Most of it is automatic. Insert, find, update, delete, and query rows right away. Rows come back as DBIx::QuickORM::Row objects, but custom row classes can be defined, or you can request plain hashrefs be returned if you do not want the overhead of a full row object. When the scan gets something wrong, or you need custom behavior, it is easy to adjust: omit fields by default, give a field a data type for inflation, add foreign keys the database does not declare, and so on. See new (under "Constructor"), or the easy to use DSL (DBIx::QuickORM::DSL), for details. Larger applications can declare the ORM and its row classes in their own modules. See DBIx::QuickORM::ORM. Supported databases: PostgreSQL, MySQL, MariaDB, SQLite, and DuckDB. SYNOPSIS use DBIx::QuickORM; my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, ); my $bob = $orm->insert(users => {name => 'Bob'}); my $row = $orm->find(users => $bob->field('id')); $bob->update({name => 'Robert'}); my @roberts = $orm->handle('users') ->where({name => 'Robert'}) ->all; $orm->txn(sub { $orm->insert(users => {name => 'Ann'}); $orm->insert(users => {name => 'Cy'}); }); $bob->delete; PUBLIC METHODS The examples use the users and posts tables shown in the DESCRIPTION of DBIx::QuickORM::Manual::Quickstart, on PostgreSQL. $id is a users primary key, and %credentials holds dsn, user, and pass. Constructor $orm = DBIx::QuickORM->new(%args) $orm = DBIx::QuickORM->new(\%args) Connects, scans the database into a map of its tables and fields (DBIx::QuickORM::Map), and returns the ORM. Pass exactly one of dbh, connect, or credentials. An unknown argument croaks. 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 plain hashrefs retain_cache => 1, # keep rows cached until clear_cache() ); The connection argument, one of: dbh => $dbh A connected DBI handle with RaiseError and AutoCommit on. my $dbh = DBI->connect( $dsn, $user, $pass, { RaiseError => 1, AutoCommit => 1, }, ); my $orm = DBIx::QuickORM->new(dbh => $dbh); The ORM takes it over and may change its attributes. Using it elsewhere is unsupported. With this form the ORM cannot open a second connection: using the ORM from a forked child croaks, and so do aside and forked on its handles (see "Running elsewhere" in DBIx::QuickORM::Handle). connect => sub { ... } A code reference that returns a new, uncached handle with RaiseError and AutoCommit on each time it is called. my $orm = DBIx::QuickORM->new( connect => sub { DBI->connect( $dsn, $user, $pass, { RaiseError => 1, AutoCommit => 1, }, ); }, ); Unlike dbh, the ORM can open another handle, as a forked child does. credentials => {dsn => $dsn, user => $user, pass => $pass, attrs => \%attrs} Arguments for DBI->connect. dsn is required. user, pass, and attrs are optional. my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, attrs => {pg_server_prepare => 0}, # more DBI attributes }, ); Other keys croak. RaiseError and AutoCommit are always turned on, and AutoCommit given false in attrs croaks. The ORM manages transactions, so every form needs AutoCommit on. A handle with AutoCommit off, or with a transaction already open, croaks. The remaining arguments adjust the map. The database is scanned into a DBIx::QuickORM::Map unless db_map is given, once per process (see rescan). These arguments then change it, in this order. Each type or row class they name is loaded during new. Some examples below use a table or view of their own (audit, user_names, sessions, files), shown in a comment. Like any table, it must exist before this process first scans the database, or pass rescan. Naming a table or field not in the map croaks, as does an argument of the wrong type. db_map => $map A DBIx::QuickORM::Map, or a hashref of map data, used instead of a scan. # no scan: start from another ORM's map. Take it while that ORM has no # temporary tables or views, or the copy holds their records too. my $copy = DBIx::QuickORM->new( credentials => \%credentials, db_map => $orm->db_map, ); It is deep-copied, so the original is never changed. The arguments below adjust the copy. rescan => 1 Scans the database even when this process scanned it before. # a migration, through its own database handle $migration_dbh->do('CREATE TABLE tags (id SERIAL PRIMARY KEY, name TEXT NOT NULL)'); # without rescan, the map would come from this process's first scan: no tags my $orm = DBIx::QuickORM->new( credentials => \%credentials, rescan => 1, ); my $tag = $orm->insert(tags => {name => 'perl'}); The first scan of a database in a process is kept, and every later new without a db_map starts from a copy of it, so building an ORM again (after a lost connection, say) does not scan again. Each ORM still applies its own arguments to its copy. The cache is keyed by which database the connection reaches and what the session sees of it: the server, database, user, and schema (or search path, or active roles), or the database file. In-memory SQLite and DuckDB databases are never cached. Tables changed after the first scan are not seen. Pass rescan after changing tables in a running process, as a migration script does, or restart the process. "The scan cache" in DBIx::QuickORM::Connection has the details. autotype => \@types autotype => undef append_autotype => \@types The types tried, in order, on each field when the map is built. The first that matches becomes the field's orm_type. Default: UUID, JSON, then DateTime (DBIx::QuickORM::Type::UUID, DBIx::QuickORM::Type::JSON, DBIx::QuickORM::Type::DateTime). # JSON only: created comes back as the database's text, not a DateTime my $json_only = DBIx::QuickORM->new( credentials => \%credentials, autotype => ['JSON'], ); # no types at all: the ORM inflates nothing, so a non-NULL prefs comes # back as the JSON text the database gives, not a hashref my $untyped = DBIx::QuickORM->new( credentials => \%credentials, autotype => undef, ); # the default list, then a type of your own for the fields it claims my $more = DBIx::QuickORM->new( credentials => \%credentials, append_autotype => ['+My::Type::Trimmed'], ); autotype => undef or [] turns this off. append_autotype adds to the autotype list, or to the default. With a db_map, the map keeps its types unless either is given. Then every field is typed again. A type matches through its base_types or matches (see DBIx::QuickORM::Role::Type). Type names work the same everywhere: a bare name such as JSON means DBIx::QuickORM::Type::JSON, and a leading + marks a full class name, such as +My::Type. The map holds the full name. Array fields are never typed automatically: those whose db_type ends in [] or [N] (PostgreSQL arrays, DuckDB lists and fixed-size arrays). Use types to give one a type. types => {table => {field => $type_or_undef}} types => {table => {field => {class => $type_or_undef, format => \&code, generate => $mode}}} Sets a field's type. Undef removes it. # CREATE TABLE sessions (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), note TEXT) # -- gen_random_uuid() is built in from PostgreSQL 13, from pgcrypto before my $orm = DBIx::QuickORM->new( credentials => \%credentials, types => { users => { # no type: the database's JSON text in and out prefs => undef, # no class, so it stays DateTime. format gets the text the type # deflated to, such as '2024-01-02 03:04:05.5', and returns the # text to write: whole seconds created => { format => sub { my ($text) = @_; return $text =~ s/\.\d+//r; }, }, }, # a type the scan would not choose posts => {title => '+My::Type::Trimmed'}, # the ORM's version 7 UUIDs, not the database's default sessions => { id => { class => 'UUID', generate => 'prefer_orm', }, }, }, ); The hashref form also sets field hints: format and generate (see "Field hints" in DBIx::QuickORM::Role::Type). Without class it keeps the field's type. Either form replaces the field's hints with the ones given (none for the plain form). type_options then fills in the rest. Other keys croak, and so does a hint on a field left without a type. type_options => {$type => {format => \&code, generate => $mode}} Field hints for every field of a type. # a DateTime the ORM deflates, on any field, is written without # fractional seconds my $orm = DBIx::QuickORM->new( credentials => \%credentials, type_options => { DateTime => { format => sub { my ($text) = @_; return $text =~ s/\.\d+//r; }, }, }, ); A field's own hints in types win, each hint separately. fks => {table => {other_table => [{field => other_field}, ...]}} Foreign keys to add to the scanned ones. # CREATE TABLE audit (id SERIAL PRIMARY KEY, user_id INTEGER, action TEXT) # -- audit.user_id holds a users.id, but declares no key my $orm = DBIx::QuickORM->new( credentials => \%credentials, fks => {audit => {users => [{user_id => 'id'}]}}, ); my $entry = $orm->insert( audit => { user_id => $id, action => 'login', }, ); my $who = $orm->follow_fk(audit => $entry, 'users')->only; A key identical to one the table already has is ignored. A key over the same fields that maps them differently croaks. elective => \@tables Tables the database may lack. # only some installs have legacy_log my $orm = DBIx::QuickORM->new( credentials => \%credentials, elective => ['legacy_log'], omit => {legacy_log => ['payload']}, ); my $has_log = $orm->db_map->table('legacy_log') ? 1 : 0; When one is absent, the per-table arguments naming it (types, omit, default_fields, pks, row_classes, and fks, as the table or as a target) are dropped instead of croaking, and a handle on it croaks, saying it is elective and absent. A table present behaves like any other. pks => {view => \@fields, table => \@fields} Declares the primary key of a view, which the database cannot report, or of a table the database reports none for (a legacy or staging table, or one keyed by a UNIQUE NOT NULL column). # CREATE VIEW user_names AS SELECT id, name FROM users my $orm = DBIx::QuickORM->new( credentials => \%credentials, pks => {user_names => ['id']}, ); my $named = $orm->find(user_names => $id); Its rows then go through the row cache, and find and the row writes work on it (for a view, the database decides whether a write through it succeeds). Naming a table that has a primary key, or a field the table or view lacks, croaks. The database need not enforce the declared key: the ORM trusts it. If two rows share a key, update_row and delete_row change both, and the row cache takes them for one row. The row cache clears rows by table name, so a write to a view's base table does not clear rows read through the view. A view row can stay canonical after the database changed it, so refresh view rows that must be current. omit => {table => \@fields} default_fields => {table => \@fields} Set which fields a table's queries select by default (the table's default_fields). my $orm = DBIx::QuickORM->new( credentials => \%credentials, omit => {users => ['prefs']}, # every users field but prefs default_fields => {posts => ['title']}, # id and title ); omit selects every field but the ones listed. default_fields selects the ones listed plus the primary key. A table named in neither selects every field, unless a given db_map sets its default fields. Croaks when both name the same table, when omit names a primary key field, or when no field is left. auto_omit => {types => \@types, db_types => \@db_types} Leaves fields of these types out of default selects, on every table omit and default_fields do not name. Nothing is left out unless asked. # CREATE TABLE files (id SERIAL PRIMARY KEY, name TEXT, payload BYTEA) my $orm = DBIx::QuickORM->new( credentials => \%credentials, auto_omit => { types => ['JSON'], # users.prefs db_types => ['bytea'], # files.payload }, ); my $user = $orm->find(users => $id); # selects every field but prefs # reading a field left out fetches it from the database my $prefs = $user->field('prefs'); types names ORM types as types does (JSON, +My::Type), matching a field whose orm_type is that class or a subclass. Each is loaded, and one that cannot be croaks. db_types names database types, matched against the field's base type (type in DBIx::QuickORM::Map): lowercased, without sizes or array markers, so bytea also matches bytea[]. Give each name as the map reports it, which is not always the short name. PostgreSQL reports timestamp without time zone, character varying, and double precision, so timestamp or varchar matches nothing there. A field left out is fetched the first time a row reads it (see "FIELDS LEFT OUT OF A SELECT" in DBIx::QuickORM::Manual::Caching). Primary, unique, and foreign key fields are never left out, and neither is any field of a table without a primary key, which a row could not fetch later. A given db_map keeps the default fields it carries, including ones an earlier auto_omit set. Name a table in omit or default_fields to change it. In a table class, a bare omit; selects every field again. row_classes => {table => $class_or_undef} The row class for one table's rows. Undef means hashrefs. my $orm = DBIx::QuickORM->new( credentials => \%credentials, row_classes => { users => 'My::App::User', # loaded from My/App/User.pm posts => undef, # plain hashrefs }, ); Every row class named anywhere is loaded unless it already has a new method. One that cannot be loaded croaks. row_namespace => $namespace Gives each table a row class under $namespace, named from the table: user_posts gets ${namespace}::UserPosts. # users rows are My::App::Row::Users, where that module exists my $orm = DBIx::QuickORM->new( credentials => \%credentials, row_namespace => 'My::App::Row', ); A table with an entry in row_classes (or in a given db_map) keeps it. A table whose class is not loaded and has no module keeps the default row class. A module that fails to load croaks with its error. A class found this way must do DBIx::QuickORM::Role::Row. One that does not croaks, naming the table and the class. A table name that gives no valid class name (it must start with a letter or _ and hold only word characters) warns and keeps the default row class. row_class_name => sub { my ($table) = @_; return $name } Replaces how row_namespace names a table's class. It gets the table name and returns the part after the namespace, such as 'Person' for people. # users gets My::App::Row::User, posts My::App::Row::Post, where each exists my $orm = DBIx::QuickORM->new( credentials => \%credentials, row_namespace => 'My::App::Row', row_class_name => sub { my ($table) = @_; return ucfirst($table =~ s/s\z//r); }, ); Returning undef keeps the default row class for that table, without a warning. Returning an invalid name (one holding ::, say) warns and keeps the default. row_class, sql_builder, where_builders, and like_aggregates are described under "ATTRIBUTES". lookup, retain_cache, enforce_canon, debug, isolation, time_zone (or tz), and datetime_parsers are described under "Settings". A setting of the wrong type croaks. A subclass constructor can pass caller => [caller] so errors from new name its own caller's line. It is not kept on the object. Settings $conn = $orm->connection The current DBIx::QuickORM::Connection. In a forked child, the ORM drops the inherited handle without closing the parent's session. It then opens a new Connection from the connector, keeping the map and settings. That croaks when the ORM was given a dbh, and when a second connection cannot reach the same data (an in-memory SQLite database, or DuckDB). $map = $orm->db_map The current Connection's DBIx::QuickORM::Map: the one built when the ORM was constructed, plus the Connection's temporary tables and views. $class = $orm->lookup_class The lookup table class, from the lookup argument to new: DBIx::QuickORM::LookupTable::Identity unless given. A bare name gets the DBIx::QuickORM::LookupTable:: prefix, and a leading + marks a fully qualified class. DBIx::QuickORM::LookupTable lists the classes that ship and what each protects. my $orm = DBIx::QuickORM->new(credentials => \%credentials, lookup => 'Identity'); $bool = $orm->retain_cache Whether canonical copies stay in the row cache outside a transaction. Default 0. With 0 they are held weakly and freed once nothing else uses them. With 1 they stay until clear_cache. Croaks at construction when true and the lookup table does not cache. $bool = $orm->enforce_canon Whether update_row and delete_row refuse row data that is not canonical. Default 1. Outside a transaction, they croak when given row data that is not the canonical copy. Inside one, the check is on by default whatever this says. Each call can override it. $orm->set_enforce_canon($bool) Change enforce_canon on the current Connection, for every write after the call. $debug = $orm->debug The DBIx::QuickORM::Debug that records which call made row data stop being canonical, for canon_status and the non-canonical croak, or undef. Off by default. Pass debug => 1 to new to turn it on. my $orm = DBIx::QuickORM->new(credentials => \%credentials, debug => 1); It adds about 1 to 5 µs to each single-row write and about 1 µs to each find, and nothing per row to a fetch of many rows unless a row it reads replaces a copy already held: 3% to 12% on a loop of small writes, and about 1% of a web request's query time. "WHY A ROW IS NOT CANONICAL" in DBIx::QuickORM::Manual::Caching says what it records, and gives the numbers. $level = $orm->isolation The default isolation level for outermost transactions. Undef means 'read committed'. Takes the levels txn takes (see txn under "Transactions"). $tz = $orm->time_zone The session time zone, UTC unless given. MySQL and MariaDB get UTC as +00:00. SQLite has no session time zone. new also accepts it as tz. Giving both croaks. \@parsers = $orm->datetime_parsers Parsers for date and time text that neither the database's own parser nor DateTime::Format::ISO8601 reads, tried in order. Empty unless given. use DateTime::Format::Strptime; my $orm = DBIx::QuickORM->new( credentials => { dsn => $dsn, user => $user, pass => $pass, }, datetime_parsers => [ DateTime::Format::Strptime->new(pattern => '%d/%m/%Y %H:%M'), # epoch seconds sub { $_[0] =~ m/^\d+\z/ ? DateTime->from_epoch(epoch => $_[0]) : undef }, ], ); Each is a class or object with parse_datetime, or a code reference taking the text. new loads each class, and croaks when one cannot be loaded or has no parse_datetime. A parser says no by returning undef or dying. The first DateTime returned wins. Returning anything else croaks. $orm->set_datetime_parsers(\@parsers) Replace datetime_parsers on the current Connection, checked as new checks it, for values read after the call. A DateTime field read before the call keeps the parsers it was read with, even while still unparsed. Only enforce_canon and datetime_parsers have setters. The other settings are fixed when the ORM is built. Build a new ORM to change them. A forked child's new Connection keeps the changed values. The row cache With the default lookup table, the ORM caches one canonical copy of each row's data, by primary key. A row is canonical when its data is that copy. That does not mean it matches the database right now. Other lookup tables decide what is canonical differently (see lookup_class). $bool = $orm->is_canon($table, $row_or_data) True when the row data (or a row object's row_data) is canonical: with the default lookup table, the copy the row cache holds for its primary key. my $user = $orm->find(users => $id); my $obj = $orm->is_canon(users => $user); # a row object: true my $data = $orm->is_canon(users => $user->row_data); # its row data: true # a hashref the row cache never saw: false my ($bare) = $orm->handle('users') ->where({id => $id}) ->bare ->all; my $other = $orm->is_canon(users => $bare); With the default, false when it is not that copy, when the row cache has no copy for that key, and for row data that is deleted or not in the database (a new row from vivify, say), key or no key. Otherwise croaks when the primary key cannot be determined. The lookup table decides, so the others behave differently: "is_canon" in DBIx::QuickORM::LookupTable::Identity The default, described above. "canon_status" in DBIx::QuickORM::LookupTable::Scoped No row cache: every copy is canonical, except across a transaction boundary, or once deleted or not in the database. "DESCRIPTION" in DBIx::QuickORM::LookupTable::Unchecked All row data is canonical. $status = $orm->canon_status($table, $row_or_data) Why the row data (or a row object's row_data) is not canonical: undef while it is, otherwise a hashref with its cause. A row's own canon_status calls this. The lookup table gives the cause: "canon_status" in DBIx::QuickORM::LookupTable::Identity (the default), "canon_status" in DBIx::QuickORM::LookupTable::Scoped, or "DESCRIPTION" in DBIx::QuickORM::LookupTable::Unchecked (always undef). The causes the shipped lookup tables give: replaced Another copy took its place: a read of changed data or of fewer fields, a write, or a primary key change. cache_cleared Its copy was cleared on its own (clear_cache($table => $pk)). txn It was read before the open transaction began. deleted The row was deleted, or found gone. not_in_db The row is not in the database: built by vivify, or its insert was rolled back. not_cached The row cache holds no copy of it: it was read around the cache (no_cache, bare), its transaction rolled back, or its table or the whole cache was cleared. rolled_back With lookup => 'Scoped': it was read or written in a transaction that rolled back. by is the call behind a replaced, cache_cleared, or deleted, and last_clear the call that last cleared the table or the whole cache for a not_cached, each when known, as a caller frame: package, file, line, and the public method called. When a public method calls another, the outer one is recorded. They are recorded only with debug => 1 (see debug). Without debug the cause is what can be worked out when asked: row data whose key another hash holds is replaced (a copy that was never canonical looks the same), and a cleared key is not_cached. # with debug => 1 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', by => ['main', 'app.pl', 3, 'DBIx::QuickORM::Handle::only']} Writing non-canonical row data croaks naming the same cause and call. A row object that is deleted or not in the database is refused earlier by the row method, with its own error. A deleted or not_in_db row needs no primary key here. Any other croaks as is_canon does when the key cannot be determined. $orm->clear_cache $orm->clear_cache($table) $orm->clear_cache($table => $pk) Forgets canonical copies: all of them, one table's, or one row's. They are read from the database again when next looked up. my $user = $orm->find(users => $id); my $held = $orm->is_canon(users => $user); # true: $user's data is the canonical copy $orm->clear_cache(users => $id); # or clear_cache('users'), or clear_cache() my $still = $orm->is_canon(users => $user); # false $user->refresh; # canonical again $pk takes the forms find takes (see DBIx::QuickORM::Handle), and its values are deflated (turned into database form) the same way. A typed key matches in any form: a DateTime or the database's text, a UUID in upper case or as 16 bytes. Inside a transaction, it clears the current transaction or savepoint level, and the cache from before the outermost transaction. A savepoint rollback restores what the enclosing level held. "Transactions" says what ending the outermost transaction does. A handle that already ran keeps its rows. Call its clear to query again. CRUD operations # a row object my $ann = $orm->insert( users => { name => 'Ann', prefs => {theme => 'dark'}, }, ); # row data: a hashref my $ben = $orm->insert( users => {name => 'Ben'}, data => 1, ); $orm->insert(users => {name => 'Cy'}); # void: nothing read back # compare-and-swap on any hashref, a bare one included: undef if the name # changed since it was read my ($cy) = $orm->handle('users')->where({name => 'Cy'})->bare->all; my $renamed = $orm->cas_update(users => $cy, {name => 'Cyrus'}); # an arrayref of rows, or with count => 1, how many went in my $rows = $orm->insert_many(users => [{name => 'Di'}, {name => 'Ed'}]); my $n = $orm->insert_many( users => [{name => 'Flo'}], count => 1, ); $orm->update_row(users => $ann, {name => 'Anne'}); # updates the row object given my $fresh = $orm->update_row( users => $ben, {email => 'ben@example.com'}, cas => ['email'], ); my $again = $orm->refresh_row(users => {id => $ben->{id}}); # a row object, from the cache my $gone = $orm->delete_row(users => $fresh); # 1 # rows have the same operations as methods $ann->update({email => 'ann@example.com'}); # $orm->update_row(users => $ann, {...}) $ann->refresh; # $orm->refresh_row(users => $ann, cache => 0) $ann->delete; # $orm->delete_row(users => $ann) The CRUD operations work on row data: plain hashrefs where a missing key means the field was not fetched and an undef value means NULL. Wherever row data is expected, a row object works too, and its row_data is used. A row object given to update_row or refresh_row must also have set_row_data, which takes the new row data. One without it, or an aggregate row, croaks before anything is sent. Each CRUD operation croaks on an argument it does not know. The CRUD operations that return rows (insert, insert_many, update_row, and refresh_row) share one rule. find, find_or_insert, insert_fk, and insert_many_fk follow it too, and vivify takes row_class: * In void context they do the work and return nothing. * Given a row object, update_row and refresh_row return that same object, now holding the new row data (it takes the new data in void context too). * data => 1 returns the row data instead of a row. A given row object still takes the new data. A handle's data_only does the same for the rows it returns. * row_class => $class builds the rows with that class for this call, loading it when needed. row_class => undef returns the row data. With data => 1 too, data wins. A given row object still takes the new data. A handle passes its own row_class this way. * Otherwise they return a new row object. The class is the table's row_class in the map when set (even to undef), else the ORM's row_class. When that class is undef (as with row_class => undef to new), they return the row data. * insert_many returns an arrayref of these, never a list. * When no row matched, update_row and refresh_row return undef. A row object given keeps its row data, but a refresh_row that finds no row marks it deleted (see was_deleted in DBIx::QuickORM::Role::Row). For row class authors: the object is built with $class->new(row_data => \%data, orm => $orm, table => $table), or blessed from those directly when the class's fast_bless is true. Writes replace the canonical copy for that primary key. A read keeps the canonical copy when every fetched value matches it and it fetched every field the copy holds, adding any new fields. Otherwise the read replaces it, and row objects holding the old copy are no longer canonical ("FIELDS LEFT OUT OF A SELECT" in DBIx::QuickORM::Manual::Caching). A row written through RETURNING comes back with the table's default fields, the fields written, and for an update the fields the row held. Without RETURNING (MySQL always, MariaDB for updates) it holds only the primary key. Values sent are never copied into the returned row data (except with insert's as_given): defaults, triggers, and generated columns can change them. Every CRUD operation takes raw. Without it, every value sent (inserted values, changes, compare-and-swap values, and primary key values) is deflated, turned from a Perl value into database form, by its field's type: * A reference on a typed field is deflated. * A reference on a field without a type croaks. * A plain value on a typed field is deflated when the type's is_inflated says it is inflated. A plain value can be ambiguous (is 123 JSON, or already encoded?). Wrap it in raw() or inflated() to say which. * Anything else is sent as given. raw => 1 says every value is already in database form and skips deflation. It is also how to send a reference to a field without a type (a PostgreSQL array, say). raw covers only the values you gave. Values the ORM generates, such as a primary key from its type, are deflated as above whatever raw says. To mark one value instead of all, wrap it in a marker from DBIx::QuickORM::Value. A marker overrides both the default and raw: use DBIx::QuickORM::Value qw/raw inflated sql/; my $dee = $orm->insert( users => { name => 'Dee', prefs => raw('{"theme":"dark"}'), # already JSON text: sent as is created => sql('now()'), # literal SQL }, ); # raw => 1 for every value, but deflate this one my $eli = $orm->insert( users => { name => 'Eli', prefs => inflated({theme => 'light'}), }, raw => 1, ); raw() sends one value as given, and inflated() deflates one even under raw => 1. binary() binds bytes, and sql() is literal SQL. DBIx::QuickORM::Manual::Values covers each marker, deflation, and inflation on read. The single-row CRUD operations reuse prepared statements (DBI's prepare_cached). Behind a pooler in transaction mode, such as PgBouncer, turn off server-side prepares (DBD::Pg's pg_server_prepare). $row = $orm->insert($table => \%fields, raw => $bool) \%data = $orm->insert($table => \%fields, data => 1, raw => $bool) $row = $orm->insert($table => \%fields, as_given => 1, raw => $bool) Inserts one row and returns it. At least one field is required. The new primary key comes from RETURNING, from the given values, or from the database's last insert id for a single-field key. A typed primary key field left out can get its value from its type (a version 7 UUID for a UUID field). The ORM skips this when the database fills the column and can return it with RETURNING. On MySQL it always generates. The field's generate hint changes this (see "Field hints" in DBIx::QuickORM::Role::Type). A field passed as undef is sent as NULL and is not generated. Generated values are sent like your own, and as_given includes them. insert_many generates them the same way for each row. In void context it only inserts. It sends no RETURNING, caches no canonical copy, builds no row, and skips the checks below. Without RETURNING (MySQL), unless in void context: * A table without a primary key croaks. * A compound key not given in full croaks before anything is sent. * A single-field key not given (or given as sql()) is read from the last insert id after the insert. When the database generated none (a key that is not auto-increment gives 0), the insert croaks with the row already in the table. as_given => 1 returns a copy of the fields as sent, in database form, plus the new primary key, instead of reading the row back. Fields sent as sql() are left out. # the fields as sent, plus the new id: no read back my $hal = $orm->insert( users => {name => 'Hal'}, as_given => 1, ); # created was not sent, so reading it fetches it from the database my $created = $hal->field('created'); The copy is not canonical, so update and delete on it croak while enforce_canon is on. Refresh it first. A row object fetches a field the copy lacks when it is read. On a table without a primary key it returns the copy even without RETURNING, but nothing can be written or fetched through it. \@rows = $orm->insert_many($table => \@rows, raw => $bool) \@data = $orm->insert_many($table => \@rows, data => 1, raw => $bool) $count = $orm->insert_many($table => \@rows, count => 1, raw => $bool) Inserts many rows and returns an arrayref of the new rows. Every row must have the same fields, at least one. # an arrayref of row objects my $rows = $orm->insert_many( users => [ {name => 'Ola'}, {name => 'Pia'}, ], ); # an arrayref of row data (hashrefs) my $data = $orm->insert_many( users => [{name => 'Quin'}], data => 1, ); # how many went in: 2, nothing read back my $count = $orm->insert_many( users => [ {name => 'Rae'}, {name => 'Sol'}, ], count => 1, ); # raw => 1: every value is sent as given, so prefs must be JSON text my $raw = $orm->insert_many( users => [ { name => 'Tam', prefs => '{"theme":"dark"}', }, ], raw => 1, ); # void context: inserts, reads nothing back $orm->insert_many(users => [{name => 'Uma'}]); On a table with a primary key, the new rows become canonical. Copies already in the row cache stay. count => 1 returns how many rows were inserted instead. It works on every database, never reads rows back, and cannot be combined with data => 1. In void context it only inserts: nothing is read back or made canonical. An empty \@rows sends nothing and returns an empty arrayref (0 with count). The rows go in multi-row INSERT statements, each holding as many rows as the database's bind limit allows. When it takes more than one statement, they run in one transaction, so either every row is inserted or none is. Inside an open transaction it always takes a savepoint, even for one statement: a failure rolls back only these rows and leaves the open transaction usable. On DuckDB, which has no savepoints, the open transaction is used as it is. The returned rows come in the order the database gives them, with the table's default fields. Without RETURNING (MySQL) each row holds only its primary key, so every row must carry its whole primary key. A row without it, or a table without a primary key, croaks before anything is sent. Use count or void context. $row = $orm->update_row($table, $row_or_data, \%changes, %opts) \%data = $orm->update_row($table, $row_or_data, \%changes, data => 1, %opts) Updates the row with the row data's primary key and returns it, or undef when no row matched. At least one change is required. A row object given follows the rule in "CRUD operations". Options: enforce_canon => $bool When true, croaks unless the row data is canonical (see is_canon). Undef or absent means true inside a transaction, otherwise the ORM's enforce_canon. 0 skips that check, but cas and auto_cas still apply. It also skips the row state checks: a row not in the database (vivified, or deleted) is still updated by its key, where the row's own update croaks. Not recommended. cas => \@fields Compare-and-swap: update only while these fields still hold the row data's values (undef matches NULL). Otherwise return undef and change nothing. Each field must be in the row data, or it croaks. It compares with =, so it does not suit floats, PostgreSQL json, or MySQL JSON. auto_cas => $bool Compare-and-swap on every field present in both the row data and the changes. my $user = $orm->find(users => $id); # holds email, a default field # writes only while email still holds what $user read, else undef my $done = $orm->update_row( users => $user, {email => 'new@example.com'}, auto_cas => 1, ); \%data = $orm->cas_update($table, \%data, \%changes) $row = $orm->cas_update($table, $row, \%changes, cas => \@fields) update_row as a compare-and-swap: writes the changes only while the database still holds the row data's values for the changed fields (or the cas fields), and returns undef otherwise, changing nothing. # a row object: set the email only while the name is still what it read my $user = $orm->find(users => $id); my $same = $orm->cas_update( users => $user, {email => 'robert@example.com'}, cas => ['name'], ); The row data need not be canonical, so it takes any hashref holding the primary key and the compared fields, a bare one included, and returns the new row data, or a row of row_class when that option is given. Given a row object it returns that object, holding the new data ("CRUD operations"). A row's own cas_update calls this. The row data's values, its primary key included, are used as the database returned them, as a fetch gives them, not deflated as update_row deflates them. A hand-built hashref must hold stored values, or wrap an inflated one in inflated() (DBIx::QuickORM::Value). The changes are deflated as for update_row, unless raw is true. It croaks on any option but cas, raw, and row_class, on an empty cas list (an unconditional write), on row data not in the database (vivified, or deleted), and when the row data lacks a field it compares. Inside a transaction, the returned row data keeps the row's inserted-in-this-transaction mark when the given hashref or the row's cached copy carries it. When neither does (say a hashref fetched again with bare after clear_cache), it cannot. If a rollback then undoes the insert, it may still report being in the database. Find the row again before relying on it. $count = $orm->delete_row($table, $row_or_data, enforce_canon => $bool, raw => $bool) Deletes the row with the row data's primary key and returns how many rows were deleted (0 or 1). The ORM stops holding it and marks the row data deleted (see was_deleted in DBIx::QuickORM::Role::Row). A delete that matches no row also marks it deleted (it is not in the database) and returns 0. enforce_canon is as for update_row, including what 0 bypasses. $row = $orm->refresh_row($table, $row_or_data, cache => $bool, db => $bool, fields => \@fields, raw => $bool) \%data = $orm->refresh_row($table, $row_or_data, data => 1, %opts) The canonical row for a primary key, or undef when there is none. It takes row data, a row, or a primary key in any form (a value, an arrayref, or a hashref). # always a query my $fresh = $orm->refresh_row( users => $id, cache => 0, ); # never a query: the canonical copy, or undef my $cached = $orm->refresh_row( users => $id, db => 0, ); # a query for the key and name only my $named = $orm->refresh_row( users => $id, fields => ['name'], cache => 0, ); # a row object takes the new data, and data => 1 returns it as a hashref my $data = $orm->refresh_row( users => $user, data => 1, cache => 0, ); A row object given follows the rule in "CRUD operations". It reads fields plus the primary key, or the table's default fields plus the fields the given row data holds. By default it returns the canonical copy when that has every field asked for, and reads the database otherwise. cache => 0 always reads the database. db => 0 only looks in the cache, returning the canonical copy as it is, or undef. Both 0 croaks. Finding by primary key my $user = $orm->find(users => $id); my $data = $orm->find(users => $id, data => 1); # row data my $none = $orm->find(users => -1); # undef Reads one row by primary key, like refresh_row. It never writes to the database. $row = $orm->find($table, $pk, %opts) \%data = $orm->find($table, $pk, data => 1, %opts) The row with primary key $pk, or undef. $pk takes any key form (see find in DBIx::QuickORM::Handle). The options are refresh_row's. A row object passed in gives its key. It may also show the state the read found, such as new values or that the row is gone. Finding or inserting my $gil = $orm->find_or_insert( users => { name => 'Gil', email => 'gil@example.com', }, by => ['email'], ); my $same = $orm->find_or_insert( users => {email => 'gil@example.com'}, by => ['email'], ); $row = $orm->find_or_insert($table => \%fields, by => \@fields, raw => $bool) \%data = $orm->find_or_insert($table => \%fields, data => 1, %opts) Returns the row whose by fields hold the given values, inserting it from \%fields when there is none. It follows the CRUD operations' return rule. # no by: matched by the primary key. The row exists, so it is returned # as it is: name is neither compared nor written. my $robert = $orm->find_or_insert( users => { id => $id, name => 'Someone', }, ); # by email: only email is matched. The other fields are used only when # inserting, so Gil keeps the name Gil. my $gil = $orm->find_or_insert( users => { email => 'gil@example.com', name => 'Someone', }, by => ['email'], ); # without raw, values are deflated: prefs goes in as JSON text, and the # DateTime is matched and inserted as the database's text my $when = DateTime->new( year => 2025, month => 3, day => 4, hour => 5, ); my $kit = $orm->find_or_insert( users => { name => 'Kit', created => $when, prefs => {theme => 'dark'}, }, by => ['name', 'created'], ); # raw => 1: every value, by values included, is sent as given, so each # must already be database text. This finds Kit. my $same = $orm->find_or_insert( users => { name => 'Kit', created => '2025-03-04 05:00:00', prefs => '{"theme":"dark"}', }, by => ['name', 'created'], raw => 1, ); by defaults to the primary key. A table without one needs by. Every by field must be in \%fields. Croaks when more than one row matches, or for a field the table does not have, whether or not the row exists. An undef by value croaks: NULL does not identify a row, since a unique key allows many. The insert runs in a savepoint, or in a transaction when none is open, so a failed insert leaves an open transaction usable. When the insert fails (say another process inserted the row first), it looks the row up again and returns it. If it still finds none, it rethrows the insert's error. This recovery needs a unique key on the by fields. Without one, two racing calls can both insert. Recovery works at the default 'read committed'. Inside a transaction at 'repeatable read' or 'serializable' (when chosen, or the MySQL family's server default under 'server'), the second lookup reads the transaction's snapshot. A row another session committed after this transaction started stays invisible, so the insert's error is rethrown. raw => 1 also covers the by values used to look the row up. They must then be in exact database form, or the lookup misses and the insert fails on a duplicate key. On DuckDB, which has no savepoints, an insert inside an open transaction runs without one, and a failed insert leaves that transaction unusable. A table handle has it too: $h->find_or_insert(\%fields, %opts) (see DBIx::QuickORM::Handle). Rows not in the database A row can exist in memory before it is inserted. Change it with modify, then write it with its insert. $row = $orm->vivify($table => \%fields) $row = $orm->vivify($table => \%fields, row_class => $class_or_undef) A new row that is not in the database yet. Nothing is written until you call its insert. Until then, modify changes it (see DBIx::QuickORM::Role::Row). my $ivy = $orm->vivify(users => {name => 'Ivy'}); $ivy->modify({email => 'ivy@example.com'}); # still nothing written $ivy->insert; # now in the database # the row data, not a row object my $data = $orm->vivify( users => {name => 'Jo'}, row_class => undef, ); The fields are checked and deflated as insert does, into a new hashref. An empty hashref is fine. Fill it in with modify. The row is built as the CRUD operations build rows, so with no row class it is the row data. row_class picks the class for this row, as for the CRUD operations. Following foreign keys my $post = $orm->insert( posts => { user_id => $id, title => 'Hi', }, ); my $author = $orm->follow_fk(posts => $post, 'users')->only; my @posts = $orm->follow_fk(users => $author, 'posts')->order_by('id')->all; # the same, as a row method: no table needed my $writer = $post->follow_fk('users')->only; $h = $orm->follow_fk($table, $row_or_data, $other_table, link => \%link) $h = $orm->follow_fk($table, $row_or_data, $other_table, via => \%via) A table handle (DBIx::QuickORM::Handle) on $other_table for the rows linked to this row by a foreign key: the row it points to, or the rows that point to it. # users.referred_by points at users.id: link gives the direction # the user $ann points to: who referred her my $referrer = $orm->follow_fk( users => $ann, 'users', link => {referred_by => 'id'}, )->only; # the users pointing to $ann: whom she referred my @referred = $orm->follow_fk( users => $ann, 'users', link => {id => 'referred_by'}, )->all; # audit.user_id declares no key: via gives the mapping my $who = $orm->follow_fk( audit => $entry, 'users', via => {user_id => 'id'}, )->only; The handle's where holds the linked fields' values from the row, qualified as other_table.field, so the handle can be joined to other tables. Narrow the handle with and, since where would replace the link. link is {our_field => their_field, ...}, as foreign keys are written in the map, and gives the direction. On a self-referencing employees table, {manager_id => 'id'} follows to an employee's manager and {id => 'manager_id'} to their reports. It must match a foreign key of $table to $other_table, or one of $other_table to $table reversed. Without it there must be exactly one such key. via takes the same mapping for a key the map does not know, such as one the database never declared: via => {editor_id => 'id'}. No foreign key need exist, but both tables must be in the map and every field it names must exist. To declare the key for every call instead, give fks to new. Croaks on a link that matches no key, on more than one key without a link, on a key to a table not in the map, on a via field that does not exist, and when given both link and via. The handle expects one row (single, see DBIx::QuickORM::Iterator) when the fields it looks up are the other table's primary key or a unique key. Otherwise it expects many (multi), whatever the data. Linked fields missing from the row data are fetched first, with one refresh_row. It croaks if the row is gone. A NULL linked value refers to nothing, so the handle matches no rows. Inserting linked rows my $post = $orm->insert_fk(users => $alice, 'posts', {title => 'One'}); my $posts = $orm->insert_many_fk(users => $alice, 'posts', {title => 'A'}, {title => 'B'}); # the same, as row methods my $draft = $alice->insert_fk('posts', {title => 'Draft'}); Inserts rows into $other_table that point at this row, filling their foreign key fields from it. Only that direction: a key of $table to $other_table cannot be followed this way, since the new row would have to be written back into this one. $row = $orm->insert_fk($table, $row_or_data, $other_table, %opts, \%fields) \@rows = $orm->insert_many_fk($table, $row_or_data, $other_table, %opts, @fields) insert_fk inserts exactly one row and returns it, as insert does. insert_many_fk inserts any number, as insert_many does: an arrayref of rows, the count with count => 1, nothing in void context. After $other_table, a string is an option name taking the next argument as its value, and every other hashref is a row's fields: $alice->insert_fk('posts', link => {id => 'user_id'}, {title => 'Linked'}); link chooses the key when more than one of $other_table points at $table, written {our_field => their_field} as follow_fk takes it. via gives a mapping with no key behind it, as for follow_fk. The new rows' right-hand fields are filled from this row's left-hand fields. The other options are those of insert (raw, data, as_given, row_class) or insert_many (raw, data, count, row_class). Croaks, before anything is inserted, when the fields set a link field, when the row's linked value is NULL, when the row is not in the database, and on a link that points from $table. A linked field missing from the row data is fetched first, with one refresh_row. The linked values are sent as they are in the row data, so a hashref must hold them in database form, as row data does. Handles my @bobs = $orm->handle('users') ->where({name => 'Bob'}) ->order_by('id') ->all; my @rows = $orm->handle(\['SELECT id, name FROM users WHERE id > ?', 10])->all; DBIx::QuickORM::Handle covers everything a handle does. $h = $orm->handle($table) $h = $orm->handle(\$sql) $h = $orm->handle(\[$sql, @binds]) $h = $orm->handle($source) A DBIx::QuickORM::Handle over a table, an SQL query, or a source object (DBIx::QuickORM::Role::Source). # SQL with no binds my @all = $orm->handle(\'SELECT id, name FROM users')->all; # a source object, such as a temporary table my $temp = $orm->temp_table($orm->handle('posts')); my @copy = $orm->handle($temp)->all; An SQL query runs as written, and its binds are not deflated. Its rows belong to no table: they are never canonical and cannot be written through the ORM. Transactions DBIx::QuickORM::Txn shows the block and object forms. Nesting gives savepoints. isolation sets the level and retry replays a block: $orm->txn(sub { $orm->insert(users => {name => 'Outer'}); eval { $orm->txn(sub { $orm->insert(users => {name => 'Inner'}); die "undo only the inner work\n"; }); }; }); # Outer is committed, Inner was rolled back with its savepoint my $count = $orm->txn( sub { $orm->handle('users')->count }, # the block's return value isolation => 'serializable', retry => 3, ); $txn = $orm->txn $txn = $orm->txn(isolation => $level) @result = $orm->txn(sub { my $txn = shift; ... }) @result = $orm->txn(sub { ... }, retry => $n, isolation => $level) Opens a transaction, or a savepoint inside the open one, as a DBIx::QuickORM::Txn. Given a block, runs it with the transaction and returns what the block returns. # the object form: finish it yourself my $txn = $orm->txn; $orm->insert(users => {name => 'Kim'}); $txn->commit; # or $txn->rollback # an outermost transaction at another level my $strict = $orm->txn(isolation => 'serializable'); my $count = $orm->handle('users')->count; $strict->commit; Without a block, commit or roll back through the returned object. Only the innermost open transaction can be committed or rolled back. One that goes out of scope unfinished is rolled back with a warning. With a block, a normal return commits, unless the block already committed or rolled back the transaction. An exception rolls back and is rethrown. retry => $n runs the block of an outermost transaction again, up to $n more times, while the exception is a database error whose retriable is true (a deadlock, a serialization failure, or a lock timeout). See DBIx::QuickORM::Exception::DB. The block must be safe to run again. retry croaks without a block, and on a nested transaction, which cannot be replayed alone. An outermost transaction opens at the ORM's isolation, or 'read committed' by default. It states that level when it opens, so a changed server or session default cannot alter it. 'server' is the exception: it sends a plain BEGIN and uses the database's own default. isolation => $level opens an outermost transaction at another level: 'read committed', 'repeatable read', 'serializable', 'read uncommitted', or 'server', in any case. Each retry begins at the same level. isolation croaks on a nested transaction and for any other value. The ORM's isolation setting takes the same levels, and new croaks for any other. It is undef unless given, and is stored in lower case. SQLite and DuckDB cannot set a level. There the default is 'server', and any other level croaks when the transaction opens. PostgreSQL runs 'read uncommitted' as 'read committed'. "ISOLATION" in DBIx::QuickORM::Manual::Transactions has the details. Savepoints need a database that has them, so nesting croaks on DuckDB. Inside a transaction, update_row and delete_row check that row data is canonical by default, whatever enforce_canon says. Canonical copies are held strongly. Inside a transaction, rows read before it are not canonical until read again. A rollback restores the row cache and row state from before. A commit keeps what the transaction read. After a rollback, refresh a row object you still hold. See DBIx::QuickORM::Manual::Transactions for the details. Temporary tables and views my $t = $orm->temp_table(sub { my $t = shift; $t->add_column( id => { db_type => 'integer', primary_key => 1, }, ); $t->add_column(name => {db_type => 'varchar(50)'}); }); $t->handle->insert({ id => 1, name => 'Alice', }); my $v = $orm->temp_view($orm->handle('posts')->where({views => 0})); my @names = $orm->temp_tables; $orm->temp($v->name)->drop; Temporary tables and views live in the current connection's map, beside the scanned tables, until dropped, until the transaction that created them rolls back, or until the connection ends. DBIx::QuickORM::Manual::TempTables has the rules on every database. $temp = $orm->temp_table(sub { my $builder = shift; ... }, name => $name) $builder = $orm->temp_table(name => $name) $temp = $orm->temp_table($handle, name => $name, pk => \@fields) $temp = $orm->temp_table(\[$select_sql, @binds], name => $name, pk => \@fields) $temp = $orm->temp_table(\$create_sql, name => $name) Creates a temporary table and returns its DBIx::QuickORM::Source::Table::Temp, or, with no block, handle, or SQL, returns a DBIx::QuickORM::SchemaBuilder::Table::Temp builder whose build creates it. Every option is optional except name with \$create_sql. # no block: a builder, built when you say my $builder = $orm->temp_table(name => 'staged'); $builder->add_column( id => { db_type => 'integer', primary_key => 1, }, ); my $staged = $builder->build; # from a query's rows my $busy = $orm->temp_table( $orm->handle('posts')->where({views => {'>' => 100}}), pk => ['id'], ); my $mine = $orm->temp_table( \['SELECT id, title FROM posts WHERE user_id = ?', $id], name => 'mine', pk => ['id'], ); # a whole CREATE statement my $scratch = $orm->temp_table( \'CREATE TEMPORARY TABLE scratch (k TEXT PRIMARY KEY, v TEXT)', name => 'scratch', ); * A block describes it through the builder, or the keywords of DBIx::QuickORM::DSL's :temp, and the table is built when the block returns. A block that returns a handle or \[$select_sql, @binds] fills the table from it, as the builder's fill does (croaking when fill got something else). * A handle, or a SELECT as \[$select_sql, @binds] (even with no binds), creates the table from the query's rows (CREATE TEMPORARY TABLE ... AS SELECT). The database picks the column types and copies no key. pk names the fields that identify a row, for the ORM only. From a handle, a row class it set (row_class, data_only, or bare) becomes the table's, and a background mode croaks (see sync in DBIx::QuickORM::Handle). * \$create_sql is a complete CREATE TEMPORARY TABLE statement, and name must be the name it creates. Without a name, one is made up: qorm_tmp_ with a counter and random hex. A given name croaks when it is already in the map, or was dropped in a transaction still open. $temp = $orm->temp_view(\$select_sql, name => $name, pk => \@fields) $temp = $orm->temp_view(\[$select_sql, @binds], name => $name, pk => \@fields) $temp = $orm->temp_view($handle, name => $name, pk => \@fields) Creates a temporary view over the SQL or the handle's query and returns its DBIx::QuickORM::Source::Table::Temp. my $popular = $orm->temp_view( \['SELECT id, title FROM posts WHERE views > ?', 100], name => 'popular', pk => ['id'], ); # no binds my $untitled = $orm->temp_view(\"SELECT id FROM posts WHERE title = ''"); name is made up when not given, and a handle's row class and background mode are treated as by temp_table. A view cannot hold placeholders, so every bind is written into the view as a literal: the view keeps the values it was created with. pk is optional, as in pks. Croaks on MySQL and MariaDB, which have no temporary views. @names = $orm->temp_tables The current connection's temporary tables and views, sorted. $temp = $orm->temp($name) A DBIx::QuickORM::Source::Table::Temp for one of them. Croaks for any other name. Loading classes $bool = DBIx::QuickORM->load_class($what, $class) $bool = DBIx::QuickORM->load_class($what, $class, $missing_ok) Loads a class from its module file and returns true. Croaks "$what could not be loaded" with the error when it cannot. # 1, or croaks "The JSON type could not be loaded: ..." my $ok = DBIx::QuickORM->load_class('The JSON type', 'DBIx::QuickORM::Type::JSON'); # 0 when the module is not installed my $have = DBIx::QuickORM->load_class('My plugin', 'My::Optional::Plugin', 1); With $missing_ok, a missing module file returns false instead. An error inside the file still croaks. $class = $orm->require_type($type) $class = $orm->require_type($type, $context) Returns the full class name for a type name (JSON, or +My::Type for a class outside DBIx::QuickORM::Type), loading it unless it already has deflate. my $json = $orm->require_type('JSON'); # 'DBIx::QuickORM::Type::JSON' # 'My::Type::Trimmed', or croaks "'my config' names the type ..." my $class = $orm->require_type('+My::Type::Trimmed', 'my config'); Croaks when it cannot be loaded. $context, when given, says in that error what asked for the type. $orm->load_row_class($class) Loads a row class unless it already has a new. Croaks when the name is not a valid package name or the class cannot be loaded. ATTRIBUTES Read-only accessors. Each returns the constructor argument of the same name, or its default. connector, sql_builder, and where_builders hold what new built from it. $class = $orm->row_class The default row class, DBIx::QuickORM::Row unless given. Undef means plain hashrefs. \%classes = $orm->row_classes $namespace = $orm->row_namespace $code = $orm->row_class_name \%omit = $orm->omit \%fields = $orm->default_fields \%types = $orm->types \%options = $orm->type_options \@types = $orm->autotype \@types = $orm->append_autotype \%auto_omit = $orm->auto_omit \%fks = $orm->fks The arguments as given to new, or undef. See new for what each does. db_map holds the result. autotype is undef unless given, even though a default list applies. $builder = $orm->sql_builder The SQL builder that handles use. Default: DBIx::QuickORM::SQLBuilder::SQLAbstract. new takes an object composing DBIx::QuickORM::Role::SQLBuilder, or the name of a class that does. A class is loaded unless it has new, then built with no arguments. Anything else croaks. my $orm = DBIx::QuickORM->new( credentials => \%credentials, sql_builder => 'My::SQLBuilder', # or My::SQLBuilder->new(...) ); \@builders = $orm->where_builders The where builders that render a handle's where. The first that can build it wins (see DBIx::QuickORM::Role::WhereBuilder). Default: DBIx::QuickORM::WhereBuilder::RawSQL, DBIx::QuickORM::WhereBuilder::Simple, then DBIx::QuickORM::WhereBuilder::SQLAbstract. new takes a non-empty arrayref of classes or objects composing the role. A class is loaded unless it has build_where. Anything else croaks. A handle can use its own list through its where_builders. # SQL::Abstract conditions only my $orm = DBIx::QuickORM->new( credentials => \%credentials, where_builders => ['DBIx::QuickORM::WhereBuilder::SQLAbstract'], ); $code = $orm->connector The code reference the ORM calls to open a database handle, built from the connection argument. \@names = $orm->like_aggregates Extra aggregate functions whose result keeps the field's type and foreign keys, like the built-in min and max. Undef unless given. A computed column [$func, $field] using one of them gets the field's type and foreign keys (see "Computed columns" in DBIx::QuickORM::Handle). Names are matched case-insensitively. my $orm = DBIx::QuickORM->new( credentials => \%credentials, like_aggregates => ['any_value'], # PostgreSQL 16 and later ); my ($group) = $orm->handle('users') ->group_by('name') ->fields({ name => 'name', joined => [any_value => 'created'], }) ->all; # a lazy DateTime (DBIx::QuickORM::Type::DateTime::Lazy), as created gives my $year = $group->field('joined')->datetime_ref->year; PRIVATE METHODS $out = $orm->_primitive($method, $table, $row_or_data, @args) Runs the Connection's CRUD operation and returns its result by the rule the CRUD operations share. In void context it returns nothing. Given a row object for update_row or refresh_row, it returns that row after set_row_data (which runs in void context too). With data => 1 it returns the row data. Otherwise it returns a new row built by _row, with the row_class option when given (see _row_class_opt). Handles pass their row_class that way, before the caller's options. An undef result is undef, and the row is left alone. An arrayref result (insert_many) comes back as an arrayref, of rows or of row data. A plain result (insert_many's count) comes back as it is. Croaks before running the CRUD operation when a row object given to update_row or refresh_row cannot take new data: it has no set_row_data, or it is an aggregate row. $out = $orm->_find_or_insert(\@frame, $table, \%fields, %opts) find_or_insert, reporting its errors at @frame, the public method's caller(0) frame, which its reads and insert also run under in the Debug object's caller slot. Handles pass their row_class as the option of that name, before the caller's options. $row = $orm->_row($table, \%data, %opts) The row data, or a row object over it when the table has a row class. Undef for undef. A row_class option, when present (even undef), replaces the table's class. Handles and the row_class CRUD option pass it this way. Built by _row_builder. $build = $orm->_row_builder($table, %opts) What turns row data into rows of the table, resolved once for a whole result set: a code reference taking the row data and returning the row object, or undef when rows are hashrefs (no row class). The row_class option is as for _row. Every place that builds table rows uses it. When the class's fast_bless is true the row is blessed directly, otherwise built with new. The ORM asks each class for fast_bless once and remembers the answer. @args = $orm->_row_class_opt(\%opts) Takes the row_class option out of a CRUD call's options and returns it as named arguments for _row and _row_builder: (row_class => $class) when present (undef for row data), or an empty list when absent. Loads a class that is not loaded yet. Croaks for a reference. $class = $orm->_row_class($table) The table's row class: its row_class in the map when set (even to undef), otherwise the ORM's, which is also the class for an undef table. $orm->_check_args Turns tz into time_zone, then croaks naming the first argument in %SHAPES whose shape is wrong. The Connection checks datetime_parsers. _croak_at(\@frame, $message) Dies with the message at the frame's file and line, worded as croak words it. @frame is a caller frame that a public method captured, so an error found deeper, reached through a handle or a row, reports the user's line. _rethrow_at(\@frame, $what, $error) Rethrows an error caught at a public entry, with the frame's file and line appended: (from $what at FILE line N). The error keeps its own location, so a bug report still shows where it was thrown. Exception objects are rethrown unchanged, and so is a message that already ends at the frame's line. Use it where one public call reaches many errors in other modules, such as new. _croak_at suits a chain with a few known errors. $h = $orm->_follow_fk(\@frame, $table, $row_or_data, $other_table, %params) follow_fk, reporting its errors at @frame: the caller(0) frame of the public follow_fk (the ORM's or a row's). When the row lacks link fields, the read of them runs under @frame in the Debug object's caller slot. $out = $orm->_insert_fk(\@frame, $method, $table, $row_or_data, $other_table, @args) insert_fk ($method insert) or insert_many_fk (insert_many), reporting its errors at @frame: the caller(0) frame of the public method (the ORM's or a row's), which its reads and inserts also run under in the Debug object's caller slot. \%link = $orm->_link_for(\@frame, $map, $table, $other, {link => \%link, via => \%via}, $insert_method) The link a call's link or via option gives: _via_link for via, otherwise _fk_link with link (undef when absent) and $insert_method. Croaks when both are given. \%link = $orm->_via_link(\@frame, $map, $table, $other, \%via) %via, {our_field => their_field}, as the link, with no foreign key behind it. Croaks unless both tables are in the map, %via is a non-empty hashref, and every field it names is a field of its table. \%link = $orm->_fk_link(\@frame, $map, $table, $other, \%given) \%link = $orm->_fk_link(\@frame, $map, $table, $other, \%given, $insert_method) The link to follow, {our_field => their_field}, from the foreign keys of $table to $other and those of $other to $table turned around: the one matching %given, or the only one when %given is undef. Croaks otherwise, and when $other is not in the map, reporting at @frame. With $insert_method (the calling method's name, for messages), only the keys of $other to $table count, and a %given matching a key of $table to $other croaks, naming the direction. $temp = $orm->_temp_table($from_handle, ...) $temp = $orm->_temp_view($from_handle, ...) temp_table and temp_view. A handle's own temp_table and temp_view call them with $from_handle true, so the DBIx::QuickORM::Source::Table::Temp says in its errors how to get a new one from that handle. %opts = $orm->_temp_opts($method, %opts) temp_table's and temp_view's options, checked: name (a non-empty string when given) and pk. ($source, $sql, \@binds, %spec) = $orm->_temp_select($method, $what, $binds_ok) The query a temporary table or view is made from: a handle's SELECT, or \[$sql, @binds] (or \$sql when $binds_ok is false, for a view). From a handle, %spec holds the row_class it set, if any, and a background mode croaks. $temp = $orm->_build_temp_table($builder) Creates the table a DBIx::QuickORM::SchemaBuilder::Table::Temp describes: resolves each column's db_type and type (an enum column is text with a check where the database has enum types, which would outlive the table), has the dialect write the SQL (with the INSERT ... SELECT of its fill, if any), and creates it through _create_temp. \@names = $orm->_fill_columns($handle, \%spec) The columns a handle's fill inserts into, by name, in the order its SELECT lists them: its fields as the source selects them (a table adds its primary key), or its computed fields in sorted order. Croaks for a join, for a handle whose columns have no names, and for a name the table does not have. $temp = $orm->_create_temp($name, $kind, \@create, \@drop, \%spec, $from_handle) Creates a temporary table or view through the Connection's create_temp, then adjusts the record the database reports, as new would a scanned one, but with only what concerns this table: autotyping, then the spec's types, row class, map-only foreign keys (references and foreign_keys), and a declared primary key (declare_pk, for a view or a table made from a query), then the key types and passthrough fields. Returns its DBIx::QuickORM::Source::Table::Temp, marked as made by a handle when $from_handle is true. $orm->_setup_temp($name, \%record, \%spec) The adjustments _create_temp describes, in place. $name = $orm->_temp_name A new temporary table or view name: qorm_tmp_, a counter that never repeats in the process, and random hex. $source = $orm->_table_source($table) The table's DBIx::QuickORM::Source::Table, built on first use and then kept: sources are immutable, so every handle over the table shares it. Croaks as the source's new does, keeping nothing. A temporary table or view gets a new DBIx::QuickORM::Source::Table::Temp each time, never kept, since its name can later belong to another one. \%fields = $orm->_table_fields($table) The table's field records from the map, kept after the first call. Rows read them on every field read, and this skips the walk through connection. The map does not change after the ORM is built. In a forked child it goes through connection first, so the child reconnects (or croaks) as before, whatever the parent read. \@fields = $orm->_with_held($table, \%data, @missing) The fields the row data holds, then @missing: what to read so that a read of missing fields holds everything the row already had, and so cannot replace its canonical copy with a narrower one. $h = $orm->_fk_handle($other, {$their_field => $value, ...}) A handle on the rows of $other whose fields hold these values, each field qualified as other.field in the where. An undef value refers to nothing: its condition is sql('IS NULL AND 1 = 0'), which is never true. The handle is single when the fields are exactly the primary key or a unique key of $other, otherwise multi. Croaks when $other is not in the map. $bool = $orm->_can_connect True unless the ORM was given a dbh: whether the connector can open another connection. _offline => {dialect => $dialect, db_map => $map, raw_tables => \%names} A private new argument from DBIx::QuickORM::ORM's offline: init connects through a DBIx::QuickORM::Connection::Offline with these instead of a database, and needs no connection argument. _build_schema => sub { my ($dbh) = @_; ... } A private new argument from DBIx::QuickORM::ORM's deploy: init calls it with the first handle before connecting on that handle, and the connection rescans. $code = $orm->_build_connector Turns the one connection argument into the connector, removing it from the object, and sets _can_connect. ($code, $can_connect) = $class->_connector_for(\%args) What _build_connector builds, from the connection form in %args, which it removes: the connector, and whether it can open more than one handle (not for a dbh). Croaks as new does for a missing, doubled, or malformed form. $debug = $orm->_build_debug A new DBIx::QuickORM::Debug, loaded only here, so an ORM without debug never loads it. $builder = $orm->_build_sql_builder The sql_builder argument as an object, the default when none was given. \@builders = $orm->_where_builders($what, \@builders) A copy of the list, each class loaded unless it has build_where. Croaks, naming $what, for a list of the wrong shape (as new checks it) or a builder not composing DBIx::QuickORM::Role::WhereBuilder. $conn = $orm->_connect(%args) A new Connection with these arguments, on a new handle from the connector unless they give a dbh. $new = $orm->_connect_like($conn) A new Connection from the connector with the settings of the given one and the map as the ORM finished building it, without any temporary tables or views: for a forked child's reconnect, and for queries run on a second connection. $map = $orm->_copy_map($db_map) A copy of a given map as a DBIx::QuickORM::Map, or undef for undef. $orm->_drop_absent_elective($map) Drops the per-table arguments naming an elective table the map lacks, as the table or as an fks target, before _setup_map checks them. $note = $orm->_absent_note($name) What a "not in the database map" error adds: the Connection's _gone_note, or that the table is elective and absent. $orm->_setup_map($map, $given) Adjusts the Connection's map in place by the arguments, in the order new lists them, through the methods below. $given is true when the map came from db_map rather than a scan. $orm->_autotype($map, $given) Sets each field's orm_type from the autotype list, as new describes. A given map keeps its types, which are only loaded, when new got neither autotype nor append_autotype. $orm->_apply_types($map) Applies types, loading each type it names. A named field gets the type in place of any autotype, or none for undef. Its format and generate hints become the ones given (none for the plain form). Then type_options fills each hint a field of that type lacks. format and generate fall back separately. Each type it names is loaded. A field left with a hint but no type croaks. $orm->_apply_fks($map) Applies fks: adds each link to the table's foreign keys, through _add_fk. $orm->_apply_pks($map) Applies pks: sets the primary key of each named view, or of a table the database reports no primary key for. Croaks for a table that has one and for a field the table or view lacks. $orm->_apply_default_fields($map) Applies omit and default_fields, setting each named table's default fields, with the croaks new lists, then auto_omit on the other tables. $orm->_apply_row_classes($map) Applies row_classes, then row_namespace to each table left without a row class (through _namespace_class, and a class found there must do DBIx::QuickORM::Role::Row), then loads every row class the map names and the ORM's row_class, unless the class already has a new. $class = $orm->_namespace_class($namespace, $table) The table's row class under row_namespace: the namespace and the part row_class_name gives for the table, or by default each _-separated part of the name with its first letter upper-cased, joined. Undef when the part is undef. Warns and returns undef when the part is not an identifier. $orm->_apply_key_types($map) Records each table's pk_types (see DBIx::QuickORM::Map) when a primary key field has a type. Croaks when such a type has no canonical_key_value, and when a field whose type can generate values has generate => 'prefer_orm' on a column the database refuses values for. $orm->_apply_passthrough($map) Sets passthrough on each typed field whose type's inflate_is_identity is true for that field, and removes it from every other field. \%arg = $orm->_table_arg($map, $name, $want, \&check) The named argument, or an empty hash when it was not given. Croaks unless it is a hashref whose values pass check ($want describes the shape), or when it names a table not in the map. $orm->_check_fields($map, $name, $table, @fields) Croaks for the first field not in the table. $class = $orm->_lookup_class($name) The full class name for the lookup argument. The Connection loads it and checks its role. $class = $orm->_type_class($type) The full class name for a type name. $orm->_require_map_types($map) Loads every type a given map names. [$class, \%base_types, $has_matches] = $orm->_load_type($arg, $type) Loads an autotype for _autotype: its class, its base_types as a set, and whether it has matches. Croaks naming the argument when the type cannot be loaded, or has neither. $orm->_add_fk($map, $table, $other, \%link) Adds a foreign key from the table to the other one, unless the table already has the same link. Croaks when it has a link on the same fields that points at different fields of the other table. $orm->_set_default_fields($map, $arg, $table, @fields) Sets the table's default fields to @fields, sorted and without duplicates. Croaks naming the argument when @fields is empty. SOURCE The source code repository for DBIx-QuickORM can be found at https://github.com/exodist/DBIx-QuickORM. 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/