So I am in the process of converting a node app into Elixir and have some queries that I would like to use Ecto for but I haven't found a way that works and would like to refrain from concatenating strings and arguments if possible.
I have about 10 queries that are chained within a transaction that look somewhat like this:
INSERT INTO user_servers(user_id, server_id, server_type_code, position, active_flag, create_date, created_by)
SELECT ?, ?, 'SERVER', (COALESCE(MAX(position), 0) + 1), 'Y', CURRENT_TIMESTAMP, ?
FROM user_servers WHERE server_type_code = 'SERVER' and user_id = ?;
This is within a transaction.
So my first question is, as I am really struggling figuring out the right combination in ecto to do just this query.
How can I do an INSERT with a SELECT clause in Ecto and be able to replace the question marks with hardcoded items.
I am using snowflake to create ID's so will create those ids server-side and send them through.
My next question is, how can I use Repo.transaction with multi.new with Raw SQL.
I believe you will want to use the raw query/4
API. This will allow you to write a custom query and have the benefit of not needing to escape your input. Something like the following should work.
raw_query = "INSERT INTO user_servers(user_id, server_id, server_type_code, position, active_flag, create_date, created_by)
SELECT $1, $2, 'SERVER', (COALESCE(MAX(position), 0) + 1), 'Y', CURRENT_TIMESTAMP, $3
FROM user_servers WHERE server_type_code = 'SERVER' and user_id = $4;"
Ecto.Adapters.SQL.query(MyRepo, raw_query, [value1, value2, value3, value4])
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.