in reply to Perl style/best practice question: how to [better] embed SQL in code ?

There are obvious constraints on what you can do with embedded SQL to make it readable. I personally would format the lines above as

my $sql = qq{ SELECT a.somedata1, } . qq{ a.somedata2, } . qq{ a.somedata3, } . qq{ [...] } . qq{ FROM table1 a, } . qq{ table2 b, } . qq{ table3 c } . qq{ WHERE a.somedata4 > ? } ; $sql .= qq{ AND a.somedata5 <= ? } . qq{ AND [...] } if some_perl_code_condition1; $sql .= qq{ AND b.somedata6 >= ? } . qq{ [...] } if some_perl_code_condition2; $sql .= qq{ ORDER BY somedata7 };

It removes a lot of the white space and all the new lines, but I'm pretty sure that my floating ; is not PBP. I'll play with field widths depending on case, but always put starting period and the closing brace at tab stops. One nice thing about this format is that mixing and matching is generally easy and safe, and changing width tends to be very fast.

Replies are listed 'Best First'.
Re^2: Perl style/best practice question: how to [better] embed SQL in code ?
by jeffa (Bishop) on Dec 16, 2008 at 18:45 UTC

    Sorry, but I think that formatting is horrible. Just horrible. Why? Because who said you have to remove white space and new lines? The idea is to not make the output pretty for the SQL engine, but to make changes to your code painless, simple and efficient. And having to concatenate like that is none of the above for me. No, I would not change the original formatting at all. I cannot possible see how leading periods and closing brace at the tab stops beats ... nothing!

    my $sql = qq/ SELECT a.somedata1, a.somedata2, a.somedata3, [...] FROM table1 a, table2 b, table3 c WHERE a.somedata4 > ? /;
    See? No periods. No braces. No nothing. Just SQL.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      The OP specifically requested removing new lines and white space for testing and logging. The format is busy, but it also sets the SQL clearly apart from the surrounding Perl.

        The format is too busy and does anything but set the SQL clearly apart from the surrounding Perl.

        If the OP needs to have the white space removed for testing and logging -- then remove it for testing and logging!

        $sql =~ s/\s+/ /g;
        I use this all the time so that I can keep my embedded SQL multi line and free of Perl while still being able to log single lines.

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)