MySQL 8.4.2
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, 2024, 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#include <new>
30
31#include "lex_string.h"
32#include "my_alloc.h"
33#include "my_command.h"
34
35#include "my_inttypes.h"
36#include "my_psi_config.h"
38#include "mysql_com.h"
39#include "sql/sql_class.h" // Query_arena
40#include "sql/sql_error.h"
41#include "sql/sql_list.h"
43
44class Item;
45class Item_param;
48class String;
49struct LEX;
50struct PS_PARAM;
51class Table_ref;
52union COM_DATA;
53
54/**
55 An interface that is used to take an action when
56 the locking module notices that a table version has changed
57 since the last execution. "Table" here may refer to any kind of
58 table -- a base table, a temporary table, a view or an
59 information schema table.
60
61 When we open and lock tables for execution of a prepared
62 statement, we must verify that they did not change
63 since statement prepare. If some table did change, the statement
64 parse tree *may* be no longer valid, e.g. in case it contains
65 optimizations that depend on table metadata.
66
67 This class provides an interface (a method) that is
68 invoked when such a situation takes place.
69 The implementation of the method simply reports an error, but
70 the exact details depend on the nature of the SQL statement.
71
72 At most 1 instance of this class is active at a time, in which
73 case THD::m_reprepare_observer is not NULL.
74
75 @sa check_and_update_table_version() for details of the
76 version tracking algorithm
77
78 @sa Open_tables_state::m_reprepare_observer for the life cycle
79 of metadata observers.
80*/
81
82class Reprepare_observer final {
83 public:
84 /**
85 Check if a change of metadata is OK. In future
86 the signature of this method may be extended to accept the old
87 and the new versions, but since currently the check is very
88 simple, we only need the THD to report an error.
89 */
90 bool report_error(THD *thd);
91 /**
92 @returns true if some table metadata is changed and statement should be
93 re-prepared.
94 */
95 bool is_invalidated() const { return m_invalidated; }
97 /// @returns true if prepared statement can (and will) be retried
98 bool can_retry() const {
99 // Only call for a statement that is invalidated
100 assert(is_invalidated());
102 DBUG_EVALUATE_IF("simulate_max_reprepare_attempts_hit_case", false,
103 true);
104 }
105
106 private:
107 bool m_invalidated{false};
108 int m_attempt{0};
109
110 /*
111 We take only 3 attempts to reprepare the query, otherwise we might end up
112 in endless loop.
113 */
114 static constexpr int MAX_REPREPARE_ATTEMPTS = 3;
115};
116
117void rewrite_query(THD *thd);
118void log_execute_line(THD *thd);
119
120bool ask_to_reprepare(THD *thd);
121bool mysql_stmt_precheck(THD *thd, const COM_DATA *com_data,
122 enum enum_server_command cmd,
123 Prepared_statement **stmt);
124void mysqld_stmt_prepare(THD *thd, const char *query, uint length,
125 Prepared_statement *stmt);
126void mysqld_stmt_execute(THD *thd, Prepared_statement *stmt, bool has_new_types,
127 ulong execute_flags, PS_PARAM *parameters);
129void mysql_sql_stmt_prepare(THD *thd);
130void mysql_sql_stmt_execute(THD *thd);
131void mysql_sql_stmt_close(THD *thd);
132void mysqld_stmt_fetch(THD *thd, Prepared_statement *stmt, ulong num_rows);
135 uint param_number, uchar *longdata, ulong length);
137 ulong setup_tables_done_option);
139
140/**
141 Execute direct interface.
142
143 @todo Implement support for prelocked mode.
144*/
145
147
148/**
149 Prepared_statement: a statement that can contain placeholders.
150*/
151
153 public:
154 /// Memory allocation arena, for permanent allocations to statement.
156
157 /// Array of parameters used for statement, may be NULL if there are none.
159
160 /// Pointer to cursor, may be NULL if statement never used with a cursor.
162
163 /// Used to check that the protocol is stable during execution
165
166 /// Number of parameters expected for statement
168
171
172 /**
173 Uniquely identifies each statement object in thread scope; change during
174 statement lifetime.
175 */
176 const ulong m_id;
177
178 LEX *m_lex{nullptr}; // parse tree descriptor
179
180 /// The query string associated with this statement.
182
183 /// Performance Schema interface for a prepared statement.
185
186 private:
187 /// True if statement is used with cursor, false if used in regular execution
188 bool m_used_as_cursor{false};
189
190 /// Query result used when statement is used in regular execution.
192
193 /// Query result used when statement is used with a cursor.
195
196 /// Auxiliary query result object, saved for proper destruction
198
199 /// Flag that specifies preparation state
200 bool m_is_sql_prepare{false};
201
202 /// Flag that prevents recursive invocation of prepared statements
203 bool m_in_use{false};
204
205 bool m_with_log{false};
206
207 /// Name of the prepared statement.
209 /**
210 Name of the current (default) database.
211
212 If there is the current (default) database, "db" contains its name. If
213 there is no current (default) database, "db" is NULL and "db_length" is
214 0. In other words, "db", "db_length" must either be NULL, or contain a
215 valid database name.
216
217 @note this attribute is set and allocated by the slave SQL thread (for
218 the THD of that thread); that thread is (and must remain, for now) the
219 only responsible for freeing this member.
220 */
222
223 /**
224 The memory root to allocate parsed tree elements (instances of Item,
225 Query_block and other classes).
226 */
228
229 bool prepare_query(THD *thd);
230
231 public:
232 Prepared_statement(THD *thd_arg);
233 virtual ~Prepared_statement();
234
235 bool set_name(const LEX_CSTRING &name);
236 const LEX_CSTRING &name() const { return m_name; }
237 ulong id() const { return m_id; }
238 bool is_in_use() const { return m_in_use; }
239 bool is_sql_prepare() const { return m_is_sql_prepare; }
241 void deallocate(THD *thd);
242 bool prepare(THD *thd, const char *packet, size_t packet_length,
243 Item_param **orig_param_array);
244 bool execute_loop(THD *thd, String *expanded_query, bool open_cursor);
245 bool execute_server_runnable(THD *thd, Server_runnable *server_runnable);
246#ifdef HAVE_PSI_PS_INTERFACE
248#endif
249
250 /**
251 Assign parameter values from the execute packet.
252
253 @param thd current thread
254 @param expanded_query a container with the original SQL statement.
255 '?' placeholders will be replaced with
256 their values in case of success.
257 The result is used for logging and replication
258 @param has_new_types flag used to signal that new types are provided.
259 @param parameters prepared statement's parsed parameters.
260
261 @returns false if success, true if error
262 (likely a conversion error, out of memory, or malformed packet)
263 */
264 bool set_parameters(THD *thd, String *expanded_query, bool has_new_types,
265 PS_PARAM *parameters);
266
268 /*
269 Parameter values are coming from client over network (vio).
270 */
272
273 /*
274 Parameter values are sent either using using Server_component service
275 API's or Plugins or directly from SQL layer modules.
276
277 UNPACKED means that the parameter value buffer points to MYSQL_TIME*
278 */
280 };
281
282 /**
283 Assign parameter values from the execute packet.
284
285 @param thd current thread
286 @param expanded_query a container with the original SQL statement.
287 '?' placeholders will be replaced with
288 their values in case of success.
289 The result is used for logging and replication
290 @param has_new_types flag used to signal that new types are provided.
291 @param parameters prepared statement's parsed parameters.
292 @param param_pack_type parameters pack type.
293
294 @returns false if success, true if error
295 (likely a conversion error, out of memory, or malformed packet)
296 */
297 bool set_parameters(THD *thd, String *expanded_query, bool has_new_types,
298 PS_PARAM *parameters,
299 enum enum_param_pack_type param_pack_type);
300
301 bool set_parameters(THD *thd, String *expanded_query);
302 void trace_parameter_types(THD *thd);
303 void close_cursor();
304
305 private:
306 void cleanup_stmt(THD *thd);
307 void setup_stmt_logging(THD *thd);
309 void copy_parameter_types(Item_param **from_param_array);
310 bool set_db(const LEX_CSTRING &db_length);
311
312 bool execute(THD *thd, String *expanded_query, bool open_cursor);
313 bool reprepare(THD *thd);
317 String *query);
318 bool insert_parameters(THD *thd, String *query, bool has_new_types,
319 PS_PARAM *parameters,
320 enum enum_param_pack_type param_pack_type);
321};
322
323#endif // SQL_PREPARE_H
Dynamic parameters used as placeholders ('?') inside prepared statements.
Definition: item.h:4757
Base class that is used to represent any kind of expression in a relational query.
Definition: item.h:936
Definition: sql_list.h:467
Prepared_statement: a statement that can contain placeholders.
Definition: sql_prepare.h:152
bool set_db(const LEX_CSTRING &db_length)
Remember the current database.
Definition: sql_prepare.cc:2281
bool execute_loop(THD *thd, String *expanded_query, bool open_cursor)
Execute a prepared statement.
Definition: sql_prepare.cc:2856
Prepared_statement(THD *thd_arg)
Definition: sql_prepare.cc:2164
const Protocol * m_active_protocol
Used to check that the protocol is stable during execution.
Definition: sql_prepare.h:164
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:642
LEX_CSTRING m_query_string
The query string associated with this statement.
Definition: sql_prepare.h:181
bool prepare_query(THD *thd)
Perform semantic analysis of query and send a response packet to client.
Definition: sql_prepare.cc:1193
LEX_CSTRING m_db
Name of the current (default) database.
Definition: sql_prepare.h:221
bool execute(THD *thd, String *expanded_query, bool open_cursor)
Execute a prepared statement that has already been prepared.
Definition: sql_prepare.cc:3259
ulong id() const
Definition: sql_prepare.h:237
Server_side_cursor * m_cursor
Pointer to cursor, may be NULL if statement never used with a cursor.
Definition: sql_prepare.h:161
bool validate_metadata(THD *thd, Prepared_statement *copy)
Validate statement result set metadata (if the statement returns a result set).
Definition: sql_prepare.cc:3168
bool check_parameter_types()
Check resolved parameter types versus actual parameter types.
Definition: sql_prepare.cc:2648
void trace_parameter_types(THD *thd)
Definition: sql_prepare.cc:1407
void swap_prepared_statement(Prepared_statement *copy)
Swap the MEM_ROOT allocated data of two prepared statements.
Definition: sql_prepare.cc:3199
const LEX_CSTRING & name() const
Definition: sql_prepare.h:236
virtual ~Prepared_statement()
Destroy this prepared statement, cleaning up all used memory and resources.
Definition: sql_prepare.cc:2230
enum_param_pack_type
Definition: sql_prepare.h:267
@ PACKED
Definition: sql_prepare.h:271
@ UNPACKED
Definition: sql_prepare.h:279
bool m_used_as_cursor
True if statement is used with cursor, false if used in regular execution.
Definition: sql_prepare.h:188
Item_param ** m_param_array
Array of parameters used for statement, may be NULL if there are none.
Definition: sql_prepare.h:158
void deallocate(THD *thd)
Common part of DEALLOCATE PREPARE and mysqld_stmt_close.
Definition: sql_prepare.cc:3569
bool m_in_use
Flag that prevents recursive invocation of prepared statements.
Definition: sql_prepare.h:203
void setup_stmt_logging(THD *thd)
Definition: sql_prepare.cc:2178
bool is_sql_prepare() const
Definition: sql_prepare.h:239
Query_arena m_arena
Memory allocation arena, for permanent allocations to statement.
Definition: sql_prepare.h:155
void set_sql_prepare(bool prepare=true)
Definition: sql_prepare.h:240
bool execute_server_runnable(THD *thd, Server_runnable *server_runnable)
Definition: sql_prepare.cc:3020
LEX_CSTRING m_name
Name of the prepared statement.
Definition: sql_prepare.h:208
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:227
bool reprepare(THD *thd)
Reprepare this prepared statement.
Definition: sql_prepare.cc:3078
Query_result * m_regular_result
Query result used when statement is used in regular execution.
Definition: sql_prepare.h:191
LEX * m_lex
Definition: sql_prepare.h:178
bool m_with_log
Definition: sql_prepare.h:205
bool insert_parameters_from_vars(THD *thd, List< LEX_STRING > &varnames, String *query)
Assign prepared statement parameters from user variables.
Definition: sql_prepare.cc:863
void cleanup_stmt(THD *thd)
Definition: sql_prepare.cc:2256
void close_cursor()
Definition: sql_prepare.cc:2172
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:2325
Query_result * m_cursor_result
Query result used when statement is used with a cursor.
Definition: sql_prepare.h:194
uint m_param_count
Number of parameters expected for statement.
Definition: sql_prepare.h:167
Query_result * m_aux_result
Auxiliary query result object, saved for proper destruction.
Definition: sql_prepare.h:197
const ulong m_id
Uniquely identifies each statement object in thread scope; change during statement lifetime.
Definition: sql_prepare.h:176
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:2582
bool m_is_sql_prepare
Flag that specifies preparation state.
Definition: sql_prepare.h:200
bool set_name(const LEX_CSTRING &name)
Definition: sql_prepare.cc:2264
void copy_parameter_types(Item_param **from_param_array)
Copy parameter metada data from parameter array into current prepared stmt.
Definition: sql_prepare.cc:793
char m_last_error[MYSQL_ERRMSG_SIZE]
Definition: sql_prepare.h:170
PSI_prepared_stmt * get_PS_prepared_stmt()
Definition: sql_prepare.h:247
uint m_last_errno
Definition: sql_prepare.h:169
bool is_in_use() const
Definition: sql_prepare.h:238
PSI_prepared_stmt * m_prepared_stmt
Performance Schema interface for a prepared statement.
Definition: sql_prepare.h:184
Definition: protocol.h:33
Definition: sql_class.h:348
Definition: query_result.h:191
Definition: query_result.h:58
An interface that is used to take an action when the locking module notices that a table version has ...
Definition: sql_prepare.h:82
bool is_invalidated() const
Definition: sql_prepare.h:95
bool report_error(THD *thd)
Check if a change of metadata is OK.
Definition: sql_prepare.cc:2126
bool can_retry() const
Definition: sql_prepare.h:98
void reset_reprepare_observer()
Definition: sql_prepare.h:96
bool m_invalidated
Definition: sql_prepare.h:107
int m_attempt
Definition: sql_prepare.h:108
static constexpr int MAX_REPREPARE_ATTEMPTS
Definition: sql_prepare.h:114
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:167
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_lexer_thd.h:36
Definition: table.h:2864
struct PSI_prepared_stmt PSI_prepared_stmt
Definition: psi_statement_bits.h:105
constexpr const LEX_CSTRING NULL_CSTR
Definition: lex_string.h:47
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
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.
#define MYSQL_ERRMSG_SIZE
Max length of a error message.
Definition: mysql_com.h:881
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:1485
void mysql_sql_stmt_close(THD *thd)
SQLCOM_DEALLOCATE implementation.
Definition: sql_prepare.cc:2006
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:1917
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:2047
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:1534
void mysqld_stmt_close(THD *thd, Prepared_statement *stmt)
Delete a prepared statement from memory.
Definition: sql_prepare.cc:1983
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:2151
void reset_stmt_parameters(Prepared_statement *stmt)
Clears parameters from data left from previous execution or long data.
Definition: sql_prepare.cc:1790
void mysql_sql_stmt_execute(THD *thd)
SQLCOM_EXECUTE implementation.
Definition: sql_prepare.cc:1881
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:251
void rewrite_query(THD *thd)
Rewrite the current query (to obfuscate passwords etc.).
Definition: sql_prepare.cc:228
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:1818
void mysqld_stmt_reset(THD *thd, Prepared_statement *stmt)
Reset a prepared statement in case there was a recoverable error.
Definition: sql_prepare.cc:1956
void mysql_sql_stmt_prepare(THD *thd)
SQLCOM_PREPARE implementation.
Definition: sql_prepare.cc:1723
The LEX object currently serves three different purposes:
Definition: sql_lex.h:3823
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
Definition: com_data.h:104