Skip to content

Instantly share code, notes, and snippets.

@robertmclaws
Created January 31, 2014 17:44
Show Gist options
  • Save robertmclaws/8738432 to your computer and use it in GitHub Desktop.
Save robertmclaws/8738432 to your computer and use it in GitHub Desktop.
Example of outputting the Mobile Services query object to SQL for use in custom queries.
function read(query, user, request) {
query.toSql = function() {
var result = "";
var queryComponents = query.getComponents();
//RWM: Reflection component for getting the sort order.
if (queryComponents.ordering != null) {
queryComponents.ordering.getProperties = function() {
var properties = [];
for (var prop in this) {
if (typeof this[prop] != 'function') {
properties.push(prop);
}
}
return properties;
};
}
if (queryComponents.filters != null && queryComponents.filters.queryString != null) {
var queryString = queryComponents.filters.queryString
.replace(/ eq /g, " = ")
.replace(/ lt /g, " < ")
.replace(/ gt /g, " > ")
.replace(/L\)/g, ")")
.replace(/ true/g, " 1")
.replace(/ false/g, "0");
result += queryString;
}
//console.log(result);
if (queryComponents.ordering != null) {
result += " ORDER BY " + queryComponents.ordering.getProperties().join(',') + " DESC";
//TODO: Add support for ascending sorts.
}
//console.log(result);
return result;
}
var sqlQuery = "SELECT * FROM [yourMobileServicesName].[yourTable] WHERE ";
//RWM: example of server-side manipulation instead of using the query object.
if (user.level != "admin")
{
sqlQuery += "[is_published] = 1 AND ";
}
sqlQuery += query.toSql();
console.log(sqlQuery);
mssql.query(sqlQuery, {
success: function(results) {
request.respond(200, results);
},
error: function(err) {
console.log("table.read Error: " + err);
request.respond(500);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment