in reply to How do Monks programatically construct SQL selects

So am I ... working too hard?

Yep. It's understandable that you need to construct an SQL query dynamically. I had to do the same thing when search parameters were given through an XML. But since this kind of Structured information is exactly what perl is for, there are ways to make your code do more with less. The code I use:

my $db_query = 'SELECT '; $db_query .= join ', ', @select; $db_query .= ' FROM '; $db_query .= join ', ', @from; $db_query .= ' WHERE '; $db_query .= join ' AND ', @limits; $db_query .= ';'; # Not mandatory, just for good order.

The way I did this, I had XML tags stating:

Of course, your construction need are probably different, so customize happily. What I really wanted to say was use map, join, reduce, and other list functions instead of loop and concatenation.

As for modules, sometimes it's just quicker, and surely more fun (if you're not under a deadline) to do your own coding, and you always learn from it. Well, TIMTOWTDI...

PS - If you're expecting outside input throw in extra validation and taint checking code or you'll get errors from the DB or much worse.

Replies are listed 'Best First'.
Re: Re: How do Monks programatically construct SQL selects
by hardburn (Abbot) on Sep 03, 2003 at 13:40 UTC

    $db_query .= ';'; # Not mandatory, just for good order.

    Actualy not. I don't know what DBD you're using, but some databases don't like having a trailing semicolon when fed via DBI. It's generally better to leave it out.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated