| 1 | package DBIx::QuickORM::Manual::Quickstart; | ||
| 2 | 2 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 2 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | |||
| 5 | 2 | our $VERSION = '0.000031'; | |
| 6 | |||
| 7 | =pod | ||
| 8 | |||
| 9 | =encoding UTF-8 | ||
| 10 | |||
| 11 | =head1 NAME | ||
| 12 | |||
| 13 | DBIx::QuickORM::Manual::Quickstart - Introduces the fundamentals with a simple example, then expands into advanced capabilities from there. | ||
| 14 | |||
| 15 | =head1 DESCRIPTION | ||
| 16 | |||
| 17 | Short examples of what most applications do with the ORM. They use | ||
| 18 | PostgreSQL and this schema: | ||
| 19 | |||
| 20 | =for highlighter language=sql | ||
| 21 | |||
| 22 | CREATE TABLE users ( | ||
| 23 | id SERIAL PRIMARY KEY, | ||
| 24 | name TEXT NOT NULL, | ||
| 25 | email TEXT UNIQUE, | ||
| 26 | prefs JSON, | ||
| 27 | referred_by INTEGER REFERENCES users (id), | ||
| 28 | created TIMESTAMP NOT NULL DEFAULT now() | ||
| 29 | ); | ||
| 30 | |||
| 31 | CREATE TABLE posts ( | ||
| 32 | id SERIAL PRIMARY KEY, | ||
| 33 | user_id INTEGER NOT NULL REFERENCES users (id), | ||
| 34 | title TEXT NOT NULL, | ||
| 35 | views INTEGER NOT NULL DEFAULT 0 | ||
| 36 | ); | ||
| 37 | |||
| 38 | And a log whose C<user_id> has no foreign key constraint: | ||
| 39 | |||
| 40 | CREATE TABLE audit_log ( | ||
| 41 | id SERIAL PRIMARY KEY, | ||
| 42 | user_id INTEGER, | ||
| 43 | action TEXT NOT NULL | ||
| 44 | ); | ||
| 45 | |||
| 46 | The ORM reads the schema from the database. Nothing is declared in Perl. | ||
| 47 | C<prefs> comes back as Perl data and C<created> as a lazy L<DateTime> | ||
| 48 | (L<DBIx::QuickORM::Type::DateTime::Lazy>), from their declared types | ||
| 49 | (L<DBIx::QuickORM::Manual::Types>). | ||
| 50 | |||
| 51 | Other databases differ in places: L<DBIx::QuickORM::Manual::Dialects>. | ||
| 52 | |||
| 53 | =head1 CONNECTING | ||
| 54 | |||
| 55 | =for highlighter language=perl | ||
| 56 | |||
| 57 | use DBIx::QuickORM; | ||
| 58 | |||
| 59 | my $orm = DBIx::QuickORM->new( | ||
| 60 | credentials => { | ||
| 61 | dsn => $dsn, | ||
| 62 | user => $user, | ||
| 63 | pass => $pass, | ||
| 64 | }, | ||
| 65 | ); | ||
| 66 | |||
| 67 | Or a sub that returns a new handle each time it is called: | ||
| 68 | |||
| 69 | my $orm = DBIx::QuickORM->new( | ||
| 70 | connect => sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1}) }, | ||
| 71 | ); | ||
| 72 | |||
| 73 | Or a handle you already have, with C<RaiseError> on: | ||
| 74 | |||
| 75 | my $orm = DBIx::QuickORM->new(dbh => $dbh); | ||
| 76 | |||
| 77 | The ORM cannot open a second connection from a C<dbh>, so with it a forked | ||
| 78 | child cannot reconnect, and C<aside()> and C<forked()> croak | ||
| 79 | (L<DBIx::QuickORM::Manual::Background>). | ||
| 80 | |||
| 81 | The ORM controls its handle's attributes and may change any of them. Do not | ||
| 82 | change them, run SQL on the handle, or control transactions on it outside the | ||
| 83 | ORM. | ||
| 84 | |||
| 85 | Change rows only through the ORM's methods, such as C<< $row->update >>. If | ||
| 86 | you edit a row's data hash directly, the ORM does not know about it, so its | ||
| 87 | row cache and change tracking go stale (L<DBIx::QuickORM::Manual::Caching>). | ||
| 88 | |||
| 89 | =head1 CREATE, READ, UPDATE, DELETE, FIND | ||
| 90 | |||
| 91 | my $alice = $orm->insert(users => { | ||
| 92 | name => 'Alice', | ||
| 93 | email => 'alice@example.com', | ||
| 94 | prefs => {theme => 'dark'}, | ||
| 95 | }); | ||
| 96 | |||
| 97 | my $id = $alice->field('id'); # the key the database generated | ||
| 98 | my $theme = $alice->field('prefs')->{theme}; # JSON comes back as Perl data | ||
| 99 | my $json = $alice->raw_field('prefs'); # '{"theme":"dark"}': the value as stored | ||
| 100 | my $year = $alice->field('created')->datetime_ref->year; # timestamps come back as lazy DateTimes | ||
| 101 | |||
| 102 | my $found = $orm->find(users => $id); # by primary key | ||
| 103 | |||
| 104 | # undef: no such user | ||
| 105 | my $bob = $orm->handle('users')->where({email => 'bob@example.com'})->only; | ||
| 106 | |||
| 107 | $alice->update({name => 'Alice Smith'}); | ||
| 108 | $alice->refresh; # read it again from the database | ||
| 109 | |||
| 110 | my $temp = $orm->insert(users => {name => 'Temp'}); | ||
| 111 | $temp->delete; | ||
| 112 | |||
| 113 | Rows have no setters: change them with C<update>. | ||
| 114 | |||
| 115 | Find a row, or insert it when there is none: | ||
| 116 | |||
| 117 | my $gil = $orm->find_or_insert( | ||
| 118 | users => { | ||
| 119 | name => 'Gil', | ||
| 120 | email => 'gil@example.com', | ||
| 121 | }, | ||
| 122 | by => ['email'], # the fields to find by (the primary key by default) | ||
| 123 | ); | ||
| 124 | |||
| 125 | When another process inserts the same row first, it finds that one, given a | ||
| 126 | unique constraint on the C<by> fields (limits: | ||
| 127 | L<DBIx::QuickORM/Finding or inserting>). | ||
| 128 | |||
| 129 | A table handle has it too: C<< $users->find_or_insert(\%fields, by => ['email']) >>. | ||
| 130 | |||
| 131 | Values are deflated by their field's type on the way in: Alice's C<prefs> | ||
| 132 | hashref went in as JSON. C<raw()> sends one value as given: | ||
| 133 | |||
| 134 | use DBIx::QuickORM::Value qw/raw/; | ||
| 135 | |||
| 136 | my $hal = $orm->insert(users => { | ||
| 137 | name => 'Hal', | ||
| 138 | prefs => raw('{"theme":"light"}'), # already JSON text: sent as is | ||
| 139 | }); | ||
| 140 | |||
| 141 | C<< raw => 1 >> on the call does the same for every value. | ||
| 142 | |||
| 143 | See L<DBIx::QuickORM::Manual::Keys> for the forms a key takes, and | ||
| 144 | L<DBIx::QuickORM::Manual::Values> for inflation, deflation, and the value | ||
| 145 | markers. Rows are L<DBIx::QuickORM::Row> objects, and table handles are | ||
| 146 | L<DBIx::QuickORM::Handle> objects. | ||
| 147 | |||
| 148 | =head1 HANDLES | ||
| 149 | |||
| 150 | A handle is a query. Modifiers return a new handle. The one they are called | ||
| 151 | on never changes, so calling one in void context croaks. | ||
| 152 | |||
| 153 | my $users = $orm->handle('users'); | ||
| 154 | my $sorted = $users->order_by('name'); # $users is unchanged | ||
| 155 | my $page = $sorted->limit(10)->offset(20); | ||
| 156 | my $alices = $users->where({name => {-like => 'Alice%'}}); | ||
| 157 | |||
| 158 | my $count = $users->count; | ||
| 159 | my @all = $sorted->all; | ||
| 160 | my @data = $sorted->data_only->all; # plain hashrefs, not row objects | ||
| 161 | |||
| 162 | One row at a time, on a table handle: | ||
| 163 | |||
| 164 | my $carol = $users->insert({name => 'Carol'}); | ||
| 165 | my $again = $users->find($carol->field('id')); | ||
| 166 | $users->update_row($carol, {email => 'carol@example.com'}); | ||
| 167 | $users->delete_row($carol); | ||
| 168 | |||
| 169 | Many rows at once: | ||
| 170 | |||
| 171 | my $added = $users->insert_many([{name => 'Dan'}, {name => 'Erin'}]); # an arrayref of rows | ||
| 172 | my $renamed = $users->where({name => 'Dan'})->update({name => 'Daniel'}); | ||
| 173 | my $removed = $users->where({name => 'Erin'})->delete; | ||
| 174 | |||
| 175 | See L<DBIx::QuickORM::Manual::BulkInsert> for C<insert_many>, and | ||
| 176 | L<DBIx::QuickORM::Manual::RowClasses> for C<data_only> and row classes of | ||
| 177 | your own. L<DBIx::QuickORM::Handle> documents every handle method. | ||
| 178 | |||
| 179 | =head1 ITERATING | ||
| 180 | |||
| 181 | my $posts = $orm->handle('posts')->order_by('id'); | ||
| 182 | while (my $row = $posts->next) { | ||
| 183 | my $title = $row->field('title'); | ||
| 184 | } | ||
| 185 | |||
| 186 | my $it = $posts->iter; # its own position over the same rows | ||
| 187 | $posts->clear; # forget the rows, so the next read queries again | ||
| 188 | |||
| 189 | A handle sends its query on the first read and keeps the rows until C<clear>. | ||
| 190 | C<next> and C<reset> move the handle's own position. Each C<iter> returns a | ||
| 191 | new iterator with its own. | ||
| 192 | |||
| 193 | A handle from a foreign key knows whether it can match more than one row: | ||
| 194 | |||
| 195 | my $post = $posts->first; | ||
| 196 | my $author = $post->follow_fk('users')->only; # single: the key points at one row | ||
| 197 | my @posts = $alice->follow_fk('posts')->all; # multi: any number of rows | ||
| 198 | |||
| 199 | C<only> returns the one row, or undef. It croaks when there is more than one, | ||
| 200 | and always on a multi handle. See L<DBIx::QuickORM::Manual::ForeignKeys>. | ||
| 201 | |||
| 202 | C<via> follows fields the database never declared as a key: | ||
| 203 | |||
| 204 | my $entry = $orm->insert(audit_log => {user_id => $alice->field('id'), action => 'login'}); | ||
| 205 | my $who = $entry->follow_fk('users', via => {user_id => 'id'})->only; # Alice | ||
| 206 | |||
| 207 | L<DBIx::QuickORM::Iterator> documents iterators. | ||
| 208 | |||
| 209 | =head1 JOINS | ||
| 210 | |||
| 211 | my @pairs = $orm->handle('posts') | ||
| 212 | ->join('users') | ||
| 213 | ->where({'users.name' => 'Alice Smith'}) | ||
| 214 | ->all; | ||
| 215 | |||
| 216 | for my $pair (@pairs) { | ||
| 217 | my $title = $pair->row('posts')->field('title'); | ||
| 218 | my $author = $pair->row('users')->field('name'); | ||
| 219 | } | ||
| 220 | |||
| 221 | Each result holds one row per table. Fields are named C<table.field>. | ||
| 222 | |||
| 223 | C<left_join> keeps every user. C<row('posts')> is undef for a user without | ||
| 224 | posts: | ||
| 225 | |||
| 226 | my @everyone = $orm->handle('users')->left_join('posts')->all; | ||
| 227 | |||
| 228 | C<as> names the joined table, and its fields are C<alias.field>. C<link> | ||
| 229 | picks the foreign key when there is more than one way to join, as a self join | ||
| 230 | has: | ||
| 231 | |||
| 232 | my @referred = $orm->handle('users') | ||
| 233 | ->join( | ||
| 234 | 'users', | ||
| 235 | as => 'referrer', | ||
| 236 | link => {referred_by => 'id'}, | ||
| 237 | ) | ||
| 238 | ->order_by('referrer.name') | ||
| 239 | ->all; | ||
| 240 | |||
| 241 | for my $pair (@referred) { | ||
| 242 | my $who = $pair->row('users')->field('name'); | ||
| 243 | my $by = $pair->row('referrer')->field('name'); | ||
| 244 | } | ||
| 245 | |||
| 246 | See L<DBIx::QuickORM::Manual::Joins>. | ||
| 247 | |||
| 248 | =head1 AGGREGATES | ||
| 249 | |||
| 250 | my @stats = $orm->handle('posts') | ||
| 251 | ->group_by('user_id') | ||
| 252 | ->fields({ | ||
| 253 | user_id => 'user_id', | ||
| 254 | posts => [count => '*'], # COUNT(*) | ||
| 255 | titles => \'COUNT(DISTINCT title)', # or any SQL | ||
| 256 | views => [sum => 'views'], | ||
| 257 | }) | ||
| 258 | ->order_by('user_id') | ||
| 259 | ->all; | ||
| 260 | |||
| 261 | for my $stat (@stats) { | ||
| 262 | my $count = $stat->field('posts'); | ||
| 263 | my $poster = $stat->follow_fk('users')->only; # user_id keeps its foreign key | ||
| 264 | } | ||
| 265 | |||
| 266 | See L<DBIx::QuickORM::Manual::Aggregates>, and L<DBIx::QuickORM::Manual::Values> | ||
| 267 | for C<sql()>. | ||
| 268 | |||
| 269 | =head1 TRANSACTIONS | ||
| 270 | |||
| 271 | $orm->txn(sub { | ||
| 272 | my $dave = $orm->insert(users => {name => 'Dave'}); | ||
| 273 | $orm->insert(posts => { | ||
| 274 | user_id => $dave->field('id'), | ||
| 275 | title => 'First post', | ||
| 276 | }); | ||
| 277 | }); # commits when the block returns. An exception rolls back and is rethrown | ||
| 278 | |||
| 279 | my $txn = $orm->txn; | ||
| 280 | $orm->insert(users => {name => 'Nobody'}); | ||
| 281 | $txn->rollback; # or $txn->commit | ||
| 282 | |||
| 283 | A transaction opened inside another is a savepoint. | ||
| 284 | |||
| 285 | Rows read before a transaction are not canonical inside it: refresh one before | ||
| 286 | writing it there, or write it with C<cas_update> (L</COMPARE-AND-SWAP>). | ||
| 287 | |||
| 288 | $orm->txn( | ||
| 289 | sub { | ||
| 290 | $post->refresh; # $post was read before the transaction | ||
| 291 | $post->update({views => 2}); | ||
| 292 | }, | ||
| 293 | isolation => 'serializable', | ||
| 294 | retry => 3, | ||
| 295 | ); | ||
| 296 | |||
| 297 | Every outermost transaction opens at C<read committed> unless C<isolation> | ||
| 298 | (on the call, or the ORM's) names another level. A savepoint keeps its | ||
| 299 | transaction's level. At C<serializable>, a write that conflicts with another | ||
| 300 | transaction fails with a serialization failure instead of overwriting it. | ||
| 301 | |||
| 302 | C<retry> runs the block again, up to 3 more times, after a deadlock, a | ||
| 303 | serialization failure, or a lock timeout (L<DBIx::QuickORM::Manual::Errors>). | ||
| 304 | |||
| 305 | See L<DBIx::QuickORM::Manual::Transactions>. | ||
| 306 | |||
| 307 | =head1 COMPARE-AND-SWAP | ||
| 308 | |||
| 309 | # cas_update writes only while views still holds the value this row read, and | ||
| 310 | # returns undef when it changed elsewhere first: read the row again and retry. | ||
| 311 | while (1) { | ||
| 312 | last if $post->cas_update({views => $post->field('views') + 1}); | ||
| 313 | $post->refresh; | ||
| 314 | } | ||
| 315 | |||
| 316 | The loop ends once this process is the one that incremented C<views>, however | ||
| 317 | many others increment it at the same time. C<cas_update> compares the fields | ||
| 318 | it changes. C<< cas => [...] >> names other fields to compare instead. | ||
| 319 | |||
| 320 | C<update> compares too, given C<cas>, or C<auto_cas> for every changed field | ||
| 321 | the row holds: | ||
| 322 | |||
| 323 | $post->update({views => 10}, auto_cas => 1); | ||
| 324 | |||
| 325 | C<cas_update> also works on a row that is not canonical, such as one read | ||
| 326 | before a transaction: | ||
| 327 | |||
| 328 | $orm->txn(sub { | ||
| 329 | $post->cas_update({views => 11}) or die "Changed elsewhere\n"; | ||
| 330 | }); | ||
| 331 | |||
| 332 | See L<DBIx::QuickORM::Manual::Caching> for which rows are canonical. | ||
| 333 | |||
| 334 | =head1 ASYNC, ASIDE, AND FORKED QUERIES | ||
| 335 | |||
| 336 | my $later = $orm->handle('posts')->async->iter; # starts the query and returns at once | ||
| 337 | |||
| 338 | do_something_else() until $later->ready; | ||
| 339 | |||
| 340 | # waits for the rows when they are not there yet | ||
| 341 | my @fetched = $later->all; | ||
| 342 | |||
| 343 | An async query runs on the ORM's connection: until its rows are collected, | ||
| 344 | anything else that sends SQL on that connection croaks. C<aside> and | ||
| 345 | C<forked> run elsewhere: | ||
| 346 | |||
| 347 | my $aside = $orm->handle('users')->aside->iter; # on a second connection | ||
| 348 | my $forked = $orm->handle('users')->forked->iter; # in a child process | ||
| 349 | my @found = ($aside->all, $forked->all); | ||
| 350 | |||
| 351 | A handle runs one background query, however many iterators read it. | ||
| 352 | |||
| 353 | See L<DBIx::QuickORM::Manual::Background>, and | ||
| 354 | L<DBIx::QuickORM::Manual::Dialects> for the databases each one runs on. | ||
| 355 | |||
| 356 | =head1 DEFINING THE ORM IN PACKAGES | ||
| 357 | |||
| 358 | Larger applications can define the ORM, its table adjustments, and row classes | ||
| 359 | as packages. F<lib/My/ORM.pm>: | ||
| 360 | |||
| 361 | package My::ORM; | ||
| 362 | use DBIx::QuickORM::DSL ':orm'; | ||
| 363 | |||
| 364 | orm { | ||
| 365 | tables 'My::Tables'; # the modules directly under My::Tables | ||
| 366 | }; | ||
| 367 | |||
| 368 | 1; | ||
| 369 | |||
| 370 | F<lib/My/Tables/Users.pm> adjusts C<users> and is its row class: | ||
| 371 | |||
| 372 | package My::Tables::Users; | ||
| 373 | use DBIx::QuickORM::DSL qw/:table :row/; | ||
| 374 | |||
| 375 | table { | ||
| 376 | name 'users'; | ||
| 377 | omit qw/prefs/; # selected only when asked for | ||
| 378 | }; | ||
| 379 | |||
| 380 | row { parent }; | ||
| 381 | |||
| 382 | sub display_name { $_[0]->field('name') . ' <' . $_[0]->field('email') . '>' } | ||
| 383 | |||
| 384 | 1; | ||
| 385 | |||
| 386 | Then: | ||
| 387 | |||
| 388 | use My::ORM; | ||
| 389 | |||
| 390 | my $app = My::ORM->new( | ||
| 391 | credentials => { | ||
| 392 | dsn => $dsn, | ||
| 393 | user => $user, | ||
| 394 | pass => $pass, | ||
| 395 | }, | ||
| 396 | ); | ||
| 397 | |||
| 398 | my $label = $app->find(users => $id)->display_name; # a My::Tables::Users row | ||
| 399 | |||
| 400 | Without the DSL, C<row_namespace> gives each table the row class named after | ||
| 401 | it, when that module exists: C<users> gets C<My::Rows::Users>. | ||
| 402 | C<row_class_name> picks other names. | ||
| 403 | |||
| 404 | my $named = DBIx::QuickORM->new( | ||
| 405 | credentials => { | ||
| 406 | dsn => $dsn, | ||
| 407 | user => $user, | ||
| 408 | pass => $pass, | ||
| 409 | }, | ||
| 410 | row_namespace => 'My::Rows', | ||
| 411 | ); | ||
| 412 | |||
| 413 | See L<DBIx::QuickORM::Manual::Classes> for the class-based ORM and | ||
| 414 | L<DBIx::QuickORM::Manual::RowClasses> for row classes. | ||
| 415 | |||
| 416 | =head1 FORKING | ||
| 417 | |||
| 418 | A forked child that uses the ORM gets its own connection. The parent's is | ||
| 419 | left alone. | ||
| 420 | |||
| 421 | my $pid = fork // die "Could not fork: $!"; | ||
| 422 | unless ($pid) { | ||
| 423 | my $count = $orm->handle('users')->count; # the ORM reconnects in the child by itself | ||
| 424 | exit($count ? 0 : 1); | ||
| 425 | } | ||
| 426 | waitpid($pid, 0); | ||
| 427 | |||
| 428 | Rows the child inherited are not canonical there: refresh one before writing | ||
| 429 | it. See L<DBIx::QuickORM::Manual::Background/"FORKING YOUR OWN PROCESS">. | ||
| 430 | |||
| 431 | =cut | ||
| 432 | |||
| 433 | 2 | 1; | |
| 434 | |||
| 435 | __END__ | ||