0

I'm using Ecto.Adapters.SQL.query

query = " select id from $1 where id = $2 "
Ecto.Adapters.SQL.query!(Repo, query, [table, id])

But the adapter not replace my table as parameter

[debug] QUERY ERROR db=0.5ms
 select id from $1 where sysid = $2  ["activities", "469601326"]
[info] Application dgtidx exited: Docomo.Application.start(:normal, []) returned an error: shutdown: failed to start child: Docomo.Consumer
    ** (EXIT) an exception was raised:
        ** (Mariaex.Error) (1146): Table 'test.$1' doesn't exist

1 Answer 1

2

You can't use a parameter to specify the table name like that as explained here.

If you're absolutely sure table is a valid table name and not arbitrary user input, you can use string interpolation:

query = "select id from #{table} where id = $1"
Ecto.Adapters.SQL.query!(Repo, query, [id])

You must ensure table is not arbitrary user input if you do this or you'll open yourself up to SQL injection attacks.

Sign up to request clarification or add additional context in comments.

2 Comments

It's a string, i validate this value. But, are there a way to sanitize it?
I'd create a whitelist of table names and check against that: if table in ["posts", "comments"] do .... query ... else ... show error ... end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.