blib/lib/DBIx/QuickORM/Manual/Dialects.pm untested

filter: Statementstmt 0.0% 0 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 2 Podpod n/a totaltotal 0.0% 0 / 10 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package DBIx::QuickORM::Manual::Dialects;
2 use strict;
3 use warnings;
4  
5 our $VERSION = '0.000033';
6  
7 =pod
8  
9 =encoding UTF-8
10  
11 =head1 NAME
12  
13 DBIx::QuickORM::Manual::Dialects - What differs between PostgreSQL, MySQL, MariaDB, SQLite, and DuckDB, and what it means for your code.
14  
15 =head1 DESCRIPTION
16  
17 The ORM hides most database differences. Here is what still affects your
18 code, at a glance:
19  
20 =over 4
21  
22 =item PostgreSQL
23  
24 PostgreSQL is the baseline, so everything on these pages works as shown.
25 Compare-and-swap fails on a C<json> column, which has no C<=> (C<jsonb>
26 has). Behind a pooler in transaction mode, such as PgBouncer, set
27 C<< pg_server_prepare => 0 >> in the attributes of the connection: the ORM
28 reuses prepared statements.
29  
30 =item MySQL and MariaDB
31  
32 Both connect through L<DBD::MariaDB>. L<DBD::mysql> is not supported. MySQL
33 has no C<RETURNING>, and QuickORM uses MariaDB's on C<INSERT> and C<DELETE>
34 only (L</RETURNING>). Neither has temporary views, and a rollback does not
35 undo creating or dropping a temporary table, which the ORM makes up for.
36 Named time zones need the server's time zone tables. MySQL compares a
37 C<JSON> column with a text bind as a JSON string, and MariaDB stores
38 C<JSON> as C<longtext> (L</JSON>).
39  
40 =item SQLite
41  
42 No C<async> or C<aside>, no isolation levels to set, and no session time
43 zone. Values are bound as text. QuickORM opens no second connection to an
44 in-memory database. Schema building croaks for tables that reference each
45 other.
46  
47 =item DuckDB
48  
49 No savepoints, no C<async> or C<aside>, no isolation levels to set, and no
50 foreign key actions. QuickORM opens no second connection. Errors are
51 classified from their message, and time zones work by name only. Schema
52 building croaks for tables that reference each other.
53  
54 =back
55  
56 L</DIFFERENCES THE ORM HIDES> lists what the ORM makes the same everywhere,
57 and how.
58  
59 =head1 SCHEMA
60  
61 The examples use PostgreSQL and this schema:
62  
63 =for highlighter language=sql
64  
65 CREATE TABLE users (
66 id SERIAL PRIMARY KEY,
67 name TEXT NOT NULL,
68 email TEXT UNIQUE,
69 prefs JSON,
70 referred_by INTEGER REFERENCES users (id),
71 created TIMESTAMP NOT NULL DEFAULT now()
72 );
73  
74 CREATE TABLE posts (
75 id SERIAL PRIMARY KEY,
76 user_id INTEGER NOT NULL REFERENCES users (id),
77 title TEXT NOT NULL,
78 views INTEGER NOT NULL DEFAULT 0
79 );
80  
81 =head1 ASKING THE DIALECT
82  
83 =for highlighter language=perl
84  
85 my $dialect = $orm->connection->dialect;
86  
87 # 'PostgreSQL', 'MySQL', 'MariaDB', 'SQLite', or 'DuckDB'
88 my $name = $dialect->name;
89  
90 # 170004 for PostgreSQL 17.4 (its own number), and elsewhere
91 # major * 1_000_000 + minor * 1_000 + patch: 8000036 for MySQL 8.0.36
92 my $version = $dialect->server_version;
93  
94 # branch on a capability, not a name
95 my $whole = $dialect->supports_returning_update ? 'the row' : 'its key';
96  
97 The capabilities: C<supports_returning_insert>, C<supports_returning_update>,
98 C<supports_returning_delete>, C<supports_savepoints>, C<supports_isolation>,
99 C<supports_async>, C<supports_second_connection($dbh)>,
100 C<supports_temp_views>, C<temp_ddl_transactional>, C<having_uses_alias>, and
101 C<bind_limit>. The dialect tells MySQL from MariaDB by the server's version
102 string, which names MariaDB.
103  
104 =head1 RETURNING
105  
106 With C<RETURNING>, C<insert> and a row's C<update> hand back the written row
107 (its default fields and the fields written, and for an update the fields the
108 row held), so the row object holds them. QuickORM uses it on every statement
109 on PostgreSQL, SQLite, and DuckDB, and on C<INSERT> and C<DELETE> on MariaDB
110 (L</Rows written without RETURNING>). MySQL has none.
111  
112 my $ann = $orm->insert(users => {
113 name => 'Ann',
114 email => 'ann@example.com',
115 });
116 $ann->update({name => 'Ann B'});
117  
118 # every field, but on MySQL, and on MariaDB after an update, only id
119 my @have = sort keys %{$ann->row_data};
120  
121 # 'Ann B' everywhere: a field the row lacks is fetched when read
122 my $name = $ann->field('name');
123  
124 Without C<RETURNING> a written row holds only its primary key, and fetches a
125 missing field when first read (C<< $row->fields(@names) >> fetches several in
126 one query). So:
127  
128 =over 4
129  
130 =item *
131  
132 C<cas_update> croaks after an update (on MySQL, after an insert too) until
133 the fields it compares are read again (L<DBIx::QuickORM::Role::Row>).
134  
135 =item *
136  
137 C<insert> on MySQL, unless in void context: a table with no primary key
138 needs C<< as_given => 1 >>. A compound key must be given whole, after any
139 UUID key fields the ORM generates. A single-field key comes from the last
140 insert id, which only C<AUTO_INCREMENT> sets. When there is none, the insert
141 croaks after the row is written.
142  
143 =item *
144  
145 C<insert_many> on MySQL needs every row to carry its whole primary key to
146 return the rows, unless called with C<< count => 1 >> or in void context
147 (L<DBIx::QuickORM::Manual::BulkInsert>).
148  
149 =item *
150  
151 A row's C<update> that sets a primary key field to C<sql()> croaks on MySQL
152 and MariaDB, since the new key could not be read back.
153  
154 =item *
155  
156 C<< $h->delete(mark_deleted => 1) >> on MySQL runs a C<SELECT ... FOR UPDATE>
157 of the keys, then the C<DELETE>, in a transaction of its own when none is
158 open. At C<read committed> a row another session commits between the two
159 may be deleted unmarked (L<DBIx::QuickORM::Handle/Writing>).
160  
161 =back
162  
163 QuickORM needs MariaDB 10.5 or later (C<INSERT ... RETURNING>) and an SQLite
164 library of 3.35 or later. Connecting to an older one croaks, naming the
165 version found. The DBD::SQLite QuickORM requires bundles a newer SQLite, but a
166 DBD::SQLite built against an older system library (as some operating system
167 packages are) is refused.
168  
169 =head1 TRANSACTIONS
170  
171 DuckDB has no savepoints, so a transaction inside another croaks there.
172 C<insert_many> and C<find_or_insert> inside a transaction use that
173 transaction as it is (on the other databases they take a savepoint), so a
174 failed insert leaves it unusable.
175  
176 my $nested = eval {
177 $orm->txn(sub {
178 # a savepoint. DuckDB has none, so this croaks
179 $orm->txn(sub { $orm->insert(users => {name => 'Bob'}) });
180 });
181 1;
182 };
183  
184 On PostgreSQL, MySQL, and MariaDB every root transaction states its level,
185 C<read committed> unless the ORM or the C<txn> call names another
186 (L</Isolation level>). On SQLite and DuckDB a level croaks
187 (L<DBIx::QuickORM::Manual::Transactions/ISOLATION>).
188  
189 With C<binlog_format=STATEMENT>, the MySQL family refuses writes at C<read
190 committed>: switch the server to C<ROW> or C<MIXED>, or give the ORM
191 C<< isolation => 'repeatable read' >>. Under C<< isolation => 'server' >>
192 they run at the server's default, usually C<repeatable read>, where
193 C<find_or_insert> may not see a row another session committed after its
194 transaction began.
195  
196 After a statement fails, the transaction can only be rolled back, on every
197 database (L</Failed statements in a transaction>).
198  
199 =head1 BACKGROUND QUERIES AND FORKING
200  
201 C<async> and C<aside> need PostgreSQL, MySQL, or MariaDB. C<aside>,
202 C<forked>, and a forked child using the ORM at all need a second connection
203 to the same data, and QuickORM opens one only to a server or a database file:
204 not to DuckDB, not to an in-memory SQLite database (a shared-cache
205 C<file::memory:> URI included), and not for an ORM given a C<dbh>.
206  
207 my $memory = DBIx::QuickORM->new(
208 connect => sub { DBI->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1}) },
209 );
210  
211 # croaks: no second connection can reach this SQLite database
212 my $ok = eval { $memory->handle(\'SELECT 1 AS one')->forked->iter; 1 };
213  
214 C<can_async>, C<can_aside>, and C<can_forked> say whether a mode can run
215 here. A forked child reconnects on its first use of the ORM and leaves the
216 parent's session alone (L</Forked children>,
217 L<DBIx::QuickORM::Manual::Background>).
218  
219 Cancelling an async query aborts the enclosing transaction on PostgreSQL,
220 and blocks until the query ends on MySQL and MariaDB
221 (L</Cancelling an async query>). On some platforms a child forked while a
222 PostgreSQL async query is pending may crash on exit
223 (L<https://github.com/bucardo/dbdpg/issues/218>).
224  
225 =head1 TEMPORARY TABLES AND VIEWS
226  
227 Temporary tables and views (L<DBIx::QuickORM::Manual::TempTables>) work the
228 same everywhere, with these differences:
229  
230 =over 4
231  
232 =item *
233  
234 MySQL and MariaDB have no temporary views, so C<temp_view> croaks there.
235  
236 =item *
237  
238 Creating and dropping roll back with the transaction everywhere
239 (L</Temporary tables in transactions>).
240  
241 =item *
242  
243 An enum column is C<text> with a C<CHECK>, except on MySQL and MariaDB
244 (L</Enums in temporary tables>).
245  
246 =item *
247  
248 Foreign keys declared through the builder are links in the ORM's map only
249 (L</Foreign keys of temporary tables>).
250  
251 =item *
252  
253 MySQL cannot open one temporary table twice in a query, so a self-join of
254 one fails with "Can't reopen table". MariaDB can.
255  
256 =item *
257  
258 Identity columns, generated columns, and C<using> differ as in schema
259 building (L</SCHEMA BUILDING>).
260  
261 =item *
262  
263 Dropping a temporary table that a temporary view reads from: PostgreSQL
264 refuses, while SQLite and DuckDB leave a view that fails when used.
265  
266 =back
267  
268 =head1 SCANNING
269  
270 The scan (see C<new> in L<DBIx::QuickORM>) reads one schema:
271 C<current_schema()> on PostgreSQL, C<DATABASE()> on MySQL and MariaDB (the
272 connection croaks when none is selected), C<main> on SQLite (not attached
273 databases), and the current database and schema on DuckDB. It finds views
274 everywhere, and PostgreSQL's materialized views. Beyond that:
275  
276 =over 4
277  
278 =item *
279  
280 Unique keys it cannot use are left out: partial and expression indexes,
281 MySQL prefix indexes, and DuckDB indexes over expressions.
282  
283 =item *
284  
285 SQLite applies its affinity rules: a column with no declared type has
286 C<binary> affinity, and an unknown type name C<numeric>. A temporary table
287 made from a query on SQLite keeps few column types.
288  
289 =item *
290  
291 DuckDB's catalog does not mark generated columns, so the ORM does not know
292 the database computes them.
293  
294 =item *
295  
296 Array fields (PostgreSQL arrays, DuckDB lists) are never autotyped, and
297 MariaDB's C<JSON> is autotyped by name only (L</JSON>).
298  
299 =back
300  
301 The ORM reads each catalog into the same map (L</Schema scanning>).
302  
303 =head1 SCHEMA BUILDING
304  
305 Schema building (L<DBIx::QuickORM::Manual::SchemaBuilding>) writes one
306 definition for every database. What differs:
307  
308 =over 4
309  
310 =item *
311  
312 Enums (L</Enums in schema building>).
313  
314 =item *
315  
316 Tables that reference each other get their keys after, with C<ALTER TABLE>.
317 SQLite and DuckDB cannot add a key to a table, so they croak there. Foreign
318 key actions croak on DuckDB, which has none.
319  
320 =item *
321  
322 C<identity>: PostgreSQL 10 or later. On MySQL and MariaDB the column must be
323 a key, and on SQLite the sole primary key, declared C<integer>
324 (L</Identity columns>). C<generated> is stored, except on DuckDB, which
325 computes it on read, and PostgreSQL needs 12 or later.
326  
327 =item *
328  
329 C<using> (the index type) works on PostgreSQL, MySQL, and MariaDB, and croaks
330 on SQLite and DuckDB. On MySQL and MariaDB the index declarations go inside
331 C<CREATE TABLE>, and an index given as a whole statement runs after it.
332  
333 =item *
334  
335 C<extension> works on PostgreSQL and DuckDB only (L</Settings and extensions>).
336  
337 =item *
338  
339 Collation names differ on every database. PostgreSQL's is quoted, the others
340 are written as given.
341  
342 =item *
343  
344 A per-database value (C<db_type>, C<collate>, C<indexed>, C<schema_sql>,
345 C<view_sql>) is looked up by the exact dialect, then C<any_mysql> (MySQL and
346 MariaDB), then C<any>. So C<mysql> is MySQL's alone, and C<mariadb>
347 MariaDB's alone.
348  
349 =back
350  
351 =head1 COLUMN TYPES
352  
353 The types pick a column type per database, for schema building and
354 temporary tables:
355  
356 =over 4
357  
358 =item UUID
359  
360 C<uuid>, or C<binary(16)> on MySQL and on MariaDB before 10.7 (L</UUIDs>).
361  
362 =item JSON
363  
364 C<jsonb> on PostgreSQL 9.4 and later, C<json> elsewhere.
365  
366 =item DateTime
367  
368 C<timestamptz> on PostgreSQL and DuckDB, which holds an instant. On MySQL and
369 MariaDB C<datetime(6)>, and on SQLite C<datetime>: wall clocks with no zone.
370 For an instant there, give C<db_type> (C<timestamp> on MySQL and MariaDB).
371  
372 =back
373  
374 C<build_sql> with no C<version> writes for the newest server. Give the
375 version you run (My::ORM is the one in L</Enums in schema building>):
376  
377 # `token` uuid
378 my $new = My::ORM->build_sql(dialect => 'mariadb');
379  
380 # `token` binary(16): MariaDB 10.6 has no uuid type
381 my $old = My::ORM->build_sql(dialect => 'mariadb', version => '10.6');
382  
383 Booleans are not converted. A C<BOOLEAN> reads back as 1 when true, and as 0
384 when false, except on DuckDB, which gives an empty string. MySQL and MariaDB
385 store it as C<tinyint(1)>, so the scan sees a number there.
386  
387 =head1 TIME ZONES
388  
389 The ORM's C<time_zone> (default C<UTC>) becomes the session time zone on
390 PostgreSQL, MySQL, MariaDB, and DuckDB (L</Session time zone>). SQLite has
391 none.
392  
393 my $ny = DBIx::QuickORM->new(
394 credentials => {
395 dsn => $dsn,
396 user => $user,
397 pass => $pass,
398 },
399 # a floating DateTime written to a timestamp with time zone is taken to be in it
400 time_zone => 'America/New_York',
401 );
402  
403 On MySQL and MariaDB a named zone needs the server's time zone tables
404 (C<mysql_tzinfo_to_sql>). Without them the connection fails with C<Unknown
405 or incorrect time zone>. An offset always works there. DuckDB is the
406 reverse: names only, and an offset fails.
407  
408 my $maria = DBIx::QuickORM->new(
409 credentials => {
410 dsn => $dsn,
411 user => $user,
412 pass => $pass,
413 },
414 # MySQL and MariaDB without time zone tables (DuckDB takes names only)
415 time_zone => '+05:30',
416 );
417  
418 Which columns hold an instant, and the exceptions, are in L</Instants>.
419  
420 =head1 JSON
421  
422 PostgreSQL C<json>:
423  
424 my $cy = $orm->insert(users => {
425 name => 'Cy',
426 prefs => {theme => 'dark'},
427 });
428  
429 # undef: json has no = operator, so the database raises an error ($@)
430 my $compared = eval { $cy->update({name => 'Cy B'}, cas => ['prefs']) };
431 $cy->update({name => 'Cy B'}, cas => ['name']); # compare a plain field instead
432  
433 Compare-and-swap (C<cas_update>, or C<cas> on C<update>, see
434 L<DBIx::QuickORM::Manual::Caching>) compares with C<=>. PostgreSQL C<json>
435 has no C<=> (C<jsonb> does). MySQL takes a text bind compared with a C<JSON>
436 column as a JSON string, not as parsed JSON, so a stored object or array
437 never equals it, and the C<cas> misses and returns undef.
438  
439 MariaDB stores C<JSON> as C<longtext> with a validity check, so autotype
440 claims such a column by name only (C<json> as a word of the name, such as
441 C<prefs_json>). Name the type yourself:
442  
443 my $maria_json = DBIx::QuickORM->new(
444 credentials => {
445 dsn => $dsn,
446 user => $user,
447 pass => $pass,
448 },
449 # MariaDB: a JSON column is longtext to the scan
450 types => {users => {prefs => 'JSON'}},
451 );
452  
453 L<DBD::MariaDB> returns a MySQL C<JSON> column as UTF-8 bytes. The JSON type
454 decodes them, but C<raw_field>, or a C<JSON> column left untyped, sees the
455 bytes.
456  
457 =head1 ERRORS
458  
459 my $ok = eval {
460 $orm->insert(users => {
461 name => 'Dup',
462 email => 'ann@example.com', # taken: Ann's, from RETURNING above
463 });
464 1;
465 };
466 my $err = $@;
467 my $kind = $err->kind; # 'unique_violation' on every database
468  
469 # '23505' on PostgreSQL, '23000' on MySQL and MariaDB, 'S1000' on SQLite and DuckDB
470 my $state = $err->state;
471  
472 # 7 on PostgreSQL, 1062 on MySQL and MariaDB, 2067 on SQLite, 1 on DuckDB
473 my $native = $err->native;
474  
475 Code against C<kind> and C<retriable>, not C<state> or C<native>
476 (L</Error kinds>, L<DBIx::QuickORM::Manual::Errors>).
477  
478 =head1 SQL YOU WRITE
479  
480 # "users", or `users` on MySQL and MariaDB
481 my $q = $orm->connection->dialect->quote_identifier('users');
482 my @rows = $orm->handle(\"SELECT * FROM $q")->all;
483  
484 The ORM quotes every name it writes, and uses the names the scan reports.
485 Use the map's spelling: a quoted name matches only that spelling on most
486 databases (PostgreSQL stores an unquoted C<Users> as C<users>). DuckDB
487 matches names without regard to case, quoted or not.
488  
489 SQLite binds values as text. A column comparison still works, through the
490 column's affinity, but a bound number never compares as a number with an
491 expression such as a count: C<< sql('COUNT(*) > ?', 1) >> in C<having>
492 matches nothing there. Write the number into the SQL, C<sql('COUNT(*) > 1')>,
493 or cast the bind: C<< sql('COUNT(*) > CAST(? AS INTEGER)', $min) >>.
494  
495 A C<having> may name a computed column everywhere (L</A computed column in HAVING>).
496 On MySQL and MariaDB give it a name no grouped column has, since a grouped
497 column of the same name can win.
498  
499 On MySQL and MariaDB, values the ORM writes into SQL (an enum value, a
500 default, a view's bind) are quoted by the connection's handle, which follows
501 the session's SQL mode, C<NO_BACKSLASH_ESCAPES> included. SQL built with no
502 connection (C<build_sql>) escapes with backslashes, as the default mode does,
503 so it is wrong on a server running C<NO_BACKSLASH_ESCAPES>.
504  
505 =head1 BULK INSERTS
506  
507 C<insert_many> puts as many rows in one statement as the dialect's
508 C<bind_limit> allows (L</Bind limits>, L<DBIx::QuickORM::Manual::BulkInsert>).
509  
510 =head1 DUCKDB
511  
512 DuckDB locks its database file for one connection. Close any other handle on
513 the file before the ORM opens it: a second connection in the same process
514 does not see tables the first created.
515  
516 =head1 DIFFERENCES THE ORM HIDES
517  
518 Where the databases differ natively but the ORM behaves the same on all of
519 them. Each entry says what the databases do, then what QuickORM does.
520  
521 =head2 Temporary tables in transactions
522  
523 PostgreSQL, SQLite, and DuckDB undo creating or dropping a temporary table
524 when the transaction rolls back. On MySQL and MariaDB a temporary table's
525 rows roll back, but creating and dropping it do not: C<CREATE TEMPORARY
526 TABLE> and C<DROP TEMPORARY TABLE> stand after a rollback (and do not commit
527 the open transaction). C<CREATE INDEX>, and a C<DROP TABLE> without
528 C<TEMPORARY>, commit it.
529  
530 QuickORM gives every database the transactional behavior. On MySQL and
531 MariaDB it drops a table created in a rolled-back transaction or savepoint
532 itself. A drop inside a transaction hides the table from the map at once,
533 and QuickORM sends the C<DROP> only when the outermost transaction commits.
534 It declares indexes inside C<CREATE TEMPORARY TABLE> and drops with
535 C<DROP TEMPORARY TABLE>, so neither commits the transaction.
536  
537 use DBIx::QuickORM::DSL ':temp';
538  
539 my $scratch = $orm->temp_table(sub { column 'n' => {db_type => 'integer'} });
540  
541 my $txn = $orm->txn;
542 $scratch->drop; # on MySQL and MariaDB the DROP waits for the commit
543 $txn->rollback;
544  
545 my $live = $scratch->is_live; # true on every database: the drop is undone
546  
547 On every database, a name dropped inside a transaction cannot be used for a
548 new temporary table or view until that transaction ends.
549  
550 =head2 Enums in schema building
551  
552 PostgreSQL enums must be named types, created with C<CREATE TYPE ... AS
553 ENUM>. DuckDB has named types and inline C<ENUM(...)>. MySQL and MariaDB have
554 only the inline C<ENUM(...)>, so an enum cannot be named and shared. SQLite
555 has no enums.
556  
557 The schema builder takes a named enum (the DSL's C<enum>) and a column's own
558 values on every database:
559  
560 package My::ORM::Feelings;
561 use DBIx::QuickORM::DSL qw/:table :schema/;
562  
563 table { name 'feelings' };
564  
565 schema {
566 column 'id' => sub { db_type 'integer'; primary_key };
567 column 'mood' => sub { enum 'mood'; not_null };
568 column 'level' => sub { enum [qw/low high/] };
569 column 'token' => sub { type 'UUID' };
570 };
571  
572 package My::ORM;
573 use DBIx::QuickORM::DSL qw/:orm enum/;
574  
575 enum mood => [qw/happy sad/];
576 orm { tables ['My::ORM::Feelings'] };
577  
578 package main;
579  
580 # CREATE TYPE "mood" AS ENUM ('happy', 'sad') before the tables,
581 # CREATE TYPE "feelings_enum_1" AS ENUM ('low', 'high') just before feelings,
582 # then "mood" "mood" NOT NULL and "level" "feelings_enum_1" (DuckDB the same)
583 my $pg = My::ORM->build_sql(dialect => 'postgresql', pretty => 1);
584  
585 # no type: `mood` ENUM('happy', 'sad') NOT NULL and `level` ENUM('low', 'high')
586 my $mysql = My::ORM->build_sql(dialect => 'mysql', pretty => 1);
587  
588 # "mood" text NOT NULL and "level" text, with
589 # CHECK ("mood" IN ('happy', 'sad')) and CHECK ("level" IN ('low', 'high'))
590 my $sqlite = My::ORM->build_sql(dialect => 'sqlite', pretty => 1);
591  
592 A type for a column's own values is named for its table, numbered by the
593 table's columns with values of their own, in column order. On DuckDB the
594 named types are QuickORM's choice, to match PostgreSQL.
595  
596 What stays different: a native enum sorts by its values' order, while
597 C<text> with a C<CHECK> sorts as text. MySQL and MariaDB refuse a value
598 outside the enum only in strict mode (the default C<sql_mode>), and
599 otherwise store an empty string with a warning. QuickORM leaves C<sql_mode>
600 alone.
601  
602 =head2 Enums in temporary tables
603  
604 PostgreSQL needs a named type for an enum column, and DuckDB can use one or
605 an inline C<ENUM(...)>. Neither forbids either in a temporary table. But a
606 type made for the table would outlive it, and a named enum's type may not
607 exist in the database at all (nothing built the schema).
608  
609 So QuickORM makes a temporary table's enum column, named or not, C<text>
610 with a C<CHECK> listing the values on PostgreSQL, DuckDB, and SQLite. No type
611 is created or needed. MySQL and MariaDB get C<ENUM(...)>.
612  
613 my $moods = $orm->temp_table(sub {
614 column 'id' => {db_type => 'integer', primary_key => 1};
615 column 'mood' => sub { enum [qw/happy sad/] };
616 });
617  
618 # PostgreSQL: "mood" text, ... CHECK ("mood" IN ('happy', 'sad'))
619 $moods->handle->insert({id => 1, mood => 'sad'});
620  
621 # undef on every database (in strict mode on MySQL and MariaDB): 'meh' is not one of the values
622 my $ok = eval { $moods->handle->insert({id => 2, mood => 'meh'}); 1 };
623  
624 =head2 Foreign keys of temporary tables
625  
626 PostgreSQL, MariaDB, DuckDB, and recent MySQL refuse a foreign key from a
627 temporary table to an ordinary one. PostgreSQL says "constraints on temporary
628 tables may reference only temporary tables".
629  
630 QuickORM never writes one from the builder. A temporary table's
631 C<references> and C<foreign_key> are links in the ORM's map on every
632 database: C<follow_fk> and joins use them, the database enforces nothing,
633 and C<on_delete> or C<on_update> croaks. A table created from your own
634 C<CREATE> statement keeps whatever constraints that statement declares.
635  
636 =head2 Reading a temporary table back
637  
638 MySQL's catalog tables do not list temporary tables. Recent MariaDB releases
639 list them, with C<TEMPORARY> as their type.
640  
641 QuickORM reads a new temporary table back with C<SHOW COLUMNS> and
642 C<SHOW INDEX> on both, and from each other database's temporary catalog, so
643 its fields, types, and keys are in the map as a scanned table's would be.
644  
645 =head2 Rows written without RETURNING
646  
647 MySQL has no C<RETURNING>. MariaDB has it, but QuickORM does not use its
648 C<UPDATE ... RETURNING>, which leaves out rows that matched without changing
649 (MDEV-41113).
650  
651 QuickORM takes a new key from the given values or the last insert id, and a
652 row fetches any field it lacks when read. It generates a UUID key the
653 database would fill (L<DBIx::QuickORM::Manual::Keys>). C<mark_deleted>
654 selects the keys C<FOR UPDATE> before deleting. L</RETURNING> lists what
655 still differs.
656  
657 =head2 Failed statements in a transaction
658  
659 PostgreSQL and DuckDB refuse every statement after one fails, until the
660 transaction rolls back. MySQL, MariaDB, and SQLite undo only the failed
661 statement, and the transaction goes on.
662  
663 QuickORM marks the transaction failed after any error on every database.
664 Later statements croak, and a commit rolls back instead, then croaks. To go
665 on after a failure, run the work that may fail in a nested transaction.
666  
667 QuickORM also sends C<BEGIN>, C<SAVEPOINT>, C<COMMIT>, and C<ROLLBACK> as
668 SQL on every database, not through DBI's C<begin_work>, whose behavior
669 differs by driver.
670  
671 =head2 Isolation level
672  
673 A transaction's default level is C<read committed> on PostgreSQL and
674 C<repeatable read> on MySQL and MariaDB. PostgreSQL runs C<read uncommitted>
675 as C<read committed>. SQLite transactions are serializable (unless a shared
676 cache turns on C<read_uncommitted>), and DuckDB's use snapshot isolation.
677  
678 QuickORM states C<read committed> for every root transaction on PostgreSQL,
679 MySQL, and MariaDB, unless the ORM or the C<txn> call names another, so they
680 start alike. On SQLite and DuckDB it sends a plain C<BEGIN>.
681  
682 =head2 OFFSET without LIMIT
683  
684 MySQL, MariaDB, and SQLite reject an C<OFFSET> without a C<LIMIT>.
685 PostgreSQL and DuckDB take one.
686  
687 QuickORM adds the largest signed 64-bit integer, 9223372036854775807, as the
688 C<LIMIT> of an offset given alone:
689  
690 # ... LIMIT 9223372036854775807 OFFSET 1, on every database
691 my @rest = $orm->handle('users')->order_by('id')->offset(1)->all;
692  
693 =head2 A computed column in HAVING
694  
695 MySQL and MariaDB take a select alias in C<HAVING>. PostgreSQL rejects it,
696 and SQLite takes a table column of the same name over it.
697  
698 QuickORM sends the alias to MySQL and MariaDB, and writes the computed
699 column's SQL in its place on PostgreSQL, SQLite, and DuckDB
700 (L<DBIx::QuickORM::Manual::Aggregates/HAVING>).
701  
702 =head2 Bind limits
703  
704 The binds one statement may hold: 65535 on PostgreSQL, MySQL, and MariaDB
705 (their protocols' limit), 32766 on SQLite since 3.32.0 and 999 before, and no
706 fixed limit on DuckDB.
707  
708 C<insert_many> splits its rows into statements under the dialect's
709 C<bind_limit>, and runs them in one transaction, so all the rows go in or
710 none. That is 65535 on PostgreSQL, MySQL, and MariaDB, 999 on SQLite (so
711 older libraries work), and 7000 on DuckDB, where bulk inserts ran about 30%
712 slower at 65535.
713  
714 =head2 Error kinds
715  
716 PostgreSQL reports a useful SQLSTATE, MySQL, MariaDB, and SQLite a native
717 code, and DuckDB only a message. A failed C<CHECK> is 3819 on MySQL but 4025
718 on MariaDB.
719  
720 QuickORM maps each to the same C<kind> and C<retriable>. It turns on
721 SQLite's extended result codes, which tell a unique violation from other
722 constraint failures.
723  
724 =head2 Text encoding
725  
726 The drivers hand back text as Perl characters or as UTF-8 bytes, depending
727 on their settings.
728  
729 QuickORM sets each connection up so text goes in and comes out as
730 characters: C<client_encoding> C<UTF8> and C<pg_enable_utf8> on PostgreSQL,
731 C<SET NAMES utf8mb4> on MySQL and MariaDB, the strict Unicode string mode on
732 SQLite, and on DuckDB it encodes and decodes each value itself. The JSON
733 type decodes either.
734  
735 What stays different: SQLite's strict mode croaks on reading text that is
736 not valid UTF-8, and a MySQL C<JSON> column read raw is bytes (L</JSON>).
737  
738 =head2 Session time zone
739  
740 Each server starts a session in its own configured zone. MySQL and MariaDB
741 know a named zone only when the server's time zone tables are loaded.
742  
743 QuickORM sets the session zone to its C<time_zone>, C<UTC> by default. It
744 sends C<UTC> to MySQL and MariaDB as C<+00:00>, which needs no time zone
745 tables. On PostgreSQL it also sets C<DateStyle> to C<ISO, YMD>, the form it
746 parses, whatever the server's setting.
747  
748 =head2 Instants
749  
750 PostgreSQL and DuckDB have C<TIMESTAMP WITH TIME ZONE>. On MySQL and MariaDB
751 C<TIMESTAMP> holds an instant, read and written in the session zone. SQLite
752 stores text.
753  
754 QuickORM treats as instants: C<timestamptz> or C<timestamp with time zone>
755 columns everywhere, and C<TIMESTAMP> on MySQL and MariaDB. It converts a
756 DateTime to the session zone before writing one on MySQL and MariaDB, and on
757 SQLite writes the offset after the time, with a colon, as SQLite's date
758 functions need. Other date columns hold wall clocks.
759  
760 The exceptions: on MySQL and MariaDB a C<TIMESTAMP> in the repeated hour of a
761 daylight saving C<time_zone> may read back an hour off (keep C<time_zone> at
762 C<UTC>, and convert for display with
763 C<< $row->field($name)->datetime->set_time_zone($zone) >>). L<DBD::DuckDB>
764 drops the leading zeros of a fractional second (500 microseconds come back as
765 C<.500>), so such a timestamp key does not find its held row
766 (L<DBIx::QuickORM::Manual::Keys/"TYPED KEYS">). L<DateTime::Format::MySQL>
767 0.08 ignores an offset after fractional seconds when reading text
768 (L<DBIx::QuickORM::Type::DateTime>).
769  
770 =head2 UUIDs
771  
772 MySQL, and MariaDB before 10.7, have no C<uuid> type, so a UUID column is
773 C<binary(16)> there.
774  
775 The UUID type stores the 16 bytes in a C<binary> column and hands back the
776 lower-case 36-character string. Any other column stores and returns the
777 string as given. The row cache keys UUIDs in lower case, but a query binds
778 the spelling given: a native C<uuid> column matches any case, a text column
779 only the stored one. For a text UUID key, a C<format> hint can fix the case
780 (L<DBIx::QuickORM::Role::Type/Field hints>).
781  
782 =head2 SQLite foreign keys
783  
784 SQLite enforces foreign keys only on a connection that asks for it.
785  
786 QuickORM sends C<PRAGMA foreign_keys = ON> on every SQLite connection it
787 opens or is given.
788  
789 =head2 Binary values
790  
791 Each driver needs its own bind type for bytes, and each database its own
792 literal form.
793  
794 QuickORM binds a field of C<binary> affinity, or a C<binary()> marker, with
795 the driver's type (C<bytea> on PostgreSQL, C<SQL_BLOB> elsewhere). A view
796 writes bytes as PostgreSQL's C<'\x...'::bytea>, C<X'...'> on SQLite, MySQL,
797 and MariaDB, or DuckDB's C<'\xAB\xCD'::BLOB>.
798  
799 =head2 Identity columns
800  
801 PostgreSQL numbers a column with an identity, MySQL and MariaDB with
802 C<AUTO_INCREMENT>, SQLite with its rowid, and DuckDB with a sequence.
803  
804 C<< identity => 1 >> writes the right one: C<GENERATED BY DEFAULT AS
805 IDENTITY>, C<AUTO_INCREMENT>, an inline C<integer PRIMARY KEY>, or
806 C<CREATE SEQUENCE> and a C<DEFAULT nextval(...)>. On DuckDB, dropping a
807 temporary table drops its sequences too.
808  
809 =head2 Schema scanning
810  
811 Each database describes its tables in its own catalog, in its own terms.
812  
813 QuickORM reads each into the same map. A PostgreSQL domain keeps its name as
814 the field's type and takes its base type's affinity. A MySQL integer's
815 display width (C<int(11)>) is dropped. A MariaDB default reported as the
816 text C<NULL> counts as none. SQLite's rowid alias is marked as filled by the
817 database. DuckDB's unique indexes join its unique constraints. A SQLite
818 foreign key that names no column on the other table points at its primary
819 key. The scan cache key is per database (the server and session, or the
820 file's path), and an in-memory SQLite or DuckDB database is never cached.
821  
822 =head2 Quoting
823  
824 PostgreSQL, SQLite, and DuckDB quote names with double quotes, MySQL and
825 MariaDB with backticks. A string literal doubles a quote, but MySQL and
826 MariaDB by default escape with a backslash, and with C<NO_BACKSLASH_ESCAPES>
827 double it too.
828  
829 QuickORM quotes and escapes for the dialect in use. On a connection to MySQL
830 or MariaDB it quotes through the handle, so it follows the session's SQL mode
831 (L</SQL YOU WRITE>).
832  
833 =head2 Settings and extensions
834  
835 A session setting is C<SET> on most databases and C<PRAGMA> on SQLite. An
836 extension is C<CREATE EXTENSION> on PostgreSQL, C<INSTALL> then C<LOAD> on
837 DuckDB, and a loadable library on SQLite.
838  
839 The schema builder's C<setting> writes C<SET> or C<PRAGMA>. Its C<extension>
840 writes PostgreSQL's and DuckDB's statements, and croaks on MySQL, MariaDB,
841 and SQLite.
842  
843 =head2 Version numbers
844  
845 PostgreSQL numbers its versions its own way (C<170004> for 17.4). The others
846 give a version string.
847  
848 C<server_version> is PostgreSQL's own number there, and
849 C<major * 1_000_000 + minor * 1_000 + patch> elsewhere (L</ASKING THE DIALECT>).
850  
851 =head2 Forked children
852  
853 A child process that uses or frees a database handle it inherited can break
854 the parent's session.
855  
856 A forked child opens its own connection on first use. On PostgreSQL, MySQL,
857 and MariaDB QuickORM points the inherited socket at C</dev/null>, and since
858 L<DBD::MariaDB> closes the session at exit even so, it disconnects inherited
859 MySQL family handles in an C<END> block after pointing their sockets away.
860  
861 =head2 Cancelling an async query
862  
863 MySQL and MariaDB can stop a running query with C<KILL QUERY> from another
864 connection. PostgreSQL's driver cancels it directly.
865  
866 What QuickORM makes the same: a cancelled query's iterators throw when read.
867 What still differs: on PostgreSQL QuickORM cancels the query, which aborts
868 the transaction it runs in. On MySQL and MariaDB it sends no C<KILL QUERY>:
869 it waits for the result and discards it.
870  
871 =cut
872  
873 1;
874  
875 __END__