MySQL 9.7.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, 2026, 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 EXECUTE statement. */
234 /** DIGEST and DIGEST_TEXT of the DEALLOCATE statement. */
236
237 /** Token array used to store DIGEST and DIGEST_TEXT (EXECUTE). */
238 unsigned char *m_execute_token_array{nullptr};
239 /** Token array used to store DIGEST and DIGEST_TEXT (DEALLOCATE). */
240 unsigned char *m_deallocate_token_array{nullptr};
241
242 /** Length of m_execute_token_array. */
244 /** Length of m_deallocate_token_array. */
246
247 bool prepare_query(THD *thd);
248
249 public:
250 explicit Prepared_statement(THD *thd_arg);
252
253 /** Performance schema instrumentation for execute. */
255 /** Performance schema instrumentation for deallocate. */
257
258 void set_display_query_string(const char *display_query_string,
259 size_t display_query_string_length);
260 void get_display_query_string(const char **display_query_string_ptr,
261 size_t *display_query_string_length_ptr) const;
262
263 void set_digest(const sql_digest_storage *digest);
264
265 bool set_name(const LEX_CSTRING &name);
266 const LEX_CSTRING &name() const { return m_name; }
267 ulong id() const { return m_id; }
268 bool is_in_use() const { return m_in_use; }
269 bool is_sql_prepare() const { return m_is_sql_prepare; }
271 void deallocate(THD *thd);
272 bool prepare(THD *thd, const char *packet, size_t packet_length,
273 Item_param **orig_param_array);
274 bool execute_loop(THD *thd, String *expanded_query, bool open_cursor);
275 bool execute_server_runnable(THD *thd, Server_runnable *server_runnable);
276#ifdef HAVE_PSI_PS_INTERFACE
278#endif
279
280 /**
281 Assign parameter values from the execute packet.
282
283 @param thd current thread
284 @param expanded_query a container with the original SQL statement.
285 '?' placeholders will be replaced with
286 their values in case of success.
287 The result is used for logging and replication
288 @param has_new_types flag used to signal that new types are provided.
289 @param parameters prepared statement's parsed parameters.
290
291 @returns false if success, true if error
292 (likely a conversion error, out of memory, or malformed packet)
293 */
294 bool set_parameters(THD *thd, String *expanded_query, bool has_new_types,
295 PS_PARAM *parameters);
296
298 /*
299 Parameter values are coming from client over network (vio).
300 */
302
303 /*
304 Parameter values are sent either using using Server_component service
305 API's or Plugins or directly from SQL layer modules.
306
307 UNPACKED means that the parameter value buffer points to MYSQL_TIME*
308 */
310 };
311
312 /**
313 Assign parameter values from the execute packet.
314
315 @param thd current thread
316 @param expanded_query a container with the original SQL statement.
317 '?' placeholders will be replaced with
318 their values in case of success.
319 The result is used for logging and replication
320 @param has_new_types flag used to signal that new types are provided.
321 @param parameters prepared statement's parsed parameters.
322 @param param_pack_type parameters pack type.
323
324 @returns false if success, true if error
325 (likely a conversion error, out of memory, or malformed packet)
326 */
327 bool set_parameters(THD *thd, String *expanded_query, bool has_new_types,
328 PS_PARAM *parameters,
329 enum enum_param_pack_type param_pack_type);
330
331 bool set_parameters(THD *thd, String *expanded_query);
332 void trace_parameter_types(THD *thd);
333 void close_cursor();
334
335 private:
336 void cleanup_stmt(THD *thd);
337 void setup_stmt_logging(THD *thd);
339 void copy_parameter_types(Item_param **from_param_array);
340 bool set_db(const LEX_CSTRING &db_length);
341
342 bool execute(THD *thd, String *expanded_query, bool open_cursor);
343 bool reprepare(THD *thd);
347 String *query);
348 bool insert_parameters(THD *thd, String *query, bool has_new_types,
349 PS_PARAM *parameters,
350 enum enum_param_pack_type param_pack_type);
351};
352
353#endif // SQL_PREPARE_H
Dynamic parameters used as placeholders ('?') inside prepared statements.
Definition: item.h:4950
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:2409
bool execute_loop(THD *thd, String *expanded_query, bool open_cursor)
Execute a prepared statement.
Definition: sql_prepare.cc:3062
Prepared_statement(THD *thd_arg)
Definition: sql_prepare.cc:2227
const Protocol * m_active_protocol
Used to check that the protocol is stable during execution.
Definition: sql_prepare.h:162
unsigned char * m_execute_token_array
Token array used to store DIGEST and DIGEST_TEXT (EXECUTE).
Definition: sql_prepare.h:238
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:665
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:1215
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:3546
ulong id() const
Definition: sql_prepare.h:267
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:3446
bool check_parameter_types()
Check resolved parameter types versus actual parameter types.
Definition: sql_prepare.cc:2853
void trace_parameter_types(THD *thd)
Definition: sql_prepare.cc:1442
void swap_prepared_statement(Prepared_statement *copy)
Swap the MEM_ROOT allocated data of two prepared statements.
Definition: sql_prepare.cc:3477
const LEX_CSTRING & name() const
Definition: sql_prepare.h:266
~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:297
@ PACKED
Definition: sql_prepare.h:301
@ UNPACKED
Definition: sql_prepare.h:309
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:3924
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
bool is_sql_prepare() const
Definition: sql_prepare.h:269
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:270
bool execute_server_runnable(THD *thd, Server_runnable *server_runnable)
Definition: sql_prepare.cc:3298
sql_digest_storage m_execute_digest
DIGEST and DIGEST_TEXT of the EXECUTE statement.
Definition: sql_prepare.h:233
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:3356
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:885
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:2453
unsigned char * m_deallocate_token_array
Token array used to store DIGEST and DIGEST_TEXT (DEALLOCATE).
Definition: sql_prepare.h:240
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
sql_digest_storage m_deallocate_digest
DIGEST and DIGEST_TEXT of the DEALLOCATE statement.
Definition: sql_prepare.h:235
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:2803
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:2392
size_t m_deallocate_token_array_length
Length of m_deallocate_token_array.
Definition: sql_prepare.h:245
void psi_execute_instrumentation(THD *thd)
Performance schema instrumentation for execute.
Definition: sql_prepare.cc:3854
void copy_parameter_types(Item_param **from_param_array)
Copy parameter metada data from parameter array into current prepared stmt.
Definition: sql_prepare.cc:815
char m_last_error[MYSQL_ERRMSG_SIZE]
Definition: sql_prepare.h:168
void psi_deallocate_instrumentation(THD *thd)
Performance schema instrumentation for deallocate.
Definition: sql_prepare.cc:3882
PSI_prepared_stmt * get_PS_prepared_stmt()
Definition: sql_prepare.h:277
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
size_t m_execute_token_array_length
Length of m_execute_token_array.
Definition: sql_prepare.h:243
bool is_in_use() const
Definition: sql_prepare.h:268
PSI_prepared_stmt * m_prepared_stmt
Performance Schema interface for a prepared statement.
Definition: sql_prepare.h:185
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:2189
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:112
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:1520
void mysql_sql_stmt_close(THD *thd)
SQLCOM_DEALLOCATE implementation.
Definition: sql_prepare.cc:2066
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:1968
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:2110
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:1575
void mysqld_stmt_close(THD *thd, Prepared_statement *stmt)
Delete a prepared statement from memory.
Definition: sql_prepare.cc:2034
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:2214
void reset_stmt_parameters(Prepared_statement *stmt)
Clears parameters from data left from previous execution or long data.
Definition: sql_prepare.cc:1831
void mysql_sql_stmt_execute(THD *thd)
SQLCOM_EXECUTE implementation.
Definition: sql_prepare.cc:1930
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:1859
void mysqld_stmt_reset(THD *thd, Prepared_statement *stmt)
Reset a prepared statement in case there was a recoverable error.
Definition: sql_prepare.cc:2007
void mysql_sql_stmt_prepare(THD *thd)
SQLCOM_PREPARE implementation.
Definition: sql_prepare.cc:1764
The LEX object currently serves three different purposes:
Definition: sql_lex.h:4002
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
Definition: com_data.h:104