-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsql_derived.cc
1816 lines (1594 loc) · 69.3 KB
/
sql_derived.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2002, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
// Support for derived tables.
#include "sql/sql_derived.h"
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include "lex_string.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_bitmap.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_sys.h"
#include "my_table_map.h"
#include "mysqld_error.h"
#include "sql/auth/auth_acls.h"
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/join_optimizer/join_optimizer.h"
#include "sql/mem_root_array.h"
#include "sql/nested_join.h"
#include "sql/opt_trace.h" // opt_trace_disable_etc
#include "sql/query_options.h"
#include "sql/sql_base.h" // EXTRA_RECORD
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_opt_exec_shared.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_parse.h" // parse_sql
#include "sql/sql_resolver.h" // check_right_lateral_join
#include "sql/sql_tmp_table.h" // Tmp tables
#include "sql/sql_union.h" // Query_result_union
#include "sql/sql_view.h" // check_duplicate_names
#include "sql/table.h"
#include "sql/table_function.h"
#include "sql/thd_raii.h"
#include "strfunc.h"
#include "thr_lock.h"
class Opt_trace_context;
/**
Produces, from the first tmp TABLE object, a clone TABLE object for
Table_ref 'tl', to have a single materialization of multiple references
to a CTE.
How sharing of a single tmp table works
=======================================
There are several scenarios.
(1) Non-recursive CTE referenced only once: nothing special.
(2) Non-recursive CTE referenced more than once:
- multiple TABLEs, one TABLE_SHARE.
- The first ref in setup_materialized_derived() calls
create_tmp_table(); others call open_table_from_share().
- The first ref in create_derived() calls instantiate_tmp_table()
(which calls handler::create() then open_tmp_table()); others call
open_tmp_table(). open_tmp_table() calls handler::open().
- The first ref in materialize_derived() evaluates the subquery and does
all writes to the tmp table.
- Finally all refs set up a read access method (table scan, index scan,
index lookup, etc) and do reads, possibly interlaced (example: a
nested-loop join of two references to the CTE).
- The storage engine (MEMORY or InnoDB) must be informed of the uses above;
this is done by having TABLE_SHARE::ref_count>=2 for every handler::open()
call.
(3) Recursive CTE, referenced once or more than once:
All of (2) applies, where the set of refs is the non-recursive
ones (a recursive ref is a ref appearing in the definition of a recursive
CTE). Additionally:
- recursive refs do not call setup_materialized_derived(),
create_derived(), materialize_derived().
- right after a non-recursive ref has been in setup_materialized_derived(),
its recursive refs are replaced with clones of that ref, made with
open_table_from_share().
- the first non-recursive ref in materialized_derived() initiates the
with-recursive algorithm:
* its recursive refs call open_tmp_table().
* Then writes (to the non-recursive ref) and reads (from the recursive
refs) happen interlaced.
- a particular recursive ref is the UNION table, if UNION DISTINCT is
present in the CTE's definition: there is a single TABLE for it,
writes/reads to/from it happen interlaced (writes are done by
Query_result_union::send_data(); reads are done by the fake_query_block's
JOIN).
- Finally all non-recursive refs set up a read access method and do reads,
possibly interlaced.
- The storage engine (MEMORY or InnoDB) must be informed of the uses above;
this is done by having TABLE_SHARE::ref_count>=2 for every handler::open()
call.
- The Server code handling tmp table creation must also be informed:
see how Query_result_union::create_result_table() disables PK promotion.
How InnoDB manages the uses above
=================================
The storage engine needs to take measures so that inserts and reads
don't corrupt each other's behaviour. In InnoDB that means two things
(@see row_search_no_mvcc()):
(a) A certain way to use its cursor when reading
(b) Making the different handlers inform each other when one insertion
modifies the structure of the index tree (e.g. splits a page; this
triggers a refreshing of all read cursors).
Requirements on tmp tables used to write/read CTEs
==================================================
The internal tmp table must support a phase where table scans and
insertions happen interlaced, either issued from a single TABLE or from
multiple TABLE clones. If from a single TABLE, that object does repetitions
of {"write rows" then "init scan / read rows / close scan"}. If from
multiple TABLEs, one does "write rows", every other one does "init scan /
read rows / close scan".
During this, neither updates, nor deletes, nor any other type of read
access than table scans, are allowed on this table (they are allowed after
the phase's end).
Any started table scan on this table:
- must remember its position between two read operations, without influence
from other scans/inserts;
- must return rows inserted before and after it started (be catching up
continuously) (however, when it reports EOF it is allowed to stop catching
up and report EOF until closed).
- must return rows in insertion order.
- may be started from the first record (ha_rnd_init, ha_rnd_next) or from
the record where the previous scan was ended (position(), ha_rnd_end,
[...], ha_rnd_init, ha_rnd_pos(saved position), ha_rnd_next).
- must return positions (handler::position()) which are stable if a write
later occurs, so that a handler::rnd_pos() happening after the write finds
the same record.
Cursor re-positioning when MEMORY is converted to InnoDB
========================================================
See create_ondisk_from_heap(). A requirement is that InnoDB is able to
start a scan like this: rnd_init, rnd_pos(some PK value), rnd_next.
@param thd Thread handler
@param tl Table reference wanting the copy
@returns New clone, or NULL if error
*/
TABLE *Common_table_expr::clone_tmp_table(THD *thd, Table_ref *tl) {
// Should have been attached to CTE already.
assert(tl->common_table_expr() == this);
#ifndef NDEBUG
/*
We're adding a clone; if another clone has been opened before, it was not
aware of the new one, so perhaps the storage engine has not set up the
necessary logic to share data among clones. Check that no clone is open:
*/
Derived_refs_iterator it(tmp_tables[0]);
while (TABLE *t = it.get_next()) assert(!t->is_created() && !t->materialized);
#endif
TABLE *first = tmp_tables[0]->table;
// Allocate clone on the memory root of the TABLE_SHARE.
TABLE *t = static_cast<TABLE *>(first->s->mem_root.Alloc(sizeof(TABLE)));
if (!t) return nullptr; /* purecov: inspected */
if (open_table_from_share(thd, first->s, tl->alias,
/*
Pass db_stat == 0 to delay opening of table in SE,
as table is not instantiated in SE yet.
*/
0,
/* We need record[1] for this TABLE instance. */
EXTRA_RECORD |
/*
Use DELAYED_OPEN to have its own record[0]
(necessary because db_stat is 0).
Otherwise it would be shared with 'first'
and thus a write to tmp table would modify
the row just read by readers.
*/
DELAYED_OPEN,
0, t, false, nullptr))
return nullptr; /* purecov: inspected */
assert(t->s == first->s && t != first && t->file != first->file);
t->s->increment_ref_count();
t->s->tmp_handler_count++;
// In case this clone is used to fill the materialized table:
bitmap_set_all(t->write_set);
t->reginfo.lock_type = TL_WRITE;
t->copy_blobs = true;
tl->table = t;
t->pos_in_table_list = tl;
// If initial CTE table has a hash key, set up a hash key for
// all clones too.
if (first->hash_field) {
t->hash_field = t->field[0];
}
t->hidden_field_count = first->hidden_field_count;
t->set_not_started();
if (tmp_tables.push_back(tl)) return nullptr; /* purecov: inspected */
if (tl->derived_result != nullptr) {
// Make clone's copy of tmp_table_param contain correct info, so copy
tl->derived_result->tmp_table_param =
tmp_tables[0]->derived_result->tmp_table_param;
}
return t;
}
/**
Replaces the recursive reference in query block 'sl' with a clone of
the first tmp table.
@param thd Thread handler
@param sl Query block
@returns true if error
*/
bool Common_table_expr::substitute_recursive_reference(THD *thd,
Query_block *sl) {
Table_ref *tl = sl->recursive_reference;
assert(tl != nullptr && tl->table == nullptr);
TABLE *t = clone_tmp_table(thd, tl);
if (t == nullptr) return true; /* purecov: inspected */
// Eliminate the dummy unit:
tl->derived_query_expression()->exclude_tree();
tl->set_derived_query_expression(nullptr);
tl->set_privileges(SELECT_ACL);
return false;
}
void Common_table_expr::remove_table(Table_ref *tr) {
(void)tmp_tables.erase_value(tr);
}
/**
Resolve a derived table or view reference, including recursively resolving
contained subqueries.
@param thd thread handle
@param apply_semijoin Apply possible semi-join transforms if this is true
@returns false if success, true if error
*/
bool Table_ref::resolve_derived(THD *thd, bool apply_semijoin) {
DBUG_TRACE;
/*
Helper class which takes care of restoration of members like
THD::derived_tables_processing. These members are changed in this
method scope for resolving derived tables.
*/
class Context_handler {
public:
Context_handler(THD *thd)
: m_thd(thd),
m_deny_window_func_saved(thd->lex->m_deny_window_func),
m_derived_tables_processing_saved(thd->derived_tables_processing) {
/*
Window functions are allowed; they're aggregated in the derived
table's definition.
*/
m_thd->lex->m_deny_window_func = 0;
m_thd->derived_tables_processing = true;
}
~Context_handler() {
m_thd->lex->m_deny_window_func = m_deny_window_func_saved;
m_thd->derived_tables_processing = m_derived_tables_processing_saved;
}
private:
// Thread handle.
THD *m_thd;
// Saved state of THD::LEX::m_deny_window_func.
nesting_map m_deny_window_func_saved;
// Saved state of THD::derived_tables_processing.
bool m_derived_tables_processing_saved;
};
if (!is_view_or_derived() || is_merged() || is_table_function()) return false;
// Dummy derived tables for recursive references disappear before this stage
assert(this != query_block->recursive_reference);
if (is_derived() && derived->m_lateral_deps)
query_block->end_lateral_table = this;
const Context_handler ctx_handler(thd);
#ifndef NDEBUG // CTEs, derived tables can have outer references
if (is_view()) // but views cannot.
for (Query_block *sl = derived->first_query_block(); sl;
sl = sl->next_query_block()) {
// Make sure there are no outer references
assert(sl->context.outer_context == nullptr);
}
#endif
if (m_common_table_expr && m_common_table_expr->recursive &&
!derived->is_recursive()) {
// Ensure it's UNION.
if (!derived->is_union()) {
my_error(ER_CTE_RECURSIVE_REQUIRES_UNION, MYF(0), alias);
return true;
}
if (derived->global_parameters()->is_ordered()) {
/*
ORDER BY applied to the UNION causes the use of the union tmp
table. The fake_query_block would want to sort that table, which isn't
going to work as the table is incomplete when fake_query_block first
reads it. Workaround: put ORDER BY in the top query.
Another reason: allowing
ORDER BY <condition using fulltext> would make the UNION tmp table be
of MyISAM engine which recursive CTEs don't support.
LIMIT is allowed and will stop the row generation after N rows.
However, without ORDER BY the CTE's content is ordered in an
unpredictable way, so LIMIT theoretically returns an unpredictable
subset of rows. Users are on their own.
Instead of LIMIT, users can have a counter column and use a WHERE
on it, to control depth level, which sounds more intelligent than a
limit.
*/
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"ORDER BY over UNION "
"in recursive Common Table Expression");
return true;
}
/*
Should be:
SELECT1 UNION [DISTINCT | ALL] ... SELECTN
where SELECT1 is non-recursive, and all non-recursive SELECTs are before
all recursive SELECTs.
In SQL standard terms, the CTE must be "expandable" except that we allow
it to have more than one recursive SELECT.
*/
bool previous_is_recursive = false;
Query_block *last_non_recursive = nullptr;
for (Query_block *sl = derived->first_query_block(); sl;
sl = sl->next_query_block()) {
if (sl->is_recursive()) {
if (sl->parent()->term_type() != QT_UNION) {
my_error(ER_CTE_RECURSIVE_NOT_UNION, MYF(0));
return true;
} else if (sl->parent()->parent() != nullptr) {
/*
Right-nested UNIONs with recursive query blocks are not allowed. It
is expected that all possible flattening of UNION blocks is done
beforehand. Any nested UNION indicates a mixing of UNION DISTINCT
and UNION ALL, which cannot be flattened further.
*/
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"right nested recursive query blocks, in "
"Common Table Expression");
return true;
}
if (sl->is_ordered() || sl->has_limit() || sl->is_distinct()) {
/*
On top of posing implementation problems, it looks meaningless to
want to order/limit every iterative sub-result.
SELECT DISTINCT, if all expressions are constant, is implemented
as LIMIT in QEP_TAB::remove_duplicates(); do_query_block() starts
with send_records=0 so loses track of rows which have been sent in
previous iterations.
*/
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"ORDER BY / LIMIT / SELECT DISTINCT"
" in recursive query block of Common Table Expression");
return true;
}
if (sl == derived->last_distinct() && sl->next_query_block()) {
/*
Consider
anchor UNION ALL rec1 UNION DISTINCT rec2 UNION ALL rec3:
after execution of rec2 we must turn off the duplicate-checking
index; it will thus not contain the keys of rows of rec3, so it
becomes permanently unusable. The next iteration of rec1 or rec2
may insert rows which are actually duplicates of those of rec3.
So: if the last QB having DISTINCT to its left is recursive, and
it is followed by another QB (necessarily connected with ALL),
reject the query.
*/
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"recursive query blocks with"
" UNION DISTINCT then UNION ALL, in recursive "
"Common Table Expression");
return true;
}
} else {
if (previous_is_recursive) {
my_error(ER_CTE_RECURSIVE_REQUIRES_NONRECURSIVE_FIRST, MYF(0), alias);
return true;
}
last_non_recursive = sl;
}
previous_is_recursive = sl->is_recursive();
}
if (last_non_recursive == nullptr) {
my_error(ER_CTE_RECURSIVE_REQUIRES_NONRECURSIVE_FIRST, MYF(0), alias);
return true;
}
derived->first_recursive = last_non_recursive->next_query_block();
assert(derived->is_recursive());
}
DEBUG_SYNC(thd, "derived_not_set");
derived->derived_table = this;
if (!(derived_result = new (thd->mem_root) Query_result_union()))
return true; /* purecov: inspected */
/// Give the unit to the result (the other fields are ignored).
mem_root_deque<Item *> empty_list(thd->mem_root);
if (derived_result->prepare(thd, empty_list, derived_query_expression()))
return true;
/*
Prepare the underlying query expression of the derived table.
*/
if (derived->prepare(thd, derived_result, nullptr,
!apply_semijoin ? SELECT_NO_SEMI_JOIN : 0, 0))
return true;
if (check_duplicate_names(m_derived_column_names,
*derived->get_unit_column_types(), false))
return true;
if (is_derived()) {
// The underlying tables of a derived table are all readonly:
for (Query_block *sl = derived->first_query_block(); sl;
sl = sl->next_query_block())
sl->set_tables_readonly();
/*
A derived table is transparent with respect to privilege checking.
This setting means that privilege checks ignore the derived table
and are done properly in underlying base tables and views.
SELECT_ACL is used because derived tables cannot be used for update,
delete or insert.
*/
set_privileges(SELECT_ACL);
if (derived->m_lateral_deps) {
query_block->end_lateral_table = nullptr;
derived->m_lateral_deps &= ~PSEUDO_TABLE_BITS;
/*
It is possible that derived->m_lateral_deps is now 0, if it was
declared as LATERAL but actually contained no lateral references. Then
it will be handled as if LATERAL hadn't been specified.
*/
}
}
return false;
}
/// Helper function for Table_ref::setup_materialized_derived()
static void swap_column_names_of_unit_and_tmp_table(
const mem_root_deque<Item *> &unit_items,
const Create_col_name_list &tmp_table_col_names) {
if (CountVisibleFields(unit_items) != tmp_table_col_names.size())
// check_duplicate_names() will find and report error
return;
uint fieldnr = 0;
for (Item *item : VisibleFields(unit_items)) {
const char *s = item->item_name.ptr();
size_t l = item->item_name.length();
LEX_CSTRING &other_name =
const_cast<LEX_CSTRING &>(tmp_table_col_names[fieldnr]);
item->item_name.set(other_name.str, other_name.length);
other_name.str = s;
other_name.length = l;
fieldnr++;
}
}
/**
Copy field information like table_ref, context etc of all the fields
from the original expression to the cloned expression.
@param thd current thread
@param orig_expr original expression
@param cloned_expr cloned expression
@returns true on error, false otherwise
*/
bool copy_field_info(THD *thd, Item *orig_expr, Item *cloned_expr) {
class Field_info {
public:
Name_resolution_context *m_field_context{nullptr};
Table_ref *m_table_ref{nullptr};
Query_block *m_depended_from{nullptr};
Field *m_field{nullptr};
Field_info(Name_resolution_context *field_context, Table_ref *table_ref,
Query_block *depended_from, Field *field)
: m_field_context(field_context),
m_table_ref(table_ref),
m_depended_from(depended_from),
m_field(field) {}
};
mem_root_deque<Field_info> field_info(thd->mem_root);
class Collect_field_info : public Item_tree_walker {
public:
using Item_tree_walker::is_stopped;
using Item_tree_walker::stop_at;
};
Collect_field_info info;
Item_ref *ref_item = nullptr;
// Collect information for fields from the original expression
if (WalkItem(
orig_expr, enum_walk::PREFIX | enum_walk::POSTFIX,
[&info, &field_info, &ref_item](Item *inner_item) {
if (info.is_stopped(inner_item)) return false;
if (ref_item == inner_item) {
// We have returned back to this root (POSTFIX) from where
// we copied the "depended_from" information. Reset it now.
ref_item = nullptr;
return false;
}
if (inner_item->type() == Item::REF_ITEM &&
inner_item->is_outer_reference()) {
// If we have cloned a reference item that is an outer
// reference, the underlying field might not be marked as
// such. So we copy the "depended_from" information from the
// reference.
ref_item = down_cast<Item_ref *>(inner_item);
return false;
} else if (inner_item->type() == Item::FIELD_ITEM) {
Item_field *field = down_cast<Item_field *>(inner_item);
// If this field is being referenced, then it's "depended_from"
// is part of reference. If it is part of the field as well,
// check for consistency and then use the information.
Query_block *depended_from =
(ref_item != nullptr) ? ref_item->depended_from : nullptr;
Name_resolution_context *context =
(ref_item != nullptr) ? ref_item->context : nullptr;
assert(depended_from == nullptr ||
depended_from == field->depended_from ||
depended_from == field->context->query_block);
depended_from = field->depended_from != nullptr
? field->depended_from
: depended_from;
context = (context == nullptr)
? field->context
: ((field->context->query_block->nest_level >=
context->query_block->nest_level)
? field->context
: context);
if (field_info.push_back(Field_info(context, field->m_table_ref,
depended_from, field->field)))
return true;
info.stop_at(inner_item);
}
return false;
}))
return true;
// Copy the information to the fields in the cloned expression.
WalkItem(cloned_expr, enum_walk::PREFIX, [&field_info](Item *inner_item) {
if (inner_item->type() == Item::FIELD_ITEM) {
assert(!field_info.empty());
Item_field *field = down_cast<Item_field *>(inner_item);
field->context = field_info[0].m_field_context;
field->m_table_ref = field_info[0].m_table_ref;
field->depended_from = field_info[0].m_depended_from;
field->field = field_info[0].m_field;
field_info.pop_front();
}
return false;
});
assert(field_info.empty());
return false;
}
/**
Given an item and a query block, this function creates a clone of the
item (unresolved) by reparsing the item. Used during condition pushdown
to derived tables.
@param thd Current thread.
@param item Item to be reparsed to get a clone.
@param query_block query block where expression is being parsed
@param derived_table derived table to which the item belongs to.
"nullptr" when cloning to make a copy of the
original condition to be pushed down
to a derived table that has SET operations.
@returns A copy of the original item (unresolved) on success else nullptr.
*/
static Item *parse_expression(THD *thd, Item *item, Query_block *query_block,
Table_ref *derived_table) {
// Set up for parsing item
LEX *const old_lex = thd->lex;
LEX new_lex;
thd->lex = &new_lex;
if (lex_start(thd)) {
thd->lex = old_lex;
return nullptr; // OOM
}
View_creation_ctx *view_creation_ctx =
derived_table != nullptr ? derived_table->view_creation_ctx : nullptr;
const CHARSET_INFO *charset = view_creation_ctx != nullptr
? view_creation_ctx->get_client_cs()
: thd->charset();
// Take care not to print the variable index for stored procedure variables.
// Also do not write a cloned stored procedure variable to query logs.
thd->lex->reparse_derived_table_condition = true;
// Get the printout of the expression
StringBuffer<1024> str_buf(charset);
// For printing parameters we need to specify the flag QT_NO_DATA_EXPANSION
// because for a case when statement gets reprepared during execution, we
// still need Item_param::print() to print the '?' rather than the actual data
// specified for the parameter.
// The flag QT_TO_ARGUMENT_CHARSET is required for printing character string
// literals with correct character set introducer.
item->print(thd, &str_buf,
enum_query_type(QT_NO_DATA_EXPANSION | QT_TO_ARGUMENT_CHARSET));
str_buf.append('\0');
String str;
if (copy_string(thd->mem_root, &str, &str_buf)) return nullptr;
Derived_expr_parser_state parser_state;
parser_state.init(thd, str.ptr(), str.length());
// Native functions introduced for INFORMATION_SCHEMA system views are
// allowed to be invoked from *only* INFORMATION_SCHEMA system views.
// THD::parsing_system_view is set if the view being parsed is
// INFORMATION_SCHEMA system view and is allowed to invoke native function.
// If not, error ER_NO_ACCESS_TO_NATIVE_FCT is reported.
// Since we are cloning a condition here, we set it unconditionally
// to avoid the errors.
const bool parsing_system_view_saved = thd->parsing_system_view;
thd->parsing_system_view = true;
// Set the correct query block to parse the item. In some cases, like
// fulltext functions, parser needs to add them to ftfunc_list of the
// query block.
thd->lex->unit = query_block->master_query_expression();
thd->lex->set_current_query_block(query_block);
// If this query block is part of a stored procedure, we might have to
// parse a stored procedure variable (if present). Set the context
// correctly.
thd->lex->set_sp_current_parsing_ctx(old_lex->get_sp_current_parsing_ctx());
thd->lex->sphead = old_lex->sphead;
// If this is a prepare statement, we need to set prepare_mode correctly
// so that parser does not raise errors for "params(?)".
parser_state.m_lip.stmt_prepare_mode =
(old_lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_PREPARE);
if (parser_state.m_lip.stmt_prepare_mode) {
// Collect positions of all parameters in the "item". Used to create
// clones for the original parameters(Item_param::m_clones).
WalkItem(item, enum_walk::POSTFIX, [&thd](Item *inner_item) {
if (inner_item->type() == Item::PARAM_ITEM) {
thd->lex->reparse_derived_table_params_at.push_back(
down_cast<Item_param *>(inner_item)->pos_in_query);
}
return false;
});
thd->lex->param_list = old_lex->param_list;
}
// Get a newly created item from parser. Use the view creation
// context if the item being parsed is part of a view.
const bool result = parse_sql(thd, &parser_state, view_creation_ctx);
// If a statement is being re-prepared, then all the parameters
// that are cloned above need to be synced with the original
// parameters that are specified in the query. In case of
// re-prepare original parameters would have been assigned
// a value and therefore the types too. When fix_fields() is
// later called for the cloned expression, resolver would be
// able to assign the type correctly for the cloned parameter
// if it is synced with it's master.
if (parser_state.result != nullptr) {
List_iterator_fast<Item_param> it(thd->lex->param_list);
WalkItem(parser_state.result, enum_walk::POSTFIX, [&it](Item *inner_item) {
if (inner_item->type() == Item::PARAM_ITEM) {
Item_param *master;
while ((master = it++)) {
if (master->pos_in_query ==
down_cast<Item_param *>(inner_item)->pos_in_query)
master->sync_clones();
}
}
return false;
});
}
thd->lex->reparse_derived_table_condition = false;
// lex_end() would try to destroy sphead if set. So we reset it.
thd->lex->set_sp_current_parsing_ctx(nullptr);
thd->lex->sphead = nullptr;
// End of parsing.
lex_end(thd->lex);
thd->lex = old_lex;
thd->parsing_system_view = parsing_system_view_saved;
if (result) return nullptr;
return parser_state.result;
}
/**
Resolves the expression given. Used with parse_expression()
to clone an item during condition pushdown. For all the
column references in the expression, information like table
reference, field, context etc is expected to be correctly set.
This will just do a short cut fix_fields() for Item_field.
@param thd Current thread.
@param item Item to resolve.
@param query_block query block where this item needs to be
resolved.
@returns
resolved item if resolving was successful else nullptr.
*/
Item *resolve_expression(THD *thd, Item *item, Query_block *query_block) {
const Access_bitmask save_old_privilege = thd->want_privilege;
thd->want_privilege = 0;
Query_block *saved_current_query_block = thd->lex->current_query_block();
thd->lex->set_current_query_block(query_block);
const nesting_map save_allow_sum_func = thd->lex->allow_sum_func;
thd->lex->allow_sum_func |= static_cast<nesting_map>(1)
<< thd->lex->current_query_block()->nest_level;
if (item->fix_fields(thd, &item)) {
return nullptr;
}
// For items with params, propagate the default data type.
if (item->data_type() == MYSQL_TYPE_INVALID &&
item->propagate_type(thd, item->default_data_type())) {
return nullptr;
}
// Restore original state back
thd->want_privilege = save_old_privilege;
thd->lex->set_current_query_block(saved_current_query_block);
thd->lex->allow_sum_func = save_allow_sum_func;
return item;
}
/**
Clone an expression. This clone will be used for pushing conditions
down to a materialized derived table.
Cloning of an expression is done for two purposes:
1. When the derived table has a query expression with multiple query
blocks, each query block involved will be getting a clone of the
condition that is being pushed down.
2. When pushing a condition down to a derived table (with or without
unions), columns in the condition are replaced with the derived
table's expressions. If there are nested derived tables, these columns
will be replaced again with another derived table's expression when
the condition is pushed further down. If the derived table expressions
are simple columns, we would just keep replacing the original columns
with derived table columns. However if the derived table expressions
are not simple column references E.g. functions, then columns will be
replaced with functions, and arguments to these functions would get
replaced when the condition is pushed further down. However, arguments
to a function are part of both the SELECT clause of one derived table
and the WHERE clause of another derived table where the condition is
pushed down (Example below). To keep the sanity of the derived table's
expression, a clone is created and used before pushing a condition down.
Ex: Where cloned objects become necessary even when the derived
table does not have a UNION.
Consider a query like this one:
SELECT * FROM (SELECT i+10 AS n FROM
(SELECT a+7 AS i FROM t1) AS dt1 ) AS dt2 WHERE n > 100;
The first call to Query_block::push_conditions_to_derived_tables would
result in the following query. "n" in the where clause is
replaced with (i+10).
SELECT * FROM (SELECT i+10 AS n FROM
(SELECT a+7 AS i FROM t1) AS dt1 WHERE (dt1.i+10) > 100) as dt2;
The next call to Query_block::push_conditions_to_derived_tables should
result in the following query. "i" is replaced with "a+7".
SELECT * FROM (SELECT i+10 AS n FROM
(SELECT a+7 AS i FROM t1 WHERE ((t1.a+7)+10) > 100) AS dt1) as dt2;
However without cloned expressions, it would be
SELECT * FROM (SELECT ((t1.a+7)+10) AS n FROM
(SELECT a+7 AS i FROM t1 WHERE ((t1.a+7)+10) > 100) AS dt1) as dt2;
Notice that the column "i" in derived table dt2 is getting replaced
with (a+7) because the argument of the function in Item_func_plus
in (i+10) is replaced with (a+7). The arguments to the function
(i+10) need to be different so as to be able to replace them with
some other expressions later.
To clone an expression, we re-parse the expression to get another copy
and resolve it against the tables of the query block where it will be
placed.
@param thd Current thread
@param item Item for which clone is requested
@param derived_table derived table to which the item belongs to.
@returns
Cloned object for the item.
*/
Item *Query_block::clone_expression(THD *thd, Item *item,
Table_ref *derived_table) {
Item *cloned_item = parse_expression(thd, item, this, derived_table);
if (cloned_item == nullptr) return nullptr;
if (item->item_name.is_set())
cloned_item->item_name.set(item->item_name.ptr(), item->item_name.length());
// Collect details like table reference, field etc from the fields in the
// original expression. Assign it to the corresponding field in the cloned
// expression.
if (copy_field_info(thd, item, cloned_item)) return nullptr;
// A boolean expression to be cloned comes from a WHERE condition,
// which treats UNKNOWN the same as FALSE, thus the cloned expression
// should have the same property. apply_is_true() is ignored for
// non-boolean expressions
cloned_item->apply_is_true();
return resolve_expression(thd, cloned_item, this);
}
/**
Prepare a derived table or view for materialization.
The derived table must have been
- resolved by resolve_derived(),
- or resolved as a subquery (by Item_*_subselect_::fix_fields()) then
converted to a derived table.
@param thd THD pointer
@return false if successful, true if error
*/
bool Table_ref::setup_materialized_derived(THD *thd)
{
return setup_materialized_derived_tmp_table(thd) ||
derived->check_materialized_derived_query_blocks(thd);
}
/**
Sets up the tmp table to contain the derived table's rows.
@param thd THD pointer
@return false if successful, true if error
*/
bool Table_ref::setup_materialized_derived_tmp_table(THD *thd)
{
DBUG_TRACE;
assert(is_view_or_derived() && !is_merged() && table == nullptr);
DBUG_PRINT("info", ("algorithm: TEMPORARY TABLE"));
Opt_trace_context *const trace = &thd->opt_trace;
const Opt_trace_object trace_wrapper(trace);
Opt_trace_object trace_derived(trace, is_view() ? "view" : "derived");
trace_derived.add_utf8_table(this)
.add("select#", derived->first_query_block()->select_number)
.add("materialized", true);
set_uses_materialization();
// From resolver POV, columns of this table are readonly
set_readonly();
if (m_common_table_expr && m_common_table_expr->tmp_tables.size() > 0) {
trace_derived.add("reusing_tmp_table", true);
table = m_common_table_expr->clone_tmp_table(thd, this);
if (table == nullptr) return true; /* purecov: inspected */
derived_result->table = table;
}
if (table == nullptr) {
// Create the result table for the materialization
const ulonglong create_options =
derived->first_query_block()->active_options() | TMP_TABLE_ALL_COLUMNS;
if (m_derived_column_names) {
/*
Tmp table's columns will be created from derived->types (the SELECT
list), names included.
But the user asked that the tmp table's columns use other specified
names. So, we replace the names of SELECT list items with specified
column names, just for the duration of tmp table creation.
*/
swap_column_names_of_unit_and_tmp_table(*derived->get_unit_column_types(),
*m_derived_column_names);
}
// If we're materializing directly into the result and we have a UNION
// DISTINCT query, we're going to need a unique index for deduplication.
// (If we're materializing into a temporary table instead, the deduplication
// will happen on that table, and is not set here.) create_result_table()
// will figure out whether it wants to create it as the primary key or just
// a regular index.
const bool is_distinct = derived->can_materialize_directly_into_result() &&
derived->has_top_level_distinct();
const bool rc = derived_result->create_result_table(
thd, *derived->get_unit_column_types(), is_distinct, create_options,
alias, false);
if (m_derived_column_names) // Restore names
swap_column_names_of_unit_and_tmp_table(*derived->get_unit_column_types(),
*m_derived_column_names);
if (rc) return true; /* purecov: inspected */
table = derived_result->table;
table->pos_in_table_list = this;
if (m_common_table_expr && m_common_table_expr->tmp_tables.push_back(this))
return true; /* purecov: inspected */
}
table->s->tmp_table = NON_TRANSACTIONAL_TMP_TABLE;
// Table is "nullable" if inner table of an outer_join
if (is_inner_table_of_outer_join()) table->set_nullable();
dep_tables |= derived->m_lateral_deps;
return false;
}
/**
Sets up query blocks belonging to the query expression of a materialized
derived table.
@param thd_arg THD pointer
@return false if successful, true if error
*/
bool Query_expression::check_materialized_derived_query_blocks(THD *thd_arg) {
for (Query_block *sl = first_query_block(); sl; sl = sl->next_query_block()) {
// All underlying tables are read-only
sl->set_tables_readonly();
/*
Derived tables/view are materialized prior to UPDATE, thus we can skip
them from table uniqueness check
*/
sl->propagate_unique_test_exclusion();
/*
SELECT privilege is needed for all materialized derived tables and views,
and columns must be marked for read.
*/
if (sl->check_view_privileges(thd_arg, SELECT_ACL, SELECT_ACL)) return true;
// Set all selected fields to be read:
// @todo Do not set fields that are not referenced from outer query
const Column_privilege_tracker tracker(thd_arg, SELECT_ACL);
Mark_field mf(MARK_COLUMNS_READ);
for (Item *item : sl->fields) {
if (item->walk(&Item::check_column_privileges, enum_walk::PREFIX,
(uchar *)thd_arg))
return true;
item->walk(&Item::mark_field_in_map, enum_walk::POSTFIX, (uchar *)&mf);
}
}
return false;
}
/**
Prepare a table function for materialization.
@param thd THD pointer