friedo has asked for the wisdom of the Perl Monks concerning the following question:
I have a MySQL database which I am searching using MySQL's fulltext indexing. The search results are inserted into a table so they can be saved for later. Right now, I am constructing queries manually like so:
my $mquery = "INSERT INTO Search_Results ( search_id, page_id ) SELECT ?, P.id FROM Pages P, Documents D, Dirs DI WHERE MATCH ( P.pgdata ) AGAINST ( ? IN BOOLEAN MODE ) AND P.doc_id = D.id AND D.dir_id = DI.id ";
For the basic case, that works fine, but over time, the code to build and munge the SQL has gotten more complex, as more features are added to the interface. Users now do searches via author and date range in addition to text, they include and exclude certain subsets of documents, and so on. All of this leads to a very complex (and buggy) form handling script which must know about a plethora of form options and construct a query dynamically.
For example, here's what the query code looks like for a more complex case, when the user might be searching within an existing result set.
I got myself into this hole and now I want to climb out by rewriting the search stuff over the coming holiday. I have a few ideas for how I can handle this better.my $mquery = "INSERT INTO Search_Results ( search_id, page_id ) SELECT ?, P.id FROM Pages P, Documents D, Dirs DI "; if( $ref_sid ) { # constrain search to a previous result set. $mquery .= ", Search_Results SR "; } $mquery .= "WHERE MATCH ( P.pgdata ) AGAINST ( ? IN BOOLEAN MODE ) AND P.doc_id = D.id AND D.dir_id = DI.id "; if( $ref_sid ) { $mquery .= "AND P.id = SR.page_id AND SR.search_id = ? "; push @query_args, $ref_sid; }
I'm sure the problem of dynamically generating SQL is a common one. Any experience you can share, even if not directly related, could be helpful. Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Architecture of Constructing Complex SQL
by zby (Vicar) on Dec 22, 2005 at 08:11 UTC | |
|
Re: Architecture of Constructing Complex SQL
by beachbum (Beadle) on Dec 22, 2005 at 20:08 UTC |