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
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, orcredentials. 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
RaiseErrorandAutoCommiton. 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
asideandforkedon its handles (see "Running elsewhere" in DBIx::QuickORM::Handle). - connect => sub { ... }
-
A code reference that returns a new, uncached handle with
RaiseErrorandAutoCommiton each time it is called. - credentials => {dsn => $dsn, user => $user, pass => $pass, attrs => \%attrs}
-
Arguments for
DBI->connect.dsnis required.user,pass, andattrsare optional. Other keys croak.RaiseErrorandAutoCommitare always turned on, andAutoCommitgiven false inattrscroaks.
The ORM manages transactions, so every form needs
AutoCommiton. A handle withAutoCommitoff, or with a transaction already open, croaks.The remaining arguments adjust the map. The database is scanned into a DBIx::QuickORM::Map unless
db_mapis given, once per process (seerescan). These arguments then change it, in this order. Each type or row class they name is loaded duringnew.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. 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.
The first scan of a database in a process is kept, and every later
newwithout adb_mapstarts 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
rescanafter 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, thenDateTime(DBIx::QuickORM::Type::UUID, DBIx::QuickORM::Type::JSON, DBIx::QuickORM::Type::DateTime).autotype => undefor[]turns this off.append_autotypeadds to theautotypelist, or to the default. With adb_map, the map keeps its types unless either is given. Then every field is typed again.A type matches through its
base_typesormatches(see DBIx::QuickORM::Role::Type).Type names work the same everywhere: a bare name such as
JSONmeansDBIx::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_typeends in[]or[N](PostgreSQL arrays, DuckDB lists and fixed-size arrays). Usetypesto 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.
The hashref form also sets field hints:
formatandgenerate(see "Field hints" in DBIx::QuickORM::Role::Type). Withoutclassit keeps the field's type.Either form replaces the field's hints with the ones given (none for the plain form).
type_optionsthen 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, such as
{UUID => {format => sub { uc $_[0] }}}. A field's own hints intypeswin, each hint separately. - fks => {table => {other_table => [{field => other_field}, ...]}}
-
Foreign keys to add to the scanned ones. A key identical to one the table already has is ignored. A key over the same fields that maps them differently croaks.
- omit => {table => \@fields}
- default_fields => {table => \@fields}
-
Set which fields a table's queries select by default (the table's
default_fields).omitselects every field but the ones listed.default_fieldsselects the ones listed plus the primary key. A table named in neither selects every field, unless a givendb_mapsets its default fields.Croaks when both name the same table, when
omitnames 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
omitanddefault_fieldsdo not name. Nothing is left out unless asked. For example,auto_omit => {types => ['JSON'], db_types => ['bytea']}.typesnames ORM types astypesdoes (JSON,+My::Type), matching a field whoseorm_typeis that class or a subclass. Each is loaded, and one that cannot be croaks.db_typesnames database types, matched against the field's base type (typein DBIx::QuickORM::Map): lowercased, without sizes or array markers, sobyteaalso matchesbytea[].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_mapkeeps the default fields it carries, including ones an earlierauto_omitset. Name a table inomitordefault_fieldsto change it. In a table class, a bareomit;selects every field again. - row_classes => {table => $class_or_undef}
-
The row class for one table's rows. Undef means hashrefs.
Every row class named anywhere is loaded unless it already has a
newmethod. One that cannot be loaded croaks. - row_namespace => $namespace
-
Gives each table a row class under
$namespace, named from the table:user_postsgets${namespace}::UserPosts.A table with an entry in
row_classes(or in a givendb_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_namespacenames a table's class. It gets the table name and returns the part after the namespace, such as'Person'forpeople.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, andlike_aggregatesare described under "ATTRIBUTES".retain_cache,enforce_canon,debug,isolation,time_zone(ortz), anddatetime_parsersare described under "Settings". A setting of the wrong type croaks.A subclass constructor can pass
caller => [caller]so errors fromnewname 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 DBIx::QuickORM::Map built when the ORM was constructed.
- $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. - $bool = $orm->enforce_canon
-
Whether
update_rowanddelete_rowrefuse 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_canonon the current Connection, for every write after the call. - $bool = $orm->debug
-
Whether the ORM records which call made row data stop being canonical, for
canon_statusand the non-canonical croak. Default 0. Passdebug => 1tonewto 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 levelstxntakes (seetxnunder "Transactions"). - $tz = $orm->time_zone
-
The session time zone,
UTCunless given. MySQL and MariaDB getUTCas+00:00. SQLite has no session time zone.newalso accepts it astz. 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.newloads each class, and croaks when one cannot be loaded or has noparse_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_parserson the current Connection, checked asnewchecks 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
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.
- $bool = $orm->is_canon($table, $row_or_data)
-
True when the row data (or a row object's
row_data) is the canonical copy for its primary key.False when it is not, or when the row cache has no copy for that key. Croaks when the primary key cannot be determined.
So a row missing part of its key (a new row from
vivify, say) croaks here, while the row's ownis_canonanswers false. - $status = $orm->canon_status($table, $row_or_data)
-
Why the row data (or a row object's
row_data) is not the canonical copy: undef while it is, otherwise a hashref with itscause. A row's owncanon_statuscalls this.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.
byis the call behind areplaced,cache_cleared, ordeleted, andlast_clearthe call that last cleared the table or the whole cache for anot_cached, each when known, as acallerframe: package, file, line, and the public method called. When a public method calls another, the outer one is recorded. They are recorded only withdebug => 1(seedebug).Without
debugthe cause is what can be worked out when asked: row data whose key another hash holds isreplaced(a copy that was never canonical looks the same), and a cleared key isnot_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_dbrow needs no primary key here. Any other croaks asis_canondoes 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$pktakes the formsfindtakes (see DBIx::QuickORM::Handle), and its values are deflated (turned into database form) the same way.A typed key matches in any form: a
DateTimeor 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
clearto 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_rowandrefresh_rowreturn that same object, now holding the new row data (it takes the new data in void context too).data => 1returns the row data instead of a row. A given row object still takes the new data. A handle'sdata_onlydoes the same for the rows it returns.row_class => $classbuilds the rows with that class for this call, loading it when needed.row_class => undefreturns the row data. Withdata => 1too,datawins. A given row object still takes the new data. A handle passes its ownrow_classthis way.Otherwise they return a new row object. The class is the table's
row_classin the map when set (even to undef), else the ORM'srow_class. When that class is undef (as withrow_class => undeftonew), they return the row data.insert_manyreturns an arrayref of these, never a list.When no row matched,
update_rowandrefresh_rowreturn undef. A row object given keeps its row data, but arefresh_rowthat finds no row marks it deleted (seewas_deletedin 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_inflatedsays it is inflated. A plain value can be ambiguous (is123JSON, or already encoded?). Wrap it inraw()orinflated()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'sgeneratehint 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_givenincludes them.insert_manygenerates 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 => 1returns a copy of the fields as sent, in database form, plus the new primary key, instead of reading the row back. Fields sent assql()are left out.The copy is not canonical, so
updateanddeleteon it croak whileenforce_canonis 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.
On a table with a primary key, the new rows become canonical. Copies already in the row cache stay.
count => 1returns how many rows were inserted instead. It works on every database, never reads rows back, and cannot be combined withdata => 1.In void context it only inserts: nothing is read back or made canonical.
An empty
\@rowssends nothing and returns an empty arrayref (0 withcount).The rows go in multi-row
INSERTstatements, 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. Usecountor 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'senforce_canon.0 skips that check, but
casandauto_casstill 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 ownupdatecroaks. 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, PostgreSQLjson, or MySQLJSON. - auto_cas => $bool
-
Compare-and-swap on every field present in both the row data and the changes.
- \%data = $orm->cas_update($table, \%data, \%changes)
- $row = $orm->cas_update($table, $row, \%changes, cas => \@fields)
-
update_rowas a compare-and-swap: writes the changes only while the database still holds the row data's values for the changed fields (or thecasfields), and returns undef otherwise, changing nothing.The row data need not be canonical, so it takes any hashref holding the primary key and the compared fields, a
bareone included, and returns the new row data, or a row ofrow_classwhen that option is given. Given a row object it returns that object, holding the new data ("CRUD operations"). A row's owncas_updatecalls 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_rowdeflates them. A hand-built hashref must hold stored values, or wrap an inflated one ininflated()(DBIx::QuickORM::Value). The changes are deflated as forupdate_row, unlessrawis true.It croaks on any option but
cas,raw, androw_class, on an emptycaslist (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
bareafterclear_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_deletedin DBIx::QuickORM::Role::Row).A delete that matches no row also marks it deleted (it is not in the database) and returns 0.
enforce_canonis as forupdate_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).
A row object given follows the rule in "CRUD operations".
It reads
fieldsplus 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 => 0always reads the database.db => 0only 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.$pktakes any key form (seefindin DBIx::QuickORM::Handle). The options arerefresh_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
byfields hold the given values, inserting it from\%fieldswhen there is none. It follows the CRUD operations' return rule.bydefaults to the primary key. A table without one needsby. Everybyfield 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
byvalue 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
byfields. 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 => 1also covers thebyvalues 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,modifychanges it (see DBIx::QuickORM::Role::Row).The fields are checked and deflated as
insertdoes, into a new hashref. An empty hashref is fine. Fill it in withmodify. The row is built as the CRUD operations build rows, so with no row class it is the row data.row_classpicks 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_tablefor the rows linked to this row by a foreign key: the row it points to, or the rows that point to it.The handle's
whereholds the linked fields' values from the row, qualified asother_table.field, so the handle can be joined to other tables. Narrow the handle withand, sincewherewould replace the link.linkis{our_field => their_field, ...}, as foreign keys are written in the map, and gives the direction. On a self-referencingemployeestable,{manager_id => 'id'}follows to an employee's manager and{id => 'manager_id'}to their reports. It must match a foreign key of$tableto$other_table, or one of$other_tableto$tablereversed. Without it there must be exactly one such key.viatakes 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, givefkstonew.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 aviafield that does not exist, and when given bothlinkandvia.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_fkinserts exactly one row and returns it, asinsertdoes.insert_many_fkinserts any number, asinsert_manydoes: an arrayref of rows, the count withcount => 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'});linkchooses the key when more than one of$other_tablepoints at$table, written{our_field => their_field}asfollow_fktakes it.viagives a mapping with no key behind it, as forfollow_fk. The new rows' right-hand fields are filled from this row's left-hand fields. The other options are those ofinsert(raw,data,as_given,row_class) orinsert_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
linkthat points from$table. A linked field missing from the row data is fetched first, with onerefresh_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;
- $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).
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.
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 => $nruns the block of an outermost transaction again, up to$nmore times, while the exception is a database error whoseretriableis true (a deadlock, a serialization failure, or a lock timeout). See DBIx::QuickORM::Exception::DB. The block must be safe to run again.retrycroaks 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 plainBEGINand uses the database's own default.isolation => $levelopens an outermost transaction at another level:'read committed','repeatable read','serializable','read uncommitted', or'server', in any case. Eachretrybegins at the same level.isolationcroaks on a nested transaction and for any other value.The ORM's
isolationsetting takes the same levels, andnewcroaks 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_rowanddelete_rowcheck that row data is canonical by default, whateverenforce_canonsays. 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.
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.
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::Typefor a class outsideDBIx::QuickORM::Type), loading it unless it already hasdeflate.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::Rowunless 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. Seenewfor what each does.db_mapholds the result.autotypeis undef unless given, even though a default list applies. - $builder = $orm->sql_builder
-
The SQL builder that handles use. Default: DBIx::QuickORM::SQLBuilder::SQLAbstract.
newtakes an object composing DBIx::QuickORM::Role::SQLBuilder, or the name of a class that does. A class is loaded unless it hasnew, then built with no arguments. Anything else croaks. - \@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.
newtakes a non-empty arrayref of classes or objects composing the role. A class is loaded unless it hasbuild_where. Anything else croaks. A handle can use its own list through itswhere_builders. - $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
minandmax. 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.
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_roworrefresh_row, it returns that row afterset_row_data(which runs in void context too). Withdata => 1it returns the row data. Otherwise it returns a new row built by_row, with therow_classoption when given (see_row_class_opt). Handles pass theirrow_classthat 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'scount) comes back as it is.Croaks before running the CRUD operation when a row object given to
update_roworrefresh_rowcannot take new data: it has noset_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'scaller(0)frame, which its reads and insert also run under in the lookup table'scallerslot. Handles pass theirrow_classas 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_classoption, when present (even undef), replaces the table's class. Handles and therow_classCRUD 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_classoption is as for_row.Every place that builds table rows uses it. When the class's
fast_blessis true the row is blessed directly, otherwise built withnew. The ORM asks each class forfast_blessonce and remembers the answer.
- @args = $orm->_row_class_opt(\%opts)
-
Takes the
row_classoption out of a CRUD call's options and returns it as named arguments for_rowand_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_classin the map when set (even to undef), otherwise the ORM's, which is also the class for an undef table.
- $orm->_check_args
-
Turns
tzintotime_zone, then croaks naming the first argument in%SHAPESwhose shape is wrong. The Connection checksdatetime_parsers.
- _croak_at(\@frame, $message)
-
Dies with the message at the frame's file and line, worded as
croakwords it.@frameis acallerframe 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_atsuits 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: thecaller(0)frame of the publicfollow_fk(the ORM's or a row's). When the row lacks link fields, the read of them runs under@framein the lookup table'scallerslot.
- $out = $orm->_insert_fk(\@frame, $method, $table, $row_or_data, $other_table, @args)
-
insert_fk($methodinsert) orinsert_many_fk(insert_many), reporting its errors at@frame: thecaller(0)frame of the public method (the ORM's or a row's), which its reads and inserts also run under in the lookup table'scallerslot.
- \%link = $orm->_link_for(\@frame, $map, $table, $other, {link => \%link, via => \%via}, $insert_method)
-
The link a call's
linkorviaoption gives:_via_linkforvia, otherwise_fk_linkwithlink(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,%viais 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$tableto$otherand those of$otherto$tableturned around: the one matching%given, or the only one when%givenis undef. Croaks otherwise, and when$otheris not in the map, reporting at@frame.With
$insert_method(the calling method's name, for messages), only the keys of$otherto$tablecount, and a%givenmatching a key of$tableto$othercroaks, naming the direction.
- $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
newdoes, keeping nothing.
- \%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
connectionfirst, 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
$otherwhose fields hold these values, each field qualified asother.fieldin thewhere. An undef value refers to nothing: its condition issql('IS NULL AND 1 = 0'), which is never true. The handle issinglewhen the fields are exactly the primary key or a unique key of$other, otherwisemulti. Croaks when$otheris not in the map.
- $bool = $orm->_can_connect
-
True unless the ORM was given a
dbh: whether the connector can open another connection. - $code = $orm->_build_connector
-
Turns the one connection argument into the connector, removing it from the object, and sets
_can_connect.
- $builder = $orm->_build_sql_builder
-
The
sql_builderargument 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 (asnewchecks it) or a builder not composing DBIx::QuickORM::Role::WhereBuilder.
- $conn = $orm->_connect(%args)
-
A new Connection with these arguments and a handle from the connector.
- $new = $orm->_connect_like($conn)
-
A new Connection from the connector with the map and settings of the given one: 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->_setup_map($map, $given)
-
Adjusts the Connection's map in place by the arguments, in the order
newlists them, through the methods below.$givenis true when the map came fromdb_maprather than a scan.
- $orm->_autotype($map, $given)
-
Sets each field's
orm_typefrom the autotype list, asnewdescribes. A given map keeps its types, which are only loaded, whennewgot neitherautotypenorappend_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. Itsformatandgeneratehints become the ones given (none for the plain form).Then
type_optionsfills each hint a field of that type lacks.formatandgeneratefall back separately. Each type it names is loaded. A field left with a hint but no type croaks.
- $orm->_apply_default_fields($map)
-
Applies
omitanddefault_fields, setting each named table's default fields, with the croaksnewlists, thenauto_omiton the other tables.
- $orm->_apply_row_classes($map)
-
Applies
row_classes, thenrow_namespaceto 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'srow_class, unless the class already has anew.
- $class = $orm->_namespace_class($namespace, $table)
-
The table's row class under
row_namespace: the namespace and the partrow_class_namegives 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 nocanonical_key_value, and when a field whose type can generate values hasgenerate => 'prefer_orm'on a column the database refuses values for.
- $orm->_apply_passthrough($map)
-
Sets
passthroughon each typed field whose type'sinflate_is_identityis 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($wantdescribes the shape), or when it names a table not in the map.
- [$class, \%base_types, $has_matches] = $orm->_load_type($arg, $type)
-
Loads an autotype for
_autotype: its class, itsbase_typesas a set, and whether it hasmatches. 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@fieldsis empty.
SOURCE
The source code repository for DBIx-QuickORM can be found at https://github.com/exodist/DBIx-QuickORM.
MAINTAINERS
AUTHORS
COPYRIGHT
Copyright Chad Granum <exodist7@gmail.com>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.