【发布时间】:2012-02-17 02:49:25
【问题描述】:
多年来,我注意到 Perl 脚本中的 SQL 查询存在一些问题:
- 它们很难阅读
- 大多数开发人员并不擅长使用 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 子句用于描述表之间的链接。这将使编程更容易,也更容易理解。
如果没有这样的模块可以做到这一点,我会制作一个。但是,在花费几周时间进行这项工作之前,我想确保我没有重复任何工作。
【问题讨论】:
-
尝试浏览google.com/search?q=Perl+ORM;看看有没有你喜欢的东西。
标签: sql-server perl dbi