1 /*
2    Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License, version 2.0,
6    as published by the Free Software Foundation.
7 
8    This program is also distributed with certain software (including
9    but not limited to OpenSSL) that is licensed under separate terms,
10    as designated in a particular file or component or in included license
11    documentation.  The authors of MySQL hereby grant you an additional
12    permission to link the program and your derivative works with the
13    separately licensed software that they have included with MySQL.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License, version 2.0, for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
23 
24 
25 #define MYSQL_LEX 1
26 #include "my_global.h"                          /* NO_EMBEDDED_ACCESS_CHECKS */
27 #include "sql_priv.h"
28 #include "unireg.h"
29 #include "sp_head.h"
30 #include "sql_trigger.h"
31 #include "sql_parse.h"                          // parse_sql
32 #include "parse_file.h"
33 #include "sp.h"
34 #include "sql_base.h"                          // find_temporary_table
35 #include "sql_show.h"                // append_definer, append_identifier
36 #include "sql_table.h"                        // build_table_filename,
37                                               // check_n_cut_mysql50_prefix
38 #include "sql_db.h"                        // get_default_db_collation
39 #include "sql_acl.h"                       // *_ACL, is_acl_user
40 #include "sql_handler.h"                        // mysql_ha_rm_tables
41 #include "sp_cache.h"                     // sp_invalidate_cache
42 #include <mysys_err.h>
43 
44 /*************************************************************************/
45 
46 template <class T>
alloc_type(MEM_ROOT * m)47 inline T *alloc_type(MEM_ROOT *m)
48 {
49   return (T *) alloc_root(m, sizeof (T));
50 }
51 
52 /*
53   NOTE: Since alloc_type() is declared as inline, alloc_root() calls should
54   be inlined by the compiler. So, implementation of alloc_root() is not
55   needed. However, let's put the implementation in object file just in case
56   of stupid MS or other old compilers.
57 */
58 
59 template LEX_STRING *alloc_type<LEX_STRING>(MEM_ROOT *m);
60 template ulonglong *alloc_type<ulonglong>(MEM_ROOT *m);
61 
alloc_lex_string(MEM_ROOT * m)62 inline LEX_STRING *alloc_lex_string(MEM_ROOT *m)
63 {
64   return alloc_type<LEX_STRING>(m);
65 }
66 
67 /*************************************************************************/
68 /**
69   Trigger_creation_ctx -- creation context of triggers.
70 */
71 
72 class Trigger_creation_ctx : public Stored_program_creation_ctx,
73                              public Sql_alloc
74 {
75 public:
76   static Trigger_creation_ctx *create(THD *thd,
77                                       const char *db_name,
78                                       const char *table_name,
79                                       const LEX_STRING *client_cs_name,
80                                       const LEX_STRING *connection_cl_name,
81                                       const LEX_STRING *db_cl_name);
82 
83 public:
clone(MEM_ROOT * mem_root)84   virtual Stored_program_creation_ctx *clone(MEM_ROOT *mem_root)
85   {
86     return new (mem_root) Trigger_creation_ctx(m_client_cs,
87                                                m_connection_cl,
88                                                m_db_cl);
89   }
90 
91 protected:
create_backup_ctx(THD * thd) const92   virtual Object_creation_ctx *create_backup_ctx(THD *thd) const
93   {
94     return new Trigger_creation_ctx(thd);
95   }
96 
97 private:
Trigger_creation_ctx(THD * thd)98   Trigger_creation_ctx(THD *thd)
99     :Stored_program_creation_ctx(thd)
100   { }
101 
Trigger_creation_ctx(const CHARSET_INFO * client_cs,const CHARSET_INFO * connection_cl,const CHARSET_INFO * db_cl)102   Trigger_creation_ctx(const CHARSET_INFO *client_cs,
103                        const CHARSET_INFO *connection_cl,
104                        const CHARSET_INFO *db_cl)
105     :Stored_program_creation_ctx(client_cs, connection_cl, db_cl)
106   { }
107 };
108 
109 /**************************************************************************
110   Trigger_creation_ctx implementation.
111 **************************************************************************/
112 
113 Trigger_creation_ctx *
create(THD * thd,const char * db_name,const char * table_name,const LEX_STRING * client_cs_name,const LEX_STRING * connection_cl_name,const LEX_STRING * db_cl_name)114 Trigger_creation_ctx::create(THD *thd,
115                              const char *db_name,
116                              const char *table_name,
117                              const LEX_STRING *client_cs_name,
118                              const LEX_STRING *connection_cl_name,
119                              const LEX_STRING *db_cl_name)
120 {
121   const CHARSET_INFO *client_cs;
122   const CHARSET_INFO *connection_cl;
123   const CHARSET_INFO *db_cl;
124 
125   bool invalid_creation_ctx= FALSE;
126 
127   if (resolve_charset(client_cs_name->str,
128                       thd->variables.character_set_client,
129                       &client_cs))
130   {
131     sql_print_warning("Trigger for table '%s'.'%s': "
132                       "invalid character_set_client value (%s).",
133                       (const char *) db_name,
134                       (const char *) table_name,
135                       (const char *) client_cs_name->str);
136 
137     invalid_creation_ctx= TRUE;
138   }
139 
140   if (resolve_collation(connection_cl_name->str,
141                         thd->variables.collation_connection,
142                         &connection_cl))
143   {
144     sql_print_warning("Trigger for table '%s'.'%s': "
145                       "invalid collation_connection value (%s).",
146                       (const char *) db_name,
147                       (const char *) table_name,
148                       (const char *) connection_cl_name->str);
149 
150     invalid_creation_ctx= TRUE;
151   }
152 
153   if (resolve_collation(db_cl_name->str, NULL, &db_cl))
154   {
155     sql_print_warning("Trigger for table '%s'.'%s': "
156                       "invalid database_collation value (%s).",
157                       (const char *) db_name,
158                       (const char *) table_name,
159                       (const char *) db_cl_name->str);
160 
161     invalid_creation_ctx= TRUE;
162   }
163 
164   if (invalid_creation_ctx)
165   {
166     push_warning_printf(thd,
167                         Sql_condition::WARN_LEVEL_WARN,
168                         ER_TRG_INVALID_CREATION_CTX,
169                         ER(ER_TRG_INVALID_CREATION_CTX),
170                         (const char *) db_name,
171                         (const char *) table_name);
172   }
173 
174   /*
175     If we failed to resolve the database collation, load the default one
176     from the disk.
177   */
178 
179   if (!db_cl)
180     db_cl= get_default_db_collation(thd, db_name);
181 
182   return new Trigger_creation_ctx(client_cs, connection_cl, db_cl);
183 }
184 
185 /*************************************************************************/
186 
187 static const LEX_STRING triggers_file_type=
188   { C_STRING_WITH_LEN("TRIGGERS") };
189 
190 const char * const TRG_EXT= ".TRG";
191 
192 /**
193   Table of .TRG file field descriptors.
194   We have here only one field now because in nearest future .TRG
195   files will be merged into .FRM files (so we don't need something
196   like md5 or created fields).
197 */
198 static File_option triggers_file_parameters[]=
199 {
200   {
201     { C_STRING_WITH_LEN("triggers") },
202     my_offsetof(class Table_triggers_list, definitions_list),
203     FILE_OPTIONS_STRLIST
204   },
205   {
206     { C_STRING_WITH_LEN("sql_modes") },
207     my_offsetof(class Table_triggers_list, definition_modes_list),
208     FILE_OPTIONS_ULLLIST
209   },
210   {
211     { C_STRING_WITH_LEN("definers") },
212     my_offsetof(class Table_triggers_list, definers_list),
213     FILE_OPTIONS_STRLIST
214   },
215   {
216     { C_STRING_WITH_LEN("client_cs_names") },
217     my_offsetof(class Table_triggers_list, client_cs_names),
218     FILE_OPTIONS_STRLIST
219   },
220   {
221     { C_STRING_WITH_LEN("connection_cl_names") },
222     my_offsetof(class Table_triggers_list, connection_cl_names),
223     FILE_OPTIONS_STRLIST
224   },
225   {
226     { C_STRING_WITH_LEN("db_cl_names") },
227     my_offsetof(class Table_triggers_list, db_cl_names),
228     FILE_OPTIONS_STRLIST
229   },
230   { { 0, 0 }, 0, FILE_OPTIONS_STRING }
231 };
232 
233 File_option sql_modes_parameters=
234 {
235   { C_STRING_WITH_LEN("sql_modes") },
236   my_offsetof(class Table_triggers_list, definition_modes_list),
237   FILE_OPTIONS_ULLLIST
238 };
239 
240 /**
241   This must be kept up to date whenever a new option is added to the list
242   above, as it specifies the number of required parameters of the trigger in
243   .trg file.
244 */
245 
246 static const int TRG_NUM_REQUIRED_PARAMETERS= 6;
247 
248 /*
249   Structure representing contents of .TRN file which are used to support
250   database wide trigger namespace.
251 */
252 
253 struct st_trigname
254 {
255   LEX_STRING trigger_table;
256 };
257 
258 static const LEX_STRING trigname_file_type=
259   { C_STRING_WITH_LEN("TRIGGERNAME") };
260 
261 const char * const TRN_EXT= ".TRN";
262 
263 static File_option trigname_file_parameters[]=
264 {
265   {
266     { C_STRING_WITH_LEN("trigger_table")},
267     offsetof(struct st_trigname, trigger_table),
268     FILE_OPTIONS_ESTRING
269   },
270   { { 0, 0 }, 0, FILE_OPTIONS_STRING }
271 };
272 
273 
274 const LEX_STRING trg_action_time_type_names[]=
275 {
276   { C_STRING_WITH_LEN("BEFORE") },
277   { C_STRING_WITH_LEN("AFTER") }
278 };
279 
280 const LEX_STRING trg_event_type_names[]=
281 {
282   { C_STRING_WITH_LEN("INSERT") },
283   { C_STRING_WITH_LEN("UPDATE") },
284   { C_STRING_WITH_LEN("DELETE") }
285 };
286 
287 
288 class Handle_old_incorrect_sql_modes_hook: public Unknown_key_hook
289 {
290 private:
291   char *path;
292 public:
Handle_old_incorrect_sql_modes_hook(char * file_path)293   Handle_old_incorrect_sql_modes_hook(char *file_path)
294     :path(file_path)
295   {};
296   virtual bool process_unknown_string(const char *&unknown_key, uchar* base,
297                                       MEM_ROOT *mem_root, const char *end);
298 };
299 
300 
301 class Handle_old_incorrect_trigger_table_hook: public Unknown_key_hook
302 {
303 public:
Handle_old_incorrect_trigger_table_hook(char * file_path,LEX_STRING * trigger_table_arg)304   Handle_old_incorrect_trigger_table_hook(char *file_path,
305                                           LEX_STRING *trigger_table_arg)
306     :path(file_path), trigger_table_value(trigger_table_arg)
307   {};
308   virtual bool process_unknown_string(const char *&unknown_key, uchar* base,
309                                       MEM_ROOT *mem_root, const char *end);
310 private:
311   char *path;
312   LEX_STRING *trigger_table_value;
313 };
314 
315 
316 /**
317   An error handler that catches all non-OOM errors which can occur during
318   parsing of trigger body. Such errors are ignored and corresponding error
319   message is used to construct a more verbose error message which contains
320   name of problematic trigger. This error message is later emitted when
321   one tries to perform DML or some of DDL on this table.
322   Also, if possible, grabs name of the trigger being parsed so it can be
323   used to correctly drop problematic trigger.
324 */
325 class Deprecated_trigger_syntax_handler : public Internal_error_handler
326 {
327 private:
328 
329   char m_message[MYSQL_ERRMSG_SIZE];
330   LEX_STRING *m_trigger_name;
331 
332 public:
333 
Deprecated_trigger_syntax_handler()334   Deprecated_trigger_syntax_handler() : m_trigger_name(NULL) {}
335 
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_warning_level level,const char * message,Sql_condition ** cond_hdl)336   virtual bool handle_condition(THD *thd,
337                                 uint sql_errno,
338                                 const char* sqlstate,
339                                 Sql_condition::enum_warning_level level,
340                                 const char* message,
341                                 Sql_condition ** cond_hdl)
342   {
343     if (sql_errno != EE_OUTOFMEMORY &&
344         sql_errno != ER_OUT_OF_RESOURCES)
345     {
346       if(thd->lex->spname)
347         m_trigger_name= &thd->lex->spname->m_name;
348       if (m_trigger_name)
349         my_snprintf(m_message, sizeof(m_message),
350                     ER(ER_ERROR_IN_TRIGGER_BODY),
351                     m_trigger_name->str, message);
352       else
353         my_snprintf(m_message, sizeof(m_message),
354                     ER(ER_ERROR_IN_UNKNOWN_TRIGGER_BODY), message);
355       return true;
356     }
357     return false;
358   }
359 
get_trigger_name()360   LEX_STRING *get_trigger_name() { return m_trigger_name; }
get_error_message()361   char *get_error_message() { return m_message; }
362 };
363 
364 
365 /**
366   Create or drop trigger for table.
367 
368   @param thd     current thread context (including trigger definition in LEX)
369   @param tables  table list containing one table for which trigger is created.
370   @param create  whenever we create (TRUE) or drop (FALSE) trigger
371 
372   @note
373     This function is mainly responsible for opening and locking of table and
374     invalidation of all its instances in table cache after trigger creation.
375     Real work on trigger creation/dropping is done inside Table_triggers_list
376     methods.
377 
378   @todo
379     TODO: We should check if user has TRIGGER privilege for table here.
380     Now we just require SUPER privilege for creating/dropping because
381     we don't have proper privilege checking for triggers in place yet.
382 
383   @retval
384     FALSE Success
385   @retval
386     TRUE  error
387 */
mysql_create_or_drop_trigger(THD * thd,TABLE_LIST * tables,bool create)388 bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create)
389 {
390   /*
391     FIXME: The code below takes too many different paths depending on the
392     'create' flag, so that the justification for a single function
393     'mysql_create_or_drop_trigger', compared to two separate functions
394     'mysql_create_trigger' and 'mysql_drop_trigger' is not apparent.
395     This is a good candidate for a minor refactoring.
396   */
397   TABLE *table;
398   bool result= TRUE;
399   String stmt_query;
400   bool lock_upgrade_done= FALSE;
401   MDL_ticket *mdl_ticket= NULL;
402   Query_tables_list backup;
403 
404   DBUG_ENTER("mysql_create_or_drop_trigger");
405 
406   /* Charset of the buffer for statement must be system one. */
407   stmt_query.set_charset(system_charset_info);
408 
409   /*
410     QQ: This function could be merged in mysql_alter_table() function
411     But do we want this ?
412   */
413 
414   /*
415     Note that once we will have check for TRIGGER privilege in place we won't
416     need second part of condition below, since check_access() function also
417     checks that db is specified.
418   */
419   if (!thd->lex->spname->m_db.length || (create && !tables->db_length))
420   {
421     my_error(ER_NO_DB_ERROR, MYF(0));
422     DBUG_RETURN(TRUE);
423   }
424 
425   /*
426     We don't allow creating triggers on tables in the 'mysql' schema
427   */
428   if (create && !my_strcasecmp(system_charset_info, "mysql", tables->db))
429   {
430     my_error(ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA, MYF(0));
431     DBUG_RETURN(TRUE);
432   }
433 
434   /*
435     There is no DETERMINISTIC clause for triggers, so can't check it.
436     But a trigger can in theory be used to do nasty things (if it supported
437     DROP for example) so we do the check for privileges. For now there is
438     already a stronger test right above; but when this stronger test will
439     be removed, the test below will hold. Because triggers have the same
440     nature as functions regarding binlogging: their body is implicitly
441     binlogged, so they share the same danger, so trust_function_creators
442     applies to them too.
443   */
444 #ifdef WITH_WSREP
445   if (!trust_function_creators                                &&
446       (WSREP_EMULATE_BINLOG(thd) || mysql_bin_log.is_open())  &&
447       !(thd->security_ctx->master_access & SUPER_ACL))
448 #else
449   if (!trust_function_creators && mysql_bin_log.is_open() &&
450       !(thd->security_ctx->master_access & SUPER_ACL))
451 #endif /* WITH_WSREP */
452   {
453     my_error(ER_BINLOG_CREATE_ROUTINE_NEED_SUPER, MYF(0));
454     DBUG_RETURN(TRUE);
455   }
456 
457   if (!create)
458   {
459     bool if_exists= thd->lex->drop_if_exists;
460 
461     /*
462       Protect the query table list from the temporary and potentially
463       destructive changes necessary to open the trigger's table.
464     */
465     thd->lex->reset_n_backup_query_tables_list(&backup);
466     /*
467       Restore Query_tables_list::sql_command, which was
468       reset above, as the code that writes the query to the
469       binary log assumes that this value corresponds to the
470       statement that is being executed.
471     */
472     thd->lex->sql_command= backup.sql_command;
473 
474     if (opt_readonly && !(thd->security_ctx->master_access & SUPER_ACL) &&
475         !thd->slave_thread)
476     {
477       my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
478       goto end;
479     }
480 
481     if (add_table_for_trigger(thd, thd->lex->spname, if_exists, & tables))
482       goto end;
483 
484     if (!tables)
485     {
486       DBUG_ASSERT(if_exists);
487       /*
488         Since the trigger does not exist, there is no associated table,
489         and therefore :
490         - no TRIGGER privileges to check,
491         - no trigger to drop,
492         - no table to lock/modify,
493         so the drop statement is successful.
494       */
495       result= FALSE;
496       /* Still, we need to log the query ... */
497       stmt_query.append(thd->query(), thd->query_length());
498       goto end;
499     }
500   }
501 
502   /*
503     Check that the user has TRIGGER privilege on the subject table.
504   */
505   {
506     bool err_status;
507     TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
508     thd->lex->query_tables_own_last= 0;
509 
510     err_status= check_table_access(thd, TRIGGER_ACL, tables, FALSE, 1, FALSE);
511 
512     thd->lex->query_tables_own_last= save_query_tables_own_last;
513 
514     if (err_status)
515       goto end;
516   }
517   WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
518 
519   /* We should have only one table in table list. */
520   DBUG_ASSERT(tables->next_global == 0);
521 
522   /* We do not allow creation of triggers on temporary tables. */
523   if (create && find_temporary_table(thd, tables))
524   {
525     my_error(ER_TRG_ON_VIEW_OR_TEMP_TABLE, MYF(0), tables->alias);
526     goto end;
527   }
528 
529   /* We also don't allow creation of triggers on views. */
530   tables->required_type= FRMTYPE_TABLE;
531   /*
532     Also prevent DROP TRIGGER from opening temporary table which might
533     shadow base table on which trigger to be dropped is defined.
534   */
535   tables->open_type= OT_BASE_ONLY;
536 
537   /* Keep consistent with respect to other DDL statements */
538   mysql_ha_rm_tables(thd, tables);
539 
540   if (thd->locked_tables_mode)
541   {
542     /* Under LOCK TABLES we must only accept write locked tables. */
543     if (!(tables->table= find_table_for_mdl_upgrade(thd, tables->db,
544                                                     tables->table_name,
545                                                     FALSE)))
546       goto end;
547   }
548   else
549   {
550     tables->table= open_n_lock_single_table(thd, tables,
551                                             TL_READ_NO_INSERT, 0);
552     if (! tables->table)
553       goto end;
554     tables->table->use_all_columns();
555   }
556   table= tables->table;
557 
558   /* Later on we will need it to downgrade the lock */
559   mdl_ticket= table->mdl_ticket;
560 
561   if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
562     goto end;
563 
564   lock_upgrade_done= TRUE;
565 
566   if (!table->triggers)
567   {
568     if (!create)
569     {
570       my_error(ER_TRG_DOES_NOT_EXIST, MYF(0));
571       goto end;
572     }
573 
574     if (!(table->triggers= new (&table->mem_root) Table_triggers_list(table)))
575       goto end;
576   }
577 
578   result= (create ?
579            table->triggers->create_trigger(thd, tables, &stmt_query):
580            table->triggers->drop_trigger(thd, tables, &stmt_query));
581 
582   if (result)
583     goto end;
584 
585   close_all_tables_for_name(thd, table->s, false, NULL);
586   /*
587     Reopen the table if we were under LOCK TABLES.
588     Ignore the return value for now. It's better to
589     keep master/slave in consistent state.
590   */
591   thd->locked_tables_list.reopen_tables(thd);
592 
593   /*
594     Invalidate SP-cache. That's needed because triggers may change list of
595     pre-locking tables.
596   */
597   sp_cache_invalidate();
598 
599 end:
600   if (!result)
601   {
602     if (tables)
603       thd->add_to_binlog_accessed_dbs(tables->db);
604     result= write_bin_log(thd, TRUE, stmt_query.ptr(), stmt_query.length());
605   }
606 
607   /*
608     If we are under LOCK TABLES we should restore original state of
609     meta-data locks. Otherwise all locks will be released along
610     with the implicit commit.
611   */
612   if (thd->locked_tables_mode && tables && lock_upgrade_done)
613     mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
614 
615   /* Restore the query table list. Used only for drop trigger. */
616   if (!create)
617     thd->lex->restore_backup_query_tables_list(&backup);
618 
619   if (!result)
620     my_ok(thd);
621 
622   DBUG_RETURN(result);
623 #ifdef WITH_WSREP
624  error:
625   DBUG_RETURN(TRUE);
626 #endif /* WITH_WSREP */
627 }
628 
629 
630 /**
631   Create trigger for table.
632 
633   @param thd           current thread context (including trigger definition in
634                        LEX)
635   @param tables        table list containing one open table for which the
636                        trigger is created.
637   @param[out] stmt_query    after successful return, this string contains
638                             well-formed statement for creation this trigger.
639 
640   @note
641     - Assumes that trigger name is fully qualified.
642     - NULL-string means the following LEX_STRING instance:
643     { str = 0; length = 0 }.
644     - In other words, definer_user and definer_host should contain
645     simultaneously NULL-strings (non-SUID/old trigger) or valid strings
646     (SUID/new trigger).
647 
648   @retval
649     False   success
650   @retval
651     True    error
652 */
create_trigger(THD * thd,TABLE_LIST * tables,String * stmt_query)653 bool Table_triggers_list::create_trigger(THD *thd, TABLE_LIST *tables,
654                                          String *stmt_query)
655 {
656   LEX *lex= thd->lex;
657   TABLE *table= tables->table;
658   char file_buff[FN_REFLEN], trigname_buff[FN_REFLEN];
659   LEX_STRING file, trigname_file;
660   LEX_STRING *trg_def;
661   LEX_STRING definer_user;
662   LEX_STRING definer_host;
663   sql_mode_t *trg_sql_mode;
664   char trg_definer_holder[USER_HOST_BUFF_SIZE];
665   LEX_STRING *trg_definer;
666   struct st_trigname trigname;
667   LEX_STRING *trg_client_cs_name;
668   LEX_STRING *trg_connection_cl_name;
669   LEX_STRING *trg_db_cl_name;
670   bool was_truncated;
671 
672   if (check_for_broken_triggers())
673     return true;
674 
675   /* Trigger must be in the same schema as target table. */
676   if (my_strcasecmp(table_alias_charset, table->s->db.str,
677                     lex->spname->m_db.str))
678   {
679     my_error(ER_TRG_IN_WRONG_SCHEMA, MYF(0));
680     return 1;
681   }
682 
683   sp_head *trg= lex->sphead;
684   int trg_event= trg->m_trg_chistics.event;
685   int trg_action_time= trg->m_trg_chistics.action_time;
686 
687   /* We don't allow creation of several triggers of the same type yet */
688   if (bodies[trg_event][trg_action_time] != NULL)
689   {
690     my_error(ER_NOT_SUPPORTED_YET, MYF(0),
691              "multiple triggers with the same action time"
692              " and event for one table");
693     return 1;
694   }
695 
696   if (!lex->definer)
697   {
698     /*
699       DEFINER-clause is missing.
700 
701       If we are in slave thread, this means that we received CREATE TRIGGER
702       from the master, that does not support definer in triggers. So, we
703       should mark this trigger as non-SUID. Note that this does not happen
704       when we parse triggers' definitions during opening .TRG file.
705       LEX::definer is ignored in that case.
706 
707       Otherwise, we should use CURRENT_USER() as definer.
708 
709       NOTE: when CREATE TRIGGER statement is allowed to be executed in PS/SP,
710       it will be required to create the definer below in persistent MEM_ROOT
711       of PS/SP.
712     */
713 
714     if (!thd->slave_thread)
715     {
716       if (!(lex->definer= create_default_definer(thd)))
717         return 1;
718     }
719   }
720 
721   /*
722     If the specified definer differs from the current user, we should check
723     that the current user has SUPER privilege (in order to create trigger
724     under another user one must have SUPER privilege).
725   */
726 
727   if (lex->definer &&
728       (strcmp(lex->definer->user.str, thd->security_ctx->priv_user) ||
729        my_strcasecmp(system_charset_info,
730                      lex->definer->host.str,
731                      thd->security_ctx->priv_host)))
732   {
733     if (check_global_access(thd, SUPER_ACL))
734     {
735       my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "SUPER");
736       return TRUE;
737     }
738   }
739 
740   /*
741     Let us check if all references to fields in old/new versions of row in
742     this trigger are ok.
743 
744     NOTE: We do it here more from ease of use standpoint. We still have to
745     do some checks on each execution. E.g. we can catch privilege changes
746     only during execution. Also in near future, when we will allow access
747     to other tables from trigger we won't be able to catch changes in other
748     tables...
749 
750     Since we don't plan to access to contents of the fields it does not
751     matter that we choose for both OLD and NEW values the same versions
752     of Field objects here.
753   */
754   old_field= new_field= table->field;
755 
756   for (SQL_I_List<Item_trigger_field> *trig_field_list=
757          lex->sphead->m_list_of_trig_fields_item_lists.first;
758       trig_field_list;
759       trig_field_list= trig_field_list->first->next_trig_field_list)
760   {
761     for (Item_trigger_field *trg_field= trig_field_list->first;
762          trg_field; trg_field= trg_field->next_trg_field)
763     {
764       /*
765         NOTE: now we do not check privileges at CREATE TRIGGER time. This will
766         be changed in the future.
767       */
768       trg_field->setup_field(thd, table, NULL);
769 
770       if (!trg_field->fixed &&
771           trg_field->fix_fields(thd, (Item **)0))
772         return 1;
773     }
774   }
775 
776   /*
777     Here we are creating file with triggers and save all triggers in it.
778     sql_create_definition_file() files handles renaming and backup of older
779     versions
780   */
781   file.length= build_table_filename(file_buff, FN_REFLEN - 1,
782                                     tables->db, tables->table_name,
783                                     TRG_EXT, 0);
784   file.str= file_buff;
785 
786   trigname_file.length= build_table_filename(trigname_buff, FN_REFLEN-1,
787                                              tables->db,
788                                              lex->spname->m_name.str,
789                                              TRN_EXT, 0, &was_truncated);
790   // Check if we hit FN_REFLEN bytes in path length
791   if (was_truncated)
792   {
793     my_error(ER_IDENT_CAUSES_TOO_LONG_PATH, MYF(0), sizeof(trigname_buff)-1,
794              trigname_buff);
795     return 1;
796   }
797   trigname_file.str= trigname_buff;
798 
799 
800   /* Use the filesystem to enforce trigger namespace constraints. */
801   if (!access(trigname_buff, F_OK))
802   {
803     my_error(ER_TRG_ALREADY_EXISTS, MYF(0));
804     return 1;
805   }
806 
807   trigname.trigger_table.str= tables->table_name;
808   trigname.trigger_table.length= tables->table_name_length;
809 
810   if (sql_create_definition_file(NULL, &trigname_file, &trigname_file_type,
811                                  (uchar*)&trigname, trigname_file_parameters))
812     return 1;
813 
814   /*
815     Soon we will invalidate table object and thus Table_triggers_list object
816     so don't care about place to which trg_def->ptr points and other
817     invariants (e.g. we don't bother to update names_list)
818 
819     QQ: Hmm... probably we should not care about setting up active thread
820         mem_root too.
821   */
822   if (!(trg_def= alloc_lex_string(&table->mem_root)) ||
823       definitions_list.push_back(trg_def, &table->mem_root) ||
824 
825       !(trg_sql_mode= alloc_type<sql_mode_t>(&table->mem_root)) ||
826       definition_modes_list.push_back(trg_sql_mode, &table->mem_root) ||
827 
828       !(trg_definer= alloc_lex_string(&table->mem_root)) ||
829       definers_list.push_back(trg_definer, &table->mem_root) ||
830 
831       !(trg_client_cs_name= alloc_lex_string(&table->mem_root)) ||
832       client_cs_names.push_back(trg_client_cs_name, &table->mem_root) ||
833 
834       !(trg_connection_cl_name= alloc_lex_string(&table->mem_root)) ||
835       connection_cl_names.push_back(trg_connection_cl_name, &table->mem_root) ||
836 
837       !(trg_db_cl_name= alloc_lex_string(&table->mem_root)) ||
838       db_cl_names.push_back(trg_db_cl_name, &table->mem_root))
839   {
840     goto err_with_cleanup;
841   }
842 
843   *trg_sql_mode= thd->variables.sql_mode;
844 
845 #ifndef NO_EMBEDDED_ACCESS_CHECKS
846   if (lex->definer && !is_acl_user(lex->definer->host.str,
847                                    lex->definer->user.str))
848   {
849     push_warning_printf(thd,
850                         Sql_condition::WARN_LEVEL_NOTE,
851                         ER_NO_SUCH_USER,
852                         ER(ER_NO_SUCH_USER),
853                         lex->definer->user.str,
854                         lex->definer->host.str);
855   }
856 #endif /* NO_EMBEDDED_ACCESS_CHECKS */
857 
858   if (lex->definer)
859   {
860     /* SUID trigger. */
861 
862     definer_user= lex->definer->user;
863     definer_host= lex->definer->host;
864 
865     trg_definer->str= trg_definer_holder;
866     trg_definer->length= strxmov(trg_definer->str, definer_user.str, "@",
867                                  definer_host.str, NullS) - trg_definer->str;
868   }
869   else
870   {
871     /* non-SUID trigger. */
872 
873     definer_user.str= 0;
874     definer_user.length= 0;
875 
876     definer_host.str= 0;
877     definer_host.length= 0;
878 
879     trg_definer->str= (char*) "";
880     trg_definer->length= 0;
881   }
882 
883   /*
884     Fill character set information:
885       - client character set contains charset info only;
886       - connection collation contains pair {character set, collation};
887       - database collation contains pair {character set, collation};
888   */
889 
890   lex_string_set(trg_client_cs_name, thd->charset()->csname);
891 
892   lex_string_set(trg_connection_cl_name,
893                  thd->variables.collation_connection->name);
894 
895   lex_string_set(trg_db_cl_name,
896                  get_default_db_collation(thd, tables->db)->name);
897 
898   /*
899     Create well-formed trigger definition query. Original query is not
900     appropriated, because definer-clause can be not truncated.
901   */
902 
903   stmt_query->append(STRING_WITH_LEN("CREATE "));
904 
905   if (trg_definer)
906   {
907     /*
908       Append definer-clause if the trigger is SUID (a usual trigger in
909       new MySQL versions).
910     */
911 
912     append_definer(thd, stmt_query, &definer_user, &definer_host);
913   }
914 
915   LEX_STRING stmt_definition;
916   stmt_definition.str= (char*) thd->lex->stmt_definition_begin;
917   stmt_definition.length= thd->lex->stmt_definition_end
918     - thd->lex->stmt_definition_begin;
919   trim_whitespace(thd->charset(), & stmt_definition);
920 
921   stmt_query->append(stmt_definition.str, stmt_definition.length);
922 
923   trg_def->str= stmt_query->c_ptr();
924   trg_def->length= stmt_query->length();
925 
926   /* Create trigger definition file. */
927 
928   if (!sql_create_definition_file(NULL, &file, &triggers_file_type,
929                                   (uchar*)this, triggers_file_parameters))
930     return 0;
931 
932 err_with_cleanup:
933   mysql_file_delete(key_file_trn, trigname_buff, MYF(MY_WME));
934   return 1;
935 }
936 
937 
938 /**
939   Deletes the .TRG file for a table.
940 
941   @param path         char buffer of size FN_REFLEN to be used
942                       for constructing path to .TRG file.
943   @param db           table's database name
944   @param table_name   table's name
945 
946   @retval
947     False   success
948   @retval
949     True    error
950 */
951 
rm_trigger_file(char * path,const char * db,const char * table_name)952 static bool rm_trigger_file(char *path, const char *db,
953                             const char *table_name)
954 {
955   build_table_filename(path, FN_REFLEN-1, db, table_name, TRG_EXT, 0);
956   return mysql_file_delete(key_file_trg, path, MYF(MY_WME));
957 }
958 
959 
960 /**
961   Deletes the .TRN file for a trigger.
962 
963   @param path         char buffer of size FN_REFLEN to be used
964                       for constructing path to .TRN file.
965   @param db           trigger's database name
966   @param trigger_name trigger's name
967 
968   @retval
969     False   success
970   @retval
971     True    error
972 */
973 
rm_trigname_file(char * path,const char * db,const char * trigger_name)974 static bool rm_trigname_file(char *path, const char *db,
975                              const char *trigger_name)
976 {
977   build_table_filename(path, FN_REFLEN - 1, db, trigger_name, TRN_EXT, 0);
978   return mysql_file_delete(key_file_trn, path, MYF(MY_WME));
979 }
980 
981 
982 /**
983   Helper function that saves .TRG file for Table_triggers_list object.
984 
985   @param triggers    Table_triggers_list object for which file should be saved
986   @param db          Name of database for subject table
987   @param table_name  Name of subject table
988 
989   @retval
990     FALSE  Success
991   @retval
992     TRUE   Error
993 */
994 
save_trigger_file(Table_triggers_list * triggers,const char * db,const char * table_name)995 static bool save_trigger_file(Table_triggers_list *triggers, const char *db,
996                               const char *table_name)
997 {
998   char file_buff[FN_REFLEN];
999   LEX_STRING file;
1000 
1001   file.length= build_table_filename(file_buff, FN_REFLEN - 1, db, table_name,
1002                                     TRG_EXT, 0);
1003   file.str= file_buff;
1004   return sql_create_definition_file(NULL, &file, &triggers_file_type,
1005                                     (uchar*)triggers, triggers_file_parameters);
1006 }
1007 
1008 
1009 /**
1010   Drop trigger for table.
1011 
1012   @param thd           current thread context
1013                        (including trigger definition in LEX)
1014   @param tables        table list containing one open table for which trigger
1015                        is dropped.
1016   @param[out] stmt_query    after successful return, this string contains
1017                             well-formed statement for creation this trigger.
1018 
1019   @todo
1020     Probably instead of removing .TRG file we should move
1021     to archive directory but this should be done as part of
1022     parse_file.cc functionality (because we will need it
1023     elsewhere).
1024 
1025   @retval
1026     False   success
1027   @retval
1028     True    error
1029 */
drop_trigger(THD * thd,TABLE_LIST * tables,String * stmt_query)1030 bool Table_triggers_list::drop_trigger(THD *thd, TABLE_LIST *tables,
1031                                        String *stmt_query)
1032 {
1033   const char *sp_name= thd->lex->spname->m_name.str; // alias
1034 
1035   LEX_STRING *name;
1036   char path[FN_REFLEN];
1037 
1038   List_iterator_fast<LEX_STRING> it_name(names_list);
1039 
1040   List_iterator<sql_mode_t> it_mod(definition_modes_list);
1041   List_iterator<LEX_STRING> it_def(definitions_list);
1042   List_iterator<LEX_STRING> it_definer(definers_list);
1043   List_iterator<LEX_STRING> it_client_cs_name(client_cs_names);
1044   List_iterator<LEX_STRING> it_connection_cl_name(connection_cl_names);
1045   List_iterator<LEX_STRING> it_db_cl_name(db_cl_names);
1046 
1047   stmt_query->append(thd->query(), thd->query_length());
1048 
1049   while ((name= it_name++))
1050   {
1051     it_def++;
1052     it_mod++;
1053     it_definer++;
1054     it_client_cs_name++;
1055     it_connection_cl_name++;
1056     it_db_cl_name++;
1057 
1058     if (my_strcasecmp(table_alias_charset, sp_name, name->str) == 0)
1059     {
1060       /*
1061         Again we don't care much about other things required for
1062         clean trigger removing since table will be reopened anyway.
1063       */
1064       it_def.remove();
1065       it_mod.remove();
1066       it_definer.remove();
1067       it_client_cs_name.remove();
1068       it_connection_cl_name.remove();
1069       it_db_cl_name.remove();
1070 
1071       if (definitions_list.is_empty())
1072       {
1073         /*
1074           TODO: Probably instead of removing .TRG file we should move
1075           to archive directory but this should be done as part of
1076           parse_file.cc functionality (because we will need it
1077           elsewhere).
1078         */
1079         if (rm_trigger_file(path, tables->db, tables->table_name))
1080           return 1;
1081       }
1082       else
1083       {
1084         if (save_trigger_file(this, tables->db, tables->table_name))
1085           return 1;
1086       }
1087 
1088       if (rm_trigname_file(path, tables->db, sp_name))
1089         return 1;
1090       return 0;
1091     }
1092   }
1093 
1094   my_message(ER_TRG_DOES_NOT_EXIST, ER(ER_TRG_DOES_NOT_EXIST), MYF(0));
1095   return 1;
1096 }
1097 
1098 
~Table_triggers_list()1099 Table_triggers_list::~Table_triggers_list()
1100 {
1101   for (int i= 0; i < (int)TRG_EVENT_MAX; i++)
1102     for (int j= 0; j < (int)TRG_ACTION_MAX; j++)
1103       delete bodies[i][j];
1104 
1105   if (record1_field)
1106     for (Field **fld_ptr= record1_field; *fld_ptr; fld_ptr++)
1107       delete *fld_ptr;
1108 }
1109 
1110 
1111 /**
1112   Prepare array of Field objects referencing to TABLE::record[1] instead
1113   of record[0] (they will represent OLD.* row values in ON UPDATE trigger
1114   and in ON DELETE trigger which will be called during REPLACE execution).
1115 
1116   @retval
1117     False   success
1118   @retval
1119     True    error
1120 */
prepare_record1_accessors()1121 bool Table_triggers_list::prepare_record1_accessors()
1122 {
1123   Field **fld, **old_fld;
1124 
1125   if (!(record1_field= (Field **)alloc_root(&trigger_table->mem_root,
1126                                             (trigger_table->s->fields + 1) *
1127                                             sizeof(Field*))))
1128     return true;
1129 
1130   for (fld= trigger_table->field, old_fld= record1_field; *fld; fld++, old_fld++)
1131   {
1132     /*
1133       QQ: it is supposed that it is ok to use this function for field
1134       cloning...
1135     */
1136     if (!(*old_fld= (*fld)->new_field(&trigger_table->mem_root, trigger_table,
1137                                       trigger_table == (*fld)->table)))
1138       return true;
1139     (*old_fld)->move_field_offset((my_ptrdiff_t)(trigger_table->record[1] -
1140                                                  trigger_table->record[0]));
1141   }
1142   *old_fld= 0;
1143 
1144   return false;
1145 }
1146 
1147 
1148 /**
1149   Adjust Table_triggers_list with new TABLE pointer.
1150 
1151   @param new_table   new pointer to TABLE instance
1152 */
1153 
set_table(TABLE * new_table)1154 void Table_triggers_list::set_table(TABLE *new_table)
1155 {
1156   trigger_table= new_table;
1157   for (Field **field= new_table->triggers->record1_field ; *field ; field++)
1158   {
1159     (*field)->table= (*field)->orig_table= new_table;
1160     (*field)->table_name= &new_table->alias;
1161   }
1162 }
1163 
1164 
1165 /**
1166   Check whenever .TRG file for table exist and load all triggers it contains.
1167 
1168   @param thd          current thread context
1169   @param db           table's database name
1170   @param table_name   table's name
1171   @param table        pointer to table object
1172   @param names_only   stop after loading trigger names
1173 
1174   @todo
1175     A lot of things to do here e.g. how about other funcs and being
1176     more paranoical ?
1177 
1178   @todo
1179     This could be avoided if there is no triggers for UPDATE and DELETE.
1180 
1181   @retval
1182     False   success
1183   @retval
1184     True    error
1185 */
1186 
check_n_load(THD * thd,const char * db,const char * table_name,TABLE * table,bool names_only)1187 bool Table_triggers_list::check_n_load(THD *thd, const char *db,
1188                                        const char *table_name, TABLE *table,
1189                                        bool names_only)
1190 {
1191   char path_buff[FN_REFLEN];
1192   LEX_STRING path;
1193   File_parser *parser;
1194   LEX_STRING save_db;
1195   sql_digest_state *parent_digest= thd->m_digest;
1196   PSI_statement_locker *parent_locker= thd->m_statement_psi;
1197 
1198   DBUG_ENTER("Table_triggers_list::check_n_load");
1199 
1200   path.length= build_table_filename(path_buff, FN_REFLEN - 1,
1201                                     db, table_name, TRG_EXT, 0);
1202   path.str= path_buff;
1203 
1204   // QQ: should we analyze errno somehow ?
1205   if (access(path_buff, F_OK))
1206     DBUG_RETURN(0);
1207 
1208   /*
1209     File exists so we got to load triggers.
1210     FIXME: A lot of things to do here e.g. how about other funcs and being
1211     more paranoical ?
1212   */
1213 
1214   if ((parser= sql_parse_prepare(&path, &table->mem_root, 1)))
1215   {
1216     if (is_equal(&triggers_file_type, parser->type()))
1217     {
1218       Table_triggers_list *triggers=
1219         new (&table->mem_root) Table_triggers_list(table);
1220       Handle_old_incorrect_sql_modes_hook sql_modes_hook(path.str);
1221 
1222       if (!triggers)
1223         DBUG_RETURN(1);
1224 
1225       /*
1226         We don't have the following attributes in old versions of .TRG file, so
1227         we should initialize the list for safety:
1228           - sql_modes;
1229           - definers;
1230           - character sets (client, connection, database);
1231       */
1232       triggers->definition_modes_list.empty();
1233       triggers->definers_list.empty();
1234       triggers->client_cs_names.empty();
1235       triggers->connection_cl_names.empty();
1236       triggers->db_cl_names.empty();
1237 
1238       if (parser->parse((uchar*)triggers, &table->mem_root,
1239                         triggers_file_parameters,
1240                         TRG_NUM_REQUIRED_PARAMETERS,
1241                         &sql_modes_hook))
1242         DBUG_RETURN(1);
1243 
1244       List_iterator_fast<LEX_STRING> it(triggers->definitions_list);
1245       LEX_STRING *trg_create_str;
1246       sql_mode_t *trg_sql_mode;
1247 
1248       if (triggers->definition_modes_list.is_empty() &&
1249           !triggers->definitions_list.is_empty())
1250       {
1251         /*
1252           It is old file format => we should fill list of sql_modes.
1253 
1254           We use one mode (current) for all triggers, because we have not
1255           information about mode in old format.
1256         */
1257         if (!(trg_sql_mode= alloc_type<sql_mode_t>(&table->mem_root)))
1258         {
1259           DBUG_RETURN(1); // EOM
1260         }
1261         *trg_sql_mode= global_system_variables.sql_mode;
1262         while (it++)
1263         {
1264           if (triggers->definition_modes_list.push_back(trg_sql_mode,
1265                                                         &table->mem_root))
1266           {
1267             DBUG_RETURN(1); // EOM
1268           }
1269         }
1270         it.rewind();
1271       }
1272 
1273       if (triggers->definers_list.is_empty() &&
1274           !triggers->definitions_list.is_empty())
1275       {
1276         /*
1277           It is old file format => we should fill list of definers.
1278 
1279           If there is no definer information, we should not switch context to
1280           definer when checking privileges. I.e. privileges for such triggers
1281           are checked for "invoker" rather than for "definer".
1282         */
1283 
1284         LEX_STRING *trg_definer;
1285 
1286         if (!(trg_definer= alloc_lex_string(&table->mem_root)))
1287           DBUG_RETURN(1); // EOM
1288 
1289         trg_definer->str= (char*) "";
1290         trg_definer->length= 0;
1291 
1292         while (it++)
1293         {
1294           if (triggers->definers_list.push_back(trg_definer,
1295                                                 &table->mem_root))
1296           {
1297             DBUG_RETURN(1); // EOM
1298           }
1299         }
1300 
1301         it.rewind();
1302       }
1303 
1304       if (!triggers->definitions_list.is_empty() &&
1305           (triggers->client_cs_names.is_empty() ||
1306            triggers->connection_cl_names.is_empty() ||
1307            triggers->db_cl_names.is_empty()))
1308       {
1309         /*
1310           It is old file format => we should fill lists of character sets.
1311         */
1312 
1313         LEX_STRING *trg_client_cs_name;
1314         LEX_STRING *trg_connection_cl_name;
1315         LEX_STRING *trg_db_cl_name;
1316 
1317         if (!triggers->client_cs_names.is_empty() ||
1318             !triggers->connection_cl_names.is_empty() ||
1319             !triggers->db_cl_names.is_empty())
1320         {
1321           my_error(ER_TRG_CORRUPTED_FILE, MYF(0),
1322                    (const char *) db,
1323                    (const char *) table_name);
1324 
1325           DBUG_RETURN(1); // EOM
1326         }
1327 
1328         push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1329                             ER_TRG_NO_CREATION_CTX,
1330                             ER(ER_TRG_NO_CREATION_CTX),
1331                             (const char*) db,
1332                             (const char*) table_name);
1333 
1334         if (!(trg_client_cs_name= alloc_lex_string(&table->mem_root)) ||
1335             !(trg_connection_cl_name= alloc_lex_string(&table->mem_root)) ||
1336             !(trg_db_cl_name= alloc_lex_string(&table->mem_root)))
1337         {
1338           DBUG_RETURN(1); // EOM
1339         }
1340 
1341         /*
1342           Backward compatibility: assume that the query is in the current
1343           character set.
1344         */
1345 
1346         lex_string_set(trg_client_cs_name,
1347                        thd->variables.character_set_client->csname);
1348 
1349         lex_string_set(trg_connection_cl_name,
1350                        thd->variables.collation_connection->name);
1351 
1352         lex_string_set(trg_db_cl_name,
1353                        thd->variables.collation_database->name);
1354 
1355         while (it++)
1356         {
1357           if (triggers->client_cs_names.push_back(trg_client_cs_name,
1358                                                   &table->mem_root) ||
1359 
1360               triggers->connection_cl_names.push_back(trg_connection_cl_name,
1361                                                       &table->mem_root) ||
1362 
1363               triggers->db_cl_names.push_back(trg_db_cl_name,
1364                                               &table->mem_root))
1365           {
1366             DBUG_RETURN(1); // EOM
1367           }
1368         }
1369 
1370         it.rewind();
1371       }
1372 
1373       DBUG_ASSERT(triggers->definition_modes_list.elements ==
1374                   triggers->definitions_list.elements);
1375       DBUG_ASSERT(triggers->definers_list.elements ==
1376                   triggers->definitions_list.elements);
1377       DBUG_ASSERT(triggers->client_cs_names.elements ==
1378                   triggers->definitions_list.elements);
1379       DBUG_ASSERT(triggers->connection_cl_names.elements ==
1380                   triggers->definitions_list.elements);
1381       DBUG_ASSERT(triggers->db_cl_names.elements ==
1382                   triggers->definitions_list.elements);
1383 
1384       table->triggers= triggers;
1385 
1386       /*
1387         TODO: This could be avoided if there is no triggers
1388               for UPDATE and DELETE.
1389       */
1390       if (!names_only && triggers->prepare_record1_accessors())
1391         DBUG_RETURN(1);
1392 
1393       List_iterator_fast<sql_mode_t> itm(triggers->definition_modes_list);
1394       List_iterator_fast<LEX_STRING> it_definer(triggers->definers_list);
1395       List_iterator_fast<LEX_STRING> it_client_cs_name(triggers->client_cs_names);
1396       List_iterator_fast<LEX_STRING> it_connection_cl_name(triggers->connection_cl_names);
1397       List_iterator_fast<LEX_STRING> it_db_cl_name(triggers->db_cl_names);
1398       LEX *old_lex= thd->lex, lex;
1399       sp_rcontext *sp_runtime_ctx_saved= thd->sp_runtime_ctx;
1400       sql_mode_t save_sql_mode= thd->variables.sql_mode;
1401       LEX_STRING *on_table_name;
1402 
1403       thd->lex= &lex;
1404 
1405       save_db.str= thd->db;
1406       save_db.length= thd->db_length;
1407       thd->reset_db((char*) db, strlen(db));
1408       while ((trg_create_str= it++))
1409       {
1410         trg_sql_mode= itm++;
1411         LEX_STRING *trg_definer= it_definer++;
1412 
1413         thd->variables.sql_mode= *trg_sql_mode;
1414 
1415         Parser_state parser_state;
1416         if (parser_state.init(thd, trg_create_str->str, trg_create_str->length))
1417           goto err_with_lex_cleanup;
1418 
1419         Trigger_creation_ctx *creation_ctx=
1420           Trigger_creation_ctx::create(thd,
1421                                        db,
1422                                        table_name,
1423                                        it_client_cs_name++,
1424                                        it_connection_cl_name++,
1425                                        it_db_cl_name++);
1426 
1427         lex_start(thd);
1428         thd->sp_runtime_ctx= NULL;
1429 
1430         Deprecated_trigger_syntax_handler error_handler;
1431         thd->push_internal_handler(&error_handler);
1432         thd->m_digest= NULL;
1433         thd->m_statement_psi= NULL;
1434         bool parse_error= parse_sql(thd, & parser_state, creation_ctx);
1435         thd->m_digest= parent_digest;
1436         thd->m_statement_psi= parent_locker;
1437         thd->pop_internal_handler();
1438 
1439         /*
1440           Not strictly necessary to invoke this method here, since we know
1441           that we've parsed CREATE TRIGGER and not an
1442           UPDATE/DELETE/INSERT/REPLACE/LOAD/CREATE TABLE, but we try to
1443           maintain the invariant that this method is called for each
1444           distinct statement, in case its logic is extended with other
1445           types of analyses in future.
1446         */
1447         lex.set_trg_event_type_for_tables();
1448 
1449         if (parse_error)
1450         {
1451           if (!triggers->m_has_unparseable_trigger)
1452             triggers->set_parse_error_message(error_handler.get_error_message());
1453           /* Currently sphead is always set to NULL in case of a parse error */
1454           DBUG_ASSERT(lex.sphead == NULL);
1455           if (error_handler.get_trigger_name())
1456           {
1457             LEX_STRING *trigger_name;
1458             const LEX_STRING *orig_trigger_name= error_handler.get_trigger_name();
1459 
1460             if (!(trigger_name= alloc_lex_string(&table->mem_root)) ||
1461                 !(trigger_name->str= strmake_root(&table->mem_root,
1462                                                   orig_trigger_name->str,
1463                                                   orig_trigger_name->length)))
1464               goto err_with_lex_cleanup;
1465 
1466             trigger_name->length= orig_trigger_name->length;
1467 
1468             if (triggers->names_list.push_back(trigger_name,
1469                                                &table->mem_root))
1470               goto err_with_lex_cleanup;
1471           }
1472           else
1473           {
1474             /*
1475                The Table_triggers_list is not constructed as a list of
1476                trigger objects as one would expect, but rather of lists of
1477                properties of equal length. Thus, even if we don't get the
1478                trigger name, we still fill all in all the lists with
1479                placeholders as we might otherwise create a skew in the
1480                lists. Obviously, this has to be refactored.
1481             */
1482             LEX_STRING *empty= alloc_lex_string(&table->mem_root);
1483             if (!empty)
1484               goto err_with_lex_cleanup;
1485 
1486             empty->str= const_cast<char*>("");
1487             empty->length= 0;
1488             if (triggers->names_list.push_back(empty, &table->mem_root))
1489               goto err_with_lex_cleanup;
1490           }
1491           lex_end(&lex);
1492           continue;
1493         }
1494 
1495         sp_head *sp= lex.sphead;
1496         sp->set_info(0, 0, &lex.sp_chistics, *trg_sql_mode);
1497         sp->m_trg_list= triggers;
1498 
1499         int trg_event= sp->m_trg_chistics.event;
1500         int trg_action_time= sp->m_trg_chistics.action_time;
1501 
1502         triggers->bodies[trg_event][trg_action_time]= sp;
1503         lex.sphead= NULL; /* Prevent double cleanup. */
1504 
1505         sp->set_info(0, 0, &lex.sp_chistics, *trg_sql_mode);
1506         sp->set_creation_ctx(creation_ctx);
1507 
1508         if (!trg_definer->length)
1509         {
1510           /*
1511             This trigger was created/imported from the previous version of
1512             MySQL, which does not support triggers definers. We should emit
1513             warning here.
1514           */
1515 
1516           push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1517                               ER_TRG_NO_DEFINER, ER(ER_TRG_NO_DEFINER),
1518                               (const char*) db,
1519                               (const char*) sp->m_name.str);
1520 
1521           /*
1522             Set definer to the '' to correct displaying in the information
1523             schema.
1524           */
1525 
1526           sp->set_definer((char*) "", 0);
1527 
1528           /*
1529             Triggers without definer information are executed under the
1530             authorization of the invoker.
1531           */
1532 
1533           sp->m_chistics->suid= SP_IS_NOT_SUID;
1534         }
1535         else
1536           sp->set_definer(trg_definer->str, trg_definer->length);
1537 
1538         if (triggers->names_list.push_back(&sp->m_name, &table->mem_root))
1539             goto err_with_lex_cleanup;
1540 
1541         if (!(on_table_name= alloc_lex_string(&table->mem_root)))
1542           goto err_with_lex_cleanup;
1543 
1544         on_table_name->str= (char*) lex.raw_trg_on_table_name_begin;
1545         on_table_name->length= lex.raw_trg_on_table_name_end
1546           - lex.raw_trg_on_table_name_begin;
1547 
1548         if (triggers->on_table_names_list.push_back(on_table_name, &table->mem_root))
1549           goto err_with_lex_cleanup;
1550 #ifndef DBUG_OFF
1551         /*
1552           Let us check that we correctly update trigger definitions when we
1553           rename tables with triggers.
1554 
1555           In special cases like "RENAME TABLE `#mysql50#somename` TO `somename`"
1556           or "ALTER DATABASE `#mysql50#somename` UPGRADE DATA DIRECTORY NAME"
1557           we might be given table or database name with "#mysql50#" prefix (and
1558           trigger's definiton contains un-prefixed version of the same name).
1559           To remove this prefix we use check_n_cut_mysql50_prefix().
1560         */
1561 
1562         char fname[NAME_LEN + 1];
1563         DBUG_ASSERT((!my_strcasecmp(table_alias_charset, lex.query_tables->db, db) ||
1564                      (check_n_cut_mysql50_prefix(db, fname, sizeof(fname)) &&
1565                       !my_strcasecmp(table_alias_charset, lex.query_tables->db, fname))));
1566         DBUG_ASSERT((!my_strcasecmp(table_alias_charset, lex.query_tables->table_name, table_name) ||
1567                      (check_n_cut_mysql50_prefix(table_name, fname, sizeof(fname)) &&
1568                       !my_strcasecmp(table_alias_charset, lex.query_tables->table_name, fname))));
1569 #endif
1570         if (names_only)
1571         {
1572           lex_end(&lex);
1573           continue;
1574         }
1575 
1576         /*
1577           Also let us bind these objects to Field objects in table being
1578           opened.
1579 
1580           We ignore errors here, because if even something is wrong we still
1581           will be willing to open table to perform some operations (e.g.
1582           SELECT)...
1583           Anyway some things can be checked only during trigger execution.
1584         */
1585         for (SQL_I_List<Item_trigger_field> *trig_field_list=
1586                sp->m_list_of_trig_fields_item_lists.first;
1587              trig_field_list;
1588              trig_field_list= trig_field_list->first->next_trig_field_list)
1589         {
1590           for (Item_trigger_field *trg_field= trig_field_list->first;
1591                trg_field;
1592                trg_field= trg_field->next_trg_field)
1593           {
1594             trg_field->setup_field(thd, table,
1595               &triggers->subject_table_grants[trg_event][trg_action_time]);
1596           }
1597         }
1598 
1599         lex_end(&lex);
1600       }
1601       thd->reset_db(save_db.str, save_db.length);
1602       thd->lex= old_lex;
1603       thd->sp_runtime_ctx= sp_runtime_ctx_saved;
1604       thd->variables.sql_mode= save_sql_mode;
1605 
1606       DBUG_RETURN(0);
1607 
1608 err_with_lex_cleanup:
1609       // QQ: anything else ?
1610       lex_end(&lex);
1611       thd->lex= old_lex;
1612       thd->sp_runtime_ctx= sp_runtime_ctx_saved;
1613       thd->variables.sql_mode= save_sql_mode;
1614       thd->reset_db(save_db.str, save_db.length);
1615       DBUG_RETURN(1);
1616     }
1617 
1618     /*
1619       We don't care about this error message much because .TRG files will
1620       be merged into .FRM anyway.
1621     */
1622     my_error(ER_WRONG_OBJECT, MYF(0),
1623              table_name, TRG_EXT + 1, "TRIGGER");
1624     DBUG_RETURN(1);
1625   }
1626 
1627   DBUG_RETURN(1);
1628 }
1629 
1630 
1631 /**
1632   Obtains and returns trigger metadata.
1633 
1634   @param thd           current thread context
1635   @param event         trigger event type
1636   @param time_type     trigger action time
1637   @param trigger_name  returns name of trigger
1638   @param trigger_stmt  returns statement of trigger
1639   @param sql_mode      returns sql_mode of trigger
1640   @param definer       returns definer/creator of trigger. The caller is
1641                        responsible to allocate enough space for storing
1642                        definer information.
1643 
1644   @retval
1645     False   success
1646   @retval
1647     True    error
1648 */
1649 
get_trigger_info(THD * thd,trg_event_type event,trg_action_time_type time_type,LEX_STRING * trigger_name,LEX_STRING * trigger_stmt,sql_mode_t * sql_mode,LEX_STRING * definer,LEX_STRING * client_cs_name,LEX_STRING * connection_cl_name,LEX_STRING * db_cl_name)1650 bool Table_triggers_list::get_trigger_info(THD *thd, trg_event_type event,
1651                                            trg_action_time_type time_type,
1652                                            LEX_STRING *trigger_name,
1653                                            LEX_STRING *trigger_stmt,
1654                                            sql_mode_t *sql_mode,
1655                                            LEX_STRING *definer,
1656                                            LEX_STRING *client_cs_name,
1657                                            LEX_STRING *connection_cl_name,
1658                                            LEX_STRING *db_cl_name)
1659 {
1660   sp_head *body;
1661   DBUG_ENTER("get_trigger_info");
1662   if ((body= bodies[event][time_type]))
1663   {
1664     Stored_program_creation_ctx *creation_ctx=
1665       bodies[event][time_type]->get_creation_ctx();
1666 
1667     *trigger_name= body->m_name;
1668     *trigger_stmt= body->m_body_utf8;
1669     *sql_mode= body->m_sql_mode;
1670 
1671     if (body->m_chistics->suid == SP_IS_NOT_SUID)
1672     {
1673       definer->str[0]= 0;
1674       definer->length= 0;
1675     }
1676     else
1677     {
1678       definer->length= strxmov(definer->str, body->m_definer_user.str, "@",
1679                                body->m_definer_host.str, NullS) - definer->str;
1680     }
1681 
1682     lex_string_set(client_cs_name,
1683                    creation_ctx->get_client_cs()->csname);
1684 
1685     lex_string_set(connection_cl_name,
1686                    creation_ctx->get_connection_cl()->name);
1687 
1688     lex_string_set(db_cl_name,
1689                    creation_ctx->get_db_cl()->name);
1690 
1691     DBUG_RETURN(0);
1692   }
1693   DBUG_RETURN(1);
1694 }
1695 
1696 
get_trigger_info(THD * thd,int trigger_idx,LEX_STRING * trigger_name,sql_mode_t * sql_mode,LEX_STRING * sql_original_stmt,LEX_STRING * client_cs_name,LEX_STRING * connection_cl_name,LEX_STRING * db_cl_name)1697 void Table_triggers_list::get_trigger_info(THD *thd,
1698                                            int trigger_idx,
1699                                            LEX_STRING *trigger_name,
1700                                            sql_mode_t *sql_mode,
1701                                            LEX_STRING *sql_original_stmt,
1702                                            LEX_STRING *client_cs_name,
1703                                            LEX_STRING *connection_cl_name,
1704                                            LEX_STRING *db_cl_name)
1705 {
1706   List_iterator_fast<LEX_STRING> it_trigger_name(names_list);
1707   List_iterator_fast<sql_mode_t> it_sql_mode(definition_modes_list);
1708   List_iterator_fast<LEX_STRING> it_sql_orig_stmt(definitions_list);
1709   List_iterator_fast<LEX_STRING> it_client_cs_name(client_cs_names);
1710   List_iterator_fast<LEX_STRING> it_connection_cl_name(connection_cl_names);
1711   List_iterator_fast<LEX_STRING> it_db_cl_name(db_cl_names);
1712 
1713   for (int i = 0; i < trigger_idx; ++i)
1714   {
1715     it_trigger_name.next_fast();
1716     it_sql_mode.next_fast();
1717     it_sql_orig_stmt.next_fast();
1718 
1719     it_client_cs_name.next_fast();
1720     it_connection_cl_name.next_fast();
1721     it_db_cl_name.next_fast();
1722   }
1723 
1724   *trigger_name= *(it_trigger_name++);
1725   *sql_mode= *(it_sql_mode++);
1726   *sql_original_stmt= *(it_sql_orig_stmt++);
1727 
1728   *client_cs_name= *(it_client_cs_name++);
1729   *connection_cl_name= *(it_connection_cl_name++);
1730   *db_cl_name= *(it_db_cl_name++);
1731 }
1732 
1733 
find_trigger_by_name(const LEX_STRING * trg_name)1734 int Table_triggers_list::find_trigger_by_name(const LEX_STRING *trg_name)
1735 {
1736   List_iterator_fast<LEX_STRING> it(names_list);
1737 
1738   for (int i = 0; ; ++i)
1739   {
1740     LEX_STRING *cur_name= it++;
1741 
1742     if (!cur_name)
1743       return -1;
1744 
1745     if (strcmp(cur_name->str, trg_name->str) == 0)
1746       return i;
1747   }
1748 }
1749 
1750 /**
1751   Find trigger's table from trigger identifier and add it to
1752   the statement table list.
1753 
1754   @param[in] thd       Thread context.
1755   @param[in] trg_name  Trigger name.
1756   @param[in] if_exists TRUE if SQL statement contains "IF EXISTS" clause.
1757                        That means a warning instead of error should be
1758                        thrown if trigger with given name does not exist.
1759   @param[out] table    Pointer to TABLE_LIST object for the
1760                        table trigger.
1761 
1762   @return Operation status
1763     @retval FALSE On success.
1764     @retval TRUE  Otherwise.
1765 */
1766 
add_table_for_trigger(THD * thd,const sp_name * trg_name,bool if_exists,TABLE_LIST ** table)1767 bool add_table_for_trigger(THD *thd,
1768                            const sp_name *trg_name,
1769                            bool if_exists,
1770                            TABLE_LIST **table)
1771 {
1772   LEX *lex= thd->lex;
1773   char trn_path_buff[FN_REFLEN];
1774   LEX_STRING trn_path= { trn_path_buff, 0 };
1775   LEX_STRING tbl_name= { NULL, 0 };
1776 
1777   DBUG_ENTER("add_table_for_trigger");
1778 
1779   build_trn_path(thd, trg_name, &trn_path);
1780 
1781   if (check_trn_exists(&trn_path))
1782   {
1783     if (if_exists)
1784     {
1785       push_warning_printf(thd,
1786                           Sql_condition::WARN_LEVEL_NOTE,
1787                           ER_TRG_DOES_NOT_EXIST,
1788                           ER(ER_TRG_DOES_NOT_EXIST));
1789 
1790       *table= NULL;
1791 
1792       DBUG_RETURN(FALSE);
1793     }
1794 
1795     my_error(ER_TRG_DOES_NOT_EXIST, MYF(0));
1796     DBUG_RETURN(TRUE);
1797   }
1798 
1799   if (load_table_name_for_trigger(thd, trg_name, &trn_path, &tbl_name))
1800     DBUG_RETURN(TRUE);
1801 
1802   *table= sp_add_to_query_tables(thd, lex, trg_name->m_db.str,
1803                                  tbl_name.str, TL_IGNORE,
1804                                  MDL_SHARED_NO_WRITE);
1805 
1806   DBUG_RETURN(*table ? FALSE : TRUE);
1807 }
1808 
1809 
1810 /**
1811   Drop all triggers for table.
1812 
1813   @param thd      current thread context
1814   @param db       schema for table
1815   @param name     name for table
1816 
1817   @retval
1818     False   success
1819   @retval
1820     True    error
1821 */
1822 
drop_all_triggers(THD * thd,char * db,char * name)1823 bool Table_triggers_list::drop_all_triggers(THD *thd, char *db, char *name)
1824 {
1825   TABLE table;
1826   char path[FN_REFLEN];
1827   bool result= 0;
1828   DBUG_ENTER("drop_all_triggers");
1829 
1830   memset(&table, 0, sizeof(table));
1831   init_sql_alloc(&table.mem_root, 8192, 0);
1832 
1833   if (Table_triggers_list::check_n_load(thd, db, name, &table, 1))
1834   {
1835     result= 1;
1836     goto end;
1837   }
1838   if (table.triggers)
1839   {
1840     LEX_STRING *trigger;
1841     List_iterator_fast<LEX_STRING> it_name(table.triggers->names_list);
1842 
1843     while ((trigger= it_name++))
1844     {
1845       /*
1846         Trigger, which body we failed to parse during call
1847         Table_triggers_list::check_n_load(), might be missing name.
1848         Such triggers have zero-length name and are skipped here.
1849       */
1850       if (trigger->length == 0)
1851         continue;
1852       if (rm_trigname_file(path, db, trigger->str))
1853       {
1854         /*
1855           Instead of immediately bailing out with error if we were unable
1856           to remove .TRN file we will try to drop other files.
1857         */
1858         result= 1;
1859         continue;
1860       }
1861     }
1862 
1863     if (rm_trigger_file(path, db, name))
1864     {
1865       result= 1;
1866       goto end;
1867     }
1868   }
1869 end:
1870   if (table.triggers)
1871     delete table.triggers;
1872   free_root(&table.mem_root, MYF(0));
1873   DBUG_RETURN(result);
1874 }
1875 
1876 
1877 /**
1878   Update .TRG file after renaming triggers' subject table
1879   (change name of table in triggers' definitions).
1880 
1881   @param thd                 Thread context
1882   @param old_db_name         Old database of subject table
1883   @param new_db_name         New database of subject table
1884   @param old_table_name      Old subject table's name
1885   @param new_table_name      New subject table's name
1886 
1887   @retval
1888     FALSE  Success
1889   @retval
1890     TRUE   Failure
1891 */
1892 
1893 bool
change_table_name_in_triggers(THD * thd,const char * old_db_name,const char * new_db_name,LEX_STRING * old_table_name,LEX_STRING * new_table_name)1894 Table_triggers_list::change_table_name_in_triggers(THD *thd,
1895                                                    const char *old_db_name,
1896                                                    const char *new_db_name,
1897                                                    LEX_STRING *old_table_name,
1898                                                    LEX_STRING *new_table_name)
1899 {
1900   char path_buff[FN_REFLEN];
1901   LEX_STRING *def, *on_table_name, new_def;
1902   sql_mode_t save_sql_mode= thd->variables.sql_mode;
1903   List_iterator_fast<LEX_STRING> it_def(definitions_list);
1904   List_iterator_fast<LEX_STRING> it_on_table_name(on_table_names_list);
1905   List_iterator_fast<ulonglong> it_mode(definition_modes_list);
1906   size_t on_q_table_name_len, before_on_len;
1907   String buff;
1908 
1909   DBUG_ASSERT(definitions_list.elements == on_table_names_list.elements &&
1910               definitions_list.elements == definition_modes_list.elements);
1911 
1912   while ((def= it_def++))
1913   {
1914     on_table_name= it_on_table_name++;
1915     thd->variables.sql_mode= *(it_mode++);
1916 
1917     /* Construct CREATE TRIGGER statement with new table name. */
1918     buff.length(0);
1919 
1920     /* WARNING: 'on_table_name' is supposed to point inside 'def' */
1921     DBUG_ASSERT(on_table_name->str > def->str);
1922     DBUG_ASSERT(on_table_name->str < (def->str + def->length));
1923     before_on_len= on_table_name->str - def->str;
1924 
1925     buff.append(def->str, before_on_len);
1926     buff.append(STRING_WITH_LEN("ON "));
1927     append_identifier(thd, &buff, new_table_name->str, new_table_name->length);
1928     buff.append(STRING_WITH_LEN(" "));
1929     on_q_table_name_len= buff.length() - before_on_len;
1930     buff.append(on_table_name->str + on_table_name->length,
1931                 def->length - (before_on_len + on_table_name->length));
1932     /*
1933       It is OK to allocate some memory on table's MEM_ROOT since this
1934       table instance will be thrown out at the end of rename anyway.
1935     */
1936     new_def.str= (char*) memdup_root(&trigger_table->mem_root, buff.ptr(),
1937                                      buff.length());
1938     new_def.length= buff.length();
1939     on_table_name->str= new_def.str + before_on_len;
1940     on_table_name->length= on_q_table_name_len;
1941     *def= new_def;
1942   }
1943 
1944   thd->variables.sql_mode= save_sql_mode;
1945 
1946   if (thd->is_fatal_error)
1947     return TRUE; /* OOM */
1948 
1949   if (save_trigger_file(this, new_db_name, new_table_name->str))
1950     return TRUE;
1951   if (rm_trigger_file(path_buff, old_db_name, old_table_name->str))
1952   {
1953     (void) rm_trigger_file(path_buff, new_db_name, new_table_name->str);
1954     return TRUE;
1955   }
1956   return FALSE;
1957 }
1958 
1959 
1960 /**
1961   Iterate though Table_triggers_list::names_list list and update
1962   .TRN files after renaming triggers' subject table.
1963 
1964   @param old_db_name         Old database of subject table
1965   @param new_db_name         New database of subject table
1966   @param new_table_name      New subject table's name
1967   @param stopper             Pointer to Table_triggers_list::names_list at
1968                              which we should stop updating.
1969 
1970   @retval
1971     0      Success
1972   @retval
1973     non-0  Failure, pointer to Table_triggers_list::names_list element
1974     for which update failed.
1975 */
1976 
1977 LEX_STRING*
change_table_name_in_trignames(const char * old_db_name,const char * new_db_name,LEX_STRING * new_table_name,LEX_STRING * stopper)1978 Table_triggers_list::change_table_name_in_trignames(const char *old_db_name,
1979                                                     const char *new_db_name,
1980                                                     LEX_STRING *new_table_name,
1981                                                     LEX_STRING *stopper)
1982 {
1983   char trigname_buff[FN_REFLEN];
1984   struct st_trigname trigname;
1985   LEX_STRING trigname_file;
1986   LEX_STRING *trigger;
1987   List_iterator_fast<LEX_STRING> it_name(names_list);
1988 
1989   while ((trigger= it_name++) != stopper)
1990   {
1991     trigname_file.length= build_table_filename(trigname_buff, FN_REFLEN-1,
1992                                                new_db_name, trigger->str,
1993                                                TRN_EXT, 0);
1994     trigname_file.str= trigname_buff;
1995 
1996     trigname.trigger_table= *new_table_name;
1997 
1998     if (sql_create_definition_file(NULL, &trigname_file, &trigname_file_type,
1999                                    (uchar*)&trigname, trigname_file_parameters))
2000       return trigger;
2001 
2002     /* Remove stale .TRN file in case of database upgrade */
2003     if (old_db_name)
2004     {
2005       if (rm_trigname_file(trigname_buff, old_db_name, trigger->str))
2006       {
2007         (void) rm_trigname_file(trigname_buff, new_db_name, trigger->str);
2008         return trigger;
2009       }
2010     }
2011   }
2012 
2013   return 0;
2014 }
2015 
2016 
2017 /**
2018   Update .TRG and .TRN files after renaming triggers' subject table.
2019 
2020   @param[in,out] thd Thread context
2021   @param[in] db Old database of subject table
2022   @param[in] old_alias Old alias of subject table
2023   @param[in] old_table Old name of subject table
2024   @param[in] new_db New database for subject table
2025   @param[in] new_table New name of subject table
2026 
2027   @note
2028     This method tries to leave trigger related files in consistent state,
2029     i.e. it either will complete successfully, or will fail leaving files
2030     in their initial state.
2031     Also this method assumes that subject table is not renamed to itself.
2032     This method needs to be called under an exclusive table metadata lock.
2033 
2034   @retval FALSE Success
2035   @retval TRUE  Error
2036 */
2037 
change_table_name(THD * thd,const char * db,const char * old_alias,const char * old_table,const char * new_db,const char * new_table)2038 bool Table_triggers_list::change_table_name(THD *thd, const char *db,
2039                                             const char *old_alias,
2040                                             const char *old_table,
2041                                             const char *new_db,
2042                                             const char *new_table)
2043 {
2044   TABLE table;
2045   bool result= 0;
2046   bool upgrading50to51= FALSE;
2047   LEX_STRING *err_trigname;
2048   DBUG_ENTER("change_table_name");
2049 
2050   memset(&table, 0, sizeof(table));
2051   init_sql_alloc(&table.mem_root, 8192, 0);
2052 
2053   /*
2054     This method interfaces the mysql server code protected by
2055     an exclusive metadata lock.
2056   */
2057   DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE, db, old_table,
2058                                              MDL_EXCLUSIVE));
2059 
2060   DBUG_ASSERT(my_strcasecmp(table_alias_charset, db, new_db) ||
2061               my_strcasecmp(table_alias_charset, old_alias, new_table));
2062 
2063   if (Table_triggers_list::check_n_load(thd, db, old_table, &table, TRUE))
2064   {
2065     result= 1;
2066     goto end;
2067   }
2068   if (table.triggers)
2069   {
2070     if (table.triggers->check_for_broken_triggers())
2071     {
2072       result= 1;
2073       goto end;
2074     }
2075     LEX_STRING old_table_name= { (char *) old_alias, strlen(old_alias) };
2076     LEX_STRING new_table_name= { (char *) new_table, strlen(new_table) };
2077     /*
2078       Since triggers should be in the same schema as their subject tables
2079       moving table with them between two schemas raises too many questions.
2080       (E.g. what should happen if in new schema we already have trigger
2081        with same name ?).
2082 
2083       In case of "ALTER DATABASE `#mysql50#db1` UPGRADE DATA DIRECTORY NAME"
2084       we will be given table name with "#mysql50#" prefix
2085       To remove this prefix we use check_n_cut_mysql50_prefix().
2086     */
2087     if (my_strcasecmp(table_alias_charset, db, new_db))
2088     {
2089       char dbname[NAME_LEN + 1];
2090       if (check_n_cut_mysql50_prefix(db, dbname, sizeof(dbname)) &&
2091           !my_strcasecmp(table_alias_charset, dbname, new_db))
2092       {
2093         upgrading50to51= TRUE;
2094       }
2095       else
2096       {
2097         my_error(ER_TRG_IN_WRONG_SCHEMA, MYF(0));
2098         result= 1;
2099         goto end;
2100       }
2101     }
2102     if (table.triggers->change_table_name_in_triggers(thd, db, new_db,
2103                                                       &old_table_name,
2104                                                       &new_table_name))
2105     {
2106       result= 1;
2107       goto end;
2108     }
2109     if ((err_trigname= table.triggers->change_table_name_in_trignames(
2110                                          upgrading50to51 ? db : NULL,
2111                                          new_db, &new_table_name, 0)))
2112     {
2113       /*
2114         If we were unable to update one of .TRN files properly we will
2115         revert all changes that we have done and report about error.
2116         We assume that we will be able to undo our changes without errors
2117         (we can't do much if there will be an error anyway).
2118       */
2119       (void) table.triggers->change_table_name_in_trignames(
2120                                upgrading50to51 ? new_db : NULL, db,
2121                                &old_table_name, err_trigname);
2122       (void) table.triggers->change_table_name_in_triggers(
2123                                thd, db, new_db,
2124                                &new_table_name, &old_table_name);
2125       result= 1;
2126       goto end;
2127     }
2128   }
2129 
2130 end:
2131   delete table.triggers;
2132   free_root(&table.mem_root, MYF(0));
2133   DBUG_RETURN(result);
2134 }
2135 
2136 
2137 /**
2138   Execute trigger for given (event, time) pair.
2139 
2140   The operation executes trigger for the specified event (insert, update,
2141   delete) and time (after, before) if it is set.
2142 
2143   @param thd
2144   @param event
2145   @param time_type
2146   @param old_row_is_record1
2147 
2148   @return Error status.
2149     @retval FALSE on success.
2150     @retval TRUE  on error.
2151 */
2152 
process_triggers(THD * thd,trg_event_type event,trg_action_time_type time_type,bool old_row_is_record1)2153 bool Table_triggers_list::process_triggers(THD *thd,
2154                                            trg_event_type event,
2155                                            trg_action_time_type time_type,
2156                                            bool old_row_is_record1)
2157 {
2158   bool err_status;
2159   Sub_statement_state statement_state;
2160   sp_head *sp_trigger= bodies[event][time_type];
2161   SELECT_LEX *save_current_select;
2162 
2163   if (check_for_broken_triggers())
2164     return true;
2165 
2166   if (sp_trigger == NULL)
2167     return FALSE;
2168 
2169   if (old_row_is_record1)
2170   {
2171     old_field= record1_field;
2172     new_field= trigger_table->field;
2173   }
2174   else
2175   {
2176     new_field= record1_field;
2177     old_field= trigger_table->field;
2178   }
2179   /*
2180     This trigger must have been processed by the pre-locking
2181     algorithm.
2182   */
2183   DBUG_ASSERT(trigger_table->pos_in_table_list->trg_event_map &
2184               static_cast<uint>(1 << static_cast<int>(event)));
2185 
2186   thd->reset_sub_statement_state(&statement_state, SUB_STMT_TRIGGER);
2187 
2188   /*
2189     Reset current_select before call execute_trigger() and
2190     restore it after return from one. This way error is set
2191     in case of failure during trigger execution.
2192   */
2193   save_current_select= thd->lex->current_select;
2194   thd->lex->current_select= NULL;
2195   err_status=
2196     sp_trigger->execute_trigger(thd,
2197                                 &trigger_table->s->db,
2198                                 &trigger_table->s->table_name,
2199                                 &subject_table_grants[event][time_type]);
2200   thd->lex->current_select= save_current_select;
2201 
2202   thd->restore_sub_statement_state(&statement_state);
2203 
2204   return err_status;
2205 }
2206 
2207 
2208 /**
2209   Add triggers for table to the set of routines used by statement.
2210   Add tables used by them to statement table list. Do the same for
2211   routines used by triggers.
2212 
2213   @param thd             Thread context.
2214   @param prelocking_ctx  Prelocking context of the statement.
2215   @param table_list      Table list element for table with trigger.
2216 
2217   @retval FALSE  Success.
2218   @retval TRUE   Failure.
2219 */
2220 
2221 bool
2222 Table_triggers_list::
add_tables_and_routines_for_triggers(THD * thd,Query_tables_list * prelocking_ctx,TABLE_LIST * table_list)2223 add_tables_and_routines_for_triggers(THD *thd,
2224                                      Query_tables_list *prelocking_ctx,
2225                                      TABLE_LIST *table_list)
2226 {
2227   DBUG_ASSERT(static_cast<int>(table_list->lock_type) >=
2228               static_cast<int>(TL_WRITE_ALLOW_WRITE));
2229 
2230   for (int i= 0; i < (int)TRG_EVENT_MAX; i++)
2231   {
2232     if (table_list->trg_event_map &
2233         static_cast<uint8>(1 << static_cast<int>(i)))
2234     {
2235       for (int j= 0; j < (int)TRG_ACTION_MAX; j++)
2236       {
2237         /* We can have only one trigger per action type currently */
2238         sp_head *trigger= table_list->table->triggers->bodies[i][j];
2239 
2240         if (trigger)
2241         {
2242           MDL_key key(MDL_key::TRIGGER, trigger->m_db.str, trigger->m_name.str);
2243 
2244           if (sp_add_used_routine(prelocking_ctx, thd->stmt_arena,
2245                                   &key, table_list->belong_to_view))
2246           {
2247             trigger->add_used_tables_to_table_list(thd,
2248                        &prelocking_ctx->query_tables_last,
2249                        table_list->belong_to_view);
2250             sp_update_stmt_used_routines(thd, prelocking_ctx,
2251                                          &trigger->m_sroutines,
2252                                          table_list->belong_to_view);
2253             trigger->propagate_attributes(prelocking_ctx);
2254           }
2255         }
2256       }
2257     }
2258   }
2259   return FALSE;
2260 }
2261 
2262 
2263 /**
2264   Check if any of the marked fields are used in the trigger.
2265 
2266   @param used_fields  Bitmap over fields to check
2267   @param event_type   Type of event triggers for which we are going to inspect
2268   @param action_time  Type of trigger action time we are going to inspect
2269 */
2270 
is_fields_updated_in_trigger(MY_BITMAP * used_fields,trg_event_type event_type,trg_action_time_type action_time)2271 bool Table_triggers_list::is_fields_updated_in_trigger(MY_BITMAP *used_fields,
2272                                                        trg_event_type event_type,
2273                                                        trg_action_time_type action_time)
2274 {
2275   Item_trigger_field *trg_field;
2276   sp_head *sp= bodies[event_type][action_time];
2277   DBUG_ASSERT(used_fields->n_bits == trigger_table->s->fields);
2278 
2279   for (SQL_I_List<Item_trigger_field> *trig_field_list=
2280          sp->m_list_of_trig_fields_item_lists.first;
2281       trig_field_list;
2282       trig_field_list= trig_field_list->first->next_trig_field_list)
2283   {
2284     for (trg_field= trig_field_list->first; trg_field;
2285          trg_field= trg_field->next_trg_field)
2286     {
2287       /* We cannot check fields which does not present in table. */
2288       if (trg_field->field_idx != (uint)-1)
2289       {
2290         if (bitmap_is_set(used_fields, trg_field->field_idx) &&
2291             trg_field->get_settable_routine_parameter())
2292           return true;
2293       }
2294     }
2295   }
2296   return false;
2297 }
2298 
2299 
2300 /**
2301   Mark fields of subject table which we read/set in its triggers
2302   as such.
2303 
2304   This method marks fields of subject table which are read/set in its
2305   triggers as such (by properly updating TABLE::read_set/write_set)
2306   and thus informs handler that values for these fields should be
2307   retrieved/stored during execution of statement.
2308 
2309   @param event  Type of event triggers for which we are going to inspect
2310 */
2311 
mark_fields_used(trg_event_type event)2312 void Table_triggers_list::mark_fields_used(trg_event_type event)
2313 {
2314   int action_time;
2315   Item_trigger_field *trg_field;
2316 
2317   for (action_time= 0; action_time < (int)TRG_ACTION_MAX; action_time++)
2318   {
2319     sp_head *sp= bodies[event][action_time];
2320 
2321     if (!sp)
2322       continue;
2323 
2324     for (SQL_I_List<Item_trigger_field> *trig_field_list=
2325            sp->m_list_of_trig_fields_item_lists.first;
2326          trig_field_list;
2327          trig_field_list= trig_field_list->first->next_trig_field_list)
2328     {
2329       for (trg_field= trig_field_list->first; trg_field;
2330            trg_field= trg_field->next_trg_field)
2331       {
2332         /* We cannot mark fields which does not present in table. */
2333         if (trg_field->field_idx != (uint)-1)
2334         {
2335           bitmap_set_bit(trigger_table->read_set, trg_field->field_idx);
2336           if (trg_field->get_settable_routine_parameter())
2337             bitmap_set_bit(trigger_table->write_set, trg_field->field_idx);
2338         }
2339       }
2340     }
2341   }
2342   trigger_table->file->column_bitmaps_signal();
2343 }
2344 
2345 
2346 /**
2347    Signals to the Table_triggers_list that a parse error has occured when
2348    reading a trigger from file. This makes the Table_triggers_list enter an
2349    error state flagged by m_has_unparseable_trigger == true. The error message
2350    will be used whenever a statement invoking or manipulating triggers is
2351    issued against the Table_triggers_list's table.
2352 
2353    @param error_message The error message thrown by the parser.
2354  */
set_parse_error_message(char * error_message)2355 void Table_triggers_list::set_parse_error_message(char *error_message)
2356 {
2357   m_has_unparseable_trigger= true;
2358   size_t len= sizeof(m_parse_error_message);
2359   strncpy(m_parse_error_message, error_message, len - 1);
2360   m_parse_error_message[len - 1] = '\0';
2361 }
2362 
2363 
2364 /**
2365   Trigger BUG#14090 compatibility hook.
2366 
2367   @param[in,out] unknown_key       reference on the line with unknown
2368     parameter and the parsing point
2369   @param[in]     base              base address for parameter writing
2370     (structure like TABLE)
2371   @param[in]     mem_root          MEM_ROOT for parameters allocation
2372   @param[in]     end               the end of the configuration
2373 
2374   @note
2375     NOTE: this hook process back compatibility for incorrectly written
2376     sql_modes parameter (see BUG#14090).
2377 
2378   @retval
2379     FALSE OK
2380   @retval
2381     TRUE  Error
2382 */
2383 
2384 #define INVALID_SQL_MODES_LENGTH 13
2385 
2386 bool
2387 Handle_old_incorrect_sql_modes_hook::
process_unknown_string(const char * & unknown_key,uchar * base,MEM_ROOT * mem_root,const char * end)2388 process_unknown_string(const char *&unknown_key, uchar* base,
2389                        MEM_ROOT *mem_root, const char *end)
2390 {
2391   DBUG_ENTER("Handle_old_incorrect_sql_modes_hook::process_unknown_string");
2392   DBUG_PRINT("info", ("unknown key: %60s", unknown_key));
2393 
2394   if (unknown_key + INVALID_SQL_MODES_LENGTH + 1 < end &&
2395       unknown_key[INVALID_SQL_MODES_LENGTH] == '=' &&
2396       !memcmp(unknown_key, STRING_WITH_LEN("sql_modes")))
2397   {
2398     const char *ptr= unknown_key + INVALID_SQL_MODES_LENGTH + 1;
2399 
2400     DBUG_PRINT("info", ("sql_modes affected by BUG#14090 detected"));
2401     push_warning_printf(current_thd,
2402                         Sql_condition::WARN_LEVEL_NOTE,
2403                         ER_OLD_FILE_FORMAT,
2404                         ER(ER_OLD_FILE_FORMAT),
2405                         (char *)path, "TRIGGER");
2406     if (get_file_options_ulllist(ptr, end, unknown_key, base,
2407                                  &sql_modes_parameters, mem_root))
2408     {
2409       DBUG_RETURN(TRUE);
2410     }
2411     /*
2412       Set parsing pointer to the last symbol of string (\n)
2413       1) to avoid problem with \0 in the junk after sql_modes
2414       2) to speed up skipping this line by parser.
2415     */
2416     unknown_key= ptr-1;
2417   }
2418   DBUG_RETURN(FALSE);
2419 }
2420 
2421 #define INVALID_TRIGGER_TABLE_LENGTH 15
2422 
2423 /**
2424   Trigger BUG#15921 compatibility hook. For details see
2425   Handle_old_incorrect_sql_modes_hook::process_unknown_string().
2426 */
2427 bool
2428 Handle_old_incorrect_trigger_table_hook::
process_unknown_string(const char * & unknown_key,uchar * base,MEM_ROOT * mem_root,const char * end)2429 process_unknown_string(const char *&unknown_key, uchar* base,
2430                        MEM_ROOT *mem_root, const char *end)
2431 {
2432   DBUG_ENTER("Handle_old_incorrect_trigger_table_hook::process_unknown_string");
2433   DBUG_PRINT("info", ("unknown key: %60s", unknown_key));
2434 
2435   if (unknown_key + INVALID_TRIGGER_TABLE_LENGTH + 1 < end &&
2436       unknown_key[INVALID_TRIGGER_TABLE_LENGTH] == '=' &&
2437       !memcmp(unknown_key, STRING_WITH_LEN("trigger_table")))
2438   {
2439     const char *ptr= unknown_key + INVALID_TRIGGER_TABLE_LENGTH + 1;
2440 
2441     DBUG_PRINT("info", ("trigger_table affected by BUG#15921 detected"));
2442     push_warning_printf(current_thd,
2443                         Sql_condition::WARN_LEVEL_NOTE,
2444                         ER_OLD_FILE_FORMAT,
2445                         ER(ER_OLD_FILE_FORMAT),
2446                         (char *)path, "TRIGGER");
2447 
2448     if (!(ptr= parse_escaped_string(ptr, end, mem_root, trigger_table_value)))
2449     {
2450       my_error(ER_FPARSER_ERROR_IN_PARAMETER, MYF(0), "trigger_table",
2451                unknown_key);
2452       DBUG_RETURN(TRUE);
2453     }
2454 
2455     /* Set parsing pointer to the last symbol of string (\n). */
2456     unknown_key= ptr-1;
2457   }
2458   DBUG_RETURN(FALSE);
2459 }
2460 
2461 
2462 /**
2463   Contruct path to TRN-file.
2464 
2465   @param thd[in]        Thread context.
2466   @param trg_name[in]   Trigger name.
2467   @param trn_path[out]  Variable to store constructed path
2468 */
2469 
build_trn_path(THD * thd,const sp_name * trg_name,LEX_STRING * trn_path)2470 void build_trn_path(THD *thd, const sp_name *trg_name, LEX_STRING *trn_path)
2471 {
2472   /* Construct path to the TRN-file. */
2473 
2474   trn_path->length= build_table_filename(trn_path->str,
2475                                          FN_REFLEN - 1,
2476                                          trg_name->m_db.str,
2477                                          trg_name->m_name.str,
2478                                          TRN_EXT,
2479                                          0);
2480 }
2481 
2482 
2483 /**
2484   Check if TRN-file exists.
2485 
2486   @return
2487     @retval TRUE  if TRN-file does not exist.
2488     @retval FALSE if TRN-file exists.
2489 */
2490 
check_trn_exists(const LEX_STRING * trn_path)2491 bool check_trn_exists(const LEX_STRING *trn_path)
2492 {
2493   return access(trn_path->str, F_OK) != 0;
2494 }
2495 
2496 
2497 /**
2498   Retrieve table name for given trigger.
2499 
2500   @param thd[in]        Thread context.
2501   @param trg_name[in]   Trigger name.
2502   @param trn_path[in]   Path to the corresponding TRN-file.
2503   @param tbl_name[out]  Variable to store retrieved table name.
2504 
2505   @return Error status.
2506     @retval FALSE on success.
2507     @retval TRUE  if table name could not be retrieved.
2508 */
2509 
load_table_name_for_trigger(THD * thd,const sp_name * trg_name,const LEX_STRING * trn_path,LEX_STRING * tbl_name)2510 bool load_table_name_for_trigger(THD *thd,
2511                                  const sp_name *trg_name,
2512                                  const LEX_STRING *trn_path,
2513                                  LEX_STRING *tbl_name)
2514 {
2515   File_parser *parser;
2516   struct st_trigname trn_data;
2517 
2518   Handle_old_incorrect_trigger_table_hook trigger_table_hook(
2519                                           trn_path->str,
2520                                           &trn_data.trigger_table);
2521 
2522   DBUG_ENTER("load_table_name_for_trigger");
2523 
2524   /* Parse the TRN-file. */
2525 
2526   if (!(parser= sql_parse_prepare(trn_path, thd->mem_root, TRUE)))
2527     DBUG_RETURN(TRUE);
2528 
2529   if (!is_equal(&trigname_file_type, parser->type()))
2530   {
2531     my_error(ER_WRONG_OBJECT, MYF(0),
2532              trg_name->m_name.str,
2533              TRN_EXT + 1,
2534              "TRIGGERNAME");
2535 
2536     DBUG_RETURN(TRUE);
2537   }
2538 
2539   if (parser->parse((uchar*) &trn_data, thd->mem_root,
2540                     trigname_file_parameters, 1,
2541                     &trigger_table_hook))
2542     DBUG_RETURN(TRUE);
2543 
2544   /* Copy trigger table name. */
2545 
2546   *tbl_name= trn_data.trigger_table;
2547 
2548   /* That's all. */
2549 
2550   DBUG_RETURN(FALSE);
2551 }
2552 #ifdef WITH_WSREP
wsrep_create_trigger_query(THD * thd,uchar ** buf,size_t * buf_len)2553 int wsrep_create_trigger_query(THD *thd, uchar** buf, size_t* buf_len)
2554 {
2555   LEX *lex= thd->lex;
2556   String stmt_query;
2557 
2558   LEX_STRING definer_user;
2559   LEX_STRING definer_host;
2560 
2561   if (!lex->definer)
2562   {
2563     if (!thd->slave_thread)
2564     {
2565       if (!(lex->definer= create_default_definer(thd)))
2566         return 1;
2567     }
2568   }
2569 
2570   if (lex->definer)
2571   {
2572     /* SUID trigger. */
2573 
2574     definer_user= lex->definer->user;
2575     definer_host= lex->definer->host;
2576   }
2577   else
2578   {
2579     /* non-SUID trigger. */
2580 
2581     definer_user.str= 0;
2582     definer_user.length= 0;
2583 
2584     definer_host.str= 0;
2585     definer_host.length= 0;
2586   }
2587 
2588   stmt_query.append(STRING_WITH_LEN("CREATE "));
2589 
2590   append_definer(thd, &stmt_query, &definer_user, &definer_host);
2591 
2592   LEX_STRING stmt_definition;
2593   stmt_definition.str= (char*) thd->lex->stmt_definition_begin;
2594   stmt_definition.length= thd->lex->stmt_definition_end
2595     - thd->lex->stmt_definition_begin;
2596   trim_whitespace(thd->charset(), & stmt_definition);
2597 
2598   stmt_query.append(stmt_definition.str, stmt_definition.length);
2599 
2600   return wsrep_to_buf_helper(thd, stmt_query.c_ptr(), stmt_query.length(),
2601                              buf, buf_len);
2602 }
2603 #endif /* WITH_WSREP */
2604