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