DBIx::Custom

簡介

use DBIx::Custom;

# Connect
my $dbi = DBIx::Custom->connect(
  "dbi:mysql:database=dbname",
  'ken',
  '!LFKD%$&',
  {mysql_enable_utf8 => 1}
);

# Create model
$dbi->create_model('book');

# Insert 
$dbi->model('book')->insert({title => 'Perl', author => 'Ken'});

# Update 
$dbi->model('book')->update({title => 'Perl', author => 'Ken'}, where  => {id => 5});

# Delete
$dbi->model('book')->delete(where => {author => 'Ken'});

# Select
my $result = $dbi->model('book')->select(['title', 'author'], where  => {author => 'Ken'});

# Select, more complex
#   select book.title as book.title,
#     book.author as book.author,
#     comnapy.name as company.name
#   form book
#     left outer join company on book.company_id = company.id
#   where book.author = ?
#   order by id limit 0, 5
my $result = $dbi->model('book')->select(
  [
    {book => [qw/title author/]},
    {company => ['name']}
  ],
  where  => {'book.author' => 'Ken'},
  join => ['left outer join company on book.company_id = company.id'],
  append => 'order by id limit 0, 5'
);

# Get all rows or only one row
my $rows = $result->all;
my $row = $result->one;

# Execute SQL with named place holder
my $result = $dbi->execute(
  "select id from book where author = :author and title like :title",
  {author => 'ken', title => '%Perl%'}
);    

DBIx::Custom是一個DBI的包裝器坠非,此模塊具有以下功能:

  1. 可以更容易的執(zhí)行insert希柿、update腐芍、deleted和select語句集侯。
  2. 可以非常靈活的創(chuàng)建where子句
  3. 支持命名占位符
  4. 支持連接管理被啼,透明的數(shù)據(jù)庫連接池管理帜消。
  5. 支持很多關(guān)系型數(shù)據(jù)庫:MySQL、SQLite趟据、PostgreSQL券犁、Oracle、Microsoft SQL Server汹碱、Microsoft Access粘衬、DB2和其他。
  6. 可以根據(jù)數(shù)據(jù)類型和列名進行過濾。
  7. 非常靈活的支持order by 子句的創(chuàng)建。

屬性

connector

my $connector = $dbi->connector;
$dbi = $dbi->connector($connector);

連接管理器對象荚孵,如果設(shè)置了一個連接管理器對象嫡意,你可以通過它的dbh方法獲取一個數(shù)據(jù)庫連接汇四。所以連接管理器對象必須有一個dbh方法。

下面是一個使用DBIx::Connector作為DBIx::Custom的連接管理器對象的例子:

my $connector = DBIx::Connector->new(
  "dbi:mysql:database=$database",
  $user,
  $password,
  DBIx::Custom->new->default_option
);

my $dbi = DBIx::Custom->connect(connector => $connector);

如果在調(diào)用DBIx::Custom的connect方法時,其屬性connector的值為1,則DBIx::Custom將默認使用DBIx::Connector創(chuàng)建一個連接管理器并為屬性connector賦值屯阀。

my $dbi = DBIx::Custom->connect(
  dsn => $dsn, user => $user, password => $password, connector => 1);

my $connector = $dbi->connector; # DBIx::Connector

注:必須安裝DBIx::Connector模塊。

dsn

my $dsn = $dbi->dsn;
$dbi = $dbi->dsn("DBI:mysql:database=dbname");

數(shù)據(jù)源名稱轴术,在調(diào)用connect方法時使用难衰。dsn支持很多種格式,具體內(nèi)容可以查閱DBI模塊的文檔獲取逗栽。

default_option

my $default_option = $dbi->default_option;
$dbi = $dbi->default_option($default_option);

使用DBI創(chuàng)建數(shù)據(jù)庫連接時的默認參數(shù)盖袭,執(zhí)行connect方法時使用,默認情況下為以下值:

{
  RaiseError => 1,
  PrintError => 0,
  AutoCommit => 1,
}

exclude_table

my $exclude_table = $dbi->exclude_table;
$dbi = $dbi->exclude_table(qr/pg_/);

使用正則表達式在以下方法(each_column彼宠、each_table鳄虱、type_rule)執(zhí)行時排除一些表。

filters

my $filters = $dbi->filters;
$dbi = $dbi->filters(\%filters);

過濾器凭峡,可以通過方法register_filter注冊拙已。

last_sql

my $last_sql = $dbi->last_sql;
$dbi = $dbi->last_sql($last_sql);

獲取通過execute方法成功執(zhí)行的最后一個SQL。

now

my $now = $dbi->now;
$dbi = $dbi->now($now);

返回當前時間的代碼引用摧冀,默認為以下代碼的引用:

sub {
  my ($sec, $min, $hour, $mday, $mon, $year) = localtime;
  $mon++;
  $year += 1900;
  return sprintf("%04d-%02d-%02d %02d:%02d:%02d");
}

通過會返回一個表示時間的字符串:2011-10-14 05:05:27悠栓。給insert方法的ctime、mtime選項以及update方法的mtime選項使用按价。

models

my $models = $dbi->models;
$dbi = $dbi->models(\%models);

數(shù)據(jù)模型,由include_model 和 create_model方法可以注冊數(shù)據(jù)模型笙瑟。

mytable_sysmbol

在“select”方法的column 選項中指定要查詢自己列的符號楼镐,默認為“MY”。

$dbi->table('book')->select({__MY__ => '*'});

option

my $option = $dbi->option;
$dbi = $dbi->option($option);

使用DBI創(chuàng)建數(shù)據(jù)庫連接時的可選參數(shù)往枷,執(zhí)行connect方法時使用框产,并且在這里設(shè)置的值會覆蓋default_option中的值凄杯。

password

my $password = $dbi->password;
$dbi = $dbi->password('lkj&le`@s');

數(shù)據(jù)庫連接的密碼,在執(zhí)行connect方法時使用秉宿。

quote

my quote = $dbi->quote;
$dbi = $dbi->quote('"');

在數(shù)據(jù)庫查詢中有一些具有特殊含義的詞(如:表名戒突,列名等),這個屬性就是給這類詞設(shè)置引用符號的描睦。在mysql默認使用反引號"`"膊存。如果是非mysql則此屬性的值默認為雙引號。

你可以為此屬性設(shè)計一對符號忱叭。

$dbi->quote('[]');

result_class

my $result_class = $dbi->result_class;
$dbi = $dbi->result_class('DBIx::Custom::Result');

結(jié)果類隔崎,對查詢結(jié)果進行包裝的類。默認為:DBIx::Custom::Result韵丑。

safety_character

my $safety_character = $dbi->safety_character;
$dbi = $dbi->safety_character($character);

表名和列名中安全字符的正則表達式爵卒,默認為“a-zA-Z_”。無需像“[a-zA-Z_]”指定撵彻。

separator

my $separator = $dbi->separator;
$dbi = $dbi->separator('-');

連接表名和列名的分隔符钓株。這會用在mycolumn和column方法中,在select方法的column選項中也會用到陌僵。默認值為.轴合。

user

my $user = $dbi->user;
$dbi = $dbi->user('Ken');

數(shù)據(jù)庫連接的用戶名,在執(zhí)行connect方法時使用拾弃。

user_column_info

my $user_column_info = $dbi->user_column_info;
$dbi = $dbi->user_column_info($user_column_info);

你可以把這個屬性的值設(shè)置為如下格式的數(shù)據(jù):

[
  {table => 'book', column => 'title', info => {...}},
  {table => 'author', column => 'name', info => {...}}
]

通常你可以使用get_column_info方法的返回值進行設(shè)置值桩。

my $user_column_info = $dbi->get_column_info(exclude_table => qr/^system/);
$dbi->user_column_info($user_column_info);

如果 user_column_info被設(shè)置了,在執(zhí)行each_column方法會使用user_column_info屬性去查找column信息豪椿,這樣做相對來說速度上有一點的優(yōu)勢奔坟。

user_table_info

my $user_table_info = $dbi->user_table_info;
$dbi = $dbi->user_table_info($user_table_info);

你可以把這個屬性的值設(shè)置為如下格式的數(shù)據(jù):

[
  {table => 'book', info => {...}},
  {table => 'author', info => {...}}
]

通常你可以使用get_table_info方法的返回值進行設(shè)置。

my $user_table_info = $dbi->get_table_info(exclude => qr/^system/);
$dbi->user_table_info($user_table_info);

如果 user_table_info被設(shè)置了搭盾,在執(zhí)行each_teble方法會使用user_table_info屬性去查找table信息咳秉,這樣做相對來說速度上有一點的優(yōu)勢。

方法

DBIx::Custom模塊了Object::Simple中的所有方法鸯隅,并實現(xiàn)了以下方法澜建。

available_datatype

print $dbi->available_datatype;

獲取可用的數(shù)據(jù)類型。(暫時不知道用它能做啥)

available_typename

print $dbi->available_typename;

