Create Trigger automatically

Asked

Viewed 114 times

0

I created a code that creates a trigger automatically to Mysql.

But my function still has flaws, one of which is that it is accepting the statements of PK's and FK's as if they were table fields.

Look at this statement from a table:

CREATE TABLE `pedidos` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `data` DATE NOT NULL DEFAULT '1000-01-01',
    `hora` TIME NOT NULL DEFAULT '00:00:00',
    `conta_id` INT(11) NOT NULL DEFAULT '0',
    `contato_id` INT(11) NOT NULL DEFAULT '0',
    `empresa_id` INT(11) NOT NULL DEFAULT '1',
    `nome_oportunidade` VARCHAR(300) NOT NULL DEFAULT ' ',
    `tipo_oportunidade_id` INT(11) NOT NULL DEFAULT '0',
    `subtipo_oportunidade_id` INT(11) NOT NULL DEFAULT '0',
    `status_oportunidade_id` INT(11) UNSIGNED NOT NULL DEFAULT '0',
    `tarefa_id` INT(11) NOT NULL DEFAULT '0',
    `status_entrega_id` INT(11) NOT NULL DEFAULT '0',   
    PRIMARY KEY (`id`),
    INDEX `Com_Contas` (`conta_id`),
    INDEX `Com_Tipos_Acao` (`tipo_oportunidade_id`),
    CONSTRAINT `fk_oportunidade_tarefa` FOREIGN KEY (`tarefa_id`) REFERENCES `tarefas` (`id`),
    CONSTRAINT `oportunidadeComStatusEntrega` FOREIGN KEY (`status_entrega_id`) REFERENCES `entrega_status` (`id`) ON UPDATE CASCADE ON DELETE SET NULL,
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=666666
;

Using a regular expression I search all fields in the table:

/`(\w*)`/g;

Look at my code:

<html>
  <head>
     <script type="text/javascript">
        function gerar(){
          var conteudo = document.formTabela.conteudo.value;
          var reg = /`(\w*)`/g;

          var res = conteudo.match(reg);
          criarTriggerInsert(res);
        }

        function criarTriggerInsert(arr){
          var tabela = arr.shift();
          tabela = tabela.replace(/`/g, '');
          var createTrigger = `CREATE TRIGGER trg_${tabela}_01
                                AFTER INSERT ON ${tabela}
                                 FOR EACH ROW BEGIN

                                 INSERT INTO historico_tabela (
                              			operacao,
                              			data_acao,
                              			hora_acao,
                              			tabela,
                              			campo_id,
                              			usuario_insercao,
                              			usuario_alteracao,
                              			campo,
                              			valor_anterior,
                              			valor_atual
                              		) VALUES `;
          for( campo in arr ){
             var campoTabela = arr[campo].replace(/`/g, '');

             createTrigger += ` (	'insert',
                            			 CURDATE(),
                            			 CURTIME(),
                            			 '${tabela}',
                            			 NEW.id,
                            			 @usuario_historico,
                            			 NULL,
                            			 '${campoTabela}',
                            			 NULL,
                            			 NEW.${campoTabela}
                          		   ),`;

          }

          createTrigger = createTrigger.substring(0,createTrigger.length -1);

          console.log(createTrigger);

        }

     </script>
  </head>
  <body>
      <form name="formTabela" method="post" onsubmit="return false;">
        <label>DDL:</label><br>
        <textarea name="conteudo" cols="100" rows="5"></textarea><br>
        <button onclick="gerar();">Gerar Trigger</button>
      <form/>
  </body>
</html>

Running on the basis of DDL above, I can generate the result more or less expected, see the result of the execution:

CREATE TRIGGER trg_pedidos_01
 AFTER INSERT ON pedidos
  FOR EACH ROW BEGIN



INSERT INTO historico_tabela (
                                        operacao,
                                        data_acao,
                                        hora_acao,
                                        tabela,
                                        campo_id,
                                        usuario_insercao,
                                        usuario_alteracao,
                                        campo,
                                        valor_anterior,
                                        valor_atual
                                    ) VALUES  ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'id',
                                         NULL,
                                         NEW.id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'data',
                                         NULL,
                                         NEW.data
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'hora',
                                         NULL,
                                         NEW.hora
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'conta_id',
                                         NULL,
                                         NEW.conta_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'contato_id',
                                         NULL,
                                         NEW.contato_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'empresa_id',
                                         NULL,
                                         NEW.empresa_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'nome_oportunidade',
                                         NULL,
                                         NEW.nome_oportunidade
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'tipo_oportunidade_id',
                                         NULL,
                                         NEW.tipo_oportunidade_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'subtipo_oportunidade_id',
                                         NULL,
                                         NEW.subtipo_oportunidade_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'status_oportunidade_id',
                                         NULL,
                                         NEW.status_oportunidade_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'tarefa_id',
                                         NULL,
                                         NEW.tarefa_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'status_entrega_id',
                                         NULL,
                                         NEW.status_entrega_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'id',
                                         NULL,
                                         NEW.id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'Com_Contas',
                                         NULL,
                                         NEW.Com_Contas
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'conta_id',
                                         NULL,
                                         NEW.conta_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'Com_Tipos_Acao',
                                         NULL,
                                         NEW.Com_Tipos_Acao
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'tipo_oportunidade_id',
                                         NULL,
                                         NEW.tipo_oportunidade_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'fk_oportunidade_tarefa',
                                         NULL,
                                         NEW.fk_oportunidade_tarefa
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'tarefa_id',
                                         NULL,
                                         NEW.tarefa_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'tarefas',
                                         NULL,
                                         NEW.tarefas
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'id',
                                         NULL,
                                         NEW.id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'oportunidadeComStatusEntrega',
                                         NULL,
                                         NEW.oportunidadeComStatusEntrega
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'status_entrega_id',
                                         NULL,
                                         NEW.status_entrega_id
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'entrega_status',
                                         NULL,
                                         NEW.entrega_status
                                   ), ( 'insert',
                                         CURDATE(),
                                         CURTIME(),
                                         'pedidos',
                                         NEW.id,
                                         @usuario_historico,
                                         NULL,
                                         'id',
                                         NULL,
                                         NEW.id
                                   );

But look, it’s not right this Rigger. Because it’s repeating the fields:

(`id`),
(`conta_id`)
(`tipo_oportunidade_id`)
(`tarefa_id`)
(`id`)
(`status_entrega_id`)

And locating the names of Index, Contraint and table name as if it were field:

INDEX `Com_Contas` ,
INDEX `Com_Tipos_Acao` ,
CONSTRAINT `fk_oportunidade_tarefa` 
REFERENCES `tarefas` (`id`),
CONSTRAINT `oportunidadeComStatusEntrega` 
REFERENCES `entrega_status` 

How do I not consider this part that is in the DDL?

PRIMARY KEY (`id`),
    INDEX `Com_Contas` (`conta_id`),
    INDEX `Com_Tipos_Acao` (`tipo_oportunidade_id`),
    CONSTRAINT `fk_oportunidade_tarefa` FOREIGN KEY (`tarefa_id`) REFERENCES `tarefas` (`id`),
    CONSTRAINT `oportunidadeComStatusEntrega` FOREIGN KEY (`status_entrega_id`) REFERENCES `entrega_status` (`id`) ON UPDATE CASCADE ON DELETE SET NULL,

This is happening due to my regular expression searching for the table FIELDS that are between aspas, but it is bringing fields that are not actually fields.

  • What exactly is your goal and your doubt?

  • @Leandroangelo due to the regular expression search all the fields that are between the simple quotes, was searching the field id there in the PK statement. With this was loading 2 times this field at the time of mounting the Trigger. as you can see in the source code. But I managed to solve through a "break" (\n) before using the regular expression.

  • I improved the text, it was understandable?

1 answer

2


After a few searches, I found a solution that meets what I need to solve.

I made some changes directly in Javascript that solved my problem.

Before using the regular expression, I broke the text into an array and ran it behind the reserved words PRIMARY KEY, INDEX and FOREIGN KEY. If you find these words I remove from the array, then I put the array together again and do the rest of what I already did.

I leave the corrected code for community use.

<html>
  <head>
     <script type="text/javascript">
        function gerar(){
          var conteudo = document.formTabela.conteudo.value;
          var reg = /`(\w*)`/g;

          conteudo = conteudo.split('\n');

          var primary = 'NAO_LOCALIZADO';

          for(linha in conteudo){
            if(conteudo[linha].toLowerCase().indexOf('primary key') !== -1){
              primary = conteudo[linha].match(reg);
              primary = primary[0].replace(/`/g, '');

              delete conteudo[linha];
            } else if(conteudo[linha].toLowerCase().indexOf('index `') !== -1 || conteudo[linha].toLowerCase().indexOf('foreign key') !== -1){
              delete conteudo[linha];
            }
          }

          conteudo = conteudo.join('\n');

          var res = conteudo.match(reg);
          criarTriggerInsert(res, primary);
          criarTriggerUpdate(res, primary);
        }

        function criarTriggerInsert(arr, primary){
          var tabela = arr.shift();
          tabela = tabela.replace(/`/g, '');
          var createTrigger = `DELIMITER //
                                CREATE TRIGGER trg_${tabela}_01
                                  AFTER INSERT ON ${tabela}
                                   FOR EACH ROW BEGIN

                                   INSERT INTO historico_tabela (
                                			operacao,
                                			data_acao,
                                			hora_acao,
                                			tabela,
                                			campo_id,
                                			usuario_insercao,
                                			usuario_alteracao,
                                			campo,
                                			valor_anterior,
                                			valor_atual
                                		) VALUES `;
          for( campo in arr ){
             var campoTabela = arr[campo].replace(/`/g, '');

             if(campoTabela != primary) {
               createTrigger += ` (	'insert',
                              			 CURDATE(),
                              			 CURTIME(),
                              			 '${tabela}',
                              			 NEW.${primary},
                              			 @usuario_historico,
                              			 NULL,
                              			 '${campoTabela}',
                              			 NULL,
                              			 NEW.${campoTabela}
                            		   ),`;
              }
          }

          createTrigger = createTrigger.substring(0,createTrigger.length -1);

          createTrigger = createTrigger + `;
          END //`;

          document.formTabela.conteudo_resultado_insert.value = createTrigger;

        }

        function criarTriggerUpdate(arr, primary){
          var tabela = arr.shift();
          tabela = tabela.replace(/`/g, '');
          var createTrigger = `DELIMITER //
                                CREATE TRIGGER trg_${tabela}_02
                                  BEFORE UPDATE ON ${tabela}
                                   FOR EACH ROW BEGIN
                              `;
          for( campo in arr ){

             var campoTabela = arr[campo].replace(/`/g, '');

             if(campoTabela != primary){

               createTrigger += ` IF( OLD.${campoTabela} <> NEW.${campoTabela} ) THEN
                    INSERT INTO historico_tabela (
                       operacao,
                       data_acao,
                       hora_acao,
                       tabela,
                       campo_id,
                       usuario_insercao,
                       usuario_alteracao,
                       campo,
                       valor_anterior,
                       valor_atual
                     ) VALUES (
                       'update',
                       CURDATE(),
                       CURTIME(),
                       '${tabela}',
                       NEW.${primary},
                       NULL,
                       @usuario_historico,
                       '${campoTabela}',
                       OLD.${campoTabela},
                       NEW.${campoTabela}
                     );
                   END IF;

               `;
              }
          }

          createTrigger = createTrigger + `  END //`;

          document.formTabela.conteudo_resultado_update.value = createTrigger;
        }

     </script>
  </head>
  <body>
      <form name="formTabela" method="post" onsubmit="return false;">
        <label>DDL:</label><br>
        <textarea name="conteudo" cols="100" rows="5"></textarea><br>
        <button onclick="gerar();">Gerar Trigger</button><br><br>
        <label>Resultado Insert:</label><br>
        <textarea name="conteudo_resultado_insert" cols="100" rows="5"></textarea><br>
        <label>Resultado Update:</label><br>
        <textarea name="conteudo_resultado_update" cols="100" rows="5"></textarea><br>
      <form/>
  </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.