DBIx::Custom

簡(jiǎn)介

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是一個(gè)DBI的包裝器,此模塊具有以下功能:

  1. 可以更容易的執(zhí)行insert、update、deleted和select語(yǔ)句。
  2. 可以非常靈活的創(chuàng)建where子句
  3. 支持命名占位符
  4. 支持連接管理,透明的數(shù)據(jù)庫(kù)連接池管理。
  5. 支持很多關(guān)系型數(shù)據(jù)庫(kù):MySQL、SQLite、PostgreSQL、Oracle、Microsoft SQL Server、Microsoft Access、DB2和其他。
  6. 可以根據(jù)數(shù)據(jù)類型和列名進(jìn)行過(guò)濾。
  7. 非常靈活的支持order by 子句的創(chuàng)建。

屬性

connector

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

連接管理器對(duì)象,如果設(shè)置了一個(gè)連接管理器對(duì)象,你可以通過(guò)它的dbh方法獲取一個(gè)數(shù)據(jù)庫(kù)連接。所以連接管理器對(duì)象必須有一個(gè)dbh方法。

下面是一個(gè)使用DBIx::Connector作為DBIx::Custom的連接管理器對(duì)象的例子:

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方法時(shí),其屬性connector的值為1,則DBIx::Custom將默認(rèn)使用DBIx::Connector創(chuàng)建一個(gè)連接管理器并為屬性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方法時(shí)使用。dsn支持很多種格式,具體內(nèi)容可以查閱DBI模塊的文檔獲取。

default_option

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

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

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

exclude_table

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

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

filters

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

過(guò)濾器,可以通過(guò)方法register_filter注冊(cè)。

last_sql

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

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

now

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

返回當(dāng)前時(shí)間的代碼引用,默認(rèn)為以下代碼的引用:

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

通過(guò)會(huì)返回一個(gè)表示時(shí)間的字符串:2011-10-14 05:05:27。給insert方法的ctime、mtime選項(xiàng)以及update方法的mtime選項(xiàng)使用。

models

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

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

mytable_sysmbol

在“select”方法的column 選項(xiàng)中指定要查詢自己列的符號(hào),默認(rèn)為“MY”。

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

option

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

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

password

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

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

quote

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

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

你可以為此屬性設(shè)計(jì)一對(duì)符號(hào)。

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

result_class

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

結(jié)果類,對(duì)查詢結(jié)果進(jìn)行包裝的類。默認(rèn)為:DBIx::Custom::Result。

safety_character

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

表名和列名中安全字符的正則表達(dá)式,默認(rèn)為“a-zA-Z_”。無(wú)需像“[a-zA-Z_]”指定。

separator

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

連接表名和列名的分隔符。這會(huì)用在mycolumn和column方法中,在select方法的column選項(xiàng)中也會(huì)用到。默認(rèn)值為.。

user

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

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

user_column_info

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

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

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

通常你可以使用get_column_info方法的返回值進(jìn)行設(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方法會(huì)使用user_column_info屬性去查找column信息,這樣做相對(duì)來(lái)說(shuō)速度上有一點(diǎn)的優(yōu)勢(shì)。

user_table_info

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

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

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

通常你可以使用get_table_info方法的返回值進(jìn)行設(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方法會(huì)使用user_table_info屬性去查找table信息,這樣做相對(duì)來(lái)說(shuō)速度上有一點(diǎn)的優(yōu)勢(shì)。

方法

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

available_datatype

print $dbi->available_datatype;

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

available_typename

print $dbi->available_typename;

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

assign_clause

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

對(duì)sql語(yǔ)句中的變量進(jìn)行數(shù)值綁定。用于在執(zhí)行更新或插入操作時(shí)創(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語(yǔ)句。

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

您可以通過(guò)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ù)庫(kù),并創(chuàng)建一個(gè)新的DBIx::Custom對(duì)象。DBIx::Custom是對(duì)DBI模塊的封裝,并且默認(rèn)情況下在創(chuàng)建連接時(shí)參數(shù)option中的AutoCommit和RaiseError兩個(gè)屬性的值是true,而PrintError屬性的值為假。(這在上面屬性小節(jié)的default_option中已經(jīng)介紹過(guò)了)

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)建一個(gè)DBIx::Custom::Model對(duì)象并初始化,對(duì)象中的列屬性是自動(dòng)設(shè)置的。您可以使用后面將要介紹的model方法使用已經(jīng)創(chuàng)建的DBIx::Custom::Model對(duì)象。

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

你可以使用與表名不同的標(biāo)識(shí)符作為DBIx::Custom::Model對(duì)象的名稱。

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

dbh

my $dbh = $dbi->dbh;

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

delete

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

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

所有對(duì)execute方法可用的參數(shù)選項(xiàng),對(duì)于delete函數(shù)都可用,并且含意完全相同。除此之外delete方法還以下參數(shù)選項(xiàng)。

prefix

prefix => 'some'

前綴,指明從哪些表中刪除數(shù)據(jù)。當(dāng)from子句中有多個(gè)表名時(shí)需要用到它。

delete some from book

table

table => 'book'

表名。對(duì)哪張表執(zhí)行DELETE操作。

where

與select方法的where選項(xiàng)相同,指明本次DELETE操作的條件。對(duì)需要?jiǎng)h除的記錄進(jìn)行過(guò)濾。

delete_all

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

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

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

其實(shí)當(dāng)我們調(diào)用delete函數(shù)時(shí),如果沒(méi)有傳where和id參數(shù)并且沒(méi)有指定allow_delete_all 為true的話,是會(huì)報(bào)錯(cuò)的。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ù)庫(kù)中的所有列信息,參數(shù)是一個(gè)回調(diào)函數(shù)?;卣{(diào)函數(shù)需要接收四個(gè)參數(shù):DBIx::Custom對(duì)象、table_name(表名)、column_name(列名)和column_info(列信息)。針對(duì)數(shù)據(jù)庫(kù)中的每一個(gè)數(shù)據(jù)列會(huì)調(diào)用一次回調(diào)函數(shù)。

如果user_column_info屬性已經(jīng)設(shè)置,each_column方法會(huì)使用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ù)是一個(gè)回調(diào)函數(shù)。回調(diào)函數(shù)接收三個(gè)參數(shù):DBIx::Custom對(duì)象、table_name(表名)和table_info(表信息)。針對(duì)數(shù)據(jù)庫(kù)中的每個(gè)一個(gè)表調(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語(yǔ)句。SQL語(yǔ)句中可以包含“命名占位符”(:author和:title)。你也可以將表名加入到“命名占位符”中(:book.author和:book.title)。第二個(gè)參數(shù)是一個(gè)hashref,其中包含需要綁定到“命名占位符”中的數(shù)據(jù)。當(dāng)執(zhí)行select語(yǔ)句時(shí)返回值是DBIx::Custom::Result對(duì)象,當(dāng)執(zhí)行的是insert、update、delete語(yǔ)句時(shí)返回值是受影響的行數(shù)。

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

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

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

您還可以通過(guò) name{operator}語(yǔ)法指定具有指定“運(yùn)算符”的“命名點(diǎn)位符”。

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

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

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

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

execute方法可接收的參數(shù):第一個(gè)參數(shù)必須為SQL語(yǔ)句;第二個(gè)參數(shù)(為占位符綁定的數(shù)據(jù))是可選的;再往后是一個(gè)元素?cái)?shù)為偶數(shù)的列表作為第三個(gè)參數(shù)(一系列鍵值對(duì)),叫OPTION。OPTION支持的屬性會(huì)在接下來(lái)分小節(jié)介紹。

after_build_sql

這個(gè)屬性的值需要是一個(gè)coderef類型的回調(diào),它用于對(duì)生成的sql進(jìn)行過(guò)濾。

after_build_sql => $code_ref

下面是一個(gè)例子

$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語(yǔ)句之后追加一些語(yǔ)句。

bind_type

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

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

這用于通過(guò)數(shù)據(jù)庫(kù)連接句柄dbh的bind_param方法對(duì)SQL語(yǔ)句進(jìn)行綁定參數(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] }
]

過(guò)濾。你可以通過(guò)這個(gè)參數(shù)為column的值綁定一個(gè)過(guò)濾器。過(guò)濾器可以是一個(gè)subroutine也可以是一個(gè)通過(guò)register_filter方法注冊(cè)的過(guò)濾器的名稱。過(guò)濾器會(huì)在數(shù)據(jù)保存到數(shù)據(jù)庫(kù)之前、且在執(zhí)行類型過(guò)濾(type_rule)之前執(zhí)行。

reuse

reuse => $hash_ref

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

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

當(dāng)您想要重復(fù)執(zhí)行相同的查詢操作時(shí),這樣做可以提高性能,因?yàn)橥ǔ?chuàng)建查詢對(duì)象速度會(huì)很慢。

table

table => 'author'

如果在列名中省略了表名,并且啟用了into1和into2過(guò)濾器,則必須設(shè)置table選項(xiàng)。

$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í)表名。在你設(shè)定表別名后,你可以在type_rule的into1和into2上使用表別名。

type_rule_of

type_rule_off => 1

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

type_rule1_of

type_rule1_off => 1

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

type_rule2_of

type_rule2_off => 1

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

prepare_attr EXPERIMENTAL

prepare_attr => {mysql_use_result => 1}

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

query EXPERIMENTAL

query => 1

如果你僅僅是為了獲取SQL信息,而不是為了執(zhí)行SQL語(yǔ)句??梢栽O(shè)置這個(gè)選項(xiàng),這時(shí)execute方法會(huì)返回一個(gè)DBIx::Custom::Query對(duì)象。

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

DBIx::Custom::Query對(duì)象具有以下信息

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

您可以通過(guò)以下方式獲取綁定值和類型。

# 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;

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

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

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

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

get_column_info

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

