mmmrrr

mmmrrr

Executing raw SQL fails with `cannot insert multiple commands into a prepared statement`

I need to include multiple legacy migrations (written in plain SQL) in an ecto migration.
The current legacy application relies heavily on custom ENUM types in postgresql.

When I try to run the existing migrations (concatenated as a string) via execute my_combined_sql I will get the error cannot insert multiple commands into a prepared statement.

The minimal example of a failing SQL file is:

CREATE TYPE UState AS ENUM ("state1", "state2");

CREATE TABLE IF NOT EXISTS Users
  (userEmail VARCHAR(320) NOT NULL PRIMARY KEY,
  state UState NOT NULL);

Is there a way to do this with ecto, or do I need another process to apply the legacy migrations to the database?

Marked As Solved

kip

kip

ex_cldr Core Team

Now I’ve paid a little more attention… I believe the issue is that you can’t create the Enum in the same transaction as using it.

Typically what I do in this case is actually prepare two migrations: one to create the Enum and the other to create the table.

However should be perfectly ok to:

def up do
  execute "CREATE TYPE UState AS ENUM (\"state1\", \"state2\");"
  execute """
    CREATE TABLE IF NOT EXISTS Users
      (userEmail VARCHAR(320) NOT NULL PRIMARY KEY,
      state UState NOT NULL);
  """
end

Also Liked

NobbZ

NobbZ

Why a macro at all? If you had written it as a function, then there would be no noeed to quote and unquote…

def up do
  execute_sql_as_one_per_line(file_reader())
end

def execute_sql_as_one_per_line(sql_list) do
  Enum.each(sql_list, &execute/1)
end

Or even simpler, have it inline:

def up do
  Enum.each(file_reader(), &execute/1)
end
mmmrrr

mmmrrr

Great! That worked. It needed a little cleanup in the sql files in order to work, but it does now.

For anyone interested: If you have a List/Array of sql statements, you can use a simple macro like:

  defmacro execute_sql_as_one_per_line(sql) do
    quote do
      Enum.each(unquote(sql), fn statement ->
        execute(statement)
      end)
    end
  end

in your up migration:

  def up do
    sql = file_reader()

    execute_sql_as_one_per_line(sql)
  end
kip

kip

ex_cldr Core Team

By default Ecto uses prepared statements (this is like a precompiled form of the statement which is the cached so that reuse is materially faster).

There is an option prepare: :unnamed which I think goes on the Repo configuration (its a Postgrex adapter option) but I can’t recall and I’m in China this week so googling isn’t an option.

Sorry its an incomplete answer but hopefully thats enough to get you started…

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement