MySQL 9.1.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, 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
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 /// Performance Schema interface for a prepared statement.
183
184 private:
185 /// True if statement is used with cursor, false if used in regular execution
186 bool m_used_as_cursor{false};
187
188 /// Query result used when statement is used in regular execution.
190
191 /// Query result used when statement is used with a cursor.
193
194 /// Auxiliary query result object, saved for proper destruction
196
197 /// Flag that specifies preparation state
198 bool m_is_sql_prepare{false};
199
200 /// Flag that prevents recursive invocation of prepared statements
201 bool m_in_use{false};
202
203 bool m_with_log{false};
204
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:4789
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:2306
bool execute_loop(THD *thd, String *expanded_query, bool open_cursor)
Execute a prepared statement.
Definition: sql_prepare.cc:2877
Prepared_statement(THD *thd_arg)
Definition: sql_prepare.cc:2183
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:654
LEX_CSTRING m_query_string
The query string associated with this statement.
Definition: sql_prepare.h:179
bool prepare_query(THD *thd)
Perform semantic analysis of query and send a response packet to client.
Definition: sql_prepare.cc:1204
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:3340
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: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:3249
bool check_parameter_types()
Check resolved parameter types versus actual parameter types.
Definition: sql_prepare.cc:2668
void trace_parameter_types(THD *thd)
Definition: sql_prepare.cc:1426
void swap_prepared_statement(Prepared_statement *copy)
Swap the MEM_ROOT allocated data of two prepared statements.
Definition: sql_prepare.cc:3280
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:2249
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:186
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:3650
bool m_in_use
Flag that prevents recursive invocation of prepared statements.
Definition: sql_prepare.h:201
void setup_stmt_logging(THD *thd)
Definition: sql_prepare.cc:2197
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:153
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:3101
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:3159
Query_result * m_regular_result
Query result used when statement is used in regular execution.
Definition: sql_prepare.h:189
LEX * m_lex
Definition: sql_prepare.h:176
bool m_with_log
Definition: sql_prepare.h:203
bool insert_parameters_from_vars(THD *thd, List< LEX_STRING > &varnames, String *query)
Assign prepared statement parameters from user variables.
Definition: sql_prepare.cc:874
void cleanup_stmt(THD *thd)
Definition: sql_prepare.cc:2281
void close_cursor()
Definition: sql_prepare.cc:2191
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:2350
Query_result * m_cursor_result
Query result used when statement is used with a cursor.
Definition: sql_prepare.h:192
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:195
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:2618
bool m_is_sql_prepare
Flag that specifies preparation state.
Definition: sql_prepare.h:198
bool set_name(const LEX_CSTRING &name)
Definition: sql_prepare.cc:2289
void copy_parameter_types(Item_param **from_param_array)
Copy parameter metada data from parameter array into current prepared stmt.
Definition: sql_prepare.cc:804
char m_last_error[MYSQL_ERRMSG_SIZE]
Definition: sql_prepare.h:168
PSI_prepared_stmt * get_PS_prepared_stmt()
Definition: sql_prepare.h:247
uint m_last_errno
Definition: sql_prepare.h:167
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:182
bool m_first_execution
Definition: sql_prepare.h:205
Definition: protocol.h:33
Definition: sql_class.h:348
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: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:2145
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:167
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: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:1504
void mysql_sql_stmt_close(THD *thd)
SQLCOM_DEALLOCATE implementation.
Definition: sql_prepare.cc:2025
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:1936
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:2066
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:1553
void mysqld_stmt_close(THD *thd, Prepared_statement *stmt)
Delete a prepared statement from memory.
Definition: sql_prepare.cc:2002
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:2170
void reset_stmt_parameters(Prepared_statement *stmt)
Clears parameters from data left from previous execution or long data.
Definition: sql_prepare.cc:1809
void mysql_sql_stmt_execute(THD *thd)
SQLCOM_EXECUTE implementation.
Definition: sql_prepare.cc:1900
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:261
void rewrite_query(THD *thd)
Rewrite the current query (to obfuscate passwords etc.).
Definition: sql_prepare.cc:238
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:1837
void mysqld_stmt_reset(THD *thd, Prepared_statement *stmt)
Reset a prepared statement in case there was a recoverable error.
Definition: sql_prepare.cc:1975
void mysql_sql_stmt_prepare(THD *thd)
SQLCOM_PREPARE implementation.
Definition: sql_prepare.cc:1742
The LEX object currently serves three different purposes:
Definition: sql_lex.h:3844
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