用于獲取數(shù)據(jù)庫(kù)中數(shù)據(jù)列的信息,參數(shù)exclude_table的值是一個(gè)正則表達(dá)式,用于排除與之相匹配的表。返回值結(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ù)庫(kù)中數(shù)據(jù)表的信息,參數(shù)exclude_table的值是一個(gè)正則表達(dá)式,用于排除與之相匹配的表。返回值結(jié)構(gòu)如下:

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

insert

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

向一個(gè)數(shù)據(jù)表中插入數(shù)據(jù),第一個(gè)參數(shù)是需要插入的數(shù)據(jù),可以是一個(gè)hashref(只插入一條記錄時(shí)),也可以是一個(gè)元素為hashref的arrayref(插入多條數(shù)據(jù)時(shí))。返回值是受影響的行數(shù)。如果數(shù)據(jù)項(xiàng)的值為常量值,則需要使用標(biāo)題引用作為參數(shù)。

{date => \"NOW()"}

注:在插入多條記錄時(shí),你不能使用id選項(xiàng)。

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

bulk_insert

bulk_insert => 1

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

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

ctime

ctime => 'created_time'

表中記錄“創(chuàng)建時(shí)間”的列。默認(rèn)時(shí)間格式為“YYYY-mm-dd HH:MM:SS”,可以通過(guò)now屬性進(jìn)行修改。

prefix

prefix => 'or replace'

表名前面的前綴。

insert or replace into book

table

table => 'book'

表名。

mtime

該選項(xiàng)與update方法mtime選項(xiàng)相同。用于指定表中記錄“更新時(shí)間”的列。默認(rèn)時(shí)間格式為“YYYY-mm-dd HH:MM:SS”,可以通過(guò)now屬性進(jìn)行修改。

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對(duì)象,需要如下的包結(jié)構(gòu)。

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

名稱空間的模塊必須是DBIx::Custom::Model的子類。請(qǐng)參閱DBIx::Custom::Model來(lái)了解更多信息。

like_value

my $like_value = $dbi->like_value

返回一個(gè)可以包值包裝成like value格式的代碼引用。

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

mapper

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

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

merge_param

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

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

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

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

model

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

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

mycolumn

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

創(chuàng)建列子句,如上代碼會(huì)創(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)建一個(gè)新的DBIx::Custom對(duì)象。

not_exists

my $not_exists = $dbi->not_exists;

返回一個(gè)DBIx::Custom::NotExists對(duì)象,表示當(dāng)前列不存在。這個(gè)方法僅用于DBIx::Custom::Where對(duì)象中的param方法中。

order

my $order = $dbi->order;

創(chuàng)建一個(gè)DBIx::Custom::Order對(duì)象。

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');
  }
);

注冊(cè)過(guò)濾器,給某些方法參數(shù)中的filter選項(xiàng)使用。

select

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

執(zhí)行select語(yǔ)句。你可以傳遞奇數(shù)個(gè)參數(shù)。第一個(gè)參數(shù)是column,后面的所有參數(shù)共同組成了OPTION。

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

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

column

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

指定列子句,如果沒(méi)有指定column,則默認(rèn)為*。

column => '*'

你還可以用一個(gè)元素為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"

你可以通過(guò) __MY__指定那些屬于當(dāng)前表的列。

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

__MY__可以通過(guò)mytable_symbol屬性來(lái)改變。

param

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

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

如果你要在join子句中指定“命名占位符”,則可以通過(guò)參param選項(xiàng)傳遞綁定參數(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這樣的表名,則自動(dòng)使用創(chuàng)建SQL時(shí)所需的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子句。更詳細(xì)的內(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ù)庫(kù)中獲?。╢rom)時(shí),根據(jù)數(shù)據(jù)類型對(duì)數(shù)據(jù)進(jìn)行過(guò)濾。

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

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

print $dbi->available_typename;

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

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

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

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

update

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

執(zhí)行更新語(yǔ)句。第一個(gè)參數(shù)的類型是hashref,表示要更新的數(shù)據(jù)。

如果數(shù)據(jù)項(xiàng)的值為常量值,則需要使用標(biāo)題引用作為參數(shù)。

{date => \"NOW()"}

update方法支持execute方法中的所有參數(shù)選項(xiàng),同時(shí)你還可以使用以下參數(shù)選項(xiàng)。

prefix

 prefix => 'or replace'

表名前面的前綴

update or replace book

table

table => 'book'

表名。

where

與select方法中的where選項(xiàng)相同。

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'

用于指定表中記錄“更新時(shí)間”的列。默認(rèn)時(shí)間格式為“YYYY-mm-dd HH:MM:SS”,可以通過(guò)now屬性進(jìn)行修改。

update_all

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

為表中的所有記錄執(zhí)行update操作,參數(shù)選項(xiàng)與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;

顯示當(dāng)前數(shù)據(jù)庫(kù)中的所有表。

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);

你可以在插入語(yǔ)句中使用它。

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)建一個(gè)新的DBIx::Custom::Where對(duì)象。

create_result EXPERIMENTAL

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

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

a

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容