The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Mad::Mapper::Guides::Custom - How to do custom queries

OVERVIEW

This guide will show how to run custom queries for full control.

GUIDE

Half control

It is possible to override the private methods _find_sql(), _insert_sql(), _update_sql() and _delete_sql() for more control. The benefit of overriding these methods is if you want to use optional columns for doing queries. The example below can find a row based on both the "id" and "email" column.

  sub _find_sql {
    my $self = shift;

    if ($self->email) {
      return $self->expand_sql("SELECT %pc FROM %t WHERE email=?"), $self->email;
    }
    else {
      return $self->expand_sql("SELECT %pc FROM %t WHERE id=?"), $self->id;
    }
  }

Full control

Instead of using the automatic generated methods from simple SQL statements, it is possible to do the complete query yourself. Below is an example of a completely custom _insert():

  package MyApp::Model::User;
  use Mad::Mapper -base;

  sub _insert {
    my ($self, $cb) = @_;

    Mojo::IOLoop->delay(
      sub {
        my ($delay) = @_;
        $self->db->query("INSERT INTO users (email) VALUES (?)", $self->email, $delay->begin);
      },
      sub {
        my ($delay, $err, $res) = @_;
        return $self->$cb($err) if $err;
        $self->in_storage(1);
        $self->id($db->dbh->last_insert_id(undef, undef, $self->table, $self->pk));
        $self->$cb("");
      },
    );
  }

You can also override _find(), _update() and _delete().

COPYRIGHT AND LICENSE

Copyright (C) 2014-2016, Jan Henning Thorsen

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.

AUTHOR

Jan Henning Thorsen - jhthorsen@cpan.org