獲取可用的類型名稱蝌以。(暫時不知道用它能做啥)

assign_clause

my $assign_clause = $dbi->assign_clause({title => 'a', age => 2});

對sql語句中的變量進行數(shù)值綁定炕舵。用于在執(zhí)行更新或插入操作時創(chuàng)建set子句。

"update book set " . $dbi->assign_clause({title => 'a', age => 2});

update book set  title = :title, age = :age 

column

my $column = $dbi->column(book => ['author', 'title']);

用于創(chuàng)建 column 子句跟畅,上面的代碼將生成如下所示的sql語句咽筋。

book.author as "book.author",
book.title as "book.title"

您可以通過separator屬性更改分隔符。

# Separator is hyphen
$dbi->separator('-');

book.author as "book-author",
book.title as "book-title"

connect

# DBI compatible arguments
my $dbi = DBIx::Custom->connect(
  "dbi:mysql:database=dbname",
  'ken',
  '!LFKD%$&',
  {mysql_enable_utf8 => 1}
);

# pass DBIx::Custom attributes
my $dbi = DBIx::Custom->connect(
  dsn => "dbi:mysql:database=dbname",
  user => 'ken',
  password => '!LFKD%$&',
  option => {mysql_enable_utf8 => 1}
);

連接到數(shù)據(jù)庫徊件,并創(chuàng)建一個新的DBIx::Custom對象奸攻。DBIx::Custom是對DBI模塊的封裝蒜危,并且默認情況下在創(chuàng)建連接時參數(shù)option中的AutoCommit和RaiseError兩個屬性的值是true,而PrintError屬性的值為假睹耐。(這在上面屬性小節(jié)的default_option中已經(jīng)介紹過了)

create_model

$dbi->create_model('book');
$dbi->create_model(
  'book',
  join => [
    'inner join company on book.comparny_id = company.id'
  ]
);
$dbi->create_model(
  table => 'book',
  join => [
    'inner join company on book.comparny_id = company.id'
  ],
);

創(chuàng)建一個DBIx::Custom::Model對象并初始化辐赞,對象中的列屬性是自動設(shè)置的。您可以使用后面將要介紹的model方法使用已經(jīng)創(chuàng)建的DBIx::Custom::Model對象硝训。

$dbi->model('book')->select(...);

你可以使用與表名不同的標識符作為DBIx::Custom::Model對象的名稱响委。

$dbi->create_model(name => 'book1', table => 'book');
$dbi->model('book1')->select(...);

dbh

my $dbh = $dbi->dbh;

獲取DBI數(shù)據(jù)庫連接的句柄,如果connector屬性已經(jīng)被設(shè)置捎迫,則會使用connector對象進行獲取晃酒。

delete

$dbi->delete(table => 'book', where => {title => 'Perl'});

執(zhí)行數(shù)據(jù)庫的DELETE操作。

所有對execute方法可用的參數(shù)選項窄绒,對于delete函數(shù)都可用贝次,并且含意完全相同。除此之外delete方法還以下參數(shù)選項彰导。

prefix

prefix => 'some'

前綴蛔翅,指明從哪些表中刪除數(shù)據(jù)。當from子句中有多個表名時需要用到它位谋。

delete some from book

table

table => 'book'

表名山析。對哪張表執(zhí)行DELETE操作。

where

與select方法的where選項相同掏父,指明本次DELETE操作的條件笋轨。對需要刪除的記錄進行過濾。

delete_all

$dbi->delete_all(table => $table);

刪除一張表中的所有數(shù)據(jù)赊淑。它的實現(xiàn)代碼如下:

sub delete_all { shift->delete(@_, allow_delete_all => 1) }

其實當我們調(diào)用delete函數(shù)時爵政,如果沒有傳where和id參數(shù)并且沒有指定allow_delete_all 為true的話,是會報錯的陶缺。delete_all方法和delete方法的執(zhí)行邏輯和所接收的參數(shù)完全一樣钾挟,只是delete_all允許刪除一張表中的所有數(shù)據(jù)。

each_column

$dbi->each_column(
  sub {
    my ($dbi, $table, $column, $column_info) = @_;
 
    my $type = $column_info->{TYPE_NAME};
 
    if ($type eq 'DATE') {
        # ...
    }
  }
);

迭代數(shù)據(jù)庫中的所有列信息饱岸,參數(shù)是一個回調(diào)函數(shù)掺出。回調(diào)函數(shù)需要接收四個參數(shù):DBIx::Custom對象苫费、table_name(表名)汤锨、column_name(列名)和column_info(列信息)。針對數(shù)據(jù)庫中的每一個數(shù)據(jù)列會調(diào)用一次回調(diào)函數(shù)百框。

