MySQL  8.0.22
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, 2020, 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 also distributed 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 included with MySQL.
15 
16  This program is distributed in the hope that it will be useful,
17  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  GNU General Public License, version 2.0, for more details.
20 
21  You should have received a copy of the GNU General Public License
22  along with this program; if not, write to the Free Software
23  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
24 
25 #include <stddef.h>
26 #include <sys/types.h>
27 #include <new>
28 
29 #include "lex_string.h"
30 #include "my_alloc.h"
31 #include "my_command.h"
32 #include "my_dbug.h"
33 #include "my_inttypes.h"
34 #include "my_psi_config.h"
36 #include "mysql_com.h"
37 #include "sql/sql_class.h" // Query_arena
38 #include "sql/sql_error.h"
39 #include "sql/sql_list.h"
40 
41 class Item;
42 class Item_param;
43 class Prepared_statement;
44 class Query_result_send;
45 class String;
46 struct LEX;
47 struct PS_PARAM;
48 struct TABLE_LIST;
49 union COM_DATA;
50 
51 /**
52  An interface that is used to take an action when
53  the locking module notices that a table version has changed
54  since the last execution. "Table" here may refer to any kind of
55  table -- a base table, a temporary table, a view or an
56  information schema table.
57 
58  When we open and lock tables for execution of a prepared
59  statement, we must verify that they did not change
60  since statement prepare. If some table did change, the statement
61  parse tree *may* be no longer valid, e.g. in case it contains
62  optimizations that depend on table metadata.
63 
64  This class provides an interface (a method) that is
65  invoked when such a situation takes place.
66  The implementation of the method simply reports an error, but
67  the exact details depend on the nature of the SQL statement.
68 
69  At most 1 instance of this class is active at a time, in which
70  case THD::m_reprepare_observer is not NULL.
71 
72  @sa check_and_update_table_version() for details of the
73  version tracking algorithm
74 
75  @sa Open_tables_state::m_reprepare_observer for the life cycle
76  of metadata observers.
77 */
78 
80  public:
81  /**
82  Check if a change of metadata is OK. In future
83  the signature of this method may be extended to accept the old
84  and the new versions, but since currently the check is very
85  simple, we only need the THD to report an error.
86  */
87  bool report_error(THD *thd);
88  bool is_invalidated() const { return m_invalidated; }
90 
91  private:
93 };
94 
95 bool ask_to_reprepare(THD *thd);
96 bool mysql_stmt_precheck(THD *thd, const COM_DATA *com_data,
98  Prepared_statement **stmt);
99 void mysqld_stmt_prepare(THD *thd, const char *query, uint length,
100  Prepared_statement *stmt);
101 void mysqld_stmt_execute(THD *thd, Prepared_statement *stmt, bool has_new_types,
102  ulong execute_flags, PS_PARAM *parameters);
103 void mysqld_stmt_close(THD *thd, Prepared_statement *stmt);
104 void mysql_sql_stmt_prepare(THD *thd);
105 void mysql_sql_stmt_execute(THD *thd);
106 void mysql_sql_stmt_close(THD *thd);
107 void mysqld_stmt_fetch(THD *thd, Prepared_statement *stmt, ulong num_rows);
108 void mysqld_stmt_reset(THD *thd, Prepared_statement *stmt);
110  uint param_number, uchar *longdata, ulong length);
111 bool select_like_stmt_cmd_test(THD *thd, class Sql_cmd_dml *cmd,
112  ulong setup_tables_done_option);
113 
114 /**
115  Execute a fragment of server code in an isolated context, so that
116  it doesn't leave any effect on THD. THD must have no open tables.
117  The code must not leave any open tables around.
118  The result of execution (if any) is stored in Ed_result.
119 */
120 
122  public:
123  virtual bool execute_server_code(THD *thd) = 0;
124  virtual ~Server_runnable();
125 };
126 
127 /**
128  Execute direct interface.
129 
130  @todo Implement support for prelocked mode.
131 */
132 
133 class Ed_row;
134 
135 /**
136  Ed_result_set -- a container with result set rows.
137  @todo Implement support for result set metadata and
138  automatic type conversion.
139 */
140 
142  public:
143  operator List<Ed_row> &() { return *m_rows; }
144  unsigned int size() const { return m_rows->elements; }
145  Ed_row *get_fields() { return m_fields; }
146 
147  Ed_result_set(List<Ed_row> *rows_arg, Ed_row *fields, size_t column_count,
148  MEM_ROOT *mem_root_arg);
149 
150  /** We don't call member destructors, they all are POD types. */
152 
153  size_t get_field_count() const { return m_column_count; }
154 
155  static void operator delete(void *, size_t) noexcept {
156  // Does nothing because m_mem_root is deallocated in the destructor
157  }
158 
159  static void operator delete(
160  void *, MEM_ROOT *, const std::nothrow_t &) noexcept { /* never called */
161  }
162 
163  private:
164  Ed_result_set(const Ed_result_set &); /* not implemented */
165  Ed_result_set &operator=(Ed_result_set &); /* not implemented */
166  private:
167  MEM_ROOT m_mem_root;
172  friend class Ed_connection;
173 };
174 
176  public:
177  /**
178  Construct a new "execute direct" connection.
179 
180  The connection can be used to execute SQL statements.
181  If the connection failed to initialize, the error
182  will be returned on the attempt to execute a statement.
183 
184  @pre thd must have no open tables
185  while the connection is used. However,
186  Ed_connection works okay in LOCK TABLES mode.
187  Other properties of THD, such as the current warning
188  information, errors, etc. do not matter and are
189  preserved by Ed_connection. One thread may have many
190  Ed_connections created for it.
191  */
192  Ed_connection(THD *thd);
193 
194  /**
195  Execute one SQL statement.
196 
197  Until this method is executed, no other methods of
198  Ed_connection can be used. Life cycle of Ed_connection is:
199 
200  Initialized -> a statement has been executed ->
201  look at result, move to next result ->
202  look at result, move to next result ->
203  ...
204  moved beyond the last result == Initialized.
205 
206  This method can be called repeatedly. Once it's invoked,
207  results of the previous execution are lost.
208 
209  A result of execute_direct() can be either:
210 
211  - success, no result set rows. In this case get_field_count()
212  returns 0. This happens after execution of INSERT, UPDATE,
213  DELETE, DROP and similar statements. Some other methods, such
214  as get_affected_rows() can be used to retrieve additional
215  result information.
216 
217  - success, there are some result set rows (maybe 0). E.g.
218  happens after SELECT. In this case get_field_count() returns
219  the number of columns in a result set and store_result()
220  can be used to retrieve a result set..
221 
222  - an error, methods to retrieve error information can
223  be used.
224 
225  @return execution status
226  @retval false success, use get_field_count()
227  to determine what to do next.
228  @retval true error, use get_last_error()
229  to see the error number.
230  */
231  bool execute_direct(LEX_STRING sql_text);
232 
233  /**
234  Same as the previous, but takes an instance of Server_runnable
235  instead of SQL statement text.
236 
237  @return execution status
238 
239  @retval false success, use get_field_count()
240  if your code fragment is supposed to
241  return a result set
242  @retval true failure
243  */
244  bool execute_direct(Server_runnable *server_runnable);
245 
246  /**
247  The following three members are only valid if execute_direct()
248  or move_to_next_result() returned an error.
249  They never fail, but if they are called when there is no
250  result, or no error, the result is not defined.
251  */
252  const char *get_last_error() const {
253  return m_diagnostics_area.message_text();
254  }
255 
256  unsigned int get_last_errno() const {
257  return m_diagnostics_area.mysql_errno();
258  }
259 
260  Ed_result_set *get_result_sets() { return m_rsets; }
261 
262  ~Ed_connection() { free_old_result(); }
263 
264  private:
266  /**
267  Execute direct interface does not support multi-statements, only
268  multi-results. So we never have a situation when we have
269  a mix of result sets and OK or error packets. We either
270  have a single result set, a single error, or a single OK,
271  or we have a series of result sets, followed by an OK or error.
272  */
276  friend class Protocol_local;
277 
278  private:
279  void free_old_result();
280  void add_result_set(Ed_result_set *ed_result_set);
281 
282  private:
283  Ed_connection(const Ed_connection &); /* not implemented */
284  Ed_connection &operator=(Ed_connection &); /* not implemented */
285 };
286 
287 /** One result set column. */
288 
289 struct Ed_column final : public LEX_STRING {
290  /** Implementation note: destructor for this class is never called. */
291 };
292 
293 /** One result set record. */
294 
295 class Ed_row final {
296  public:
297  const Ed_column &operator[](const unsigned int column_index) const {
298  return *get_column(column_index);
299  }
300  const Ed_column *get_column(const unsigned int column_index) const {
301  DBUG_ASSERT(column_index < size());
302  return m_column_array + column_index;
303  }
304  size_t size() const { return m_column_count; }
305 
306  Ed_row(Ed_column *column_array_arg, size_t column_count_arg)
307  : m_column_array(column_array_arg), m_column_count(column_count_arg) {}
308 
309  private:
311  size_t m_column_count; /* TODO: change to point to metadata */
312 };
313 
314 class Server_side_cursor;
315 
316 /**
317  Prepared_statement: a statement that can contain placeholders.
318 */
319 
320 class Prepared_statement final {
321  enum flag_values { IS_IN_USE = 1, IS_SQL_PREPARE = 2 };
322 
323  public:
328  /// Used to check that the protocol is stable during execution
329  const Protocol *m_active_protocol{nullptr};
333 
334  /*
335  Uniquely identifies each statement object in thread scope; change during
336  statement lifetime.
337  */
338  const ulong id;
339 
340  LEX *lex; // parse tree descriptor
341 
342  /**
343  The query associated with this statement.
344  */
346 
347  /* Performance Schema interface for a prepared statement. */
349 
350  private:
352 
354  bool with_log;
355  LEX_CSTRING m_name; /* name for named prepared statements */
356  /**
357  Name of the current (default) database.
358 
359  If there is the current (default) database, "db" contains its name. If
360  there is no current (default) database, "db" is NULL and "db_length" is
361  0. In other words, "db", "db_length" must either be NULL, or contain a
362  valid database name.
363 
364  @note this attribute is set and alloced by the slave SQL thread (for
365  the THD of that thread); that thread is (and must remain, for now) the
366  only responsible for freeing this member.
367  */
369 
370  /**
371  The memory root to allocate parsed tree elements (instances of Item,
372  SELECT_LEX and other classes).
373  */
375 
376  public:
377  Prepared_statement(THD *thd_arg);
378  virtual ~Prepared_statement();
379  bool set_name(const LEX_CSTRING &name);
380  const LEX_CSTRING &name() const { return m_name; }
381  void close_cursor();
382  bool is_in_use() const { return flags & (uint)IS_IN_USE; }
383  bool is_sql_prepare() const { return flags & (uint)IS_SQL_PREPARE; }
384  void set_sql_prepare() { flags |= (uint)IS_SQL_PREPARE; }
385  bool prepare(const char *packet, size_t packet_length,
386  Item_param **orig_param_array);
387  bool prepare_query();
388  bool execute_loop(String *expanded_query, bool open_cursor);
389  bool execute_server_runnable(Server_runnable *server_runnable);
390 #ifdef HAVE_PSI_PS_INTERFACE
391  PSI_prepared_stmt *get_PS_prepared_stmt() { return m_prepared_stmt; }
392 #endif
393  /* Destroy this statement */
394  void deallocate();
395  bool set_parameters(String *expanded_query, bool has_new_types,
396  PS_PARAM *parameters);
397  bool set_parameters(String *expanded_query);
398  void trace_parameter_types();
399 
400  private:
401  void cleanup_stmt();
402  void setup_set_params();
403  bool check_parameter_types();
404  void copy_parameter_types(Item_param **from_param_array);
405  bool set_db(const LEX_CSTRING &db_length);
406 
407  bool execute(String *expanded_query, bool open_cursor);
408  bool reprepare();
409  bool validate_metadata(Prepared_statement *copy);
410  void swap_prepared_statement(Prepared_statement *copy);
411  bool insert_params_from_vars(List<LEX_STRING> &varnames, String *query);
412  bool insert_params(String *query, PS_PARAM *parameters);
413 };
414 
415 #endif // SQL_PREPARE_H
Ed_result_set * get_result_sets()
Definition: sql_prepare.h:260
size_t size() const
Definition: sql_prepare.h:304
Ed_row(Ed_column *column_array_arg, size_t column_count_arg)
Definition: sql_prepare.h:306
void mysqld_stmt_close(THD *thd, Prepared_statement *stmt)
Delete a prepared statement from memory.
Definition: sql_prepare.cc:2022
unsigned char uchar
Definition: my_inttypes.h:51
One result set record.
Definition: sql_prepare.h:295
Prepared_statement: a statement that can contain placeholders.
Definition: sql_prepare.h:320
Definition: mysql_lex_string.h:34
bool ask_to_reprepare(THD *thd)
Requests for repreparation of statement.
Definition: sql_prepare.cc:2184
One result set column.
Definition: sql_prepare.h:289
size_t get_field_count() const
Definition: sql_prepare.h:153
The LEX object currently serves three different purposes:
Definition: sql_lex.h:3613
const Ed_column & operator[](const unsigned int column_index) const
Definition: sql_prepare.h:297
size_t m_column_count
Definition: sql_prepare.h:311
static char * query
Definition: myisam_ftdump.cc:44
int last_error()
get last socket error.
Definition: socket_error.h:81
void mysql_sql_stmt_execute(THD *thd)
SQLCOM_EXECUTE implementation.
Definition: sql_prepare.cc:1922
Some integer typedefs for easier portability.
Ed_row * get_fields()
Definition: sql_prepare.h:145
Ed_result_set – a container with result set rows.
Definition: sql_prepare.h:141
flag_values
Definition: sql_prepare.h:321
bool is_invalidated() const
Definition: sql_prepare.h:88
LEX_CSTRING m_db
Name of the current (default) database.
Definition: sql_prepare.h:368
Ed_result_set * m_current_rset
Definition: sql_prepare.h:275
bool is_sql_prepare() const
Definition: sql_prepare.h:383
Definition: mysql_lex_string.h:39
MEM_ROOT main_mem_root
The memory root to allocate parsed tree elements (instances of Item, SELECT_LEX and other classes)...
Definition: sql_prepare.h:374
void mysqld_stmt_reset(THD *thd, Prepared_statement *stmt)
Reset a prepared statement in case there was a recoverable error.
Definition: sql_prepare.cc:1996
Server_side_cursor * cursor
Definition: sql_prepare.h:327
static bool execute(MYSQL_STMT *stmt, char *packet, ulong length)
Definition: libmysql.cc:1975
Definition: com_data.h:106
Definition: com_data.h:53
Execute a fragment of server code in an isolated context, so that it doesn&#39;t leave any effect on THD...
Definition: sql_prepare.h:121
size_t m_column_count
Definition: sql_prepare.h:168
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:1589
Using this class is fraught with peril, and you need to be very careful when doing so...
Definition: sql_string.h:164
void mysqld_stmt_prepare(THD *thd, const char *query, uint length, Prepared_statement *stmt)
COM_STMT_PREPARE handler.
Definition: sql_prepare.cc:1539
Common definition between mysql server & client.
Ed_result_set * m_next_rset
Definition: sql_prepare.h:171
Dynamic parameters used as placeholders (&#39;?&#39;) inside prepared statements.
Definition: item.h:4289
PSI_prepared_stmt * get_PS_prepared_stmt()
Definition: sql_prepare.h:391
Server_side_cursor – an interface for materialized implementation of cursors.
Definition: sql_cursor.h:50
#define DBUG_ASSERT(A)
Definition: my_dbug.h:199
Protocol_local: a helper class to intercept the result of the data written to the network...
Definition: sql_prepare.cc:245
void reset_reprepare_observer()
Definition: sql_prepare.h:89
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:1958
Definition: sql_class.h:226
Query_arena m_arena
Definition: sql_prepare.h:324
struct PSI_prepared_stmt PSI_prepared_stmt
Definition: psi_statement_bits.h:80
Definition: sql_prepare.h:175
Stores status of the currently executed statement.
Definition: sql_error.h:268
Defines various enable/disable and HAVE_ macros related to the performance schema instrumentation sys...
Definition: item.h:775
#define MYSQL_ERRMSG_SIZE
Max length of a error message.
Definition: mysql_com.h:840
unsigned int uint
Definition: uca-dump.cc:29
#define final(a, b, c)
Definition: hash.c:109
case opt name
Definition: sslopt-case.h:32
const LEX_CSTRING & name() const
Definition: sql_prepare.h:380
Performance schema instrumentation interface.
LEX_CSTRING m_query_string
The query associated with this statement.
Definition: sql_prepare.h:345
Ed_column * m_column_array
Definition: sql_prepare.h:310
static bool set_parameters(gis::srid_t srid, gis::srs::wkt_parser::Projected_cs *proj, std::vector< std::pair< int, double *>> *params)
Extract projection parameter values from the parse tree and assign them to variables.
Definition: srs.cc:121
bool m_invalidated
Definition: sql_prepare.h:92
Ed_row * m_fields
Definition: sql_prepare.h:170
const char * get_last_error() const
The following three members are only valid if execute_direct() or move_to_next_result() returned an e...
Definition: sql_prepare.h:252
LEX_CSTRING m_name
Definition: sql_prepare.h:355
~Ed_result_set()
We don&#39;t call member destructors, they all are POD types.
Definition: sql_prepare.h:151
enum_server_command
A list of all MySQL protocol commands.
Definition: my_command.h:47
LEX * lex
Definition: sql_prepare.h:340
THD * m_thd
Execute direct interface does not support multi-statements, only multi-results.
Definition: sql_prepare.h:273
void set_sql_prepare()
Definition: sql_prepare.h:384
Definition: query_result.h:208
bool is_in_use() const
Definition: sql_prepare.h:382
Definition: protocol.h:34
Diagnostics_area m_diagnostics_area
Definition: sql_prepare.h:265
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:1858
unsigned int get_last_errno() const
Definition: sql_prepare.h:256
THD * thd
Definition: sql_prepare.h:325
MEM_ROOT m_mem_root
Definition: sql_prepare.h:167
Ed_result_set * m_rsets
Definition: sql_prepare.h:274
Definition: sql_cmd_dml.h:33
bool select_like_stmt_cmd_test(THD *thd, class Sql_cmd_dml *cmd, ulong setup_tables_done_option)
COM_DATA cmd
Definition: test_session_info.cc:95
Query_result_send * result
Definition: sql_prepare.h:351
~Ed_connection()
Definition: sql_prepare.h:262
struct st_binary_log_transaction_compression_stats m_rows
Definition: table_binary_log_transaction_compression_stats.cc:74
unsigned int size() const
Definition: sql_prepare.h:144
List< Ed_row > * m_rows
Definition: sql_prepare.h:169
uint flags
Definition: sql_prepare.h:353
The MEM_ROOT is a simple arena, where allocations are carved out of larger blocks.
Definition: my_alloc.h:77
Definition: table.h:2540
const Ed_column * get_column(const unsigned int column_index) const
Definition: sql_prepare.h:300
void mysql_sql_stmt_prepare(THD *thd)
SQLCOM_PREPARE implementation.
Definition: sql_prepare.cc:1764
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:2083
void mysql_sql_stmt_close(THD *thd)
SQLCOM_DEALLOCATE implementation.
Definition: sql_prepare.cc:2045
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:75
bool with_log
Definition: sql_prepare.h:354
An interface that is used to take an action when the locking module notices that a table version has ...
Definition: sql_prepare.h:79
Item_param ** param_array
Definition: sql_prepare.h:326
const ulong id
Definition: sql_prepare.h:338
void copy(Shards< COUNT > &dst, const Shards< COUNT > &src) noexcept
Copy the counters, overwrite destination.
Definition: ut0counter.h:353
This file follows Google coding style, except for the name MEM_ROOT (which is kept for historical rea...
For each client connection we create a separate thread with THD serving as a thread/connection descri...
Definition: sql_class.h:803
static void prepare(pax_msg *p, pax_op op)
Definition: xcom_base.cc:1304
PSI_prepared_stmt * m_prepared_stmt
Definition: sql_prepare.h:348
uint last_errno
Definition: sql_prepare.h:331
bool report_error(THD *thd)
Check if a change of metadata is OK.
Definition: sql_prepare.cc:2160
uint param_count
Definition: sql_prepare.h:330