简体   繁体   中英

Knex JS escape ilike special characters with url string bindings

I'm trying to use ilike in a knex js query (node/postgres) to find domains with matching hosts and path names but different prefixes ( www.site.com and m.site.com would both come up in this query). I am able to type out the full string and get a response but not when I pass a variable/binding.

Works:

knex("table")
.select()
.whereRaw("column_name ilike '%domain.com/path-string-here/%'")

Does not work:

const url = 'domain.com/path-string-here/';

knex("table")
.select()
.whereRaw(`column_name ilike '%${url}%'`)

The SQL comes out the same on my console but the second query returns an empty array. I know there I need to escape the special characters in some way since I'm using template literals but nothing I'm finding is matching up with my exact scenario.

I have also tried doing the whole query in knex.raw and playing around with whereIn and whereILike but I get the same results (or worse errors).

EDIT: I also tried variations of knex.where('column_name', 'ilike', url) with the same results -- empty return.

From what I can tell, you're passing parameters directly into SQL. Do not do that. Raw is meant to be used when you need more control and non-standard features like ilike and you're correct on using it here. But there's a better way, since knex actually supports ilike .

However column_name ilike '%${url}%' is asking for a trouble ( sqli ), you should do it like this, utilising parameter binding:

    const concatDomain = db.raw(`concat('%', ?::text, '%')`, domain)

    return db('table')
        .select()
        .where('name', 'ilike', concatDomain)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM