/
sp_head.cc
4186 lines (3466 loc) · 114 KB
/
sp_head.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, 2016, Oracle and/or its affiliates.
Copyright (c) 2011, 2016, MariaDB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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 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 */
#include <my_global.h> /* NO_EMBEDDED_ACCESS_CHECKS */
#include "sql_priv.h"
#include "unireg.h"
#include "sql_prepare.h"
#include "sql_cache.h" // query_cache_*
#include "probes_mysql.h"
#include "sql_show.h" // append_identifier
#include "sql_db.h" // mysql_opt_change_db, mysql_change_db
#include "sql_acl.h" // *_ACL
#include "sql_array.h" // Dynamic_array
#include "log_event.h" // Query_log_event
#include "sql_derived.h" // mysql_handle_derived
#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation
#endif
#include "sp_head.h"
#include "sp.h"
#include "sp_pcontext.h"
#include "sp_rcontext.h"
#include "sp_cache.h"
#include "set_var.h"
#include "sql_parse.h" // cleanup_items
#include "sql_base.h" // close_thread_tables
#include "transaction.h" // trans_commit_stmt
#include "sql_audit.h"
#include "debug_sync.h"
/*
Sufficient max length of printed destinations and frame offsets (all uints).
*/
#define SP_INSTR_UINT_MAXLEN 8
#define SP_STMT_PRINT_MAXLEN 40
#include <my_user.h>
extern "C" uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first);
/**
Helper function which operates on a THD object to set the query start_time to
the current time.
@param[in, out] thd The session object
*/
static void reset_start_time_for_sp(THD *thd)
{
if (!thd->in_sub_stmt)
thd->set_start_time();
}
Item::Type
sp_map_item_type(enum enum_field_types type)
{
switch (type) {
case MYSQL_TYPE_BIT:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_INT24:
return Item::INT_ITEM;
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_NEWDECIMAL:
return Item::DECIMAL_ITEM;
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE:
return Item::REAL_ITEM;
default:
return Item::STRING_ITEM;
}
}
bool Item_splocal::append_for_log(THD *thd, String *str)
{
if (fix_fields(thd, NULL))
return true;
if (limit_clause_param)
return str->append_ulonglong(val_uint());
if (str->append(STRING_WITH_LEN(" NAME_CONST('")) ||
str->append(&m_name) ||
str->append(STRING_WITH_LEN("',")))
return true;
StringBuffer<STRING_BUFFER_USUAL_SIZE> str_value_holder(&my_charset_latin1);
Item *item= this_item();
String *str_value= item->type_handler()->print_item_value(thd, item,
&str_value_holder);
if (str_value)
return str->append(*str_value) || str->append(')');
else
return str->append(STRING_WITH_LEN("NULL)"));
}
/**
Returns a combination of:
- sp_head::MULTI_RESULTS: added if the 'cmd' is a command that might
result in multiple result sets being sent back.
- sp_head::CONTAINS_DYNAMIC_SQL: added if 'cmd' is one of PREPARE,
EXECUTE, DEALLOCATE.
*/
uint
sp_get_flags_for_command(LEX *lex)
{
uint flags;
switch (lex->sql_command) {
case SQLCOM_SELECT:
if (lex->result)
{
flags= 0; /* This is a SELECT with INTO clause */
break;
}
/* fallthrough */
case SQLCOM_ANALYZE:
case SQLCOM_OPTIMIZE:
case SQLCOM_PRELOAD_KEYS:
case SQLCOM_ASSIGN_TO_KEYCACHE:
case SQLCOM_CHECKSUM:
case SQLCOM_CHECK:
case SQLCOM_HA_READ:
case SQLCOM_SHOW_AUTHORS:
case SQLCOM_SHOW_BINLOGS:
case SQLCOM_SHOW_BINLOG_EVENTS:
case SQLCOM_SHOW_RELAYLOG_EVENTS:
case SQLCOM_SHOW_CHARSETS:
case SQLCOM_SHOW_COLLATIONS:
case SQLCOM_SHOW_CONTRIBUTORS:
case SQLCOM_SHOW_CREATE:
case SQLCOM_SHOW_CREATE_DB:
case SQLCOM_SHOW_CREATE_FUNC:
case SQLCOM_SHOW_CREATE_PROC:
case SQLCOM_SHOW_CREATE_EVENT:
case SQLCOM_SHOW_CREATE_TRIGGER:
case SQLCOM_SHOW_CREATE_USER:
case SQLCOM_SHOW_DATABASES:
case SQLCOM_SHOW_ERRORS:
case SQLCOM_SHOW_EXPLAIN:
case SQLCOM_SHOW_FIELDS:
case SQLCOM_SHOW_FUNC_CODE:
case SQLCOM_SHOW_GRANTS:
case SQLCOM_SHOW_ENGINE_STATUS:
case SQLCOM_SHOW_ENGINE_LOGS:
case SQLCOM_SHOW_ENGINE_MUTEX:
case SQLCOM_SHOW_EVENTS:
case SQLCOM_SHOW_KEYS:
case SQLCOM_SHOW_MASTER_STAT:
case SQLCOM_SHOW_OPEN_TABLES:
case SQLCOM_SHOW_PRIVILEGES:
case SQLCOM_SHOW_PROCESSLIST:
case SQLCOM_SHOW_PROC_CODE:
case SQLCOM_SHOW_SLAVE_HOSTS:
case SQLCOM_SHOW_SLAVE_STAT:
case SQLCOM_SHOW_STATUS:
case SQLCOM_SHOW_STATUS_FUNC:
case SQLCOM_SHOW_STATUS_PROC:
case SQLCOM_SHOW_STORAGE_ENGINES:
case SQLCOM_SHOW_TABLES:
case SQLCOM_SHOW_TABLE_STATUS:
case SQLCOM_SHOW_VARIABLES:
case SQLCOM_SHOW_WARNS:
case SQLCOM_REPAIR:
flags= sp_head::MULTI_RESULTS;
break;
/*
EXECUTE statement may return a result set, but doesn't have to.
We can't, however, know it in advance, and therefore must add
this statement here. This is ok, as is equivalent to a result-set
statement within an IF condition.
*/
case SQLCOM_EXECUTE:
case SQLCOM_EXECUTE_IMMEDIATE:
flags= sp_head::MULTI_RESULTS | sp_head::CONTAINS_DYNAMIC_SQL;
break;
case SQLCOM_PREPARE:
case SQLCOM_DEALLOCATE_PREPARE:
flags= sp_head::CONTAINS_DYNAMIC_SQL;
break;
case SQLCOM_CREATE_TABLE:
if (lex->tmp_table())
flags= 0;
else
flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
break;
case SQLCOM_DROP_TABLE:
if (lex->tmp_table())
flags= 0;
else
flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
break;
case SQLCOM_FLUSH:
flags= sp_head::HAS_SQLCOM_FLUSH;
break;
case SQLCOM_RESET:
flags= sp_head::HAS_SQLCOM_RESET;
break;
case SQLCOM_CREATE_INDEX:
case SQLCOM_CREATE_DB:
case SQLCOM_CREATE_VIEW:
case SQLCOM_CREATE_TRIGGER:
case SQLCOM_CREATE_USER:
case SQLCOM_CREATE_ROLE:
case SQLCOM_ALTER_TABLE:
case SQLCOM_ALTER_USER:
case SQLCOM_GRANT:
case SQLCOM_GRANT_ROLE:
case SQLCOM_REVOKE:
case SQLCOM_REVOKE_ROLE:
case SQLCOM_BEGIN:
case SQLCOM_RENAME_TABLE:
case SQLCOM_RENAME_USER:
case SQLCOM_DROP_INDEX:
case SQLCOM_DROP_DB:
case SQLCOM_REVOKE_ALL:
case SQLCOM_DROP_USER:
case SQLCOM_DROP_ROLE:
case SQLCOM_DROP_VIEW:
case SQLCOM_DROP_TRIGGER:
case SQLCOM_TRUNCATE:
case SQLCOM_COMMIT:
case SQLCOM_ROLLBACK:
case SQLCOM_LOAD:
case SQLCOM_LOCK_TABLES:
case SQLCOM_CREATE_PROCEDURE:
case SQLCOM_CREATE_SPFUNCTION:
case SQLCOM_ALTER_PROCEDURE:
case SQLCOM_ALTER_FUNCTION:
case SQLCOM_DROP_PROCEDURE:
case SQLCOM_DROP_FUNCTION:
case SQLCOM_CREATE_EVENT:
case SQLCOM_ALTER_EVENT:
case SQLCOM_DROP_EVENT:
case SQLCOM_INSTALL_PLUGIN:
case SQLCOM_UNINSTALL_PLUGIN:
flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
break;
case SQLCOM_DELETE:
case SQLCOM_DELETE_MULTI:
{
/*
DELETE normally doesn't return resultset, but there are 3 exceptions:
- DELETE ... RETURNING
- EXPLAIN DELETE ...
- ANALYZE DELETE ...
*/
if (lex->select_lex.item_list.is_empty() &&
!lex->describe && !lex->analyze_stmt)
flags= 0;
else
flags= sp_head::MULTI_RESULTS;
break;
}
case SQLCOM_UPDATE:
case SQLCOM_UPDATE_MULTI:
case SQLCOM_INSERT:
case SQLCOM_REPLACE:
case SQLCOM_REPLACE_SELECT:
case SQLCOM_INSERT_SELECT:
{
if (!lex->describe && !lex->analyze_stmt)
flags= 0;
else
flags= sp_head::MULTI_RESULTS;
break;
}
default:
flags= 0;
break;
}
return flags;
}
/**
Prepare an Item for evaluation (call of fix_fields).
@param thd thread handler
@param it_addr pointer on item refernce
@retval
NULL error
@retval
non-NULL prepared item
*/
Item *
sp_prepare_func_item(THD* thd, Item **it_addr)
{
DBUG_ENTER("sp_prepare_func_item");
it_addr= (*it_addr)->this_item_addr(thd, it_addr);
if (!(*it_addr)->fixed &&
((*it_addr)->fix_fields(thd, it_addr) ||
(*it_addr)->check_cols(1)))
{
DBUG_PRINT("info", ("fix_fields() failed"));
DBUG_RETURN(NULL);
}
DBUG_RETURN(*it_addr);
}
/**
Evaluate an expression and store the result in the field.
@param thd current thread object
@param result_field the field to store the result
@param expr_item_ptr the root item of the expression
@retval
FALSE on success
@retval
TRUE on error
*/
bool
sp_eval_expr(THD *thd, Field *result_field, Item **expr_item_ptr)
{
Item *expr_item;
enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
bool save_abort_on_warning= thd->abort_on_warning;
bool save_stmt_modified_non_trans_table=
thd->transaction.stmt.modified_non_trans_table;
DBUG_ENTER("sp_eval_expr");
if (!*expr_item_ptr)
goto error;
if (!(expr_item= sp_prepare_func_item(thd, expr_item_ptr)))
goto error;
/*
Set THD flags to emit warnings/errors in case of overflow/type errors
during saving the item into the field.
Save original values and restore them after save.
*/
thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
thd->abort_on_warning= thd->is_strict_mode();
thd->transaction.stmt.modified_non_trans_table= FALSE;
/* Save the value in the field. Convert the value if needed. */
expr_item->save_in_field(result_field, 0);
thd->count_cuted_fields= save_count_cuted_fields;
thd->abort_on_warning= save_abort_on_warning;
thd->transaction.stmt.modified_non_trans_table= save_stmt_modified_non_trans_table;
if (!thd->is_error())
DBUG_RETURN(FALSE);
error:
/*
In case of error during evaluation, leave the result field set to NULL.
Sic: we can't do it in the beginning of the function because the
result field might be needed for its own re-evaluation, e.g. case of
set x = x + 1;
*/
result_field->set_null();
DBUG_RETURN (TRUE);
}
/**
Create temporary sp_name object from MDL key.
@note The lifetime of this object is bound to the lifetime of the MDL_key.
This should be fine as sp_name objects created by this constructor
are mainly used for SP-cache lookups.
@param key MDL key containing database and routine name.
@param qname_buff Buffer to be used for storing quoted routine name
(should be at least 2*NAME_LEN+1+1 bytes).
*/
sp_name::sp_name(const MDL_key *key, char *qname_buff)
:Database_qualified_name((char*)key->db_name(), key->db_name_length(),
(char*)key->name(), key->name_length()),
m_explicit_name(false)
{
if (m_db.length)
strxmov(qname_buff, m_db.str, ".", m_name.str, NullS);
else
strmov(qname_buff, m_name.str);
}
/**
Check that the name 'ident' is ok. It's assumed to be an 'ident'
from the parser, so we only have to check length and trailing spaces.
The former is a standard requirement (and 'show status' assumes a
non-empty name), the latter is a mysql:ism as trailing spaces are
removed by get_field().
@retval
TRUE bad name
@retval
FALSE name is ok
*/
bool
check_routine_name(LEX_STRING *ident)
{
DBUG_ASSERT(ident);
DBUG_ASSERT(ident->str);
if (!ident->str[0] || ident->str[ident->length-1] == ' ')
{
my_error(ER_SP_WRONG_NAME, MYF(0), ident->str);
return TRUE;
}
if (check_ident_length(ident))
return TRUE;
return FALSE;
}
/*
*
* sp_head
*
*/
void *
sp_head::operator new(size_t size) throw()
{
DBUG_ENTER("sp_head::operator new");
MEM_ROOT own_root;
sp_head *sp;
init_sql_alloc(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC, MYF(0));
sp= (sp_head *) alloc_root(&own_root, size);
if (sp == NULL)
DBUG_RETURN(NULL);
sp->main_mem_root= own_root;
DBUG_PRINT("info", ("mem_root 0x%lx", (ulong) &sp->mem_root));
DBUG_RETURN(sp);
}
void
sp_head::operator delete(void *ptr, size_t size) throw()
{
DBUG_ENTER("sp_head::operator delete");
MEM_ROOT own_root;
if (ptr == NULL)
DBUG_VOID_RETURN;
sp_head *sp= (sp_head *) ptr;
/* Make a copy of main_mem_root as free_root will free the sp */
own_root= sp->main_mem_root;
DBUG_PRINT("info", ("mem_root 0x%lx moved to 0x%lx",
(ulong) &sp->mem_root, (ulong) &own_root));
free_root(&own_root, MYF(0));
DBUG_VOID_RETURN;
}
sp_head::sp_head()
:Query_arena(&main_mem_root, STMT_INITIALIZED_FOR_SP),
Database_qualified_name(null_lex_str, null_lex_str),
m_flags(0),
m_sp_cache_version(0),
m_creation_ctx(0),
unsafe_flags(0),
m_recursion_level(0),
m_next_cached_sp(0),
m_cont_level(0)
{
m_first_instance= this;
m_first_free_instance= this;
m_last_cached_sp= this;
m_return_field_def.charset = NULL;
/*
FIXME: the only use case when name is NULL is events, and it should
be rewritten soon. Remove the else part and replace 'if' with
an assert when this is done.
*/
m_qname= null_lex_str;
DBUG_ENTER("sp_head::sp_head");
m_backpatch.empty();
m_cont_backpatch.empty();
m_lex.empty();
my_hash_init(&m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0);
my_hash_init(&m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key,
0, 0);
m_body_utf8.str= NULL;
m_body_utf8.length= 0;
DBUG_VOID_RETURN;
}
void
sp_head::init(LEX *lex)
{
DBUG_ENTER("sp_head::init");
lex->spcont= m_pcont= new sp_pcontext();
if (!lex->spcont)
DBUG_VOID_RETURN;
/*
Altough trg_table_fields list is used only in triggers we init for all
types of stored procedures to simplify reset_lex()/restore_lex() code.
*/
lex->trg_table_fields.empty();
my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8, MYF(0));
m_param_begin= NULL;
m_param_end= NULL;
m_body_begin= NULL ;
m_qname.str= NULL;
m_qname.length= 0;
m_explicit_name= false;
m_db.str= NULL;
m_db.length= 0;
m_name.str= NULL;
m_name.length= 0;
m_params.str= NULL;
m_params.length= 0;
m_body.str= NULL;
m_body.length= 0;
m_defstr.str= NULL;
m_defstr.length= 0;
m_return_field_def.charset= NULL;
DBUG_VOID_RETURN;
}
void
sp_head::init_sp_name(THD *thd, sp_name *spname)
{
DBUG_ENTER("sp_head::init_sp_name");
/* Must be initialized in the parser. */
DBUG_ASSERT(spname && spname->m_db.str && spname->m_db.length);
/* We have to copy strings to get them into the right memroot. */
m_db.length= spname->m_db.length;
m_db.str= strmake_root(thd->mem_root, spname->m_db.str, spname->m_db.length);
m_name.length= spname->m_name.length;
m_name.str= strmake_root(thd->mem_root, spname->m_name.str,
spname->m_name.length);
m_explicit_name= spname->m_explicit_name;
spname->make_qname(thd, &m_qname);
DBUG_VOID_RETURN;
}
void
sp_head::set_body_start(THD *thd, const char *begin_ptr)
{
m_body_begin= begin_ptr;
thd->m_parser_state->m_lip.body_utf8_start(thd, begin_ptr);
}
void
sp_head::set_stmt_end(THD *thd)
{
Lex_input_stream *lip= & thd->m_parser_state->m_lip; /* shortcut */
const char *end_ptr= lip->get_cpp_ptr(); /* shortcut */
uint not_used;
/* Make the string of parameters. */
if (m_param_begin && m_param_end)
{
m_params.length= m_param_end - m_param_begin;
m_params.str= thd->strmake(m_param_begin, m_params.length);
}
/* Remember end pointer for further dumping of whole statement. */
thd->lex->stmt_definition_end= end_ptr;
/* Make the string of body (in the original character set). */
m_body.length= end_ptr - m_body_begin;
m_body.str= thd->strmake(m_body_begin, m_body.length);
trim_whitespace(thd->charset(), &m_body, ¬_used);
/* Make the string of UTF-body. */
lip->body_utf8_append(end_ptr);
m_body_utf8.length= lip->get_body_utf8_length();
m_body_utf8.str= thd->strmake(lip->get_body_utf8_str(), m_body_utf8.length);
trim_whitespace(thd->charset(), &m_body_utf8, ¬_used);
/*
Make the string of whole stored-program-definition query (in the
original character set).
*/
m_defstr.length= end_ptr - lip->get_cpp_buf();
m_defstr.str= thd->strmake(lip->get_cpp_buf(), m_defstr.length);
trim_whitespace(thd->charset(), &m_defstr, ¬_used);
}
sp_head::~sp_head()
{
LEX *lex;
sp_instr *i;
DBUG_ENTER("sp_head::~sp_head");
/* sp_head::restore_thd_mem_root() must already have been called. */
DBUG_ASSERT(m_thd == NULL);
for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
delete i;
delete_dynamic(&m_instr);
delete m_pcont;
free_items();
/*
If we have non-empty LEX stack then we just came out of parser with
error. Now we should delete all auxilary LEXes and restore original
THD::lex. It is safe to not update LEX::ptr because further query
string parsing and execution will be stopped anyway.
*/
while ((lex= (LEX *)m_lex.pop()))
{
THD *thd= lex->thd;
thd->lex->sphead= NULL;
lex_end(thd->lex);
delete thd->lex;
thd->lex= lex;
}
my_hash_free(&m_sptabs);
my_hash_free(&m_sroutines);
delete m_next_cached_sp;
DBUG_VOID_RETURN;
}
/**
This is only used for result fields from functions (both during
fix_length_and_dec() and evaluation).
*/
Field *
sp_head::create_result_field(uint field_max_length, const char *field_name,
TABLE *table)
{
Field *field;
DBUG_ENTER("sp_head::create_result_field");
/*
m_return_field_def.length is always set to the field length calculated
by the parser, according to the RETURNS clause. See prepare_create_field()
in sql_table.cc. Value examples, depending on data type:
- 11 for INT (character representation length)
- 20 for BIGINT (character representation length)
- 22 for DOUBLE (character representation length)
- N for CHAR(N) CHARACTER SET latin1 (octet length)
- 3*N for CHAR(N) CHARACTER SET utf8 (octet length)
- 8 for blob-alike data types (packed length !!!)
field_max_length is also set according to the data type in the RETURNS
clause but can have different values depending on the execution stage:
1. During direct execution:
field_max_length is 0, because Item_func_sp::fix_length_and_dec() has
not been called yet, so Item_func_sp::max_length is 0 by default.
2a. During PREPARE:
field_max_length is 0, because Item_func_sp::fix_length_and_dec()
has not been called yet. It's called after create_result_field().
2b. During EXEC:
field_max_length is set to the maximum possible octet length of the
RETURNS data type.
- N for CHAR(N) CHARACTER SET latin1 (octet length)
- 3*N for CHAR(N) CHARACTER SET utf8 (octet length)
- 255 for TINYBLOB (octet length, not packed length !!!)
Perhaps we should refactor prepare_create_field() to set
Create_field::length to maximum octet length for BLOBs,
instead of packed length).
*/
DBUG_ASSERT(field_max_length <= m_return_field_def.length ||
(current_thd->stmt_arena->is_stmt_execute() &&
m_return_field_def.length == 8 &&
(m_return_field_def.pack_flag &
(FIELDFLAG_BLOB|FIELDFLAG_GEOM))));
field= m_return_field_def.make_field(table->s, /* TABLE_SHARE ptr */
table->in_use->mem_root,
field_name ?
field_name :
(const char *) m_name.str);
field->vcol_info= m_return_field_def.vcol_info;
if (field)
field->init(table);
DBUG_RETURN(field);
}
int cmp_rqp_locations(Rewritable_query_parameter * const *a,
Rewritable_query_parameter * const *b)
{
return (int)((*a)->pos_in_query - (*b)->pos_in_query);
}
/*
StoredRoutinesBinlogging
This paragraph applies only to statement-based binlogging. Row-based
binlogging does not need anything special like this.
Top-down overview:
1. Statements
Statements that have is_update_query(stmt) == TRUE are written into the
binary log verbatim.
Examples:
UPDATE tbl SET tbl.x = spfunc_w_side_effects()
UPDATE tbl SET tbl.x=1 WHERE spfunc_w_side_effect_that_returns_false(tbl.y)
Statements that have is_update_query(stmt) == FALSE (e.g. SELECTs) are not
written into binary log. Instead we catch function calls the statement
makes and write it into binary log separately (see #3).
2. PROCEDURE calls
CALL statements are not written into binary log. Instead
* Any FUNCTION invocation (in SET, IF, WHILE, OPEN CURSOR and other SP
instructions) is written into binlog separately.
* Each statement executed in SP is binlogged separately, according to rules
in #1, with the exception that we modify query string: we replace uses
of SP local variables with NAME_CONST('spvar_name', <spvar-value>) calls.
This substitution is done in subst_spvars().
3. FUNCTION calls
In sp_head::execute_function(), we check
* If this function invocation is done from a statement that is written
into the binary log.
* If there were any attempts to write events to the binary log during
function execution (grep for start_union_events and stop_union_events)
If the answers are No and Yes, we write the function call into the binary
log as "SELECT spfunc(<param1value>, <param2value>, ...)"
4. Miscellaneous issues.
4.1 User variables.
When we call mysql_bin_log.write() for an SP statement, thd->user_var_events
must hold set<{var_name, value}> pairs for all user variables used during
the statement execution.
This set is produced by tracking user variable reads during statement
execution.
For SPs, this has the following implications:
1) thd->user_var_events may contain events from several SP statements and
needs to be valid after exection of these statements was finished. In
order to achieve that, we
* Allocate user_var_events array elements on appropriate mem_root (grep
for user_var_events_alloc).
* Use is_query_in_union() to determine if user_var_event is created.
2) We need to empty thd->user_var_events after we have wrote a function
call. This is currently done by making
reset_dynamic(&thd->user_var_events);
calls in several different places. (TODO cosider moving this into
mysql_bin_log.write() function)
4.2 Auto_increment storage in binlog
As we may write two statements to binlog from one single logical statement
(case of "SELECT func1(),func2()": it is binlogged as "SELECT func1()" and
then "SELECT func2()"), we need to reset auto_increment binlog variables
after each binlogged SELECT. Otherwise, the auto_increment value of the
first SELECT would be used for the second too.
*/
/**
Replace thd->query{_length} with a string that one can write to
the binlog.
The binlog-suitable string is produced by replacing references to SP local
variables with NAME_CONST('sp_var_name', value) calls.
@param thd Current thread.
@param instr Instruction (we look for Item_splocal instances in
instr->free_list)
@param query_str Original query string
@return
- FALSE on success.
thd->query{_length} either has been appropriately replaced or there
is no need for replacements.
- TRUE out of memory error.
*/
static bool
subst_spvars(THD *thd, sp_instr *instr, LEX_STRING *query_str)
{
DBUG_ENTER("subst_spvars");
Dynamic_array<Rewritable_query_parameter*> rewritables;
char *pbuf;
StringBuffer<512> qbuf;
Copy_query_with_rewrite acc(thd, query_str->str, query_str->length, &qbuf);
/* Find rewritable Items used in this statement */
for (Item *item= instr->free_list; item; item= item->next)
{
Rewritable_query_parameter *rqp= item->get_rewritable_query_parameter();
if (rqp && rqp->pos_in_query)
rewritables.append(rqp);
}
if (!rewritables.elements())
DBUG_RETURN(FALSE);
rewritables.sort(cmp_rqp_locations);
thd->query_name_consts= rewritables.elements();
for (Rewritable_query_parameter **rqp= rewritables.front();
rqp <= rewritables.back(); rqp++)
{
if (acc.append(*rqp))
DBUG_RETURN(TRUE);
}
if (acc.finalize())
DBUG_RETURN(TRUE);
/*
Allocate additional space at the end of the new query string for the
query_cache_send_result_to_client function.
The query buffer layout is:
buffer :==
<statement> The input statement(s)
'\0' Terminating null char
<length> Length of following current database name 2
<db_name> Name of current database
<flags> Flags struct
*/
int buf_len= (qbuf.length() + 1 + QUERY_CACHE_DB_LENGTH_SIZE +
thd->db_length + QUERY_CACHE_FLAGS_SIZE + 1);
if ((pbuf= (char *) alloc_root(thd->mem_root, buf_len)))
{
char *ptr= pbuf + qbuf.length();
memcpy(pbuf, qbuf.ptr(), qbuf.length());
*ptr= 0;
int2store(ptr+1, thd->db_length);
}
else
DBUG_RETURN(TRUE);
thd->set_query(pbuf, qbuf.length());
DBUG_RETURN(FALSE);
}
/**
Return appropriate error about recursion limit reaching
@param thd Thread handle
@remark For functions and triggers we return error about
prohibited recursion. For stored procedures we
return about reaching recursion limit.
*/
void sp_head::recursion_level_error(THD *thd)
{
if (m_type == TYPE_ENUM_PROCEDURE)
{
my_error(ER_SP_RECURSION_LIMIT, MYF(0),
static_cast<int>(thd->variables.max_sp_recursion_depth),
m_name.str);
}
else
my_error(ER_SP_NO_RECURSION, MYF(0));
}
/**
Execute the routine. The main instruction jump loop is there.
Assume the parameters already set.
@param thd Thread context.
@param merge_da_on_success Flag specifying if Warning Info should be
propagated to the caller on Completion
Condition or not.
@todo
- Will write this SP statement into binlog separately
(TODO: consider changing the condition to "not inside event union")
@return Error status.
@retval
FALSE on success
@retval
TRUE on error
*/
bool
sp_head::execute(THD *thd, bool merge_da_on_success)
{
DBUG_ENTER("sp_head::execute");
char saved_cur_db_name_buf[SAFE_NAME_LEN+1];
LEX_STRING saved_cur_db_name=
{ saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
bool cur_db_changed= FALSE;
sp_rcontext *ctx= thd->spcont;
bool err_status= FALSE;
uint ip= 0;
ulonglong save_sql_mode;
bool save_abort_on_warning;
Query_arena *old_arena;
/* per-instruction arena */
MEM_ROOT execute_mem_root;
Query_arena execute_arena(&execute_mem_root, STMT_INITIALIZED_FOR_SP),
backup_arena;
query_id_t old_query_id;
TABLE *old_derived_tables;
LEX *old_lex;
Item_change_list old_change_list;
String old_packet;
uint old_server_status;
const uint status_backup_mask= SERVER_STATUS_CURSOR_EXISTS |
SERVER_STATUS_LAST_ROW_SENT;
Reprepare_observer *save_reprepare_observer= thd->m_reprepare_observer;
Object_creation_ctx *UNINIT_VAR(saved_creation_ctx);
Diagnostics_area *da= thd->get_stmt_da();
Warning_info sp_wi(da->warning_info_id(), false, true);
/* this 7*STACK_MIN_SIZE is a complex matter with a long history (see it!) */
if (check_stack_overrun(thd, 7 * STACK_MIN_SIZE, (uchar*)&old_packet))