Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1122652]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (10)
As of 2018-07-16 18:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (346 votes). Check out past polls.

    Notices?