blib/lib/DBIx/QuickORM/Manual/SchemaBuilding.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::SchemaBuilding;
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::SchemaBuilding - Write the database's tables in code, and create them or get their SQL, by example.
14  
15 =head1 DESCRIPTION
16  
17 Schema building creates a new database's tables from definitions in your
18 table classes, or gives the SQL that would. It is for setting up databases,
19 and for anyone who would rather not write schema SQL by hand.
20  
21 The database stays the source of truth:
22  
23 =over 4
24  
25 =item *
26  
27 After the tables exist, the ORM reads them from the database like any
28 other, by its usual scan.
29  
30 =item *
31  
32 An ORM over a database that already exists never uses the definitions. Only
33 an offline ORM (see L</OFFLINE>) maps them instead of a database.
34  
35 =item *
36  
37 A C<schema> block does not run when its class loads. It runs only when
38 schema building needs it, once, so startup is no slower for it.
39  
40 =back
41  
42 =head1 DEFINING TABLES
43  
44 A table class imports C<:schema> next to C<:table>, and describes its table
45 in a C<schema> block, one C<column> at a time:
46  
47 =for highlighter language=perl
48  
49 package My::ORM::Orgs;
50 use DBIx::QuickORM::DSL qw/:table :schema/;
51  
52 table { name 'orgs' };
53  
54 schema {
55 column 'id' => sub { db_type 'integer'; primary_key; identity };
56 column 'name' => sub { db_type 'text'; not_null; unique };
57 };
58  
59 package My::ORM::Users;
60 use DBIx::QuickORM::DSL qw/:table :schema/;
61  
62 table { name 'users' };
63  
64 schema {
65 column 'id' => sub { db_type 'integer'; primary_key; identity };
66 column 'org_id' => sub { db_type 'integer'; not_null; references 'orgs', 'id', {on_delete => 'cascade'} };
67 column 'email' => sub { db_type 'text'; check \"email LIKE '%@%'"; indexed };
68 column 'level' => {db_type => 'integer', default => 1};
69 };
70  
71 package My::ORM;
72 use DBIx::QuickORM::DSL qw/:orm/;
73  
74 orm { tables [qw/My::ORM::Orgs My::ORM::Users My::ORM::Audit My::ORM::ActiveUsers/] };
75  
76 Schema building speaks of columns, the ORM of fields: a column defined here
77 is a field of the table once the ORM scans it.
78  
79 =head2 Columns
80  
81 A column takes a block of column keywords, a hashref of the same as keys, or
82 SQL for everything after its name:
83  
84 column 'id' => sub { db_type 'integer'; primary_key; identity };
85 column 'email' => {db_type => 'citext', not_null => 1, unique => 1};
86 column 'note' => \'text COLLATE "C" NOT NULL';
87  
88 In the hashref, a keyword that takes no arguments takes a true value, and
89 C<references> takes its arguments as an arrayref:
90 C<< references => ['orgs', 'id', {on_delete => 'cascade'}] >>.
91  
92 =over 4
93  
94 =item C<db_type $type>: the column's type as the database spells it.
95  
96 =item C<type $type>: the field's type class in the ORM, as C<type> in a C<table> block.
97  
98 =item C<not_null>, C<primary_key>, C<identity>, C<unique>, C<indexed>.
99  
100 =item C<default $value>, C<check \$sql>, C<generated \$sql>, C<collate $name>.
101  
102 =item C<references $table, $column, {on_delete => ..., on_update => ...}>: a foreign key.
103  
104 =item C<enum $name> or C<enum \@values>: see L</ENUMS>.
105  
106 =back
107  
108 The column keywords are the options of
109 L<DBIx::QuickORM::SchemaBuilder::Table>'s C<add_column>, which describes each.
110 The block also gets that builder as its argument, for method calls:
111  
112 schema {
113 my $t = shift;
114 $t->add_column('id', {db_type => 'integer', primary_key => 1});
115 };
116  
117 =head2 Constraints
118  
119 Outside a column, the table's own constraints take what they apply to, then
120 an optional hashref of options:
121  
122 schema {
123 column 'user_id' => {db_type => 'integer'};
124 column 'org_id' => {db_type => 'integer'};
125 column 'role' => {db_type => 'text'};
126  
127 primary_key ['user_id', 'org_id'];
128 unique ['org_id', 'role'] => {name => 'one_role_per_org'};
129 check \"role <> ''" => {name => 'role_given'};
130 foreign_key ['user_id', 'org_id'] => {table => 'memberships', on_delete => 'cascade'};
131 };
132  
133 C<references> without a column, and C<foreign_key> without C<columns>, point
134 at the other table's columns of the same names. A foreign key's
135 C<on_delete> and C<on_update> are each C<cascade>, C<set null>,
136 C<set default>, C<restrict>, or C<no action>. DuckDB has no foreign key
137 actions, so it croaks for them.
138  
139 =head2 Indexes
140  
141 An index comes from C<indexed> on a column, named for the table and column,
142 or C<add_index> over one or several columns (see
143 L<DBIx::QuickORM::SchemaBuilder::Table>). Both take per-dialect variants:
144 an options hash, undef for no index there, or the whole statement as a
145 reference to SQL. A dialect without an entry gets the plain index, since an
146 index is never required for the table to work. C<using> takes an index
147 type, or a reference to everything after C<USING>, for what options cannot
148 say:
149  
150 schema {
151 column 'user_id' => {db_type => 'integer'};
152 column 'title' => {db_type => 'text'};
153 column 'created' => sub { db_type 'timestamp'; indexed };
154 column 'body' => sub {
155 db_type 'text';
156 indexed {
157 postgresql => {using => \'gin (to_tsvector(\'english\', body))'},
158 any_mysql => {using => \'BTREE (body(100))'},
159 sqlite => undef,
160 };
161 };
162 add_index ['user_id', 'created'];
163 add_index ['user_id', 'title'] => {name => 'posts_user_title', unique => 1};
164 add_index 'title' => {name => 'posts_title_lower', dialect => {postgresql => \'CREATE INDEX posts_title_lower ON posts (lower(title))', any => undef}};
165 };
166  
167 The ORM does not check index SQL: a mistake is the database's to report,
168 and a failed build names the statement. On MySQL and MariaDB the indexes go
169 inside C<CREATE TABLE>, except whole statements, which follow it.
170 Temporary tables take index options and C<using> SQL, not whole
171 statements: on MySQL a C<CREATE INDEX> would commit the transaction.
172  
173 =head2 Per-database values
174  
175 Anything that differs per database is keyed by dialect: C<postgresql>,
176 C<mysql>, C<mariadb>, C<sqlite>, C<duckdb>, C<any_mysql> (MySQL and
177 MariaDB), or C<any> (every database). The exact dialect wins, then
178 C<any_mysql>, then C<any>, so C<any> serves as a fallback and C<mysql> means
179 MySQL alone. C<db_type> and C<collate> take a hash of them, and
180 C<schema_sql> and C<view_sql> take C<< dialect => $sql >> pairs.
181  
182 =head2 Column types per database
183  
184 C<db_type> may give one type per database. A column with a C<type> may
185 leave the column type to it:
186  
187 column 'body' => {db_type => {postgresql => 'text', any_mysql => 'longtext', any => 'text'}};
188 column 'token' => sub { type 'UUID' };
189  
190 =head2 Collation
191  
192 C<collate> sets a column's collation, as one name or one per database, like
193 C<db_type>. Collation names differ on every database, so a portable
194 definition gives one for each:
195  
196 column 'name' => {db_type => 'text', collate => {postgresql => 'C', any_mysql => 'utf8mb4_bin', sqlite => 'NOCASE', duckdb => 'nocase'}};
197  
198 =over 4
199  
200 =item PostgreSQL
201  
202 The names the server knows: C<C>, C<POSIX>, and the system or ICU locales
203 (C<en_US.utf8>, C<en-US-x-icu>). C<SELECT collname FROM pg_collation> lists
204 them. The ORM quotes the name.
205  
206 =item MySQL and MariaDB
207  
208 A collation of the column's character set, such as C<utf8mb4_bin> or
209 C<utf8mb4_unicode_ci>. C<SHOW COLLATION> lists them. Give the character set
210 in the type when the server's default differs:
211 C<< db_type => 'varchar(50) CHARACTER SET utf8mb4' >>.
212  
213 =item SQLite
214  
215 C<BINARY> (the default), C<NOCASE>, or C<RTRIM>.
216  
217 =item DuckDB
218  
219 C<nocase>, C<noaccent>, C<nfc>, and the ICU locales its C<icu> extension
220 adds.
221  
222 =back
223  
224 =head2 Tables as SQL
225  
226 A table may be its SQL instead, with C<schema_sql>, per dialect. Building on
227 a dialect it gives nothing for croaks, and an undef entry builds without the
228 table there. C<depends> names the tables it references, so they are created
229 first:
230  
231 package My::ORM::Audit;
232 use DBIx::QuickORM::DSL qw/:table :schema/;
233  
234 table { name 'audit'; elective };
235  
236 schema_sql postgresql => 'CREATE TABLE audit (id bigserial PRIMARY KEY, user_id integer REFERENCES users (id), at timestamptz DEFAULT now())',
237 depends => ['users'];
238 schema_sql any_mysql => 'CREATE TABLE audit (id bigint AUTO_INCREMENT PRIMARY KEY, user_id integer, at timestamp DEFAULT CURRENT_TIMESTAMP)';
239 schema_sql any => undef; # no audit table elsewhere
240  
241 Each call's C<depends> covers its own dialects, so several calls let them
242 differ. A dialect given in two calls croaks.
243  
244 An undef entry needs C<elective> in the C<table> block: the table may be
245 missing from a database, so C<new> leaves it out instead of croaking. Any
246 table class may say C<elective>, such as one for a table another
247 application creates. Without it, a table class whose table the database
248 lacks makes C<new> croak, which catches a misspelled name.
249  
250 =head1 ENUMS
251  
252 Enums are defined outside any block, with C<enum>, for the ORM class: the
253 nearest package in the module's name that is one (loaded first if it is not
254 yet), or the one given first. A module of them is the usual place:
255  
256 package My::ORM::Enums;
257 use DBIx::QuickORM::DSL 'enum';
258  
259 enum mood => [qw/happy sad/];
260 enum status => [qw/open closed/]; # or enum 'My::ORM', status => [...]
261  
262 1;
263  
264 Without a C<tables> list, modules directly under the ORM class's namespace
265 load with its table classes, so this one needs nothing more. Otherwise load
266 it before building. A column names an enum in place of a type, or gives
267 values for one of its own:
268  
269 column 'mood' => sub { enum 'mood'; not_null; default 'happy' };
270 column 'level' => sub { enum [qw/low high/] };
271  
272 A named enum is a type on PostgreSQL and DuckDB, created before the tables,
273 only when a column uses it. A column's own enum is a type named for its
274 table (C<users_enum_1>), created just before the table. On MySQL and
275 MariaDB either is C<ENUM('happy', 'sad')>, and on SQLite C<text> with a
276 C<CHECK>. Defining one name again with the same values is fine, with other
277 values it croaks. Each ORM class has its own enums: another's are reached
278 by naming it, C<enum 'Other::ORM', 'mood'>.
279  
280 C<enum_sql> gives the named enums' statements alone:
281  
282 my $sql = My::ORM->enum_sql(dialect => 'postgresql');
283  
284 =head1 VIEWS
285  
286 A view class imports C<:view> in place of C<:table> and has a C<view> block
287 in place of a C<table> block: the same keywords, and a promise that the
288 class names a view (C<new> croaks when the database has a table by that
289 name). Its C<schema> block gives the query with C<view_sql>, per dialect,
290 with the rules of C<schema_sql>, and the tables and views it reads in
291 C<depends>. Views are created after every table, each after the views it
292 reads.
293  
294 What a scan cannot tell about a view, such as its key, belongs in its C<view>
295 block, so it applies to an ORM over an existing database too. Give it a key
296 there to use C<find> and row methods on it:
297  
298 package My::ORM::ActiveUsers;
299 use DBIx::QuickORM::DSL qw/:view :schema/;
300  
301 view { name 'active_users'; pk 'id' };
302  
303 schema {
304 view_sql any => 'SELECT id, email FROM users WHERE level > 0', depends => ['users'];
305 };
306  
307 =head2 Views from handles
308  
309 A view's query may come from a handle: C<view_sql> takes code that gets an
310 offline ORM of your ORM class over the tables (and the views built before
311 it) and returns a handle. Its binds are written into the query. A column the
312 handle selects that is one table's field keeps that field's facts. Give the
313 column type of any other, such as a computed column, in C<columns>:
314  
315 package My::ORM::Seniors;
316 use DBIx::QuickORM::DSL qw/:view :schema/;
317  
318 view { name 'seniors'; pk 'id' };
319  
320 schema {
321 view_sql any => sub {
322 my $orm = shift;
323 $orm->handle('users')->where({level => {'>' => 5}})->fields({id => 'id', email => 'email', rank => \'level * 10'});
324 }, depends => ['users'], columns => {rank => 'integer'};
325 };
326  
327 =head1 THE ORM'S SCHEMA BLOCK
328  
329 A C<schema> block inside the C<orm> block gives what goes around the tables:
330 session settings, extensions, and SQL of your own:
331  
332 package My::ORM::App;
333 use DBIx::QuickORM::DSL qw/:orm/;
334  
335 orm {
336 tables [qw/My::ORM::Orgs My::ORM::Users/];
337  
338 schema {
339 setting search_path => 'public';
340 extension 'pgcrypto';
341 schema_sql postgresql => 'CREATE FUNCTION add_one(integer) RETURNS integer AS $$ SELECT $1 + 1 $$ LANGUAGE SQL';
342 schema_sql any => 'CREATE INDEX users_org ON users (org_id)', after => 1;
343 };
344 };
345  
346 =over 4
347  
348 =item setting
349  
350 A session setting on the connection that builds the schema: C<SET> on
351 PostgreSQL, MySQL, MariaDB, and DuckDB, C<PRAGMA> on SQLite. With
352 C<< deploy => 1 >> that connection is the ORM's, so the setting stays in
353 effect.
354  
355 =item extension
356  
357 C<CREATE EXTENSION IF NOT EXISTS> on PostgreSQL, C<INSTALL> and C<LOAD> on
358 DuckDB. The others have no extensions, so they croak. For an ORM that runs
359 on several databases, give it as C<< schema_sql postgresql => ... >>.
360  
361 =item schema_sql
362  
363 SQL run before the tables, or after the tables and views with
364 C<< after => 1 >>, per dialect. Here a dialect without an entry skips it,
365 since such SQL is usually for some databases only.
366  
367 =back
368  
369 The order is settings, extensions, the named enums the tables use, SQL,
370 tables, views, then the SQL given C<after>.
371  
372 =head1 CREATING THE SCHEMA
373  
374 C<< deploy => 1 >> on C<new> creates the schema, then scans the database as
375 usual:
376  
377 my $orm = My::ORM->new(credentials => {dsn => $dsn, user => $user, pass => $pass}, deploy => 1);
378  
379 C<build_schema> creates it without making an ORM:
380  
381 My::ORM->build_schema(credentials => {dsn => $dsn, user => $user, pass => $pass});
382  
383 Both assume none of the schema exists. A failing statement croaks, leaving
384 what was created before it: there is no transaction, since a new database is
385 easy to drop and build again.
386  
387 =head1 GETTING THE SQL
388  
389 C<qorm-generate-sql> prints it, with no database. Give it the ORM class, the
390 dialect, and the directories to load the classes from. C<--version> names
391 the server version to write for (the newest without one), C<--table>
392 limits it to some tables, and C<--pretty> puts each column on a line of its
393 own, with blank lines between tables:
394  
395 =for highlighter language=shell
396  
397 qorm-generate-sql -I lib --pretty --dialect postgresql My::ORM > schema.sql
398 qorm-generate-sql -I lib --dialect mariadb --version 10.11 --table orgs --table users My::ORM
399  
400 =for highlighter language=perl
401  
402 C<build_sql> does the same from Perl:
403  
404 my $sql = My::ORM->build_sql(dialect => 'postgresql'); # one string
405 my @sql = My::ORM->build_sql(dialect => 'mysql', version => '8.0'); # one statement each
406 my $two = My::ORM->build_sql(dialect => 'sqlite', tables => ['orgs', 'users']);
407 my $nice = My::ORM->build_sql(dialect => 'postgresql', pretty => 1);
408  
409 =head1 OFFLINE
410  
411 C<offline> gives an ORM over the map the definitions describe, with no
412 database. Handles build their SQL as usual, and anything that would send a
413 query croaks. Use it to generate SQL, in tests, and to check definitions:
414  
415 my $orm = My::ORM->offline(dialect => 'postgresql', version => '17');
416 my $map = My::ORM->db_map_from_schema(dialect => 'sqlite');
417  
418 The map holds the tables C<schema> blocks describe and the views built from
419 handles, with their keys, unique keys, foreign keys, and which columns the
420 database fills. Column types are spelled as given, so they may differ from
421 what a scan of the built database reports. Tables and views given as SQL,
422 and tables whose class has no C<schema>, are not in it: a handle on one
423 croaks, saying to define it with a C<schema> block. A column given as SQL
424 gets the type its SQL starts with, and the ORM knows nothing else of it,
425 such as whether the database fills it. A query on an offline ORM dies with
426 a stack trace.
427  
428 =head1 ORDER
429  
430 Every table comes after the tables its foreign keys name, and a C<schema_sql>
431 table after its C<depends>. Views come last, each after the views it
432 reads. Tables that reference each other are created first, and the keys between them added after with C<ALTER TABLE>. SQLite and
433 DuckDB cannot add keys to a table, so they croak for such tables.
434  
435 =head1 A COMPLETE EXAMPLE
436  
437 A small application's schema: the ORM class defines an enum and gives an
438 extension and SQL run after the tables, a column has an enum of its own, two table classes describe the
439 tables, and a view class builds its query from a handle.
440  
441 F<lib/My/App.pm>:
442  
443 package My::App;
444 use DBIx::QuickORM::DSL qw/:orm enum/;
445  
446 enum role => [qw/member admin/];
447  
448 orm {
449 schema {
450 extension 'citext';
451 schema_sql postgresql => q{COMMENT ON TABLE users IS 'People who sign in'}, after => 1;
452 };
453 };
454  
455 1;
456  
457 F<lib/My/App/Orgs.pm>:
458  
459 package My::App::Orgs;
460 use DBIx::QuickORM::DSL qw/:table :schema/;
461  
462 table { name 'orgs' };
463  
464 schema {
465 column 'id' => sub { db_type 'integer'; primary_key; identity };
466 column 'name' => sub { db_type 'text'; not_null; unique };
467 column 'plan' => sub { enum [qw/free paid/]; not_null; default 'free' };
468 };
469  
470 1;
471  
472 F<lib/My/App/Users.pm>:
473  
474 package My::App::Users;
475 use DBIx::QuickORM::DSL qw/:table :schema/;
476  
477 table { name 'users' };
478  
479 schema {
480 column 'id' => sub { db_type 'integer'; primary_key; identity };
481 column 'org_id' => sub { db_type 'integer'; not_null; references 'orgs', 'id', {on_delete => 'cascade'} };
482 column 'email' => sub { db_type 'citext'; not_null; unique };
483 column 'role' => sub { enum 'role'; not_null; default 'member' };
484 column 'level' => sub { db_type 'integer'; not_null; default 1; check \'level > 0'; indexed };
485 };
486  
487 1;
488  
489 F<lib/My/App/Admins.pm>:
490  
491 package My::App::Admins;
492 use DBIx::QuickORM::DSL qw/:view :schema/;
493  
494 view { name 'admins'; pk 'id' };
495  
496 schema {
497 view_sql any => sub {
498 my $orm = shift;
499 $orm->handle('users')->where({role => 'admin'})->fields([qw/id org_id email/]);
500 }, depends => ['users'];
501 };
502  
503 1;
504  
505 Generating its SQL for PostgreSQL, laid out to read:
506  
507 =for highlighter language=shell
508  
509 qorm-generate-sql -I lib --pretty --dialect postgresql My::App > schema.sql
510  
511 =for highlighter language=sql
512  
513 F<schema.sql>:
514  
515 CREATE EXTENSION IF NOT EXISTS "citext";
516 CREATE TYPE "role" AS ENUM ('member', 'admin');
517  
518 CREATE TYPE "orgs_enum_1" AS ENUM ('free', 'paid');
519 CREATE TABLE "orgs" (
520 "id" integer GENERATED BY DEFAULT AS IDENTITY,
521  
522 "name" text NOT NULL UNIQUE,
523 "plan" "orgs_enum_1" DEFAULT 'free' NOT NULL,
524  
525 PRIMARY KEY ("id")
526 );
527  
528 CREATE TABLE "users" (
529 "id" integer GENERATED BY DEFAULT AS IDENTITY,
530  
531 "org_id" integer NOT NULL,
532 "email" citext NOT NULL UNIQUE,
533 "role" "role" DEFAULT 'member' NOT NULL,
534 "level" integer DEFAULT '1' NOT NULL CHECK (level > 0),
535  
536 PRIMARY KEY ("id"),
537 FOREIGN KEY ("org_id") REFERENCES "orgs" ("id") ON DELETE CASCADE
538 );
539 CREATE INDEX "users_level_idx" ON "users" ("level");
540  
541 CREATE VIEW "admins" AS SELECT "id", "org_id", "email" FROM "users" WHERE ( "role" = 'admin' );
542  
543 COMMENT ON TABLE users IS 'People who sign in';
544  
545 =for highlighter language=perl
546  
547 Other databases get their own SQL: C<--dialect sqlite> writes the enum
548 column as C<text> with a C<CHECK>, and croaks for the extension, which only
549 PostgreSQL and DuckDB have. A portable application gives such things with
550 C<< schema_sql postgresql => ... >> instead.
551  
552 =cut
553  
554 1;
555  
556 __END__