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

filter: Statementstmt 100% 8 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 10 / 10 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/DBIx/QuickORM/Manual/DBIC.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Errors.pm »
1 package DBIx::QuickORM::Manual::Dialects;
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.000032';
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 One caveat is C<json>: unlike C<jsonb>, it has no C<=> operator, so
26 compare-and-swap fails on a C<json> column.
27  
28 The ORM reuses prepared statements for its CRUD operations. Behind a pooler
29 in transaction mode, such as PgBouncer, turn off server-side prepares. Set
30 C<< pg_server_prepare => 0 >> in the C<attrs> of C<credentials>, or in the
31 attributes your C<connect> sub passes to C<< DBI->connect >>.
32  
33 =item MariaDB
34  
35 QuickORM does not use C<RETURNING> on MariaDB's C<UPDATE>: MariaDB 13.0.1 added
36 it, but it leaves out rows that matched without changing (MDEV-41113), so it
37 stays off until that is fixed. It declares C<JSON> as
38 C<LONGTEXT> with a validity check, so the scan sees text. Named time zones
39 need the server's time zone tables.
40  
41 =item MySQL
42  
43 MySQL has no C<RETURNING> at all. A C<JSON> value never compares equal to a
44 text bind. Named time zones need the server's time zone tables.
45  
46 =item SQLite
47  
48 SQLite has no C<async> or C<aside> (L<DBIx::QuickORM::Manual::Background>),
49 no transaction isolation levels (L<DBIx::QuickORM::Manual::Transactions>),
50 and no session time zone. It binds values as text, and an in-memory database
51 allows no second connection. Foreign keys are enforced, since the ORM sends
52 C<PRAGMA foreign_keys = ON> on every SQLite connection.
53  
54 =item DuckDB
55  
56 DuckDB has no savepoints, no second connection, no C<async> or C<aside>,
57 and no isolation levels. Errors are classified from their message, and time
58 zones work by name only.
59  
60 =back
61  
62 =head1 SCHEMA
63  
64 The examples use PostgreSQL and this schema:
65  
66 =for highlighter language=sql
67  
68 CREATE TABLE users (
69 id SERIAL PRIMARY KEY,
70 name TEXT NOT NULL,
71 email TEXT UNIQUE,
72 prefs JSON,
73 referred_by INTEGER REFERENCES users (id),
74 created TIMESTAMP NOT NULL DEFAULT now()
75 );
76  
77 CREATE TABLE posts (
78 id SERIAL PRIMARY KEY,
79 user_id INTEGER NOT NULL REFERENCES users (id),
80 title TEXT NOT NULL,
81 views INTEGER NOT NULL DEFAULT 0
82 );
83  
84 =head1 ASKING THE DIALECT
85  
86 =for highlighter language=perl
87  
88 my $dialect = $orm->connection->dialect;
89  
90 # 'PostgreSQL', 'MySQL', 'MariaDB', 'SQLite', or 'DuckDB'
91 my $name = $dialect->name;
92  
93 # 170004 for PostgreSQL 17.4 (its own number), and elsewhere
94 # major * 1_000_000 + minor * 1_000 + patch: 8000036 for MySQL 8.0.36
95 my $version = $dialect->server_version;
96  
97 # branch on a capability, not a name
98 my $whole = $dialect->supports_returning_update ? 'the row' : 'its key';
99  
100 The capabilities: C<supports_returning_insert>, C<supports_returning_update>,
101 C<supports_returning_delete>,
102 C<supports_savepoints>, C<supports_isolation>, C<supports_async>,
103 C<supports_second_connection($dbh)>, C<having_uses_alias>, and
104 C<bind_limit>. MySQL and MariaDB both connect through L<DBD::MariaDB>. The
105 dialect tells them apart by the server's version.
106  
107 =head1 RETURNING
108  
109 With C<RETURNING>, C<insert> and a row's C<update> hand back the written row
110 (its default fields and the fields written, and for an update the fields the
111 row held), so the row object holds them. PostgreSQL, SQLite, and
112 DuckDB have it on every statement. On MariaDB, QuickORM uses it on C<INSERT>
113 and C<DELETE> but not C<UPDATE> (see L</MariaDB> above). MySQL has none.
114  
115 my $ann = $orm->insert(users => {
116 name => 'Ann',
117 email => 'ann@example.com',
118 });
119 $ann->update({name => 'Ann B'});
120  
121 # every field, but on MySQL, and on MariaDB after an update, only id
122 my @have = sort keys %{$ann->row_data};
123  
124 # 'Ann B' everywhere: a field the row lacks is fetched when read
125 my $name = $ann->field('name');
126  
127 Without C<RETURNING> a written row holds only its primary key. A missing
128 field is fetched when first read. C<< $row->fields(@names) >> fetches several
129 in one query. So on MySQL and MariaDB:
130  
131 =over 4
132  
133 =item *
134  
135 C<cas_update> croaks after an update (on MySQL, after an insert too) until
136 the fields it compares are read again: C<refresh>, or C<fields> for just
137 those (L<DBIx::QuickORM::Role::Row>).
138  
139 =item *
140  
141 C<insert> into a table with no primary key must be called in void context or
142 with C<< as_given => 1 >> (MySQL).
143  
144 =item *
145  
146 C<insert_many> needs every row to carry its whole primary key to return the
147 rows, unless called with C<< count => 1 >> or in void context (MySQL, see
148 L<DBIx::QuickORM::Manual::BulkInsert>).
149  
150 =item *
151  
152 C<< $h->delete(mark_deleted => 1) >> runs a C<SELECT ... FOR UPDATE> of the
153 keys, then the C<DELETE>, holding row locks until the transaction ends
154 (MySQL, see L<DBIx::QuickORM::Handle/Writing>).
155  
156 =item *
157  
158 A UUID key the database would fill is generated by the ORM instead, since it
159 could not be read back (MySQL, see L<DBIx::QuickORM::Manual::Keys>). Only a
160 type with C<generate_key_value> does this, so a DateTime key is not generated.
161  
162 =back
163  
164 =head1 TRANSACTIONS
165  
166 DuckDB has no savepoints, so a transaction inside another croaks there.
167 C<insert_many> and C<find_or_insert> inside a transaction use that
168 transaction as it is (on the other databases they take a savepoint), so a
169 failed insert leaves it unusable.
170  
171 my $nested = eval {
172 $orm->txn(sub {
173 # a savepoint. DuckDB has none, so this croaks
174 $orm->txn(sub { $orm->insert(users => {name => 'Bob'}) });
175 });
176 1;
177 };
178  
179 Every root transaction states its isolation level on PostgreSQL, MySQL, and
180 MariaDB: C<read committed> unless the ORM or the C<txn> call names another,
181 or names C<server> for a plain C<BEGIN>.
182 PostgreSQL sends one C<BEGIN ISOLATION LEVEL ...>. The MySQL family sends
183 C<SET TRANSACTION ISOLATION LEVEL ...> then C<BEGIN>. SQLite and DuckDB have
184 no levels to set: they get a plain C<BEGIN>, and a level croaks
185 (L<DBIx::QuickORM::Manual::Transactions/ISOLATION>).
186  
187 Nothing about isolation is set when a connection opens. SQLite's
188 C<PRAGMA foreign_keys = ON> is: it is a setting of the connection, not of a
189 transaction, and SQLite enforces foreign keys only once a connection asks.
190 The ORM sends it on every SQLite connection it opens or is given.
191  
192 With C<binlog_format=STATEMENT>, the MySQL family refuses writes at C<read
193 committed>: switch the server to C<ROW> or C<MIXED>, or give the ORM
194 C<< isolation => 'repeatable read' >>.
195  
196 =head1 BACKGROUND QUERIES AND FORKING
197  
198 C<async> and C<aside> need PostgreSQL, MySQL, or MariaDB. C<aside>,
199 C<forked>, and a forked child using the ORM at all need a second connection
200 to the same data: not DuckDB, not an in-memory SQLite database, and not an
201 ORM given a C<dbh>.
202  
203 my $memory = DBIx::QuickORM->new(
204 connect => sub { DBI->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1}) },
205 );
206  
207 # croaks: no second connection can reach this SQLite database
208 my $ok = eval { $memory->handle(\'SELECT 1 AS one')->forked->iter; 1 };
209  
210 C<can_async>, C<can_aside>, and C<can_forked> say whether a mode can run
211 here. C<maybe_async> and the like switch to the mode when it can run, and
212 leave the handle's mode alone otherwise.
213  
214 A forked child reconnects on its first use of the ORM, through C<connect> or
215 C<credentials>, and leaves the parent's session alone. Nothing to do on your
216 side. L<DBIx::QuickORM::Manual::Background> has the details.
217  
218 =head1 TIME ZONES
219  
220 The ORM's C<time_zone> (default C<UTC>) becomes the session time zone on
221 PostgreSQL, MySQL, MariaDB, and DuckDB. SQLite has none.
222  
223 my $ny = DBIx::QuickORM->new(
224 credentials => {
225 dsn => $dsn,
226 user => $user,
227 pass => $pass,
228 },
229 # a floating DateTime written to a timestamp with time zone is taken to be in it
230 time_zone => 'America/New_York',
231 );
232  
233 On MySQL and MariaDB a named zone needs the server's time zone tables
234 (C<mysql_tzinfo_to_sql>). Without them the connection fails with C<Unknown
235 or incorrect time zone>. An offset always works, and C<UTC> is sent as
236 C<+00:00>:
237  
238 my $maria = DBIx::QuickORM->new(
239 credentials => {
240 dsn => $dsn,
241 user => $user,
242 pass => $pass,
243 },
244 # MySQL and MariaDB without time zone tables (DuckDB takes names only)
245 time_zone => '+05:30',
246 );
247  
248 Which column holds an instant (a point in time, with a zone) differs too:
249 C<TIMESTAMP WITH TIME ZONE> on PostgreSQL and DuckDB, C<TIMESTAMP> on MySQL
250 and MariaDB (C<DATETIME> is zoneless there). SQLite stores the text it is
251 given, and its C<CURRENT_TIMESTAMP> is UTC whatever the zone.
252  
253 On MySQL and MariaDB a C<TIMESTAMP> in the repeated hour of a daylight saving
254 C<time_zone> (when clocks go back) is ambiguous and may read back an hour off.
255 To get exact instants, run in UTC: keep C<time_zone> at its default C<UTC>
256 (or pass C<< time_zone => 'UTC' >>), and convert only for display, with
257 C<< $row->field($name)->datetime->set_time_zone($zone) >>.
258  
259 L<DBD::DuckDB> drops the leading zeros of a fractional second on every
260 timestamp it returns (500 microseconds come back as C<.500>, another
261 instant), so a timestamp key with such a fraction does not find its held row
262 (L<DBIx::QuickORM::Manual::Keys/"TYPED KEYS">). See
263 L<DBIx::QuickORM::Type::DateTime>.
264  
265 =head1 JSON
266  
267 PostgreSQL C<json>:
268  
269 my $cy = $orm->insert(users => {
270 name => 'Cy',
271 prefs => {theme => 'dark'},
272 });
273  
274 # undef: json has no = operator, so the database raises an error ($@)
275 my $compared = eval { $cy->update({name => 'Cy B'}, cas => ['prefs']) };
276 $cy->update({name => 'Cy B'}, cas => ['name']); # compare a plain field instead
277  
278 Compare-and-swap (C<cas_update>, or C<cas> on C<update>, see
279 L<DBIx::QuickORM::Manual::Caching>) compares with C<=>,
280 SQL's equality operator. PostgreSQL C<json> has no C<=> (C<jsonb> does).
281 MySQL compares a C<JSON> column with a text bind as JSON values, and an
282 object or array never equals a string, so a C<cas> on one misses and returns
283 undef. MariaDB declares C<JSON> as C<LONGTEXT> with a check, so the scan sees
284 C<longtext>: autotype claims such a column by name only (C<json> as a word of
285 the name, such as C<prefs_json>), so name the type yourself:
286  
287 my $maria_json = DBIx::QuickORM->new(
288 credentials => {
289 dsn => $dsn,
290 user => $user,
291 pass => $pass,
292 },
293 # MariaDB: a JSON column is longtext to the scan
294 types => {users => {prefs => 'JSON'}},
295 );
296  
297 =head1 ERRORS
298  
299 my $ok = eval {
300 $orm->insert(users => {
301 name => 'Dup',
302 email => 'ann@example.com', # taken: Ann's, from RETURNING above
303 });
304 1;
305 };
306 my $err = $@;
307 my $kind = $err->kind; # 'unique_violation' on every database
308  
309 # '23505' on PostgreSQL, '23000' on MySQL and MariaDB, 'S1000' on SQLite and DuckDB
310 my $state = $err->state;
311  
312 # 7 on PostgreSQL, 1062 on MySQL and MariaDB, 2067 on SQLite, 1 on DuckDB
313 my $native = $err->native;
314  
315 The kinds are the same everywhere: code against C<kind> and C<retriable>,
316 not C<state> or C<native>. PostgreSQL reports a useful SQLSTATE, SQLite and
317 the MySQL family a native code, and DuckDB neither, so its kind comes from
318 the message (L<DBIx::QuickORM::Manual::Errors>).
319  
320 =head1 SQL YOU WRITE
321  
322 # "users", or `users` on MySQL and MariaDB
323 my $q = $orm->connection->dialect->quote_identifier('users');
324 my @rows = $orm->handle(\"SELECT * FROM $q")->all;
325  
326 SQLite binds values as text. A column comparison still works, through the
327 column's affinity, but a bound number never compares as a number with an
328 expression such as a count: C<< sql('COUNT(*) > ?', 1) >> in C<having>
329 matches nothing there. Write the number into the SQL, C<sql('COUNT(*) > 1')>,
330 or cast the bind: C<< sql('COUNT(*) > CAST(? AS INTEGER)', $min) >>. The
331 same holds for a C<having> that names a computed column.
332  
333 A C<having> may name a computed column on every database. MySQL and MariaDB
334 get the name (C<having_uses_alias>). Elsewhere the ORM writes the column's
335 SQL there, since PostgreSQL rejects the name and SQLite lets a table column
336 of the same name win (L<DBIx::QuickORM::Manual::Aggregates/HAVING>).
337  
338 =head1 BULK INSERTS
339  
340 C<insert_many> puts as many rows in one statement as the dialect's
341 C<bind_limit> allows. PostgreSQL, MySQL, and MariaDB allow 65535 binds,
342 DuckDB 7000, and SQLite 999 (L<DBIx::QuickORM::Manual::BulkInsert>).
343  
344 =head1 DUCKDB
345  
346 DuckDB locks its database file for one connection. Close any other handle on
347 the file before the ORM opens it: a second connection in the same process
348 does not see tables the first created.
349  
350 =cut
351  
352 2 1;
353  
354 __END__
« blib/lib/DBIx/QuickORM/Manual/DBIC.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Errors.pm »