Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Dynamic SQL

by TGI (Parson)
on Apr 07, 2015 at 02:25 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1122652]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-03-29 12:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found