多年来,我注意到Perl脚本中的SQL查询存在一些问题:
假设我有以下表格:
PET PET_TYPE COLOR
======== ========== ============
PET_ID PET_TYPE COLOR_ID
Name Description Description
Owner
PET_TYPE
COLOR_ID
并且,我想找到所有的红狗,我将不得不产生以下SQL查询。
FIND PET_ID, Name, Owner
FROM PET, PET_TYPE, COLOR
WHERE COLOR_ID.Description = 'RED'
AND PET_TYPE.Description = 'DOG'
AND PET.COLOR_ID = COLOR.COLOR_ID
AND PET.PET_TYPE = PET_TYPE.PET_TYPE
我想要一个简化生成查询的Perl模块。允许我创建数据库连接的东西,然后预定义表的链接方式。完成后,所有开发人员必须做的是简化查询。
我想像这样的界面:
#
# Create a new Database Connection
#
my $db = Some:Module->new(\%options);
#
# Now describe how these tables relate to each other.
# It should be possible to reuse this information for
# multiple queries. Maybe even make this a subroutine
# or company wide Perl module that will do this for
# the developer.
#
$db->link_tables (
PET => "COLOR_ID",
COLOR => "COLOR_ID
);
$db->link_tables (
PET => "PET_TYPE",
PET_TYPE => "PET_TYPE",
);
#
# Now that you've created a link to the database,
# and you've describe how the tables relate to
# each other, let's create a query. I'm not 100%
# sure of the interface, but it'll be something
# like this. There might be multiple `query`
# statements.
#
my $query = $db->query (
PET_TYPE => "Description = DOG",
COLOR => "Description = RED"
);
#
# Now, execute this query
#
$db->execute_query;
while (%row = $db->fetch) {
say "Dog's name is $row{Pet.Name}";
say "The owner is $row{Pet.Owner}";
}
#
# Let's find all cats named Wiskers.
# We've already described the links,
# so that doesn't have to be redone.
#
my $query = $db->query (
PET_TYPE => "Description = CAT",
PET => "Name = Wiskers"
);
我知道我的描述不完整,无论完成模块如何,都必须有一些紧急逃生舱,您可以在其中执行原始SQL查询。然而,我们的想法是将程序集中在你想要的东西上(我想要红狗或猫叫胡须)而不是各种领域,并花费大部分 Where 子句来描述表之间的链接。这样可以更容易编程并更容易理解该程序。
如果没有这样的模块,我会生产一个。但是,在花费几周时间之前,我想确保我不会复制任何工作。
答案 0 :(得分:7)
我认为你要找的是一个ORM,而且还有很多。虽然不完全是你所描述的,但它在功能方面非常接近。看看Class :: DBI和DBIx :: Class,或只是google for perl ORM。
答案 1 :(得分:2)
有很多模块:Class :: DBI,Rose :: DB,DBIx :: Class。虽然DBIx :: Class功能更强大且更新,但Class :: DBI更易于使用。稍后,如果你想切换到DBIx :: Class,你可以不费吹灰之力就这样做。