-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
sql_prepare.cc
4142 lines (3461 loc) · 136 KB
/
sql_prepare.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 */
/**
@file
This file contains the implementation of prepared statements.
When one prepares a statement:
- Server gets the query from client with command 'COM_STMT_PREPARE';
in the following format:
[COM_STMT_PREPARE:1] [query]
- Parse the query and recognize any parameter markers '?' and
store its information list in lex->param_list
- Allocate a new statement for this prepare; and keep this in
'thd->stmt_map'.
- Without executing the query, return back to client the total
number of parameters along with result-set metadata information
(if any) in the following format:
@verbatim
[STMT_ID:4]
[Column_count:2]
[Param_count:2]
[Params meta info (stubs only for now)] (if Param_count > 0)
[Columns meta info] (if Column_count > 0)
@endverbatim
During prepare the tables used in a statement are opened, but no
locks are acquired. Table opening will block any DDL during the
operation, and we do not need any locks as we neither read nor
modify any data during prepare. Tables are closed after prepare
finishes.
When one executes a statement:
- Server gets the command 'COM_STMT_EXECUTE' to execute the
previously prepared query. If there are any parameter markers, then the
client will send the data in the following format:
@verbatim
[COM_STMT_EXECUTE:1]
[STMT_ID:4]
[NULL_BITS:(param_count+7)/8)]
[TYPES_SUPPLIED_BY_CLIENT(0/1):1]
[[length]data]
[[length]data] .. [[length]data].
@endverbatim
(Note: Except for string/binary types; all other types will not be
supplied with length field)
- If it is a first execute or types of parameters were altered by client,
then setup the conversion routines.
- Assign parameter items from the supplied data.
- Execute the query without re-parsing and send back the results
to client
During execution of prepared statement tables are opened and locked
the same way they would for normal (non-prepared) statement
execution. Tables are unlocked and closed after the execution.
When one supplies long data for a placeholder:
- Server gets the long data in pieces with command type
'COM_STMT_SEND_LONG_DATA'.
- The packet received will have the format as:
[COM_STMT_SEND_LONG_DATA:1][STMT_ID:4][parameter_number:2][data]
- data from the packet is appended to the long data value buffer for this
placeholder.
- It's up to the client to stop supplying data chunks at any point. The
server doesn't care; also, the server doesn't notify the client whether
it got the data or not; if there is any error, then it will be returned
at statement execute.
*/
#include "sql/sql_prepare.h"
#include "my_config.h"
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <limits>
#include <memory>
#include <unordered_map>
#include <utility>
#include "decimal.h"
#include "field_types.h"
#include "m_ctype.h"
#include "m_string.h"
#include "map_helpers.h"
#include "my_alloc.h"
#include "my_byteorder.h"
#include "my_command.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "my_time.h"
#include "mysql/com_data.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/plugin_audit.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/psi/mysql_ps.h" // MYSQL_EXECUTE_PS
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysqld_error.h"
#include "scope_guard.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h" // check_table_access
#include "sql/auth/sql_security_ctx.h"
#include "sql/binlog.h"
#include "sql/debug_sync.h"
#include "sql/derror.h" // ER_THD
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/item_func.h" // user_var_entry
#include "sql/log.h" // query_logger
#include "sql/mdl.h"
#include "sql/my_decimal.h"
#include "sql/mysqld.h" // opt_general_log
#include "sql/opt_trace.h" // Opt_trace_array
#include "sql/protocol.h"
#include "sql/protocol_classic.h"
#include "sql/psi_memory_key.h"
#include "sql/query_options.h"
#include "sql/query_result.h"
#include "sql/resourcegroups/resource_group_basic_types.h"
#include "sql/resourcegroups/resource_group_mgr.h"
#include "sql/session_tracker.h"
#include "sql/set_var.h" // set_var_base
#include "sql/sp_cache.h" // sp_cache_enforce_limit
#include "sql/sql_audit.h" // mysql_global_audit_mask
#include "sql/sql_base.h" // open_tables_for_query, open_temporary_table
#include "sql/sql_class.h"
#include "sql/sql_cmd.h"
#include "sql/sql_cmd_ddl_table.h"
#include "sql/sql_const.h"
#include "sql/sql_cursor.h" // Server_side_cursor
#include "sql/sql_db.h" // mysql_change_db
#include "sql/sql_digest_stream.h"
#include "sql/sql_handler.h" // mysql_ha_rm_tables
#include "sql/sql_insert.h" // Query_result_create
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_parse.h" // sql_command_flags
#include "sql/sql_profile.h"
#include "sql/sql_query_rewrite.h"
#include "sql/sql_rewrite.h" // mysql_rewrite_query
#include "sql/sql_view.h" // create_view_precheck
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql/thr_malloc.h"
#include "sql/transaction.h" // trans_rollback_implicit
#include "sql/window.h"
#include "sql_string.h"
#include "violite.h"
namespace resourcegroups {
class Resource_group;
} // namespace resourcegroups
using std::max;
using std::min;
/****************************************************************************/
namespace {
/**
Execute one SQL statement in an isolated context.
*/
class Execute_sql_statement : public Server_runnable {
public:
Execute_sql_statement(LEX_STRING sql_text);
bool execute_server_code(THD *thd) override;
private:
LEX_STRING m_sql_text;
};
/**
A result class used to send cursor rows using the binary protocol.
*/
class Query_fetch_protocol_binary final : public Query_result_send {
Protocol_binary protocol;
public:
explicit Query_fetch_protocol_binary(THD *thd)
: Query_result_send(), protocol(thd) {}
bool send_result_set_metadata(THD *thd, const mem_root_deque<Item *> &list,
uint flags) override;
bool send_data(THD *thd, const mem_root_deque<Item *> &items) override;
bool send_eof(THD *thd) override;
};
} // namespace
/**
Protocol_local: a helper class to intercept the result
of the data written to the network.
At the start of every result set, start_result_metadata allocates m_rset to
prepare for the results. The metadata is stored on m_current_row which will
be transferred to m_fields in end_result_metadata. The memory for the
metadata is allocated on m_rset_root.
Then, for every row of the result received, each of the fields is stored in
m_current_row. Then the row is moved to m_rset and m_current_row is cleared
to receive the next row. The memory for all the results are also stored in
m_rset_root.
Finally, at the end of the result set, a new instance of Ed_result_set is
created on m_rset_root and the result set (m_rset and m_fields) is moved into
this instance. The ownership of MEM_ROOT m_rset_root is also transferred to
this instance. So, at the end we have a fresh MEM_ROOT, cleared m_rset and
m_fields to accept the next result set.
*/
class Protocol_local final : public Protocol {
public:
Protocol_local(THD *thd, Ed_connection *ed_connection);
~Protocol_local() override { m_rset_root.Clear(); }
int read_packet() override;
int get_command(COM_DATA *com_data, enum_server_command *cmd) override;
ulong get_client_capabilities() override;
bool has_client_capability(unsigned long client_capability) override;
void end_partial_result_set() override;
int shutdown(bool server_shutdown = false) override;
bool connection_alive() const override;
void start_row() override;
bool end_row() override;
void abort_row() override {}
uint get_rw_status() override;
bool get_compression() override;
char *get_compression_algorithm() override;
uint get_compression_level() override;
bool start_result_metadata(uint num_cols, uint flags,
const CHARSET_INFO *resultcs) override;
bool end_result_metadata() override;
bool send_field_metadata(Send_field *field,
const CHARSET_INFO *charset) override;
bool flush() override { return true; }
bool send_parameters(List<Item_param> *, bool) override { return false; }
bool store_ps_status(ulong, uint, uint, ulong) override { return false; }
protected:
bool store_null() override;
bool store_tiny(longlong from, uint32) override;
bool store_short(longlong from, uint32) override;
bool store_long(longlong from, uint32) override;
bool store_longlong(longlong from, bool unsigned_flag, uint32) override;
bool store_decimal(const my_decimal *, uint, uint) override;
bool store_string(const char *from, size_t length,
const CHARSET_INFO *cs) override;
bool store_datetime(const MYSQL_TIME &time, uint precision) override;
bool store_date(const MYSQL_TIME &time) override;
bool store_time(const MYSQL_TIME &time, uint precision) override;
bool store_float(float value, uint32 decimals, uint32 zerofill) override;
bool store_double(double value, uint32 decimals, uint32 zerofill) override;
bool store_field(const Field *field) override;
enum enum_protocol_type type() const override { return PROTOCOL_LOCAL; }
enum enum_vio_type connection_type() const override { return VIO_TYPE_LOCAL; }
bool send_ok(uint server_status, uint statement_warn_count,
ulonglong affected_rows, ulonglong last_insert_id,
const char *message) override;
bool send_eof(uint server_status, uint statement_warn_count) override;
bool send_error(uint sql_errno, const char *err_msg,
const char *sqlstate) override;
private:
bool store_string(const char *str, size_t length, const CHARSET_INFO *src_cs,
const CHARSET_INFO *dst_cs);
bool store_column(const void *data, size_t length);
void opt_add_row_to_rset();
Ed_connection *m_connection;
MEM_ROOT m_rset_root;
List<Ed_row> *m_rset;
size_t m_column_count;
Ed_column *m_current_row;
Ed_column *m_current_column;
Ed_row *m_fields;
bool m_send_metadata;
THD *m_thd;
};
/******************************************************************************
Implementation
******************************************************************************/
/**
Rewrite the current query (to obfuscate passwords etc.).
Side-effect: thd->rewritten_query() may be populated with a rewritten
query. If the query is not of a rewritable type,
thd->rewritten_query() will be empty.
@param thd thread handle
*/
static inline void rewrite_query(THD *thd) {
/*
thd->m_rewritten_query may already contain "PREPARE stmt FROM ..."
at this point, so we reset it here so mysql_rewrite_query()
won't complain.
*/
thd->reset_rewritten_query();
/*
Now replace the "PREPARE ..." with the obfuscated version of the
actual query were prepare.
*/
mysql_rewrite_query(thd);
}
/**
Unless we're doing dynamic SQL, write the current query to the
general query log if it's open. If we have a rewritten version
of the query, use that instead of the "raw" one.
Side-effect: query may be written to general log if it's open.
@param thd thread handle
*/
static inline void log_execute_line(THD *thd) {
/*
Do not print anything if this is an SQL prepared statement and
we're inside a stored procedure (also called Dynamic SQL) --
sub-statements inside stored procedures are not logged into
the general log.
*/
if (thd->sp_runtime_ctx != nullptr) return;
if (thd->rewritten_query().length())
query_logger.general_log_write(thd, COM_STMT_EXECUTE,
thd->rewritten_query().ptr(),
thd->rewritten_query().length());
else
query_logger.general_log_write(thd, COM_STMT_EXECUTE, thd->query().str,
thd->query().length);
}
class Statement_backup {
LEX *m_lex;
LEX_CSTRING m_query_string;
String m_rewritten_query;
bool m_safe_to_display;
public:
LEX *lex() const { return m_lex; }
/**
Prepared the THD to execute the prepared statement.
Save the current THD statement state.
*/
void set_thd_to_ps(THD *thd, Prepared_statement *stmt) {
DBUG_TRACE;
mysql_mutex_lock(&thd->LOCK_thd_data);
m_lex = thd->lex;
thd->lex = stmt->m_lex;
mysql_mutex_unlock(&thd->LOCK_thd_data);
m_query_string = thd->query();
thd->set_query(stmt->m_query_string);
m_safe_to_display = thd->safe_to_display();
/* Keep the current behaviour of displaying prepared statements always by
default. This can be changed in future if required. */
thd->set_safe_display(true);
return;
}
/**
Restore the THD statement state after the prepared
statement has finished executing.
*/
void restore_thd(THD *thd, Prepared_statement *stmt) {
DBUG_TRACE;
mysql_mutex_lock(&thd->LOCK_thd_data);
stmt->m_lex = thd->lex;
thd->lex = m_lex;
mysql_mutex_unlock(&thd->LOCK_thd_data);
thd->set_safe_display(m_safe_to_display);
stmt->m_query_string = thd->query();
thd->set_query(m_query_string);
}
/**
Save the current rewritten query prior to
rewriting the prepared statement.
*/
void save_rlb(THD *thd) {
DBUG_TRACE;
if (thd->rewritten_query().length() > 0) {
/* Duplicate the original rewritten query. */
m_rewritten_query.copy(thd->rewritten_query());
/* Swap the duplicate with the original. */
thd->swap_rewritten_query(m_rewritten_query);
}
return;
}
/**
Restore the rewritten query after the prepared
statement has finished executing.
*/
void restore_rlb(THD *thd) {
DBUG_TRACE;
if (m_rewritten_query.length() > 0) {
/* Restore with swap() instead of '='. */
thd->swap_rewritten_query(m_rewritten_query);
/* Free the rewritten prepared statement. */
m_rewritten_query.mem_free();
}
return;
}
};
/**
Set source parameter type based on information from protocol buffer
@param param Parameter to set source type for
@param type Field type
@param unsigned_type true if type is unsigned (applicable for numeric types)
@param cs_source The source collation for non-binary string parameters
If parameter metadata is invalid, set source data type MYSQL_TYPE_INVALID.
*/
static void set_parameter_type(Item_param *param, enum enum_field_types type,
bool unsigned_type,
const CHARSET_INFO *cs_source) {
param->set_data_type_source(type, unsigned_type);
switch (param->data_type_source()) {
case MYSQL_TYPE_NULL:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_NEWDECIMAL:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
break;
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB: {
param->set_collation_source(&my_charset_bin);
break;
}
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_JSON:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING: {
param->set_collation_source(cs_source);
break;
}
default:
param->set_data_type_source(MYSQL_TYPE_INVALID, false);
break;
}
}
/**
Set parameter value from protocol buffer
@param param Parameter to set a value for
@param pos Pointer to parameter value in protocol buffer
@param len Length of parameter value
@returns false on success, true on error
The function reads a binary valuefrom pos, converts it to the requested type
and assigns it to the paramameter.
*/
static bool set_parameter_value(Item_param *param, const uchar **pos,
ulong len) {
switch (param->data_type_source()) {
case MYSQL_TYPE_TINY: {
assert(len >= 1);
int8 value = (int8) * *pos;
if (param->is_unsigned_actual())
param->set_int((ulonglong)((uint8)value));
else
param->set_int((longlong)value);
break;
}
case MYSQL_TYPE_SHORT: {
assert(len >= 2);
int16 value = sint2korr(*pos);
if (param->is_unsigned_actual())
param->set_int((ulonglong)((uint16)value));
else
param->set_int((longlong)value);
break;
}
case MYSQL_TYPE_LONG: {
assert(len >= 4);
int32 value = sint4korr(*pos);
if (param->is_unsigned_actual())
param->set_int((ulonglong)((uint32)value));
else
param->set_int((longlong)value);
break;
}
case MYSQL_TYPE_LONGLONG: {
assert(len >= 8);
longlong value = sint8korr(*pos);
if (param->is_unsigned_actual())
param->set_int((ulonglong)value);
else
param->set_int(value);
break;
}
case MYSQL_TYPE_FLOAT: {
assert(len >= 4);
float data = float4get(*pos);
param->set_double((double)data);
break;
}
case MYSQL_TYPE_DOUBLE: {
assert(len >= 8);
double data = float8get(*pos);
param->set_double(data);
break;
}
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_NEWDECIMAL: {
param->set_decimal((const char *)*pos, len);
break;
}
case MYSQL_TYPE_TIME: {
MYSQL_TIME tm;
if (len >= 8) {
const uchar *to = *pos;
tm.neg = (bool)to[0];
uint day = (uint)sint4korr(to + 1);
tm.hour = (uint)to[5] + day * 24;
tm.minute = (uint)to[6];
tm.second = (uint)to[7];
tm.second_part = (len > 8) ? (ulong)sint4korr(to + 8) : 0;
if (tm.hour > 838) {
/* TODO: add warning 'Data truncated' here */
tm.hour = 838;
tm.minute = 59;
tm.second = 59;
}
tm.day = tm.year = tm.month = 0;
} else {
set_zero_time(&tm, MYSQL_TIMESTAMP_TIME);
}
param->set_time(&tm, MYSQL_TIMESTAMP_TIME);
break;
}
case MYSQL_TYPE_DATE: {
MYSQL_TIME tm;
if (len >= 4) {
const uchar *to = *pos;
tm.year = (uint)sint2korr(to);
tm.month = (uint)to[2];
tm.day = (uint)to[3];
tm.hour = tm.minute = tm.second = 0;
tm.second_part = 0;
tm.neg = false;
} else {
set_zero_time(&tm, MYSQL_TIMESTAMP_DATE);
}
param->set_time(&tm, MYSQL_TIMESTAMP_DATE);
break;
}
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP: {
MYSQL_TIME tm;
enum_mysql_timestamp_type type = MYSQL_TIMESTAMP_DATETIME;
const uchar *to = *pos;
assert(len == 0 || len == 4 || len == 7 || len == 11 || len == 13);
if (len < 4) {
set_zero_time(&tm, MYSQL_TIMESTAMP_DATETIME);
} else {
tm.neg = false;
tm.year = (uint)sint2korr(to);
tm.month = (uint)to[2];
tm.day = (uint)to[3];
}
if (len >= 7) {
tm.hour = (uint)to[4];
tm.minute = (uint)to[5];
tm.second = (uint)to[6];
} else { // len == 4
tm.hour = tm.minute = tm.second = 0;
}
tm.second_part =
(len >= 11) ? static_cast<std::uint64_t>(sint4korr(to + 7)) : 0;
if (len >= 13) {
tm.time_zone_displacement = sint2korr(to + 11) * SECS_PER_MIN;
type = MYSQL_TIMESTAMP_DATETIME_TZ;
}
param->set_time(&tm, type);
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB: {
param->set_str((const char *)*pos, len);
break;
}
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_JSON:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING: {
param->set_str((const char *)*pos, len);
break;
}
default:
/*
The client library ensures that only the type codes listed above
are encountered. The 'default' label makes it possible to handle
malformed packets as well.
*/
break;
}
return false;
}
/**
Check whether this parameter data type is compatible with long data.
Used to detect whether a long data stream has been supplied to a
incompatible data type.
Notice that VARCHAR type is MYSQL_TYPE_STRING, not MYSQL_TYPE_VARCHAR,
when sent on protocol between client and server.
*/
inline bool is_param_long_data_type(Item_param *param) {
return param->data_type_source() >= MYSQL_TYPE_TINY_BLOB &&
param->data_type_source() <= MYSQL_TYPE_STRING;
}
/**
Assign parameter values from data supplied by the client.
If required, generate a valid non-parameterized query for logging.
@param thd current thread.
@param query The query with parameter markers replaced with values
supplied by user that were used to execute the query.
@param has_new_types if true, new types of actual parameters are provided,
otherwise use the parameters from previous execution.
@param parameters Array of actual parameter values.
Contains parameter types if has_new_types is true.
@returns false if success, true if error
@note
m_with_log is set when one of slow or general logs are open.
Logging of prepared statements in all cases is performed
by means of regular queries: if parameter data was supplied from C API,
each placeholder in the query is replaced with its actual value;
if we're logging a [Dynamic] SQL prepared statement, parameter markers
are replaced with variable names.
Example:
@verbatim
mysqld_stmt_prepare("UPDATE t1 SET a=a*1.25 WHERE a=?")
--> general logs gets [Prepare] UPDATE t1 SET a*1.25 WHERE a=?"
mysqld_stmt_execute(stmt);
--> general and binary logs get
[Execute] UPDATE t1 SET a*1.25 WHERE a=1"
@endverbatim
If a statement has been prepared using SQL syntax:
@verbatim
PREPARE stmt FROM "UPDATE t1 SET a=a*1.25 WHERE a=?"
--> general log gets [Query] PREPARE stmt FROM "UPDATE ..."
EXECUTE stmt USING @a
--> general log gets [Query] EXECUTE stmt USING @a;
@endverbatim
*/
bool Prepared_statement::insert_parameters(THD *thd, String *query,
bool has_new_types,
PS_PARAM *parameters) {
DBUG_TRACE;
Item_param **end = m_param_array + m_param_count;
size_t length = 0;
// Reserve an extra space of 32 bytes for each placeholder parameter.
if (m_with_log && query->reserve(m_query_string.length + 32 * m_param_count))
return true;
uint i = 0;
for (Item_param **it = m_param_array; it < end; ++it, i++) {
Item_param *const param = *it;
if (has_new_types) {
set_parameter_type(param, parameters[i].type, parameters[i].unsigned_type,
thd->variables.character_set_client);
// Client may have provided invalid metadata:
if (param->data_type_source() == MYSQL_TYPE_INVALID) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysqld_stmt_execute");
return true;
}
}
if (param->param_state() == Item_param::LONG_DATA_VALUE) {
/*
A long data stream was supplied for this parameter marker.
This was done after prepare, prior to providing a placeholder
type (the types are supplied at execute). Check that the
supplied type of placeholder can accept a data stream.
*/
if (!is_param_long_data_type(param)) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysqld_stmt_execute");
return true;
}
param->set_data_type_actual(MYSQL_TYPE_VARCHAR);
// see Item_param::set_str() for explanation
param->set_collation_actual(
param->collation_source() == &my_charset_bin ? &my_charset_bin
: param->collation.collation != &my_charset_bin
? param->collation.collation
: current_thd->variables.collation_connection);
} else if (parameters[i].null_bit) {
param->set_null();
} else {
if (set_parameter_value(param, ¶meters[i].value,
parameters[i].length)) {
return true;
}
// NO_VALUE probably means broken client, no metadata provided.
if (param->param_state() == Item_param::NO_VALUE) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysqld_stmt_execute");
return true;
}
// Pinning of data types only implemented for integers
assert(!param->is_type_pinned() || param->result_type() == INT_RESULT);
if (param->is_type_pinned()) {
// Accept string values from client
// @todo Validate string values, do not accept garbage in string
if (param->data_type_actual() == MYSQL_TYPE_VARCHAR) {
longlong val = param->val_int();
if (param->unsigned_flag)
param->set_int((ulonglong)val);
else
param->set_int(val);
} else if (param->data_type_actual() != MYSQL_TYPE_LONGLONG) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysqld_stmt_execute");
return true;
}
if ((param->unsigned_flag && !param->is_unsigned_actual() &&
param->value.integer < 0) ||
(!param->unsigned_flag && param->is_unsigned_actual() &&
param->value.integer < 0)) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "signed integer",
"mysqld_stmt_execute");
return true;
}
}
}
if (m_with_log) {
String str;
const String *val = param->query_val_str(thd, &str);
if (val == nullptr) return true;
if (param->convert_value()) return true; /* out of memory */
size_t num_bytes = param->pos_in_query - length;
if (query->length() + num_bytes + val->length() >
std::numeric_limits<uint32>::max()) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysqld_stmt_execute");
return true;
}
if (query->append(m_query_string.str + length, num_bytes) ||
query->append(*val))
return true;
length = param->pos_in_query + 1;
} else {
if (param->convert_value()) return true; /* out of memory */
}
param->sync_clones();
}
// Copy part of query string after last parameter marker
if (m_with_log && query->append(m_query_string.str + length,
m_query_string.length - length))
return true;
return false;
}
/**
Copy parameter metada data from parameter array into current prepared stmt.
@param from_param_array Parameter array to copy from.
*/
void Prepared_statement::copy_parameter_types(Item_param **from_param_array) {
for (uint i = 0; i < m_param_count; ++i) {
Item_param *from = from_param_array[i];
Item_param *to = this->m_param_array[i];
to->copy_param_actual_type(from);
}
}
/**
Setup data conversion routines using an array of parameter
markers from the original prepared statement.
Swap the parameter data of the original prepared
statement to the new one.
Used only when we re-prepare a prepared statement.
There are two reasons for this function to exist:
1) In the binary client/server protocol, parameter metadata
is sent only at first execute. Consequently, if we need to
reprepare a prepared statement at a subsequent execution,
we may not have metadata information in the packet.
In that case we use the parameter array of the original
prepared statement to setup parameter types of the new
prepared statement.
2) In the binary client/server protocol, we may supply
long data in pieces. When the last piece is supplied,
we assemble the pieces and convert them from client
character set to the connection character set. After
that the parameter value is only available inside
the parameter, the original pieces are lost, and thus
we can only assign the corresponding parameter of the
reprepared statement from the original value.
@param[out] param_array_dst parameter markers of the new statement
@param[in] param_array_src parameter markers of the original
statement
@param[in] param_count total number of parameters. Is the
same in src and dst arrays, since
the statement query is the same
*/
static void swap_parameter_array(Item_param **param_array_dst,
Item_param **param_array_src,
uint param_count) {
Item_param **dst = param_array_dst;
Item_param **src = param_array_src;
Item_param **end = param_array_dst + param_count;
for (; dst < end; ++src, ++dst) {
(*dst)->set_param_type_and_swap_value(*src);
(*dst)->sync_clones();
(*src)->sync_clones();
}
}
/**
Assign prepared statement parameters from user variables.
If m_with_log is set, also construct query string for binary log.
@param thd Current thread.
@param varnames List of variables. Caller must ensure that number
of variables in the list is equal to number of statement
parameters
@param query The query with parameter markers replaced with corresponding
user variables that were used to execute the query.
@returns false if success, true if error
*/
bool Prepared_statement::insert_parameters_from_vars(THD *thd,
List<LEX_STRING> &varnames,
String *query) {
Item_param **end = m_param_array + m_param_count;
List_iterator<LEX_STRING> var_it(varnames);
StringBuffer<STRING_BUFFER_USUAL_SIZE> buf;
size_t length = 0;
DBUG_TRACE;
// Reserve an extra space of 32 bytes for each placeholder parameter.
if (m_with_log) query->reserve(m_query_string.length + 32 * m_param_count);
// Protects thd->user_vars
mysql_mutex_lock(&thd->LOCK_thd_data);
for (Item_param **it = m_param_array; it < end; ++it) {
Item_param *const param = *it;
LEX_STRING *const varname = var_it++;
user_var_entry *entry =
find_or_nullptr(thd->user_vars, to_string(*varname));
if (m_with_log) {
if (entry != nullptr) {
set_parameter_type(param, Item::result_to_type(entry->type()),
entry->unsigned_flag, entry->collation.collation);
} else {
set_parameter_type(param, param->data_type(), param->unsigned_flag,
param->collation.collation);
}
if (param->set_from_user_var(thd, entry)) goto error;
const String *val = param->query_val_str(thd, &buf);
if (val == nullptr) goto error;
if (param->convert_value()) goto error;
size_t num_bytes = param->pos_in_query - length;
if (query->length() + num_bytes + val->length() >
std::numeric_limits<uint32>::max())
goto error;
if (query->append(m_query_string.str + length, num_bytes) ||
query->append(*val))
goto error;
length = param->pos_in_query + 1;
} else {
assert(false);
if (param->set_from_user_var(thd, entry)) goto error;
if (entry) length += entry->length();
if (length > std::numeric_limits<uint32>::max() || param->convert_value())
goto error;
}
param->sync_clones();
}
// Copy part of query string after last parameter marker
if (m_with_log && query->append(m_query_string.str + length,
m_query_string.length - length))
goto error;
mysql_mutex_unlock(&thd->LOCK_thd_data);
return false;
error:
mysql_mutex_unlock(&thd->LOCK_thd_data);
return true;
}
static bool send_statement(THD *thd, const Prepared_statement *stmt,
uint no_columns, Query_result *result,
const mem_root_deque<Item *> *types) {
// Send the statement status(id, no_columns, no_params, error_count);
bool rc = thd->get_protocol()->store_ps_status(
stmt->id(), no_columns, stmt->m_param_count,
thd->get_stmt_da()->current_statement_cond_count());
if (!rc && stmt->m_param_count != 0) {