用于简化SQL查询的Perl模块

Dav*_* W. 2 sql-server perl dbi

多年来,我注意到Perl脚本中的SQL查询存在一些问题:

  • 他们很难读
  • 大多数开发人员对SQL并不是那么好.

假设我有以下表格:

PET          PET_TYPE     COLOR
========     ==========   ============
PET_ID       PET_TYPE     COLOR_ID
Name         Description  Description
Owner
PET_TYPE
COLOR_ID
Run Code Online (Sandbox Code Playgroud)

而且,我想找到所有的红狗,我将不得不产生以下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
Run Code Online (Sandbox Code Playgroud)

我想要一个简化生成查询的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"
  );
Run Code Online (Sandbox Code Playgroud)

我知道我的描述是不完整的,无论模块有多完整,都必须有一些紧急逃生舱,你可以在那里进行原始的SQL查询.然而,我们的想法是将程序集中在你想要的东西上(我想要红狗或猫叫胡须)而不是各种领域,并花费大部分的Where子句来描述表之间的联系.这样可以更容易编程并更容易理解程序.

如果没有这样的模块,我会生产一个.但是,在花费几周时间之前,我想确保我不会复制任何工作.

小智 7

我认为你要找的是ORM,而且还有很多.虽然不完全是你所描述的,但它在功能方面非常接近.看看Class :: DBI和DBIx :: Class,或只是google for perl ORMs.