score:1

Accepted answer

if you want to build your own provider, you must know that it is not that easy. consider things like nested select, nested where, etc. there are great blog posts on this topic.

but you are interested in protecting your database against sql injection. so if you look at the sample code on this page and the visitconstant method, that's the place where you run into constants of value type (string, int, etc.) or iqueryable.

protection against sql injections is not complicated, you just create new sqlparameter or you call method dbproviderfactory.createparameter described here. you will need some collection to store your parameters while you are traversing the expression tree. so the modified code will look like this:

protected override expression visitconstant(constantexpression c) {
    iqueryable q = c.value as iqueryable;
    if (q != null) {
        // assume constant nodes w/ iqueryables are table references
        sb.append("select * from ");
        sb.append(q.elementtype.name);
    }
    else if (c.value == null) {
        sb.append("null");
    }
    else {
        switch (type.gettypecode(c.value.gettype())) {
            case typecode.boolean:
                param = dbprovider.createparameter();
                param.name = "@param" + paramslist.count;
                param.value = (((bool)c.value) ? 1 : 0;
                paramslist.add(param);
                sb.append(param.name);
                break;
            case typecode.string:
                param = dbprovider.createparameter();
                param.name = "@param" + paramslist.count;
                param.value = c.value; // you don't have to care about escaping or formatting
                paramslist.add(param);
                sb.append(param.name);
                break;
            ...
            case typecode.object:
                throw new notsupportedexception(string.format("the constant for '{0}' is not supported", c.value));
            default:
                sb.append(c.value);
                break;
        }
    }
    return c;
}

so while you are travesing the expression tree, you are building the sql string and collecting the sql parameters.

score:2

from the blog post it looks like iq toolkit (or the initial version of the toolkit) is not safe from sql injection attacks. but you can verify it by yourself - execute a query, capture the generated sql and see if there are parameters used.


Related Query

More Query from same tag