Fix test expecting multi-column in to fail on DBD::SQLite
[dbsrgits/DBIx-Class.git] / t / resultset / update_delete.t
1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Exception;
8
9 # MASSIVE FIXME - there is a hole in ::RSC / as_subselect_rs
10 # losing the order. Needs a rework/extract of the realiaser,
11 # and that's a whole another bag of dicks
12 BEGIN { $ENV{DBIC_SHUFFLE_UNORDERED_RESULTSETS} = 0 }
13
14 use DBIx::Class::_Util 'scope_guard';
15
16 use DBICTest::Schema::CD;
17 BEGIN {
18   # the default scalarref table name will not work well for this test
19   DBICTest::Schema::CD->table('cd');
20 }
21
22 use DBICTest;
23
24 my $schema = DBICTest->init_schema;
25
26 my $tkfks = $schema->resultset('FourKeys_to_TwoKeys');
27
28 my ($fa, $fb, $fc) = $tkfks->related_resultset ('fourkeys')->populate ([
29   [qw/foo bar hello goodbye sensors read_count/],
30   [qw/1   1   1     1       a       10         /],
31   [qw/2   2   2     2       b       20         /],
32   [qw/1   1   1     2       c       30         /],
33 ]);
34
35 # This is already provided by DBICTest
36 #my ($ta, $tb) = $tkfk->related_resultset ('twokeys')->populate ([
37 #  [qw/artist  cd /],
38 #  [qw/1       1  /],
39 #  [qw/2       2  /],
40 #]);
41 my ($ta, $tb) = $schema->resultset ('TwoKeys')
42                   ->search ( [ { artist => 1, cd => 1 }, { artist => 2, cd => 2 } ], { order_by => 'artist' })
43                     ->all;
44
45 my $tkfk_cnt = $tkfks->count;
46
47 my $non_void_ctx = $tkfks->populate ([
48   { autopilot => 'a', fourkeys =>  $fa, twokeys => $ta, pilot_sequence => 10 },
49   { autopilot => 'b', fourkeys =>  $fb, twokeys => $tb, pilot_sequence => 20 },
50   { autopilot => 'x', fourkeys =>  $fa, twokeys => $tb, pilot_sequence => 30 },
51   { autopilot => 'y', fourkeys =>  $fb, twokeys => $ta, pilot_sequence => 40 },
52 ]);
53 is ($tkfks->count, $tkfk_cnt += 4, 'FourKeys_to_TwoKeys populated succesfully');
54
55 #
56 # Make sure the forced group by works (i.e. the joining does not cause double-updates)
57 #
58
59 # create a resultset matching $fa and $fb only
60 my $fks = $schema->resultset ('FourKeys')->search (
61   {
62     sensors => { '!=', 'c' },
63     ( map { $_ => [1, 2] } qw/foo bar hello goodbye/ ),
64   }, { join => { fourkeys_to_twokeys => 'twokeys' }}
65 );
66
67 my $read_count = 0;
68 is ($fks->count, 4, 'Joined FourKey count correct (2x2)');
69 $schema->is_executed_sql_bind( sub {
70   $fks->update ({ read_count => \ 'read_count + 1' });
71   $read_count++;
72 }, [[
73   'UPDATE fourkeys
74    SET read_count = read_count + 1
75    WHERE ( ( ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ? ) )
76   ',
77   (1, 2) x 4,
78   'c',
79 ]], 'Correct update-SQL with multijoin with pruning' );
80
81 is ($fa->discard_changes->read_count, 10 + $read_count, 'Update ran only once on discard-join resultset');
82 is ($fb->discard_changes->read_count, 20 + $read_count, 'Update ran only once on discard-join resultset');
83 is ($fc->discard_changes->read_count, 30, 'Update did not touch outlier');
84
85 # make the multi-join stick
86 my $fks_multi = $fks->search(
87   { 'fourkeys_to_twokeys.pilot_sequence' => { '!=' => 666 } },
88   { order_by => [ $fks->result_source->primary_columns ] },
89 );
90 $schema->is_executed_sql_bind( sub {
91   $fks_multi->update ({ read_count => \ 'read_count + 1' });
92   $read_count++;
93 }, [
94   [ 'BEGIN' ],
95   [
96     'SELECT me.foo, me.bar, me.hello, me.goodbye
97       FROM fourkeys me
98       LEFT JOIN fourkeys_to_twokeys fourkeys_to_twokeys
99         ON fourkeys_to_twokeys.f_bar = me.bar AND fourkeys_to_twokeys.f_foo = me.foo AND fourkeys_to_twokeys.f_goodbye = me.goodbye AND fourkeys_to_twokeys.f_hello = me.hello
100       WHERE ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND fourkeys_to_twokeys.pilot_sequence != ? AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ?
101       GROUP BY me.foo, me.bar, me.hello, me.goodbye
102       ORDER BY foo, bar, hello, goodbye
103     ',
104     (1, 2) x 2,
105     666,
106     (1, 2) x 2,
107     'c',
108   ],
109   [
110     'UPDATE fourkeys
111      SET read_count = read_count + 1
112      WHERE ( bar = ? AND foo = ? AND goodbye = ? AND hello = ? ) OR ( bar = ? AND foo = ? AND goodbye = ? AND hello = ? )
113     ',
114     ( (1) x 4, (2) x 4 ),
115   ],
116   [ 'COMMIT' ],
117 ], 'Correct update-SQL with multijoin without pruning' );
118
119 is ($fa->discard_changes->read_count, 10 + $read_count, 'Update ran only once on joined resultset');
120 is ($fb->discard_changes->read_count, 20 + $read_count, 'Update ran only once on joined resultset');
121 is ($fc->discard_changes->read_count, 30, 'Update did not touch outlier');
122
123 $schema->is_executed_sql_bind( sub {
124   my $res = $fks_multi->search (\' "blah" = "bleh" ')->delete;
125   ok ($res, 'operation is true');
126   cmp_ok ($res, '==', 0, 'zero rows affected');
127 }, [
128   [ 'BEGIN' ],
129   [
130     'SELECT me.foo, me.bar, me.hello, me.goodbye
131       FROM fourkeys me
132       LEFT JOIN fourkeys_to_twokeys fourkeys_to_twokeys
133         ON fourkeys_to_twokeys.f_bar = me.bar AND fourkeys_to_twokeys.f_foo = me.foo AND fourkeys_to_twokeys.f_goodbye = me.goodbye AND fourkeys_to_twokeys.f_hello = me.hello
134       WHERE "blah" = "bleh" AND ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND fourkeys_to_twokeys.pilot_sequence != ? AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ?
135       GROUP BY me.foo, me.bar, me.hello, me.goodbye
136       ORDER BY foo, bar, hello, goodbye
137     ',
138     (1, 2) x 2,
139     666,
140     (1, 2) x 2,
141     'c',
142   ],
143   [ 'COMMIT' ],
144 ], 'Correct null-delete-SQL with multijoin without pruning' );
145
146
147 # try the same sql with forced multicolumn in
148 my $multicolumn_in = 0;
149 $schema->is_executed_sql_bind( sub {
150
151   my $orig_umi = $schema->storage->_use_multicolumn_in;
152   my $sg = scope_guard {
153     $schema->storage->_use_multicolumn_in($orig_umi);
154   };
155
156   $schema->storage->_use_multicolumn_in(1);
157
158   # this can't actually execute on sqlite < 3.14
159   eval {
160     $fks_multi->update ({ read_count => \ 'read_count + 1' });
161     $read_count++; $multicolumn_in++;
162   };
163 }, [[
164   'UPDATE fourkeys
165     SET read_count = read_count + 1
166     WHERE (
167       (foo, bar, hello, goodbye) IN (
168         SELECT me.foo, me.bar, me.hello, me.goodbye
169           FROM fourkeys me
170           LEFT JOIN fourkeys_to_twokeys fourkeys_to_twokeys ON
171                 fourkeys_to_twokeys.f_bar = me.bar
172             AND fourkeys_to_twokeys.f_foo = me.foo
173             AND fourkeys_to_twokeys.f_goodbye = me.goodbye
174             AND fourkeys_to_twokeys.f_hello = me.hello
175         WHERE ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND fourkeys_to_twokeys.pilot_sequence != ? AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ?
176         ORDER BY foo, bar, hello, goodbye
177       )
178     )
179   ',
180   ( 1, 2) x 2,
181   666,
182   ( 1, 2) x 2,
183   'c',
184 ]], 'Correct update-SQL with multicolumn in support' );
185
186 if ($multicolumn_in) {
187   is ($fa->discard_changes->read_count, 10 + $read_count, 'Update ran only once on joined resultset');
188   is ($fb->discard_changes->read_count, 20 + $read_count, 'Update ran only once on joined resultset');
189   is ($fc->discard_changes->read_count, 30, 'Update did not touch outlier');
190 }
191
192 $schema->is_executed_sql_bind( sub {
193   $fks->search({ 'twokeys.artist' => { '!=' => 666 } })->update({ read_count => \ 'read_count + 1' });
194   $read_count++;
195 }, [
196   [ 'BEGIN' ],
197   [
198     'SELECT me.foo, me.bar, me.hello, me.goodbye
199       FROM fourkeys me
200       LEFT JOIN fourkeys_to_twokeys fourkeys_to_twokeys
201         ON fourkeys_to_twokeys.f_bar = me.bar AND fourkeys_to_twokeys.f_foo = me.foo AND fourkeys_to_twokeys.f_goodbye = me.goodbye AND fourkeys_to_twokeys.f_hello = me.hello
202       LEFT JOIN twokeys twokeys
203         ON twokeys.artist = fourkeys_to_twokeys.t_artist AND twokeys.cd = fourkeys_to_twokeys.t_cd
204       WHERE ( bar = ? OR bar = ? ) AND ( foo = ? OR foo = ? ) AND ( goodbye = ? OR goodbye = ? ) AND ( hello = ? OR hello = ? ) AND sensors != ? AND twokeys.artist != ?
205       GROUP BY me.foo, me.bar, me.hello, me.goodbye
206     ',
207     (1, 2) x 4,
208     'c',
209     666,
210   ],
211   [
212     'UPDATE fourkeys
213      SET read_count = read_count + 1
214      WHERE ( bar = ? AND foo = ? AND goodbye = ? AND hello = ? ) OR ( bar = ? AND foo = ? AND goodbye = ? AND hello = ? )
215     ',
216     ( (1) x 4, (2) x 4 ),
217   ],
218   [ 'COMMIT' ],
219 ], 'Correct update-SQL with premultiplied restricting join without pruning' );
220
221 is ($fa->discard_changes->read_count, 10 + $read_count, 'Update ran only once on joined resultset');
222 is ($fb->discard_changes->read_count, 20 + $read_count, 'Update ran only once on joined resultset');
223 is ($fc->discard_changes->read_count, 30, 'Update did not touch outlier');
224
225 #
226 # Make sure multicolumn in or the equivalent functions correctly
227 #
228
229 my $sub_rs = $tkfks->search (
230   [
231     { map { $_ => 1 } qw/artist.artistid cd.cdid fourkeys.foo fourkeys.bar fourkeys.hello fourkeys.goodbye/ },
232     { map { $_ => 2 } qw/artist.artistid cd.cdid fourkeys.foo fourkeys.bar fourkeys.hello fourkeys.goodbye/ },
233   ],
234   {
235     join => [ 'fourkeys', { twokeys => [qw/artist cd/] } ],
236   },
237 );
238
239 is ($sub_rs->count, 2, 'Only two rows from fourkeys match');
240
241 # attempts to delete a grouped rs should fail miserably
242 throws_ok (
243   sub { $sub_rs->search ({}, { distinct => 1 })->delete },
244   qr/attempted a delete operation on a resultset which does group_by/,
245   'Grouped rs update/delete not allowed',
246 );
247
248 # grouping on PKs only should pass
249 $sub_rs->search (
250   {},
251   {
252     group_by => [ reverse $sub_rs->result_source->primary_columns ],     # reverse to make sure the PK-list comparison works
253   },
254 )->update ({ pilot_sequence => \ 'pilot_sequence + 1' });
255
256 is_deeply (
257   [ $tkfks->search ({ autopilot => [qw/a b x y/]}, { order_by => 'autopilot' })
258             ->get_column ('pilot_sequence')->all
259   ],
260   [qw/11 21 30 40/],
261   'Only two rows incremented',
262 );
263
264 # also make sure weird scalarref usage works (RT#51409)
265 $tkfks->search (
266   \ 'pilot_sequence BETWEEN 11 AND 21',
267 )->update ({ pilot_sequence => \ 'pilot_sequence + 1' });
268
269 is_deeply (
270   [ $tkfks->search ({ autopilot => [qw/a b x y/]}, { order_by => 'autopilot' })
271             ->get_column ('pilot_sequence')->all
272   ],
273   [qw/12 22 30 40/],
274   'Only two rows incremented (where => scalarref works)',
275 );
276
277 {
278   my $rs = $schema->resultset('FourKeys_to_TwoKeys')->search (
279     {
280       -or => [
281         { 'me.pilot_sequence' => 12 },
282         { 'me.autopilot'      => 'b' },
283       ],
284     }
285   );
286   lives_ok { $rs->update({ autopilot => 'z' }) }
287     'Update with table name qualifier in -or conditions lives';
288   is_deeply (
289     [ $tkfks->search ({ pilot_sequence => [12, 22]})
290               ->get_column ('autopilot')->all
291     ],
292     [qw/z z/],
293     '... and yields the right data',
294   );
295 }
296
297
298 $sub_rs->delete;
299 is ($tkfks->count, $tkfk_cnt -= 2, 'Only two rows deleted');
300
301 # make sure limit-only deletion works
302 cmp_ok ($tkfk_cnt, '>', 1, 'More than 1 row left');
303 $tkfks->search ({}, { rows => 1 })->delete;
304 is ($tkfks->count, $tkfk_cnt -= 1, 'Only one row deleted');
305
306 throws_ok {
307   $tkfks->search ({}, { rows => 0 })->delete
308 } qr/rows attribute must be a positive integer/;
309 is ($tkfks->count, $tkfk_cnt, 'Nothing deleted');
310
311 # check with sql-equality, as sqlite will accept most bad sql just fine
312 {
313   my $rs = $schema->resultset('CD')->search(
314     { 'me.year' => { '!=' => 2010 } },
315   );
316
317   $schema->is_executed_sql_bind( sub {
318     $rs->search({}, { join => 'liner_notes' })->delete;
319   }, [[
320     'DELETE FROM cd WHERE ( year != ? )',
321     2010,
322   ]], 'Non-restricting multijoins properly thrown out' );
323
324   $schema->is_executed_sql_bind( sub {
325     $rs->search({}, { prefetch => 'liner_notes' })->delete;
326   }, [[
327     'DELETE FROM cd WHERE ( year != ? )',
328     2010,
329   ]], 'Non-restricting multiprefetch thrown out' );
330
331   $schema->is_executed_sql_bind( sub {
332     $rs->search({}, { prefetch => 'artist' })->delete;
333   }, [[
334     'DELETE FROM cd WHERE ( cdid IN ( SELECT me.cdid FROM cd me JOIN artist artist ON artist.artistid = me.artist WHERE ( me.year != ? ) ) )',
335     2010,
336   ]], 'Restricting prefetch left in, selector thrown out');
337
338 ### switch artist and cd to fully qualified table names
339 ### make sure nothing is stripped out
340   my $cd_rsrc = $schema->source('CD');
341   $cd_rsrc->name('main.cd');
342   $cd_rsrc->relationship_info($_)->{attrs}{cascade_delete} = 0
343     for $cd_rsrc->relationships;
344
345   my $art_rsrc = $schema->source('Artist');
346   $art_rsrc->name(\'main.artist');
347   $art_rsrc->relationship_info($_)->{attrs}{cascade_delete} = 0
348     for $art_rsrc->relationships;
349
350   $schema->is_executed_sql_bind( sub {
351     $rs->delete
352   }, [[
353     'DELETE FROM main.cd WHERE year != ?',
354     2010,
355   ]], 'delete with fully qualified table name' );
356
357   $rs->create({ title => 'foo', artist => 1, year => 2000 });
358   $schema->is_executed_sql_bind( sub {
359     $rs->delete_all
360   }, [
361     [ 'BEGIN' ],
362     [
363       'SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM main.cd me WHERE me.year != ?',
364       2010,
365     ],
366     [
367       'DELETE FROM main.cd WHERE ( cdid = ? )',
368       1,
369     ],
370     [ 'COMMIT' ],
371   ], 'delete_all with fully qualified table name' );
372
373   $rs->create({ cdid => 42, title => 'foo', artist => 2, year => 2000 });
374   my $cd42 = $rs->find(42);
375
376   $schema->is_executed_sql_bind( sub {
377     $cd42->delete
378   }, [[
379     'DELETE FROM main.cd WHERE cdid = ?',
380     42,
381   ]], 'delete of object from table with fully qualified name' );
382
383   $schema->is_executed_sql_bind( sub {
384     $cd42->related_resultset('artist')->delete
385   }, [[
386     'DELETE FROM main.artist WHERE ( artistid IN ( SELECT me.artistid FROM main.artist me WHERE ( me.artistid = ? ) ) )',
387     2,
388   ]], 'delete of related object from scalarref fully qualified named table' );
389
390   my $art3 = $schema->resultset('Artist')->find(3);
391
392   $schema->is_executed_sql_bind( sub {
393     $art3->related_resultset('cds')->delete;
394   }, [[
395     'DELETE FROM main.cd WHERE ( artist = ? )',
396     3,
397   ]], 'delete of related object from fully qualified named table' );
398
399   $schema->is_executed_sql_bind( sub {
400     $art3->cds_unordered->delete;
401   }, [[
402     'DELETE FROM main.cd WHERE ( artist = ? )',
403     3,
404   ]], 'delete of related object from fully qualified named table via relaccessor' );
405
406   $schema->is_executed_sql_bind( sub {
407     $rs->search({}, { prefetch => 'artist' })->delete;
408   }, [[
409     'DELETE FROM main.cd WHERE ( cdid IN ( SELECT me.cdid FROM main.cd me JOIN main.artist artist ON artist.artistid = me.artist WHERE ( me.year != ? ) ) )',
410     2010,
411   ]], 'delete with fully qualified table name and subquery correct' );
412
413   # check that as_subselect_rs works ok
414   # inner query is untouched, then a selector
415   # and an IN condition
416   $schema->is_executed_sql_bind( sub {
417     $schema->resultset('CD')->search({
418       'me.cdid' => 1,
419       'artist.name' => 'partytimecity',
420     }, {
421       join => 'artist',
422     })->as_subselect_rs->delete;
423   }, [[
424     '
425       DELETE FROM main.cd
426       WHERE (
427         cdid IN (
428           SELECT me.cdid
429             FROM (
430               SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
431                 FROM main.cd me
432                 JOIN main.artist artist ON artist.artistid = me.artist
433               WHERE artist.name = ? AND me.cdid = ?
434             ) me
435         )
436       )
437     ',
438     'partytimecity',
439     1,
440   ]], 'Delete from as_subselect_rs works correctly' );
441 }
442
443 done_testing;