如果user_column_info屬性已經(jīng)設(shè)置泥畅,each_column方法會使用user_column_info屬性中的信息,這種方式可以提高each_column方法的性能。

my $column_infos = $dbi->get_column_info(exclude_table => qr/^system_/);
$dbi->user_column_info($column_info);
$dbi->each_column(sub { ... });

each_table

$dbi->each_table(
  sub {
    my ($dbi, $table, $table_info) = @_;
 
    my $table_name = $table_info->{TABLE_NAME};
  }
);

迭代數(shù)據(jù)中所有表的信息位仁,參數(shù)是一個回調(diào)函數(shù)》阶担回調(diào)函數(shù)接收三個參數(shù):DBIx::Custom對象聂抢、table_name(表名)和table_info(表信息)。針對數(shù)據(jù)庫中的每個一個表調(diào)用一次回調(diào)函數(shù)棠众。

如果user_table_info屬性已經(jīng)設(shè)置琳疏,each_table方法使用user_table_info屬性中的信息,這種方式可以提高each_table方法的性能闸拿。

my $table_infos = $dbi->get_table_info(exclude => qr/^system_/);
$dbi->user_table_info($table_info);
$dbi->each_table(sub { ... });

execute

my $result = $dbi->execute(
  "select * from book where title = :title and author like :author",
  {title => 'Perl', author => '%Ken%'}
);

my $result = $dbi->execute(
  "select * from book where title = :book.title and author like :book.author",
  {'book.title' => 'Perl', 'book.author' => '%Ken%'}
);

執(zhí)行SQL語句空盼。SQL語句中可以包含“命名占位符”(:author和:title)。你也可以將表名加入到“命名占位符”中(:book.author和:book.title)新荤。第二個參數(shù)是一個hashref揽趾,其中包含需要綁定到“命名占位符”中的數(shù)據(jù)。當執(zhí)行select語句時返回值是DBIx::Custom::Result對象苛骨,當執(zhí)行的是insert篱瞎、update、delete語句時返回值是受影響的行數(shù)痒芝。

在不支持“命名占位符”的數(shù)據(jù)庫系統(tǒng)(如Mysql)中俐筋,執(zhí)行SQL語句前“命名占位符”會被通用占位符替換严衬。

# Original
select * from book where title = :title and author like :author

# Replaced
select * from where title = ? and author like ?;

您還可以通過 name{operator}語法指定具有指定“運算符”的“命名點位符”澄者。

# Original
select * from book where :title{=} and :author{like}

# Replaced
select * from where title = ? and author like ?;

需要注意的是:時間格式(如12:13:15)中的冒號是一個例外,它不會被解析為指定的占位符请琳。一般情況下你如果想使用冒號粱挡,則必須使用\\逃避。

select * from where title = "aa\\:bb";

execute方法可接收的參數(shù):第一個參數(shù)必須為SQL語句单起;第二個參數(shù)(為占位符綁定的數(shù)據(jù))是可選的抱怔;再往后是一個元素數(shù)為偶數(shù)的列表作為第三個參數(shù)(一系列鍵值對),叫OPTION嘀倒。OPTION支持的屬性會在接下來分小節(jié)介紹屈留。

after_build_sql

這個屬性的值需要是一個coderef類型的回調(diào),它用于對生成的sql進行過濾测蘑。

after_build_sql => $code_ref

下面是一個例子

$dbi->select(
  table => 'book',
  column => 'distinct(name)',
  after_build_sql => sub {
    "select count(*) from ($_[0]) as t1"
  }
);

select count(*) from (select distinct(name) from book) as t1;

append

append => 'order by name'

在SQL語句之后追加一些語句灌危。

bind_type

指定數(shù)據(jù)庫綁定數(shù)據(jù)類型。

bind_type => {image => DBI::SQL_BLOB}
bind_type => [image => DBI::SQL_BLOB]
bind_type => [[qw/image audio/] => DBI::SQL_BLOB]

這用于通過數(shù)據(jù)庫連接句柄dbh的bind_param方法對SQL語句進行綁定參數(shù)碳胳。

$sth->bind_param($pos, $value, DBI::SQL_BLOB);

filter

filter => {
  title  => sub { uc $_[0] }
  author => sub { uc $_[0] }
}

# Filter name
filter => {
  title  => 'upper_case',
  author => 'upper_case'
}
 
# At once
filter => [
  [qw/title author/]  => sub { uc $_[0] }
]

過濾勇蝙。你可以通過這個參數(shù)為column的值綁定一個過濾器。過濾器可以是一個subroutine也可以是一個通過register_filter方法注冊的過濾器的名稱挨约。過濾器會在數(shù)據(jù)保存到數(shù)據(jù)庫之前味混、且在執(zhí)行類型過濾(type_rule)之前執(zhí)行产雹。

reuse

reuse => $hash_ref

如果設(shè)置了哈希引用變量,則重用查詢對象翁锡。

my $queries = {};
$dbi->execute($sql, $param, reuse => $queries);

當您想要重復(fù)執(zhí)行相同的查詢操作時蔓挖,這樣做可以提高性能,因為通常創(chuàng)建查詢對象速度會很慢馆衔。

table

table => 'author'

如果在列名中省略了表名瘟判,并且啟用了into1和into2過濾器,則必須設(shè)置table選項角溃。

$dbi->execute("select * from book where title = :title and author = :author",
  {title => 'Perl', author => 'Ken', table => 'book');

# Same
$dbi->execute(
  "select * from book where title = :book.title and author = :book.author",
  {title => 'Perl', author => 'Ken');

table_alias

table_alias => {worker => 'user'} # {ALIAS => TABLE}

表別名拷获。key是表別名,value是真實表名减细。在你設(shè)定表別名后匆瓜,你可以在type_rule的into1和into2上使用表別名。

type_rule_of

type_rule_off => 1

關(guān)閉 into1和into2過濾規(guī)則邪财。

type_rule1_of

type_rule1_off => 1

關(guān)閉 into1過濾規(guī)則陕壹。

type_rule2_of

type_rule2_off => 1

關(guān)閉 into2過濾規(guī)則。

prepare_attr EXPERIMENTAL

prepare_attr => {mysql_use_result => 1}

這個是由Statemend處理的屬性树埠,這是DBI的prepare方法第二個參數(shù)糠馆。

query EXPERIMENTAL

query => 1

如果你僅僅是為了獲取SQL信息,而不是為了執(zhí)行SQL語句怎憋∮致担可以設(shè)置這個選項,這時execute方法會返回一個DBIx::Custom::Query對象绊袋。

my $query = $dbi->execute(
  "insert into book (id, name) values (:id, :name)",
  {id => 1, name => 'Perl'},
  query => 1
);

DBIx::Custom::Query對象具有以下信息

my $sql = $query->sql;
my $param = $query->param;
my $columns $query->columns;

您可以通過以下方式獲取綁定值和類型毕匀。

# Build bind values and types
$query->build;

# Get bind values
my $bind_values = $query->bind_values;

# Get bind types
my $bind_value_types = $query->bind_value_types;

您可以通過DBI準備sql并執(zhí)行SQL 。

my $sth = $dbi->dbh->prepare($sql);
$sth->execute($sql, @$bind_values);

如果你知道參數(shù)沒有重復(fù)的列名癌别,沒有過濾器皂岔,你可以通過以下方式更快速的獲得綁定值。

my $ bind_values = [map {$ param-> {$ _}} @columns]

get_column_info

my $column_infos = $dbi->get_column_info(exclude_table => qr/^system_/);

用于獲取數(shù)據(jù)庫中數(shù)據(jù)列的信息展姐,參數(shù)exclude_table的值是一個正則表達式躁垛,用于排除與之相匹配的表。返回值結(jié)構(gòu)如下:

[
  {table => 'book', column => 'title', info => {...}},
  {table => 'author', column => 'name' info => {...}}
]

get_table_info

my $table_infos = $dbi->get_table_info(exclude => qr/^system_/);

用于獲取數(shù)據(jù)庫中數(shù)據(jù)表的信息圾笨,參數(shù)exclude_table的值是一個正則表達式教馆,用于排除與之相匹配的表。返回值結(jié)構(gòu)如下:

[
  {table => 'book', info => {...}},
  {table => 'author', info => {...}}
]

insert

$dbi->insert({title => 'Perl', author => 'Ken'}, table  => 'book');

向一個數(shù)據(jù)表中插入數(shù)據(jù)擂达,第一個參數(shù)是需要插入的數(shù)據(jù)土铺,可以是一個hashref(只插入一條記錄時),也可以是一個元素為hashref的arrayref(插入多條數(shù)據(jù)時)。返回值是受影響的行數(shù)悲敷。如果數(shù)據(jù)項的值為常量值究恤,則需要使用標題引用作為參數(shù)。

{date => \"NOW()"}

注:在插入多條記錄時后德,你不能使用id選項丁溅。

insert方法支持execute方法中的所有參數(shù)選項,同時你還可以使用以下參數(shù)選項探遵。

bulk_insert

bulk_insert => 1

在“插入多條記錄”時,如果數(shù)據(jù)庫支持批量插入妓柜,則執(zhí)行批量插入操作箱季。會生成如下面這樣的SQL:

insert into book (id, title) values (?, ?), (?, ?);

ctime

ctime => 'created_time'

表中記錄“創(chuàng)建時間”的列。默認時間格式為“YYYY-mm-dd HH:MM:SS”棍掐,可以通過now屬性進行修改藏雏。

prefix

prefix => 'or replace'

表名前面的前綴。

insert or replace into book

table

table => 'book'

表名作煌。

mtime

該選項與update方法mtime選項相同掘殴。用于指定表中記錄“更新時間”的列。默認時間格式為“YYYY-mm-dd HH:MM:SS”粟誓,可以通過now屬性進行修改奏寨。

wrap

wrap => {price => sub { "max($_[0])" }}

占位符包裝器。

 $dbi->insert({price => 100}, table => 'book',{price => sub { "$_[0] + 5" }});
 
 insert into book price values ( ? + 5 );

include_model

$dbi->include_model('MyModel');

導(dǎo)入指定名稱空間的DBIx::Custom::Model對象鹰服,需要如下的包結(jié)構(gòu)病瞳。

lib / MyModel.pm
    / MyModel / book.pm
              / company.pm

名稱空間的模塊必須是DBIx::Custom::Model的子類。請參閱DBIx::Custom::Model來了解更多信息悲酷。

like_value

my $like_value = $dbi->like_value

返回一個可以包值包裝成like value格式的代碼引用套菜。

sub { "%$_[0]%" }

mapper

my $mapper = $dbi->mapper(param => $param);

創(chuàng)建一個DBIx::Custom::Mapper對象。

merge_param

my $param = $dbi->merge_param({key1 => 1}, {key1 => 1, key2 => 2});

合并參數(shù)设易,如上代碼可以得到如下結(jié)果:

{key1 => [1, 1], key2 => 2}

如果被合并的兩個參數(shù)包含相同的鍵名逗柴,則該被合并后對應(yīng)鍵名的值會轉(zhuǎn)換為數(shù)組引用。

model

my $model = $dbi->model('book');

獲取一個由create_model 或 include_model方法創(chuàng)建的DBIx::Custom::Model對象顿肺。

mycolumn

my $column = $dbi->mycolumn(book => ['author', 'title']);

創(chuàng)建列子句戏溺,如上代碼會創(chuàng)建如下SQL片段:

book.author as author,
book.title as title

new

my $dbi = DBIx::Custom->new(
  dsn => "dbi:mysql:database=dbname",
  user => 'ken',
  password => '!LFKD%$&',
  option => {mysql_enable_utf8 => 1}
);

創(chuàng)建一個新的DBIx::Custom對象挟冠。

not_exists

my $not_exists = $dbi->not_exists;

返回一個DBIx::Custom::NotExists對象,表示當前列不存在知染。這個方法僅用于DBIx::Custom::Where對象中的param方法中。

order

my $order = $dbi->order;

創(chuàng)建一個DBIx::Custom::Order對象嫌吠。

q

my $quooted = $dbi->q("title");

使用quote方法引用字符串。

register_filter

$dbi->register_filter(
  # Time::Piece object to database DATE format
  tp_to_date => sub {
    my $tp = shift;
    return $tp->strftime('%Y-%m-%d');
  },
  # database DATE format to Time::Piece object
  date_to_tp => sub {
    my $date = shift;
    return Time::Piece->strptime($date, '%Y-%m-%d');
  }
);

注冊過濾器凭戴,給某些方法參數(shù)中的filter選項使用。

select

my $result = $dbi->select(
  column => ['author', 'title'],
  table  => 'book',
  where  => {author => 'Ken'},
);

執(zhí)行select語句么夫。你可以傳遞奇數(shù)個參數(shù)肤视。第一個參數(shù)是column,后面的所有參數(shù)共同組成了OPTION腐螟。

 my $result = $dbi->select(['author', 'title'], table => 'book');

select方法可以使用execute方法中所有的參數(shù)選項,除此之外還可以使用如下參數(shù)選項困后。

column

column => 'author'
column => ['author', 'title']

指定列子句乐纸,如果沒有指定column,則默認為*摇予。

column => '*'

你還可以用一個元素為hashref類型的arrayref作為column的值汽绢。

column => [
  {book => [qw/author title/]},
  {person => [qw/name age/]}
]

book.author as "book.author",
book.title as "book.title",
person.name as "person.name",
person.age as "person.age"

你可以通過 __MY__指定那些屬于當前表的列。

column => [
  {__MY__ => [qw/author title/]},
]

__MY__可以通過mytable_symbol屬性來改變趾盐。

param

param => {'table2.key3' => 5}

where子句之前“命名占位符”的綁定參數(shù)庶喜。

如果你要在join子句中指定“命名占位符”,則可以通過參param選項傳遞綁定參數(shù)救鲤。

join  => ['inner join (select * from table2 where table2.key3 = :table2.key3)as table2 on table1.key1 = table2.key1']

prefix

prefix => 'SQL_CALC_FOUND_ROWS'

列子句的前綴

select SQL_CALC_FOUND_ROWS title, author from book;

join

join => [
  'left outer join company on book.company_id = company_id',
  'left outer join location on company.location_id = location.id'
]

join子句久窟,如果column子句或where子句包含像company.name這樣的表名,則自動使用創(chuàng)建SQL時所需的join子句本缠。

$dbi->select(
  table => 'book',
  column => ['company.location_id as location_id'],
  where => {'company.name' => 'Orange'},
  join => [
    'left outer join company on book.company_id = company.id',
    'left outer join location on company.location_id = location.id'
  ]
);

select company.location_id as location_id
from book
  left outer join company on book.company_id = company.id
where company.name = ?;

table

table => 'book'

表名斥扛。

where

# (1) Hash reference
where => {author => 'Ken', 'title' => ['Perl', 'Ruby']}
# -> where author = 'Ken' and title in ('Perl', 'Ruby')

# (2) DBIx::Custom::Where object
where => $dbi->where(
  clause => ['and', ':author{=}', ':title{like}'],
  param  => {author => 'Ken', title => '%Perl%'}
)
# -> where author = 'Ken' and title like '%Perl%'

# (3) Array reference[Array refenrece, Hash reference]
where => [
  ['and', ':author{=}', ':title{like}'],
  {author => 'Ken', title => '%Perl%'}
]
# -> where author = 'Ken' and title like '%Perl%'

# (4) Array reference[String, Hash reference]
where => [
  ':author{=} and :title{like}',
  {author => 'Ken', title => '%Perl%'}
]
#  -> where author = 'Ken' and title like '%Perl%'

# (5) String
where => 'title is null'
#  -> where title is null

where子句。更詳細的內(nèi)容可以參數(shù)DBIx::Custom::Where模塊的文檔丹锹。

type_rule

$dbi->type_rule(
  into1 => {
    date => sub { ... },
    datetime => sub { ... }
  },
  into2 => {
    date => sub { ... },
    datetime => sub { ... }
  },
  from1 => {
    # DATE
    9 => sub { ... },
    # DATETIME or TIMESTAMP
    11 => sub { ... },
  }
  from2 => {
    # DATE
    9 => sub { ... },
    # DATETIME or TIMESTAMP
    11 => sub { ... },
  }
);

此方法可以設(shè)置一些回調(diào)函數(shù)稀颁,用于在數(shù)據(jù)保存到數(shù)據(jù)(into)或從數(shù)據(jù)庫中獲取(from)時楣黍,根據(jù)數(shù)據(jù)類型對數(shù)據(jù)進行過濾匾灶。

在into1和into2中你可以指定與create table時一樣的類型名,如:DATA 或 DATATIME租漂。需要注意的是阶女,在這里類型名必須要全是小寫字母颊糜。into2中回調(diào)的執(zhí)行在into1之后。

你可以使用available_typename方法獲取在你當前數(shù)據(jù)庫中可用的數(shù)據(jù)類型名稱秃踩。

print $dbi->available_typename;

在from1和from2中指定數(shù)據(jù)類型不能使用類型名衬鱼,而是使用以數(shù)字表示的類型。from2中的回調(diào)會在from1之后執(zhí)行憔杨。

你可以使用available_datatype獲取你當前數(shù)據(jù)庫所有可用的數(shù)據(jù)類型。

你還可以一次為多個類型指定過濾器回調(diào)抛蚤。

$dbi->type_rule(
  into1 => [
    [qw/DATE DATETIME/] => sub { ... },
  ],
);

update

$dbi->update({title => 'Perl'}, table  => 'book', where  => {id => 4});

執(zhí)行更新語句霉颠。第一個參數(shù)的類型是hashref,表示要更新的數(shù)據(jù)怀读。

如果數(shù)據(jù)項的值為常量值菜枷,則需要使用標題引用作為參數(shù)啤誊。

{date => \"NOW()"}

update方法支持execute方法中的所有參數(shù)選項蚊锹,同時你還可以使用以下參數(shù)選項稚瘾。

prefix

 prefix => 'or replace'

表名前面的前綴

update or replace book

table

table => 'book'

表名丢烘。

where

與select方法中的where選項相同播瞳。

warp

wrap => {price => sub { "max($_[0])" }}

占位符包裝器赢乓。

$dbi->update({price => 100}, table => 'book', {price => sub { "$_[0] + 5" }});

update book set price =  ? + 5;

mtime

mtime => 'modified_time'

用于指定表中記錄“更新時間”的列骏全。默認時間格式為“YYYY-mm-dd HH:MM:SS”姜贡,可以通過now屬性進行修改楼咳。

update_all

$dbi->update_all({title => 'Perl'}, table => 'book', );

為表中的所有記錄執(zhí)行update操作母怜,參數(shù)選項與update方法相同苹熏。

sub update_all { shift->update(@_, allow_update_all => 1) };

show_datatype

$dbi->show_datatype($table);

顯示指定表所有列的數(shù)據(jù)類型轨域。

book
title: 5
issue_date: 91

此數(shù)據(jù)類型可以用于type_rule中的from1和from2中朱巨。

show_tables

$dbi->show_tables;

顯示當前數(shù)據(jù)庫中的所有表冀续。

show_typename

$dbi->show_typename($table);

顯示指定表所有列的類型名稱洪唐。

book
title: varchar
issue_date: date

此數(shù)據(jù)類型的名稱可以用于type_rule中的into1和into2中桐罕。

values_clause

my $values_clause = $dbi->values_clause({title => 'a', age => 2});

創(chuàng)建值子句功炮。

(title, author) values (title = :title, age = :age);

你可以在插入語句中使用它薪伏。

my $insert_sql = "insert into book $values_clause";

where

my $where = $dbi->where;
$where->clause(['and', 'title = :title', 'author = :author']);
$where->param({title => 'Perl', author => 'Ken'});
$where->join(['left join author on book.author = author.id]);

創(chuàng)建一個新的DBIx::Custom::Where對象嫁怀。

create_result EXPERIMENTAL

my $result = $dbi->create_result($sth);

創(chuàng)建一個DBIx::Custom::Result對象。

a

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末萝招,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子捌治,更是在濱河造成了極大的恐慌兼吓,老刑警劉巖视搏,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件凶朗,死亡現(xiàn)場離奇詭異,居然都是意外死亡杂数,警方通過查閱死者的電腦和手機揍移,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來罕邀,“玉大人诉探,你說我怎么就攤上這事肾胯。” “怎么了毕荐?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵憎亚,是天一觀的道長虽填。 經(jīng)常有香客問我斋日,道長恶守,這世上最難降的妖魔是什么兔港? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任衫樊,我火速辦了婚禮科侈,結(jié)果婚禮上臀栈,老公的妹妹穿的比我還像新娘权薯。我一直安慰自己盟蚣,他們只是感情好刁俭,可當我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布牍戚。 她就那樣靜靜地躺著如孝,像睡著了一般第晰。 火紅的嫁衣襯著肌膚如雪茁瘦。 梳的紋絲不亂的頭發(fā)上甜熔,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天盆昙,我揣著相機與錄音淡喜,去河邊找鬼炼团。 笑死瘟芝,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的颈抚。 我是一名探鬼主播贩汉,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼褐鸥,長吁一口氣:“原來是場噩夢啊……” “哼赐稽!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起晰绎,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤伶选,失蹤者是張志新(化名)和其女友劉穎仰税,沒想到半個月后陨簇,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡葵姥,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了削咆。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拨齐。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡瞻惋,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出享怀,到底是詐尸還是另有隱情梅屉,我是刑警寧澤,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站凿滤,受9級特大地震影響庶近,放射性物質(zhì)發(fā)生泄漏反番。R本人自食惡果不足惜罢缸,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望敷鸦。 院中可真熱鬧值依,春花似錦碟案、人聲如沸辆亏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽唁情。三九已至疑苔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間甸鸟,已是汗流浹背惦费。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工兵迅, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人薪贫。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓瞧省,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子置森,可洞房花燭夜當晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容