blib/lib/DBIx/QuickORM/Manual/ForeignKeys.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/Errors.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Joins.pm »
1 package DBIx::QuickORM::Manual::ForeignKeys;
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::ForeignKeys - Follow foreign keys from a row, and insert rows linked to it, by example.
14  
15 =head1 DESCRIPTION
16  
17 C<follow_fk> returns a handle for the row this key points to, or for rows
18 pointing back to this one. C<insert_fk> and C<insert_many_fk> insert rows
19 that point back to this one.
20  
21 =head1 SCHEMA
22  
23 The examples use PostgreSQL and this schema:
24  
25 =for highlighter language=sql
26  
27 CREATE TABLE users (
28 id SERIAL PRIMARY KEY,
29 name TEXT NOT NULL,
30 email TEXT UNIQUE,
31 prefs JSON,
32 referred_by INTEGER REFERENCES users (id),
33 created TIMESTAMP NOT NULL DEFAULT now()
34 );
35  
36 CREATE TABLE posts (
37 id SERIAL PRIMARY KEY,
38 user_id INTEGER NOT NULL REFERENCES users (id),
39 title TEXT NOT NULL,
40 views INTEGER NOT NULL DEFAULT 0
41 );
42  
43 And a log whose C<user_id> has no foreign key constraint:
44  
45 CREATE TABLE audit_log (
46 id SERIAL PRIMARY KEY,
47 user_id INTEGER,
48 action TEXT NOT NULL
49 );
50  
51 C<posts.user_id> and C<users.referred_by> both reference C<users.id>.
52  
53 =head1 FOLLOWING A KEY
54  
55 =for highlighter language=perl
56  
57 my $post = $orm->handle('posts')->where({id => $post_id})->only;
58  
59 # the user posts.user_id points at
60 my $author = $post->follow_fk('users')->only;
61  
62 # the posts whose user_id points at this user
63 my @posts = $author->follow_fk('posts')->order_by('id')->all;
64  
65 =head1 SINGLE AND MULTI
66  
67 my $one = $post->follow_fk('users'); # single: user_id reaches the users primary key
68 my $many = $author->follow_fk('posts'); # multi: any number of posts may point here
69  
70 my $user = $one->only; # the row, or undef
71 my @all = $many->all;
72 my $state = $many->state; # 'multi': only() croaks if multi is true
73  
74 Single when the linked fields on the other table are its primary key or a
75 unique key, multi otherwise. The schema decides, not the data.
76  
77 =head1 DIRECTION WITH LINK
78  
79 # users.referred_by points at users.id: the same key read both ways.
80  
81 # who referred Bob
82 my $referrer = $bob->follow_fk('users', link => {referred_by => 'id'})->only;
83  
84 # whom Alice referred
85 my @referrals = $alice->follow_fk('users', link => {id => 'referred_by'})
86 ->order_by('id')
87 ->all;
88  
89 C<link> is C<< {my_field => their_field} >>: this row's field on the left,
90 the other table's on the right. Omit it when exactly one field mapping fits
91 between the two tables, counting both directions. Otherwise C<follow_fk>
92 croaks. Here C<link> distinguishes Bob's referrer from the users Bob referred.
93  
94 =head1 NULL LINKS
95  
96 # Alice was not referred
97 my $nobody = $alice->follow_fk('users', link => {referred_by => 'id'});
98 my $who = $nobody->only; # undef: a NULL key points at nothing
99  
100 A NULL key matches nothing, not even rows holding NULL in the linked field.
101 The handle keeps its single or multi state.
102  
103 =head1 NARROWING AND JOINING
104  
105 my @popular = $author->follow_fk('posts')
106 ->and({views => {'>' => 5}})
107 ->all;
108  
109 # Bob's referrer with each of their posts
110 my @theirs = $bob->follow_fk('users', link => {referred_by => 'id'})
111 ->join('posts')
112 ->order_by('posts.id')
113 ->all;
114  
115 C<and> keeps the key condition. C<where> would replace it. Either one drops
116 the single or multi state. C<join> is in L<DBIx::QuickORM::Manual::Joins>.
117  
118 =head1 KEYS THE MAP DOES NOT KNOW
119  
120 # audit_log.user_id points at users.id, but nothing declares it
121 my $entry = $orm->insert(audit_log => {user_id => $alice_id, action => 'login'});
122  
123 my $who = $entry->follow_fk('users', via => {user_id => 'id'})->only;
124 my @log = $alice->follow_fk('audit_log', via => {id => 'user_id'})->all;
125  
126 my @pairs = $orm->handle('audit_log')
127 ->join('users', via => {user_id => 'id'})
128 ->all;
129  
130 my $next = $alice->insert_fk('audit_log', via => {id => 'user_id'}, {action => 'logout'});
131  
132 C<via> takes a mapping in C<link>'s form, C<< {my_field => their_field} >>,
133 and needs no foreign key. It works wherever C<link> does. Both tables and
134 every named field must exist, so a typo still croaks. C<via> and C<link>
135 together croak. Single or multi still comes from the target fields.
136  
137 To declare the key once, for every call, give C<fks> to C<new>
138 (L<DBIx::QuickORM>). C<link> and the plain forms then work too.
139  
140 =head1 INSERTING LINKED ROWS
141  
142 my $post = $alice->insert_fk('posts', {title => 'Hi'}); # user_id is Alice's id
143 my $posts = $alice->insert_many_fk('posts', {title => 'A'}, {title => 'B'}); # an arrayref of rows
144 my $count = $alice->insert_many_fk('posts', count => 1, {title => 'C'}, {title => 'D'});
145  
146 # only keys pointing back at Alice count, so users.referred_by needs no link
147 my $dan = $alice->insert_fk('users', {name => 'Dan'}); # referred by Alice
148  
149 my $note = $orm->insert_fk(users => {id => $alice_id}, 'posts', {title => 'Note'});
150  
151 The new rows' foreign key fields come from the row, so the given fields must
152 not set them. Options go between the table and the rows: C<link> picks the
153 key when more than one points back, and the rest are C<insert>'s or
154 C<insert_many>'s. C<insert_fk> returns the row. C<insert_many_fk> returns
155 what C<insert_many> does (L<DBIx::QuickORM::Manual::BulkInsert>).
156  
157 Only rows pointing at this one: to add the row it points at, insert that row,
158 then C<update> this one. A NULL linked value, or a row not in the database,
159 croaks.
160  
161 =head1 WITHOUT ROW OBJECTS
162  
163 my $data = $orm->handle('posts')
164 ->data_only
165 ->where({id => $post_id})
166 ->only; # a hashref
167  
168 my $who = $orm->follow_fk('posts', $data, 'users')->only; # a users row object
169  
170 # user_id is fetched first
171 my $by_key = $orm->follow_fk('posts', {id => $post_id}, 'users')->only;
172  
173 C<< $orm->follow_fk >> takes row data in place of a row object
174 (L<DBIx::QuickORM::Manual::RowClasses/HASHREFS>). If a linked field is
175 missing, supply the row's primary key so the ORM can fetch it.
176  
177 =head1 FROM AGGREGATE AND JOIN ROWS
178  
179 my $stat = $orm->handle('posts')
180 ->group_by('user_id')
181 ->fields({
182 user_id => 'user_id',
183 posts => [count => '*'],
184 })
185 ->order_by('user_id')
186 ->first;
187  
188 my $user = $stat->follow_fk('users')->only; # user_id kept its key
189  
190 my $jrow = $orm->handle('posts')
191 ->join('users')
192 ->order_by('posts.id')
193 ->first;
194 # each table's row in a join is an ordinary row
195 my @more = $jrow->row('users')->follow_fk('posts')->all;
196  
197 L<DBIx::QuickORM::Manual::Aggregates> shows which computed columns keep a
198 foreign key, and how to declare one. L<DBIx::QuickORM::Manual::Joins> covers
199 join rows.
200  
201 =cut
202  
203 2 1;
204  
205 __END__
« blib/lib/DBIx/QuickORM/Manual/Errors.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Joins.pm »