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