How use Ecto.Adapters.SQL.query with MySQL

Cesar Gutierrez Source

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
elixirphoenix-frameworkecto

Answers

answered 6 days ago Dogbert #1

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.

comments powered by Disqus