I have an upsert requirement, so I need to call a postgres stored procedure or use a common table expression. I also use the pgcrypto exgtension for passwords and would like to use postgres functions (such as "crypt" to encode/decode passwords).
But I can not find a way to get Ecto to play with raw sql in part or whole, is it intended that ecto will only support the elixir dsl and not allow shelling out to raw sql when the dsl is not sufficient?
I've found that I can query via the adapter (Rocket is the name of the app)
q = Ecto.Adapters.Postgres.query(Rocket.Repo,"select * from users limit 1",[])
But not sure how to get this to the model. I'm new to elixir and it seems I should be able to use Ecto.Model.Schem.schema/3 but this fails
Rocket.User.__schema__(:load,q.rows |> List.first,0)
** (FunctionClauseError) no function clause matching in Rocket.User.__schema__/3
Ecto 2.2.8 provides
Ecto.Query.load/2
, so you can do something like this:See https://hexdocs.pm/ecto/Ecto.Repo.html#c:load/2
In addition to Ecto.Adapters.SQL.query/4, there is also Ecto.Query.API.fragment/1, which can be used to send query expressions to the database. For example, to use Postgres's array function
array_upper
, one might useEcto, at least as of version ~> 0.7 you should use:
Ecto.Adapters.SQL.query/4
Runs custom SQL query on given repo.
In case of success, it must return an :ok tuple containing a map with at least two keys:
• :num_rows - the number of rows affected • :rows - the result set as a list. nil may be returned instead of the list if the command does not yield any row as result (but still yields the number of affected rows, like a delete command without returning would)
Options
• :timeout - The time in milliseconds to wait for the call to finish, :infinity will wait indefinitely (default: 5000) • :log - When false, does not log the query
Examples
Modified solution for Ecto 2.0:
in repo.ex:
Usage:
On Ecto 2.0 (beta) with Postgres, you can use
Ecto.Adapters.SQL.query()
(current docs, 2.0-beta2 docs) to execute arbitrary SQL; in addition to a list of the rows themselves ("rows
"), it happens to return a list of column names ("columns
").In the below example, I
(You'll probably want to run the
query()
version (without the bang !) and check for{ok, res}
.)With at least ecto 4.0 you can query using the adaptor and then feed the results to Ecto.Model.schema/3: