简体   繁体   中英

How to create trigger in DB with help of `DBIx::Class` using add_trigger method?

I want to add trigger into my database. I use DBIx::Class and follow these examples: 1 , 2 .
My code is:

package App::Schema;
use base qw/DBIx::Class::Schema/;
__PACKAGE__->load_namespaces();

sub sqlt_deploy_hook {
    my ($self, $schema) = @_;
    $schema->add_trigger( name => 'foo' );
}

1;

But I get this error:

Failed to translate to YAML: translate: Error with producer 'SQL::Translator::Producer::YAML': Can't call method "name" on an undefined value at /home/kes/work/projects/x/app/local/lib/perl5/SQL/Translator/Schema/Trigger.pm line 198

When run command with all environment variables as required by dbic-migration :

dbic-migration --force --schema_class App::Schema --database PostgreSQL -Ilib prepare

Which point me somewhere into SQL::Translator::Schema::Trigger

What did I miss? How to fix this error?

UPD

Even when I add all arguments I got error:

Failed to translate to YAML: translate: Error with parser 'SQL::Translator::Parser::DBIx::Class': Table named users doesn't exist at /home/kes/work/projects/x/app/local/lib/perl5/SQL/Translator/Schema/Trigger.pm line 54

Here the target line:

my $table = $args->{schema}->get_table($arg)
   or die "Table named $arg doesn't exist";    

Modified code:

sub sqlt_deploy_hook {
    my ($self, $schema) = @_;

    warn "TABLES: " ,$schema->get_tables ,"\n";
    $schema->add_trigger(()
        ,name =>  'foo'
        ,perform_action_when => 'after'
        ,database_events     => 'insert'
        ,on_table => 'users'
        ,action => 'text'
        ,scope => 'row'
    );
}

This code produce next warnings:

TABLES: users
TABLES: dbix_class_deploymenthandler_versions

But DB has only one table at the moment. I expect it at least should produce:

TABLES: users dbix_class_deploymenthandler_versions

How to create trigger in DB ?

There maybe the problem with DBIx::Class::ResultSource::default_sqlt_deploy_hook :

which was originally designed to expect the Result class name and the $sqlt_table instance of the table being deployed

As work around add next line of code before add_trigger :

return   unless grep $_ eq 'users',  $schema->get_tables;

But the recommend way is to create deploy/upgrade/downgrade .sql files manually

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM