はじめに
DBIx::SkinnyでO/Rマッパの勉強な日々が続いています.
そんな中,カラム名の指定を行う機会が多々出てきますが,テーブル名のプリフィックス(「issm_user」というテーブルであれば「issm_」のような部分)を考慮したり,関数や制御文を挟んだり,テーブル名やカラム名のエイリアスを利用したりする際の扱いをまだよくわかっていません.
とりあえず,そのあたりを吸収するようなPerlスクリプトを書いてみました.
まぁ既出でしょうが,勉強の記録ということで><
吸収範囲
たぶん次のあたりのものを吸収します.
- カラム名のみ
- テーブルのプリフィックス + テーブル名 (基本的な部分のみ) + カラム名
- 上記のようなカラム名 + カラム名のエイリアス
- テーブル名のエイリアス + カラム名 (+ カラム名のエイリアス)
- そこそこ簡単な構造の関数や制御文 (+ カラム名のエイリアス)
実行例
まず実行例から.(サブルーチンpは,printのショートカットのようなものです.)
# TABLE_PREFIX: 'issm_' # issm_col1 p column(qw/col1/); p column(qw/col1 - -/); # issm_user.col2 p column(qw/col2 user/); # issm_item.col3 c3 p column(qw/col3 item c3/); # i.col4 item_c4 p column(qw/col4 -i item_c4/); my $sha1_ize = sub { "SHA1($_[0])"; }; # SHA1(issm_map.col5) p column(qw/col5 map -/, $sha1_ize); # SHA1(m.col6) sha1_c6 p column(qw/col6 -m sha1_c6/, $sha1_ize); # IF( issm_item.col7 >= 10, m.col8, DATE(u.col9) ) if_c789 p column( qw/col7 item if_c789/, sub { my $c7 = shift; my $c8 = column(qw/col8 -m -/); my $c9 = column( qw/col9 -u -/, sub { sprintf('DATE(%s)', shift); }, ); return "IF( $c7 >= 10, $c8, $c9 )"; } );
コード
次のような感じです.
use strict; use warnings; my %CONFIG = ( TABLE_PREFIX => 'issm_', ); sub p { print (@_, "\n"); } sub column { my ($col, $table, $alias, $sub) = @_; my $col_name = $col; if (defined $table) { if (my ($table_alias) = $table =~ /^-(.*)$/) { $col_name = "${table_alias}.${col}" if $table_alias ne ''; } else { $col_name = "${table}.${col}"; $col_name = "$CONFIG{TABLE_PREFIX}${col_name}" if defined $CONFIG{TABLE_PREFIX}; } } if (defined $sub && ref $sub eq 'CODE') { $col_name = $sub->($col_name) } return (defined $alias && $alias ne '-') ? "$col_name $alias" : $col_name; } sub main { # issm_col1 p column(qw/col1/); p column(qw/col1 - -/); # issm_user.col2 p column(qw/col2 user/); # issm_item.col3 c3 p column(qw/col3 item c3/); # i.col4 item_c4 p column(qw/col4 -i item_c4/); my $sha1_ize = sub { "SHA1($_[0])"; }; # SHA1(issm_map.col5) p column(qw/col5 map -/, $sha1_ize); # SHA1(m.col6) sha1_c6 p column(qw/col6 -m sha1_c6/, $sha1_ize); # IF( issm_item.col7 >= 10, m.col8, DATE(u.col9) ) if_c789 p column( qw/col7 item if_c789/, sub { my $c7 = shift; my $c8 = column(qw/col8 -m -/); my $c9 = column( qw/col9 -u -/, sub { sprintf('DATE(%s)', shift); }, ); return "IF( $c7 >= 10, $c8, $c9 )"; } ); } main(); __END__
おわりに
それでは,勉強に戻ります.
