I'm designing a fun little web app and one of the challenges I've run in to was abstracting away the sql. My reasons to do so is two fold. The first is that I wish to be as database agnostic as I possibly can and the best way to achieve this seems to me to abstract out the sql, the actual part that interfaces with the database, in to a small class I could just swap in an out, for example: User_data_mysql and User_data_postgre and User_data_flatfiles. My second reason is just one of elegance.. it always seemed inelegant and messy to have random bits of sql strewn around.
After pondering it for a while, I've come up with two ideas. My first idea is that I could write database accessing functions in the form of one for each table for each type of database. Eg I would have a function like User_Data_Mysql::get_data; and I could pass it things like:
get_data(['name','id','pw'],{order_by=>'id'}); but the problem there is that writing a function like that quickly becomes horrendously complicated to the point where it feels like I just rewrote sql, except in perl and much uglier. I suppose with proper planning this function wouldn't be too grotesque but I basically feel that
$sql="select foo,baz,bar from qux where foo=1 and baz=2 order by bar limit 0,20" is much cleaner then say,
qux::get_data([qw/foo baz bar/],order=>{foo=>1},limit=>[0,20]);
My second option seems to me to just write all sql I would need and store them in functions, eg:
sub get_user_data_by_id; sub get_user_data_by_name; sub get_user_data_by_date; and so on and so forth. I could just wrap these functions in a module with whatever database they apply to and just do
mysql::get_user_data_by_name; but of course this is A) massively inelegant and B) seems terribly fragile and just plain ugly.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.