Parameterized queries in ArcGIS JavaScript API

Viewed 166

I am trying to build a where clause for an ArcGIS layer query in the ArcGIS JavaScript API. All the examples I can find (including in where documentation) encourage you to do things like this:

query.where = "NAME = '" + stateName + "'";

I find this surprising, because it seems like we are encouraged to write code that's susceptible to SQL injection bugs. This is especially important to me because my "stateName" is entirely not in my control. It's raw user input.

It looks like the library supports query parameterization via the parameterValues property, however I can find no examples on how to use it, or how to format my query so that it uses parameter values. Not even the documentation contains any examples.

So how do we create properly parameterized queries?

Side note: I recognize it's probably the server administrator's job to prevent bad queries from causing harm, however half the reason I'm asking this is also purely to avoid bugs and improperly parsed queries.

1 Answers

According to ESRI, the parameterValues property is only for using Query Layers. It's not for this context.

So the answer is, no, you can't use proper SQL parameterization when you're simply running a query on a layer.

The best way I have found to make your queries at least a little bit more bulletproof is to use code like this:

function sanitizeParameter(value) {
    // We need to escape single quotes to avoid messing up SQL syntax.
    // So all ' characters need to become ''
    return value.split("'").join("''")
}

query.where = "NAME = '" + sanitizeParameter(stateName) + "'";
Related