SQLStrings.jl icon indicating copy to clipboard operation
SQLStrings.jl copied to clipboard

Selecting table as an argument

Open davibarreira opened this issue 4 years ago • 4 comments

Hey, this package is great. I'm just having one issue with trying to pass the table as an argument, e.g.

table = "foo"
runquery(conn, sql`CREATE TABLE $table (email text, userid integer)`)

Where the runquery is the one in the README.

Now, the code above does not work. I presume that the issue is that the argument foo is passed to the query as a string or something. Any way around this?

davibarreira avatar Jun 14 '22 14:06 davibarreira

I am having the same issue here. Would be nice if we could still somehow have regular string substitutions for these situations

fchorney avatar Oct 04 '22 21:10 fchorney

Oh, actually I think I've solved it. Looks like there is a Literal object you can create (https://github.com/JuliaComputing/SQLStrings.jl/blob/main/src/SQLStrings.jl#L6)

So for instance you can do

function foo(conn::Connection, table::String)
    table_literal = SQLStrings.Literal(table)
    query = sql`SELECT * FROM $table_literal`
    execute(conn, query)
end

foo(conn, "db_table")

In this case sql`SELECT * FROM $table_literal` ends up becoming SELECT * FROM db_table

fchorney avatar Oct 04 '22 21:10 fchorney

Using Literal should be fine, as long as table is never passed in from the user. (If it is passed in from the user, you're vulnerable to all the SQL injection attacks which SQLStrings is designed to prevent. Unless you escape all the possible naughty strings according to your SQL engine's escaping rules :)

c42f avatar Oct 14 '24 10:10 c42f

(Hi btw! I don't have the bandwidth to maintain this package anymore, as you might be able to tell 😅 But I just happened to come past and see this.)

c42f avatar Oct 14 '24 10:10 c42f