MySQL 9.6.0
Source Code Documentation
sql_prepare.h
Go to the documentation of this file.
1#ifndef SQL_PREPARE_H
2#define SQL_PREPARE_H
3/* Copyright (c) 2009, 2025, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License, version 2.0,
7 as published by the Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License, version 2.0, for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
25
26#include <assert.h>
27#include <stddef.h>
28#include <sys/types.h>
29
30#include "lex_string.h"
31#include "my_alloc.h"
32#include "my_command.h"
33#include "my_dbug.h"
34#include "my_inttypes.h"
35#include "my_psi_config.h"
37#include "mysql_com.h"
38#include "sql/sql_class.h" // Query_arena
39
40class Item_param;
42class Protocol;
43class Query_result;
44class Server_runnable;
45class String;
46struct LEX;
47struct PS_PARAM;
48template <class T>
49class List;
50union COM_DATA;
51
52/**
53 An interface that is used to take an action when
54 the locking module notices that a table version has changed
55 since the last execution. "Table" here may refer to any kind of
56 table -- a base table, a temporary table, a view or an
57 information schema table.
58
59 When we open and lock tables for execution of a prepared
60 statement, we must verify that they did not change
61 since statement prepare. If some table did change, the statement
62 parse tree *may* be no longer valid, e.g. in case it contains
63 optimizations that depend on table metadata.
64
65 This class provides an interface (a method) that is
66 invoked when such a situation takes place.
67 The implementation of the method simply reports an error, but
68 the exact details depend on the nature of the SQL statement.
69
70 At most 1 instance of this class is active at a time, in which
71 case THD::m_reprepare_observer is not NULL.
72
73 @sa check_and_update_table_version() for details of the
74 version tracking algorithm
75
76 @sa Open_tables_state::m_reprepare_observer for the life cycle
77 of metadata observers.
78*/
79
80class Reprepare_observer final {
81 public:
82 /**
83 Check if a change of metadata is OK. In future
84 the signature of this method may be extended to accept the old
85 and the new versions, but since currently the check is very
86 simple, we only need the THD to report an error.
87 */
88 bool report_error(THD *thd);
89 /**
90 @returns true if some table metadata is changed and statement should be
91 re-prepared.
92 */
93 bool is_invalidated() const { return m_invalidated; }
95 /// @returns true if prepared statement can (and will) be retried
96 bool can_retry() const {
97 // Only call for a statement that is invalidated
98 assert(is_invalidated());
100 DBUG_EVALUATE_IF("simulate_max_reprepare_attempts_hit_case", false,
101 true);
102 }
103
104 private:
105 bool m_invalidated{false};
106 int m_attempt{0};
107
108 /*
109 We take only 3 attempts to reprepare the query, otherwise we might end up
110 in endless loop.
111 */
112 static constexpr int MAX_REPREPARE_ATTEMPTS = 3;
113};
114
115void rewrite_query(THD *thd);
116void log_execute_line(THD *thd);
117
118bool ask_to_reprepare(THD *thd);
119bool mysql_stmt_precheck(THD *thd, const COM_DATA *com_data,
120 enum enum_server_command cmd,
121 Prepared_statement **stmt);
122void mysqld_stmt_prepare(THD *thd, const char *query, uint length,
123 Prepared_statement *stmt);
124void mysqld_stmt_execute(THD *thd, Prepared_statement *stmt, bool has_new_types,
125 ulong execute_flags, PS_PARAM *parameters);
127void mysql_sql_stmt_prepare(THD *thd);
128void mysql_sql_stmt_execute(THD *thd);
129void mysql_sql_stmt_close(THD *thd);
130void mysqld_stmt_fetch(THD *thd, Prepared_statement *stmt, ulong num_rows);
133 uint param_number, uchar *longdata, ulong length);
135 ulong setup_tables_done_option);
137
138/**
139 Execute direct interface.
140
141 @todo Implement support for prelocked mode.
142*/
143
145
146/**
147 Prepared_statement: a statement that can contain placeholders.
148*/
149
151 public:
152 /// Memory allocation arena, for permanent allocations to statement.
154
155 /// Array of parameters used for statement, may be NULL if there are none.
157
158 /// Pointer to cursor, may be NULL if statement never used with a cursor.
160
161 /// Used to check that the protocol is stable during execution
163
164 /// Number of parameters expected for statement
166
169
170 /**
171 Uniquely identifies each statement object in thread scope; change during
172 statement lifetime.
173 */
174 const ulong m_id;
175
176 LEX *m_lex{nullptr}; // parse tree descriptor
177
178 /// The query string associated with this statement.
180
181 /// The query display string associated with this statement.
183
184 /// Performance Schema interface for a prepared statement.
186
187 private:
188 /// True if statement is used with cursor, false if used in regular execution
189 bool m_used_as_cursor{false};
190
191 /// Query result used when statement is used in regular execution.
193
194 /// Query result used when statement is used with a cursor.
196
197 /// Auxiliary query result object, saved for proper destruction
199
200 /// Flag that specifies preparation state
201 bool m_is_sql_prepare{false};
202
203 /// Flag that prevents recursive invocation of prepared statements
204 bool m_in_use{false};
205
206 bool m_with_log{false};
207
209
210 /// Name of the prepared statement.
212 /**
213 Name of the current (default) database.
214
215 If there is the current (default) database, "db" contains its name. If
216 there is no current (default) database, "db" is NULL and "db_length" is
217 0. In other words, "db", "db_length" must either be NULL, or contain a
218 valid database name.
219
220 @note this attribute is set and allocated by the slave SQL thread (for
221 the THD of that thread); that thread is (and must remain, for now) the
222 only responsible for freeing this member.
223 */
225
226 /**
227 The memory root to allocate parsed tree elements (instances of Item,
228 Query_block and other classes).
229 */
231
232 /** DIGEST and DIGEST_TEXT of the prepared statement. */
234
235 /** Token array used to store DIGEST and DIGEST_TEXT. */
236 unsigned char *m_token_array{nullptr};
237
238 /** Length of m_token_array. */
240
241 bool prepare_query(THD *thd);
242
243 public:
244 explicit Prepared_statement(THD *thd_arg);
246
247 /** Performance schema instrumentation for execute / deallocate. */
248 void psi_instrumentation(THD *thd, uint digest_prefix_token, bool copy);
249
250 void set_display_query_string(const char *display_query_string,
251 size_t display_query_string_length);
252 void get_display_query_string(const char **display_query_string_ptr,
253 size_t *display_query_string_length_ptr) const;
254
255 void set_digest(const sql_digest_storage *digest);
257 return m_digest.is_empty() ? nullptr : &m_digest;
258 }
259
260 bool set_name(const LEX_CSTRING &name);
261 const LEX_CSTRING &name() const { return m_name; }
262 ulong id() const { return m_id; }
263 bool is_in_use() const { return m_in_use; }
264 bool is_sql_prepare() const { return m_is_sql_prepare; }
266 void deallocate(THD *thd);
267 bool prepare(THD *thd, const char *packet, size_t packet_length,
268 Item_param **orig_param_array);
269 bool execute_loop(THD *thd, String *expanded_query, bool open_cursor);
270 bool execute_server_runnable(THD *thd, Server_runnable *server_runnable);
271#ifdef HAVE_PSI_PS_INTERFACE
273#endif
274
275 /**
276 Assign parameter values from the execute packet.
277
278 @param thd current thread
279 @param expanded_query a container with the original SQL statement.
280 '?' placeholders will be replaced with
281 their values in case of success.
282 The result is used for logging and replication
283 @param has_new_types flag used to signal that new types are provided.
284 @param parameters prepared statement's parsed parameters.
285
286 @returns false if success, true if error
287 (likely a conversion error, out of memory, or malformed packet)
288 */
289 bool set_parameters(THD *thd, String *expanded_query, bool has_new_types,
290 PS_PARAM *parameters);
291
293 /*
294 Parameter values are coming from client over network (vio).
295 */
297
298 /*
299 Parameter values are sent either using using Server_component service
300 API's or Plugins or directly from SQL layer modules.
301
302 UNPACKED means that the parameter value buffer points to MYSQL_TIME*
303 */
305 };
306
307 /**
308 Assign parameter values from the execute packet.
309
310 @param thd current thread
311 @param expanded_query a container with the original SQL statement.
312 '?' placeholders will be replaced with
313 their values in case of success.
314 The result is used for logging and replication
315 @param has_new_types flag used to signal that new types are provided.
316 @param parameters prepared statement's parsed parameters.
317 @param param_pack_type parameters pack type.
318
319 @returns false if success, true if error
320 (likely a conversion error, out of memory, or malformed packet)
321 */
322 bool set_parameters(THD *thd, String *expanded_query, bool has_new_types,
323 PS_PARAM *parameters,
324 enum enum_param_pack_type param_pack_type);
325
326 bool set_parameters(THD *thd, String *expanded_query);
327 void trace_parameter_types(THD *thd);
328 void close_cursor();
329
330 private:
331 void cleanup_stmt(THD *thd);
332 void setup_stmt_logging(THD *thd);
334 void copy_parameter_types(Item_param **from_param_array);
335 bool set_db(const LEX_CSTRING &db_length);
336
337 bool execute(THD *thd, String *expanded_query, bool open_cursor);
338 bool reprepare(THD *thd);
342 String *query);
343 bool insert_parameters(THD *thd, String *query, bool has_new_types,
344 PS_PARAM *parameters,
345 enum enum_param_pack_type param_pack_type);
346};
347
348#endif // SQL_PREPARE_H
Kerberos Client Authentication nullptr
Definition: auth_kerberos_client_plugin.cc:247
Dynamic parameters used as placeholders ('?') inside prepared statements.
Definition: item.h:4883
Definition: sql_list.h:494
Prepared_statement: a statement that can contain placeholders.
Definition: sql_prepare.h:150
bool set_db(const LEX_CSTRING &db_length)
Remember the current database.
Definition: sql_prepare.cc:2396
bool execute_loop(THD *thd, String *expanded_query, bool open_cursor)
Execute a prepared statement.
Definition: sql_prepare.cc:3052
Prepared_statement(THD *thd_arg)
Definition: sql_prepare.cc:2228
const Protocol * m_active_protocol
Used to check that the protocol is stable during execution.
Definition: sql_prepare.h:162
bool insert_parameters(THD *thd, String *query, bool has_new_types, PS_PARAM *parameters, enum enum_param_pack_type param_pack_type)
Assign parameter values from data supplied by the client.
Definition: sql_prepare.cc:666
LEX_CSTRING m_query_string
The query string associated with this statement.
Definition: sql_prepare.h:179
void get_display_query_string(const char **display_query_string_ptr, size_t *display_query_string_length_ptr) const
Definition: sql_prepare.cc:2352
bool prepare_query(THD *thd)
Perform semantic analysis of query and send a response packet to client.
Definition: sql_prepare.cc:1216
void set_display_query_string(const char *display_query_string, size_t display_query_string_length)
Definition: sql_prepare.cc:2335
LEX_CSTRING m_db
Name of the current (default) database.
Definition: sql_prepare.h:224
bool execute(THD *thd, String *expanded_query, bool open_cursor)
Execute a prepared statement that has already been prepared.
Definition: sql_prepare.cc:3520
ulong id() const
Definition: sql_prepare.h:262
sql_digest_storage m_digest
DIGEST and DIGEST_TEXT of the prepared statement.
Definition: sql_prepare.h:233
Server_side_cursor * m_cursor
Pointer to cursor, may be NULL if statement never used with a cursor.
Definition: sql_prepare.h:159
bool validate_metadata(THD *thd, Prepared_statement *copy)
Validate statement result set metadata (if the statement returns a result set).
Definition: sql_prepare.cc:3424
bool check_parameter_types()
Check resolved parameter types versus actual parameter types.
Definition: sql_prepare.cc:2843
void trace_parameter_types(THD *thd)
Definition: sql_prepare.cc:1443
void swap_prepared_statement(Prepared_statement *copy)
Swap the MEM_ROOT allocated data of two prepared statements.
Definition: sql_prepare.cc:3455
const LEX_CSTRING & name() const
Definition: sql_prepare.h:261
~Prepared_statement()
Destroy this prepared statement, cleaning up all used memory and resources.
Definition: sql_prepare.cc:2295
enum_param_pack_type
Definition: sql_prepare.h:292
@ PACKED
Definition: sql_prepare.h:296
@ UNPACKED
Definition: sql_prepare.h:304
bool m_used_as_cursor
True if statement is used with cursor, false if used in regular execution.
Definition: sql_prepare.h:189
Item_param ** m_param_array
Array of parameters used for statement, may be NULL if there are none.
Definition: sql_prepare.h:156
void deallocate(THD *thd)
Common part of DEALLOCATE PREPARE and mysqld_stmt_close.
Definition: sql_prepare.cc:3871
bool m_in_use
Flag that prevents recursive invocation of prepared statements.
Definition: sql_prepare.h:204
void setup_stmt_logging(THD *thd)
Definition: sql_prepare.cc:2243
const sql_digest_storage * get_digest() const
Definition: sql_prepare.h:256
bool is_sql_prepare() const
Definition: sql_prepare.h:264
Query_arena m_arena
Memory allocation arena, for permanent allocations to statement.
Definition: sql_prepare.h:153
void set_sql_prepare(bool prepare=true)
Definition: sql_prepare.h:265
bool execute_server_runnable(THD *thd, Server_runnable *server_runnable)
Definition: sql_prepare.cc:3276
LEX_CSTRING m_name
Name of the prepared statement.
Definition: sql_prepare.h:211
MEM_ROOT m_mem_root
The memory root to allocate parsed tree elements (instances of Item, Query_block and other classes).
Definition: sql_prepare.h:230
bool reprepare(THD *thd)
Reprepare this prepared statement.
Definition: sql_prepare.cc:3334
unsigned char * m_token_array
Token array used to store DIGEST and DIGEST_TEXT.
Definition: sql_prepare.h:236
Query_result * m_regular_result
Query result used when statement is used in regular execution.
Definition: sql_prepare.h:192
LEX * m_lex
Definition: sql_prepare.h:176
bool m_with_log
Definition: sql_prepare.h:206
bool insert_parameters_from_vars(THD *thd, List< LEX_STRING > &varnames, String *query)
Assign prepared statement parameters from user variables.
Definition: sql_prepare.cc:886
void cleanup_stmt(THD *thd)
Definition: sql_prepare.cc:2327
void close_cursor()
Definition: sql_prepare.cc:2237
bool prepare(THD *thd, const char *packet, size_t packet_length, Item_param **orig_param_array)
Parse statement text, validate the statement, and prepare it for execution.
Definition: sql_prepare.cc:2440
Query_result * m_cursor_result
Query result used when statement is used with a cursor.
Definition: sql_prepare.h:195
uint m_param_count
Number of parameters expected for statement.
Definition: sql_prepare.h:165
Query_result * m_aux_result
Auxiliary query result object, saved for proper destruction.
Definition: sql_prepare.h:198
const ulong m_id
Uniquely identifies each statement object in thread scope; change during statement lifetime.
Definition: sql_prepare.h:174
bool set_parameters(THD *thd, String *expanded_query, bool has_new_types, PS_PARAM *parameters)
Assign parameter values from the execute packet.
Definition: sql_prepare.cc:2793
void set_digest(const sql_digest_storage *digest)
Definition: sql_prepare.cc:2366
bool m_is_sql_prepare
Flag that specifies preparation state.
Definition: sql_prepare.h:201
bool set_name(const LEX_CSTRING &name)
Definition: sql_prepare.cc:2379
void copy_parameter_types(Item_param **from_param_array)
Copy parameter metada data from parameter array into current prepared stmt.
Definition: sql_prepare.cc:816
char m_last_error[MYSQL_ERRMSG_SIZE]
Definition: sql_prepare.h:168
PSI_prepared_stmt * get_PS_prepared_stmt()
Definition: sql_prepare.h:272
LEX_CSTRING m_display_query_string
The query display string associated with this statement.
Definition: sql_prepare.h:182
uint m_last_errno
Definition: sql_prepare.h:167
void psi_instrumentation(THD *thd, uint digest_prefix_token, bool copy)
Performance schema instrumentation for execute / deallocate.
Definition: sql_prepare.cc:3828
bool is_in_use() const
Definition: sql_prepare.h:263
PSI_prepared_stmt * m_prepared_stmt
Performance Schema interface for a prepared statement.
Definition: sql_prepare.h:185
size_t m_token_array_length
Length of m_token_array.
Definition: sql_prepare.h:239
bool m_first_execution
Definition: sql_prepare.h:208
Definition: protocol.h:33
Definition: sql_class.h:352
Definition: query_result.h:60
An interface that is used to take an action when the locking module notices that a table version has ...
Definition: sql_prepare.h:80
bool is_invalidated() const
Definition: sql_prepare.h:93
bool report_error(THD *thd)
Check if a change of metadata is OK.
Definition: sql_prepare.cc:2190
bool can_retry() const
Definition: sql_prepare.h:96
void reset_reprepare_observer()
Definition: sql_prepare.h:94
bool m_invalidated
Definition: sql_prepare.h:105
int m_attempt
Definition: sql_prepare.h:106
static constexpr int MAX_REPREPARE_ATTEMPTS
Definition: sql_prepare.h:112
Execute a fragment of server code in an isolated context, so that it doesn't leave any effect on THD.
Definition: statement_runnable.h:42
Server_side_cursor – an interface for materialized implementation of cursors.
Definition: sql_cursor.h:51
Definition: sql_cmd_dml.h:35
Using this class is fraught with peril, and you need to be very careful when doing so.
Definition: sql_string.h:169
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_lexer_thd.h:36
struct PSI_prepared_stmt PSI_prepared_stmt
Definition: psi_statement_bits.h:105
constexpr const LEX_CSTRING NULL_CSTR
Definition: lex_string.h:48
This file follows Google coding style, except for the name MEM_ROOT (which is kept for historical rea...
enum_server_command
A list of all MySQL protocol commands.
Definition: my_command.h:48
#define DBUG_EVALUATE_IF(keyword, a1, a2)
Definition: my_dbug.h:179
#define MYSQL_ERRMSG_SIZE
Max length of a error message.
Definition: my_err_bits.h:28
Some integer typedefs for easier portability.
unsigned char uchar
Definition: my_inttypes.h:52
Defines various enable/disable and HAVE_ macros related to the performance schema instrumentation sys...
static char * query
Definition: myisam_ftdump.cc:47
Common definition between mysql server & client.
void copy(Shards< COUNT > &dst, const Shards< COUNT > &src) noexcept
Copy the counters, overwrite destination.
Definition: ut0counter.h:354
bool length(const dd::Spatial_reference_system *srs, const Geometry *g1, double *length, bool *null) noexcept
Computes the length of linestrings and multilinestrings.
Definition: length.cc:76
Performance schema instrumentation interface.
void mysqld_stmt_prepare(THD *thd, const char *query, uint length, Prepared_statement *stmt)
COM_STMT_PREPARE handler.
Definition: sql_prepare.cc:1521
void mysql_sql_stmt_close(THD *thd)
SQLCOM_DEALLOCATE implementation.
Definition: sql_prepare.cc:2067
void mysqld_stmt_fetch(THD *thd, Prepared_statement *stmt, ulong num_rows)
COM_STMT_FETCH handler: fetches requested amount of rows from cursor.
Definition: sql_prepare.cc:1969
void mysql_stmt_get_longdata(THD *thd, Prepared_statement *stmt, uint param_number, uchar *longdata, ulong length)
Handle long data in pieces from client.
Definition: sql_prepare.cc:2111
bool mysql_stmt_precheck(THD *thd, const COM_DATA *com_data, enum enum_server_command cmd, Prepared_statement **stmt)
Searches for the statement with the specified id and validates it.
Definition: sql_prepare.cc:1576
void mysqld_stmt_close(THD *thd, Prepared_statement *stmt)
Delete a prepared statement from memory.
Definition: sql_prepare.cc:2035
bool select_like_stmt_cmd_test(THD *thd, class Sql_cmd_dml *cmd, ulong setup_tables_done_option)
bool ask_to_reprepare(THD *thd)
Requests for repreparation of statement.
Definition: sql_prepare.cc:2215
void reset_stmt_parameters(Prepared_statement *stmt)
Clears parameters from data left from previous execution or long data.
Definition: sql_prepare.cc:1832
void mysql_sql_stmt_execute(THD *thd)
SQLCOM_EXECUTE implementation.
Definition: sql_prepare.cc:1931
void log_execute_line(THD *thd)
Unless we're doing dynamic SQL, write the current query to the general query log if it's open.
Definition: sql_prepare.cc:262
void rewrite_query(THD *thd)
Rewrite the current query (to obfuscate passwords etc.).
Definition: sql_prepare.cc:239
void mysqld_stmt_execute(THD *thd, Prepared_statement *stmt, bool has_new_types, ulong execute_flags, PS_PARAM *parameters)
COM_STMT_EXECUTE handler: execute a previously prepared statement.
Definition: sql_prepare.cc:1860
void mysqld_stmt_reset(THD *thd, Prepared_statement *stmt)
Reset a prepared statement in case there was a recoverable error.
Definition: sql_prepare.cc:2008
void mysql_sql_stmt_prepare(THD *thd)
SQLCOM_PREPARE implementation.
Definition: sql_prepare.cc:1765
The LEX object currently serves three different purposes:
Definition: sql_lex.h:3995
The MEM_ROOT is a simple arena, where allocations are carved out of larger blocks.
Definition: my_alloc.h:83
Definition: mysql_lex_string.h:40
Definition: com_data.h:46
Structure to store token count/array for a statement on which digest is to be calculated.
Definition: sql_digest.h:98
bool is_empty() const
Definition: sql_digest.h:135
Definition: com_data.h:104