Move the *preliminary* multicol IN support to the sqlmaker
[dbsrgits/DBIx-Class.git] / t / resultset / update_delete.t
1 use strict;
2 use warnings;
3
4 use lib qw(t/lib);
5 use Test::More;
6 use Test::Exception;
7 use DBICTest;
8 use DBIC::DebugObj;
9 use DBIC::SqlMakerTest;
10
11 my $schema = DBICTest->init_schema;
12
13 my ($sql, @bind);
14 my $debugobj = DBIC::DebugObj->new (\$sql, \@bind);
15 my $orig_debugobj = $schema->storage->debugobj;
16 my $orig_debug = $schema->storage->debug;
17
18 my $tkfks = $schema->resultset('FourKeys_to_TwoKeys');
19
20 my ($fa, $fb, $fc) = $tkfks->related_resultset ('fourkeys')->populate ([
21   [qw/foo bar hello goodbye sensors read_count/],
22   [qw/1   1   1     1       a       10         /],
23   [qw/2   2   2     2       b       20         /],
24   [qw/1   1   1     2       c       30         /],
25 ]);
26
27 # This is already provided by DBICTest
28 #my ($ta, $tb) = $tkfk->related_resultset ('twokeys')->populate ([
29 #  [qw/artist  cd /],
30 #  [qw/1       1  /],
31 #  [qw/2       2  /],
32 #]);
33 my ($ta, $tb) = $schema->resultset ('TwoKeys')
34                   ->search ( [ { artist => 1, cd => 1 }, { artist => 2, cd => 2 } ])
35                     ->all;
36
37 my $tkfk_cnt = $tkfks->count;
38
39 my $non_void_ctx = $tkfks->populate ([
40   { autopilot => 'a', fourkeys =>  $fa, twokeys => $ta, pilot_sequence => 10 },
41   { autopilot => 'b', fourkeys =>  $fb, twokeys => $tb, pilot_sequence => 20 },
42   { autopilot => 'x', fourkeys =>  $fa, twokeys => $tb, pilot_sequence => 30 },
43   { autopilot => 'y', fourkeys =>  $fb, twokeys => $ta, pilot_sequence => 40 },
44 ]);
45 is ($tkfks->count, $tkfk_cnt += 4, 'FourKeys_to_TwoKeys populated succesfully');
46
47 #
48 # Make sure the forced group by works (i.e. the joining does not cause double-updates)
49 #
50
51 # create a resultset matching $fa and $fb only
52 my $fks = $schema->resultset ('FourKeys')->search (
53   {
54     sensors => { '!=', 'c' },
55     ( map { $_ => [1, 2] } qw/foo bar hello goodbye/ ),
56   }, { join => 'fourkeys_to_twokeys'}
57 );
58
59 is ($fks->count, 4, 'Joined FourKey count correct (2x2)');
60
61 $schema->storage->debugobj ($debugobj);
62 $schema->storage->debug (1);
63 $fks->update ({ read_count => \ 'read_count + 1' });
64 $schema->storage->debugobj ($orig_debugobj);
65 $schema->storage->debug ($orig_debug);
66
67 is_same_sql_bind (
68   $sql,
69   \@bind,
70   'UPDATE fourkeys
71    SET read_count = read_count + 1
72    WHERE ( ( ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ? ) )
73   ',
74   [ ("'1'", "'2'") x 4, "'c'" ],
75   'Correct update-SQL with multijoin with pruning',
76 );
77
78 is ($fa->discard_changes->read_count, 11, 'Update ran only once on discard-join resultset');
79 is ($fb->discard_changes->read_count, 21, 'Update ran only once on discard-join resultset');
80 is ($fc->discard_changes->read_count, 30, 'Update did not touch outlier');
81
82 # make the multi-join stick
83 $fks = $fks->search({ 'fourkeys_to_twokeys.pilot_sequence' => { '!=' => 666 } });
84
85 $schema->storage->debugobj ($debugobj);
86 $schema->storage->debug (1);
87 $fks->update ({ read_count => \ 'read_count + 1' });
88 $schema->storage->debugobj ($orig_debugobj);
89 $schema->storage->debug ($orig_debug);
90
91 is_same_sql_bind (
92   $sql,
93   \@bind,
94   'UPDATE fourkeys
95    SET read_count = read_count + 1
96    WHERE ( bar = ? AND foo = ? AND goodbye = ? AND hello = ? ) OR ( bar = ? AND foo = ? AND goodbye = ? AND hello = ? )',
97   [ map { "'$_'" } ( (1) x 4, (2) x 4 ) ],
98   'Correct update-SQL with multijoin without pruning',
99 );
100
101 is ($fa->discard_changes->read_count, 12, 'Update ran only once on joined resultset');
102 is ($fb->discard_changes->read_count, 22, 'Update ran only once on joined resultset');
103 is ($fc->discard_changes->read_count, 30, 'Update did not touch outlier');
104
105 # try the same sql with forced multicolumn in
106 $schema->storage->_use_multicolumn_in (1);
107 $schema->storage->debugobj ($debugobj);
108 $schema->storage->debug (1);
109 throws_ok { $fks->update ({ read_count => \ 'read_count + 1' }) } # this can't actually execute, we just need the "as_query"
110   qr/\Q DBI Exception:/ or do { $sql = ''; @bind = () };
111 $schema->storage->_use_multicolumn_in (undef);
112 $schema->storage->debugobj ($orig_debugobj);
113 $schema->storage->debug ($orig_debug);
114
115 is_same_sql_bind (
116   $sql,
117   \@bind,
118   'UPDATE fourkeys
119     SET read_count = read_count + 1
120     WHERE (
121       (foo, bar, hello, goodbye) IN (
122         SELECT me.foo, me.bar, me.hello, me.goodbye
123           FROM fourkeys me
124           LEFT JOIN fourkeys_to_twokeys fourkeys_to_twokeys ON
125                 fourkeys_to_twokeys.f_bar = me.bar
126             AND fourkeys_to_twokeys.f_foo = me.foo
127             AND fourkeys_to_twokeys.f_goodbye = me.goodbye
128             AND fourkeys_to_twokeys.f_hello = me.hello
129         WHERE fourkeys_to_twokeys.pilot_sequence != ? AND ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ?
130       )
131     )
132   ',
133   [
134     "'666'",
135     ("'1'", "'2'") x 4,
136     "'c'",
137   ],
138   'Correct update-SQL with multicolumn in support',
139 );
140
141 #
142 # Make sure multicolumn in or the equivalent functions correctly
143 #
144
145 my $sub_rs = $tkfks->search (
146   [
147     { map { $_ => 1 } qw/artist.artistid cd.cdid fourkeys.foo fourkeys.bar fourkeys.hello fourkeys.goodbye/ },
148     { map { $_ => 2 } qw/artist.artistid cd.cdid fourkeys.foo fourkeys.bar fourkeys.hello fourkeys.goodbye/ },
149   ],
150   {
151     join => [ 'fourkeys', { twokeys => [qw/artist cd/] } ],
152   },
153 );
154
155 is ($sub_rs->count, 2, 'Only two rows from fourkeys match');
156
157 # attempts to delete a grouped rs should fail miserably
158 throws_ok (
159   sub { $sub_rs->search ({}, { distinct => 1 })->delete },
160   qr/attempted a delete operation on a resultset which does group_by/,
161   'Grouped rs update/delete not allowed',
162 );
163
164 # grouping on PKs only should pass
165 $sub_rs->search (
166   {},
167   {
168     group_by => [ reverse $sub_rs->result_source->primary_columns ],     # reverse to make sure the PK-list comparison works
169   },
170 )->update ({ pilot_sequence => \ 'pilot_sequence + 1' });
171
172 is_deeply (
173   [ $tkfks->search ({ autopilot => [qw/a b x y/]}, { order_by => 'autopilot' })
174             ->get_column ('pilot_sequence')->all
175   ],
176   [qw/11 21 30 40/],
177   'Only two rows incremented',
178 );
179
180 # also make sure weird scalarref usage works (RT#51409)
181 $tkfks->search (
182   \ 'pilot_sequence BETWEEN 11 AND 21',
183 )->update ({ pilot_sequence => \ 'pilot_sequence + 1' });
184
185 is_deeply (
186   [ $tkfks->search ({ autopilot => [qw/a b x y/]}, { order_by => 'autopilot' })
187             ->get_column ('pilot_sequence')->all
188   ],
189   [qw/12 22 30 40/],
190   'Only two rows incremented (where => scalarref works)',
191 );
192
193 {
194   my $rs = $schema->resultset('FourKeys_to_TwoKeys')->search (
195     {
196       -or => [
197         { 'me.pilot_sequence' => 12 },
198         { 'me.autopilot'      => 'b' },
199       ],
200     }
201   );
202   lives_ok { $rs->update({ autopilot => 'z' }) }
203     'Update with table name qualifier in -or conditions lives';
204   is_deeply (
205     [ $tkfks->search ({ pilot_sequence => [12, 22]})
206               ->get_column ('autopilot')->all
207     ],
208     [qw/z z/],
209     '... and yields the right data',
210   );
211 }
212
213
214 $sub_rs->delete;
215 is ($tkfks->count, $tkfk_cnt -= 2, 'Only two rows deleted');
216
217 # make sure limit-only deletion works
218 cmp_ok ($tkfk_cnt, '>', 1, 'More than 1 row left');
219 $tkfks->search ({}, { rows => 1 })->delete;
220 is ($tkfks->count, $tkfk_cnt -= 1, 'Only one row deleted');
221
222
223 # check with sql-equality, as sqlite will accept most bad sql just fine
224 $schema->storage->debugobj ($debugobj);
225 $schema->storage->debug (1);
226
227 {
228   my $rs = $schema->resultset('CD')->search(
229     { 'me.year' => { '!=' => 2010 } },
230   );
231
232   $rs->search({}, { join => 'liner_notes' })->delete;
233   is_same_sql_bind (
234     $sql,
235     \@bind,
236     'DELETE FROM cd WHERE ( year != ? )',
237     ["'2010'"],
238     'Non-restricting multijoins properly thrown out'
239   );
240
241   $rs->search({}, { prefetch => 'liner_notes' })->delete;
242   is_same_sql_bind (
243     $sql,
244     \@bind,
245     'DELETE FROM cd WHERE ( year != ? )',
246     ["'2010'"],
247     'Non-restricting multiprefetch thrown out'
248   );
249
250   $rs->search({}, { prefetch => 'artist' })->delete;
251   is_same_sql_bind (
252     $sql,
253     \@bind,
254     'DELETE FROM cd WHERE ( cdid IN ( SELECT me.cdid FROM cd me JOIN artist artist ON artist.artistid = me.artist WHERE ( me.year != ? ) ) )',
255     ["'2010'"],
256     'Restricting prefetch left in, selector thrown out'
257   );
258
259   $rs->result_source->name('schema_qualified.cd');
260   # this is expected to fail - we only want to collect the generated SQL
261   eval { $rs->delete };
262   is_same_sql_bind (
263     $sql,
264     \@bind,
265     'DELETE FROM schema_qualified.cd WHERE ( year != ? )',
266     ["'2010'"],
267     'delete with fully qualified table name and subquery correct'
268   );
269
270   eval { $rs->search({}, { prefetch => 'artist' })->delete };
271   is_same_sql_bind (
272     $sql,
273     \@bind,
274     'DELETE FROM schema_qualified.cd WHERE ( cdid IN ( SELECT me.cdid FROM schema_qualified.cd me JOIN artist artist ON artist.artistid = me.artist WHERE ( me.year != ? ) ) )',
275     ["'2010'"],
276     'delete with fully qualified table name and subquery correct'
277   );
278
279   $rs->result_source->name('cd');
280 }
281
282 $schema->storage->debugobj ($orig_debugobj);
283 $schema->storage->debug ($orig_debug);
284
285
286 done_testing;