2
2

More than 5 years have passed since last update.

O/RマッパーのTengを使ってみた

Last updated at Posted at 2014-04-10

ちょこっとしたものを書くのに生DBIは面倒なのでO/Rマッパーというものに挑戦してみた。

create tableする前にTeng::Schema::Loader->loadしてそのままinsertしようとすると"Table definition for user does not exist (Did you declare it in our schema?)"みたいなエラーになってハマった。テーブル情報更新したらリロードしないといけない。

// 必要なモジュールをインストール
$ cpanm DBI
$ cpanm DBD::SQLite
$ cpanm Teng
teng.pl
use strict;
use warnings;
use Teng;
use Teng::Schema::Loader;
use DBI;
use Data::Dumper;

exit main();

sub main
{
  # SQLiteはオンメモリ上でもできる
  #my $dbh = opendb(":memory:");
  my $dbh = opendb("a.db");

  unless (check_table($dbh, "user")) {
    init_table($dbh);
  }

  my $teng = Teng::Schema::Loader->load(
    dbh => $dbh,
    namespace => "MyApp::DB",
  );

  # INTEGER PRIMARY設定しているとidは連番が自動で振られる
  my $row = $teng->insert(user => {
    #id   => 1,
    name => "test1",
    age  => 26,
  });
  warn Dumper $row->get_columns;

  $dbh->commit;
  closedb($dbh);

  return 0;
}

sub init_table
{
  my ($dbh) = @_;

  my $teng = Teng::Schema::Loader->load(
    dbh => $dbh,
    namespace => 'MyApp::DB',
  );
  $teng->do(q{
    CREATE TABLE user (
      id   INTEGER PRIMARY KEY,
      name TEXT,
      age  INTEGER
    )
  });
  return;
}

sub check_table
{
  my ($dbh, $tbl) = @_;
  my $query = "select count(*) from sqlite_master where type='table' and name='$tbl'";

  # この4行はselectrow_arrayrefでできる
  #my $sth = $dbh->prepare($query);
  #$sth->execute;
  #my $row = $sth->fetch();
  #$sth->finish();

  my $row = $dbh->selectrow_arrayref($query);
  return $row->[0];
}

sub opendb
{
  my ($dbfile) = @_;
  my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
  $dbh->{AutoCommit} = 0;
  return $dbh;
}

sub closedb
{
  my ($dbh) = @_;
  return $dbh->disconnect;
}

実行するたびにidが増えていく

$ perl teng.pl
$VAR1 = {
          'name' => 'test1',
          'id' => 1,
          'age' => 26
        };
$ perl teng.pl
$VAR1 = {
          'name' => 'test1',
          'id' => 2,
          'age' => 26
        };

$ sqlite3 a.db "select * from user"
1|test1|26
2|test1|26

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2