多年来,我注意到有SQL查询的几个问题在Perl脚本: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查询。然而,这个想法是把程序集中在你想要的东西上(我想要红色的狗或者叫做胡须的猫)而不是各个领域,并花费大部分的子句来描述表之间的链接。这将使编程变得更容易,并且更容易理解该程序。
如果没有这样的模块做到这一点,我会产生一个。但是,在花费数周时间之前,我想确保我没有复制任何工作。
尝试通过https://www.google.com/search?q=Perl+ORM;看看是否有什么捕捉你的幻想。 – ruakh