Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Dynamic SQL

by TGI (Parson)
on Apr 07, 2015 at 02:25 UTC ( #1122652=note: print w/replies, xml ) Need Help??

in reply to Dynamic SQL

MidLifeXis was so kind as to recommend my module DBIx::PreQL. It's aim is to simplify the horrendous task of maintaining dynamically generated SQL.

Here's one way to handle the your particular case.

my $preql = <<'PREQL' * SELECT * Name * FROM CUST Customer SALE Sales * WHERE CUST CustID = ?customer_id? SALES SalesID = ?sales_id? PREQL my ($query, @params) = DBIx::PreQL->build_query( query => $preql, data => { sales_id => $salesid, customer_id => $custid, }, wanted => $x > 10 ? 'CUST' : 'SALES' ); my $got = $db->selectall_hashref( $query, @params );

Why do all this stuff?

  • You get the placeholders you wanted for your dynamic query.
  • This is the least sucky way I've found to build dynamic SQL. The code I maintain has tons of dynamic SQL and I spent years experimenting before I hit upon this approach.
  • You will get a good error message if you put yourself in a condition where you are expecting a customer id but one isn't available.

In fact, at $WORK, we have found it worthwhile to convert static queries to PreQL. It has helped with debugging and maintenance. Because all the placeholders are labeled, they are easier to understand. PreQL also provides useful error messages that identify missing, but expected placeholder values.

TGI says moo

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1122652]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2023-09-30 17:08 GMT
Find Nodes?
    Voting Booth?

    No recent polls found