blib/lib/DBIx/QuickORM/Manual/TempTables.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::TempTables;
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::TempTables - Temporary tables and views, and the views the scan finds, by example.
14  
15 =head1 DESCRIPTION
16  
17 The ORM can create temporary tables and views and use them like any table.
18 They belong to the connection that made them, and every database treats them
19 the same way:
20  
21 =over 4
22  
23 =item *
24  
25 A rollback of the transaction that created one removes it.
26  
27 =item *
28  
29 A rollback of the transaction that dropped one brings it back.
30  
31 =item *
32  
33 Otherwise it lasts until dropped, or until the connection ends.
34  
35 =back
36  
37 MySQL and MariaDB have no temporary views, so C<temp_view> croaks there.
38  
39 The scan also finds the database's own views, which you query like tables.
40 Give a view a primary key to use C<find> and row methods on it.
41  
42 =head1 SCHEMA
43  
44 The examples use PostgreSQL and this schema:
45  
46 =for highlighter language=sql
47  
48 CREATE TABLE users (
49 id SERIAL PRIMARY KEY,
50 name TEXT NOT NULL,
51 email TEXT UNIQUE,
52 prefs JSON,
53 referred_by INTEGER REFERENCES users (id),
54 created TIMESTAMP NOT NULL DEFAULT now()
55 );
56  
57 CREATE TABLE posts (
58 id SERIAL PRIMARY KEY,
59 user_id INTEGER NOT NULL REFERENCES users (id),
60 title TEXT NOT NULL,
61 views INTEGER NOT NULL DEFAULT 0
62 );
63  
64 The examples also use this view, a user's id in C<$id>, and the id of one
65 of that user's posts in C<$post_id>:
66  
67 CREATE VIEW active_users AS SELECT id, name FROM users;
68  
69 =head1 TEMPORARY TABLES
70  
71 =for highlighter language=perl
72  
73 use DBIx::QuickORM::DSL ':temp';
74  
75 my $scores = $orm->temp_table(sub {
76 column 'user_id' => sub { db_type 'integer'; primary_key; references 'users', 'id' };
77 column 'score' => {db_type => 'integer'};
78 column 'token' => sub { type 'UUID' }; # the type picks the column type
79 add_index 'score';
80 });
81  
82 $scores->handle->insert({user_id => $id, score => 10});
83 my $user = $orm->follow_fk($scores->name, {user_id => $id}, 'users')->only;
84  
85 The block describes the table with the column keywords of schema building
86 (L<DBIx::QuickORM::Manual::SchemaBuilding>), which C<:temp> imports (see
87 L<DBIx::QuickORM::DSL/":temp">). When it returns, the table is created and
88 read back from the database, and a L<DBIx::QuickORM::Source::Table::Temp>
89 is returned. Its C<name> is the table's name, made up unless you pass
90 C<< name => ... >>.
91  
92 The keywords act on the block's L<DBIx::QuickORM::SchemaBuilder::Table::Temp>,
93 which the block also gets, for method calls. A temporary table's column is
94 also its field, so C<add_field> is another name for C<add_column>:
95  
96 my $ranks = $orm->temp_table(sub {
97 my $t = shift;
98 $t->add_column('user_id', {db_type => 'integer', primary_key => 1});
99 $t->add_field('rank', {db_type => 'integer'});
100 });
101  
102 The keywords stay in the package, so in a module put
103 C<no DBIx::QuickORM::DSL;> after the last use: calls before it still work,
104 and the keywords do not remain as methods. C<:temp> goes in a C<use> of its
105 own, after any DSL blocks in the package.
106  
107 =head2 From a query
108  
109 my $busy = $orm->temp_table(
110 $orm->handle('posts')->where({views => {'>' => 100}}),
111 pk => ['id'],
112 );
113 my $mine = $orm->temp_table(\['SELECT id, title FROM posts WHERE user_id = ?', $id], name => 'mine');
114  
115 A handle, or a C<SELECT> as C<\[$sql, @binds]>, creates the table from the
116 query's rows. Wrap a C<SELECT> that way even with no binds: a plain C<\$sql>
117 means a whole C<CREATE TEMPORARY TABLE> statement.
118  
119 The database works out the new columns from the query, and their types may
120 not match the source's (SQLite keeps few). It copies no key. C<pk> names the
121 fields that identify a row, so the ORM can cache rows and C<find> them. The
122 database does not enforce it.
123  
124 To choose the columns and keys yourself, describe the table and return what
125 fills it:
126  
127 my $staged = $orm->temp_table(sub {
128 column 'id' => {db_type => 'integer', primary_key => 1};
129 column 'title' => {db_type => 'text'};
130 $orm->handle('posts')->fields(['id', 'title']);
131 });
132  
133 A block that returns a handle, or C<\[$sql, @binds]>, fills the table from
134 it. Anything else it returns is ignored. C<fill> does the same anywhere in
135 the block, as a keyword or a method (C<< $t->fill(...) >>).
136  
137 From a handle, the columns match by name, so every field the handle
138 selects must be a column of the table (a table handle's C<fields> always
139 includes its primary key). From C<\[$sql, @binds]>, columns match by
140 position, in the order the columns were added.
141  
142 =head2 Kept on a handle
143  
144 my $h = $orm->handle('posts')->where({views => 0});
145 my $t = $h->temp_table(pk => ['id']); # creates it
146 my $same = $h->temp_table; # the same object
147  
148 $t->drop;
149 $t = $h->temp_table->is_live ? $h->temp_table : $h->temp_table(rebuild => 1);
150  
151 A handle keeps the temporary table (or view, with C<temp_view>) it made, and
152 gives that object back, even once the table is gone. An object always refers
153 to the table it was made for, never to a later one with the same name.
154 C<< rebuild => 1 >> makes a new table the same way.
155  
156 A new handle from a modifier, such as C<where> or C<limit>, does not keep the
157 old handle's table. A handle in a background mode (C<async>, C<aside>, or
158 C<forked>) croaks: C<sync> gives a copy without one.
159  
160 =head2 Column types
161  
162 A column's type comes from the first of:
163  
164 =over 4
165  
166 =item *
167  
168 C<db_type 'varchar(20)'>, as written.
169  
170 =item *
171  
172 C<< db_type {postgresql => ..., any_mysql => ..., sqlite => ..., duckdb => ...} >>,
173 keyed by dialect: C<mysql> and C<mariadb> each alone, C<any_mysql> for both,
174 C<any> for every database, the exact dialect first.
175  
176 =item *
177  
178 The C<type>'s choice. UUID is C<uuid>, or C<binary(16)> on MySQL and on
179 MariaDB before 10.7. JSON is C<jsonb> on PostgreSQL 9.4 and later, C<json>
180 elsewhere. DateTime is C<timestamptz> on PostgreSQL and DuckDB,
181 C<datetime(6)> on MySQL and MariaDB, and C<datetime> on SQLite.
182  
183 =back
184  
185 Otherwise the build croaks.
186  
187 An enum column holds one of its values:
188  
189 my $moods = $orm->temp_table(sub {
190 column 'user_id' => {db_type => 'integer', primary_key => 1};
191 column 'mood' => sub { enum [qw/happy sad/]; not_null };
192 });
193  
194 It is C<text> with a C<CHECK> on PostgreSQL, DuckDB, and SQLite, and an
195 C<ENUM('happy', 'sad')> column on MySQL and MariaDB. A type created for it
196 would outlive the table, so none is. In an ORM class, C<enum 'mood'> uses
197 one of its named enums the same way.
198  
199 =head2 Foreign keys
200  
201 my $teams = $orm->temp_table(sub {
202 column 'id' => {db_type => 'integer', primary_key => 1};
203 column 'name' => {db_type => 'text'};
204 }, name => 'teams');
205  
206 my $roster = $orm->temp_table(sub {
207 column 'user_id' => sub { db_type 'integer'; primary_key; references 'users', 'id' };
208 column 'team_id' => sub { db_type 'integer'; references 'teams', 'id' };
209 }, name => 'roster');
210  
211 $teams->handle->insert({id => 1, name => 'Blue'});
212 $roster->handle->insert({user_id => $id, team_id => 1});
213  
214 my $entry = $orm->find(roster => $id);
215 my $member = $entry->follow_fk('users')->only; # an ordinary table
216 my $team = $entry->follow_fk('teams')->only; # another temporary table
217 my @pairs = $orm->handle('roster')->join('teams')->all;
218  
219 C<references $table, $column> adds a foreign key to the ORM's map of the
220 database, from this column to that table's column (the same name when not
221 given), and C<< foreign_key \@columns => {table => $table} >> one over
222 several columns. C<follow_fk> and joins use it as they would a key the scan
223 found, in either direction. The other table may be an ordinary one or
224 another temporary table made earlier.
225  
226 The database is not told, so it enforces nothing: a row may name a team that
227 does not exist. Most databases refuse a real foreign key from a temporary
228 table to an ordinary one, so the ORM never writes one. With no database key
229 to act, C<on_delete> and C<on_update> croak.
230  
231 =head2 Identity and generated columns
232  
233 C<identity> makes the database number a column: an identity on
234 PostgreSQL 10 and later, C<AUTO_INCREMENT> on MySQL and MariaDB (the column
235 must be a key), the rowid on SQLite (only for a sole C<integer> primary key),
236 and a temporary sequence on DuckDB.
237  
238 C<generated \'score * 2'> computes a column from an SQL expression.
239 DuckDB computes it on read, the others store it, and PostgreSQL needs 12 or
240 later.
241  
242 =head1 TEMPORARY VIEWS
243  
244 my $quiet = $orm->temp_view($orm->handle('posts')->where({views => 0}));
245 my @titles = map { $_->field('title') } $quiet->handle->all;
246  
247 my $named = $orm->temp_view(
248 \['SELECT id, title FROM posts WHERE user_id = ?', $id],
249 name => 'by_author',
250 pk => ['id'],
251 );
252 my $post = $orm->find(by_author => $post_id);
253  
254 C<temp_view> takes C<\$sql>, C<\[$sql, @binds]>, or a handle that has no
255 background mode. A view stores its query and reads the source tables each
256 time, while a temporary table made from a query stores the rows it selected
257 once.
258  
259 A view cannot hold placeholders, so the binds are written into it as
260 literals: the view keeps the values it was created with. C<pk> gives the
261 view a primary key, as C<pks> does for a scanned view.
262  
263 =head1 LIFETIME
264  
265 my $again = $orm->temp($scores->name);
266 $again->drop;
267  
268 my @names = $orm->temp_tables; # what is left, sorted by name
269  
270 The connection keeps each temporary table or view until it ends, so losing
271 the L<DBIx::QuickORM::Source::Table::Temp> loses nothing: C<temp> gives a new object for a
272 name, and C<temp_tables> lists the names. Nothing is dropped when an object
273 goes out of scope. In a long-running process, drop what you no longer need,
274 views before the tables they read.
275  
276 After one ends, C<handle> and C<drop> on its object croak saying why, and
277 C<is_live> is false. C<< $orm->handle($name) >> croaks saying why too, and so
278 does a handle made before it ended, even when a newer table has taken the
279 name.
280  
281 A forked child cannot use the parent's temporary tables and views. It opens
282 its own connection where it can (not with a given C<dbh>, an in-memory
283 SQLite database, or DuckDB). C<aside> and C<forked> queries run on a second
284 connection, so they croak on a temporary table or view.
285  
286 =head1 TRANSACTIONS
287  
288 my $txn = $orm->txn;
289 my $t = $orm->temp_table(sub { column 'n' => {db_type => 'integer'} });
290 $txn->rollback;
291 my $live = $t->is_live; # false: the rollback removed the table, on every database
292  
293 A rollback restores the temporary tables and views that existed when its
294 transaction began. One created and dropped inside it stays gone. A savepoint
295 works the same way.
296  
297 On MySQL and MariaDB a rollback does not undo creating or dropping a
298 temporary table, so the ORM does it: it drops a table created in the rolled
299 back transaction, and holds back a drop until the outermost transaction
300 commits.
301  
302 On every database, a name dropped inside a transaction cannot be used for a
303 new temporary table or view until that transaction ends.
304  
305 =head1 VIEWS IN THE SCAN
306  
307 my $orm = DBIx::QuickORM->new(
308 credentials => {dsn => $dsn, user => $user, pass => $pass},
309 pks => {active_users => ['id']},
310 );
311  
312 The scan finds the database's views (and PostgreSQL's materialized views),
313 which then work as tables for handles, joins, and aggregates. A view has no
314 primary key unless C<pks> (or C<pk> in a class's C<table> block) gives it
315 one. With a key, its rows are cached, and C<find> and the row methods
316 (C<update>, C<delete>, C<refresh>) work. Whether a write through a view
317 succeeds is up to the database.
318  
319 The cache clears rows by table name. A write to a table does not clear rows
320 read through a view of it, and a write through a view does not clear rows
321 read from its tables. Refresh rows that must be current.
322  
323 =head1 CAVEATS
324  
325 =over 4
326  
327 =item *
328  
329 Dropping a temporary table a temporary view reads does what the database
330 does: PostgreSQL refuses, SQLite and DuckDB leave a view that fails when
331 used. Drop the view first.
332  
333 =item *
334  
335 C<add_index> takes fields, and optionally a C<name>, C<unique>, and C<using>
336 (the index type, on PostgreSQL and MySQL only). It has no partial or
337 expression indexes.
338  
339 =item *
340  
341 Each C<?> in a view's SQL text is taken for a placeholder, so SQL with a
342 question mark inside a string cannot be used in C<temp_view>. A question mark
343 inside a bind value is fine.
344  
345 =back
346  
347 =cut
348  
349 1;
350  
351 __END__