Last active
December 14, 2015 05:48
-
-
Save Macagare/5037410 to your computer and use it in GitHub Desktop.
OpenBD: query builder in cfscript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Build query string and parameter array by using the placeholders like "__name__". | |
* It is mandatory to use sqlQuery or sqlName. Otherwise no sql will be used! | |
* | |
* @param optional string sqlQuery pass a query string to read and convert | |
* @param optional string sqlName pass the name of the global sql struct property instead of sqlQuery | |
* @param optional struct params map struct with key to replace and value to use in sql properties array | |
* @return a struct containing the processes "sql" as string and the "params" as array | |
*/ | |
struct function queryMake( string sqlQuery, string sqlName, struct params ) { | |
var sQuery = ""; | |
var paramArr = []; | |
var foundObj = ""; | |
var foundPos = 0; | |
var paramName = ""; | |
var paramFound = true; | |
var PLACE_HOLDER = " ? "; | |
if ( !structKeyExists(arguments, "sqlQuery") ) { arguments.sqlQuery = ""; } | |
if ( !structKeyExists(arguments, "sqlName") ) { arguments.sqlName = ""; } | |
if ( !structKeyExists(arguments, "params") ) { arguments.params = {}; } | |
if ( len( arguments.sqlQuery ) ) { | |
sQuery = arguments.sqlQuery; | |
} | |
if ( len( arguments.sqlName ) && structKeyExists( sql, arguments.sqlName )) { | |
sQuery = sql[arguments.sqlName]; | |
} | |
if ( len( sQuery ) ) { | |
while ( paramFound is true ) { | |
foundObj = Refind( "__[a-z]*__", sQuery, foundPos, true); | |
if ( structKeyExists(foundObj, "pos") && arrayLen(foundObj.pos) && foundObj.pos[1] gt 0 ) { // param found by pattern | |
paramName = mid( sQuery, foundObj.pos[1], foundObj.len[1] ); // extract param | |
sQuery = replace(sQuery, paramName, PLACE_HOLDER, "One"); // replace param with ? | |
paramName = replace( paramName , "_", "", "All"); // remove leading and tailing "__" | |
if ( len( paramName ) && structKeyExists( arguments.params, paramName ) ) { | |
arrayAppend(paramArr, arguments.params[paramName] ); | |
} | |
foundPos = foundObj.pos[1] + len(PLACE_HOLDER); | |
paramFound = true; | |
} else { | |
paramFound = false; | |
} | |
} | |
} | |
return { "sql":sQuery, "params":paramArr }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment