Current section

65 Versions

Jump to

Compare versions

15 files changed
+352 additions
-136 deletions
  @@ -1,5 +1,19 @@
1 1 # Changelog for v3.x
2 2
3 + ## v3.14.0 (2026-05-19)
4 +
5 + ### Enhancements
6 +
7 + * [migrations] Allow table modifiers such as UNLOGGED tables
8 + * [migrations] Add Safe Ecto Migration guides
9 + * [mysql] Support `insert_mode: :ignore`
10 + * [postgres] Set a default timezone on `mix ecto.create`
11 + * [sandbox] Label the sandbox owner process
12 + * [sql] Allow fragment tuple sources in adapters
13 + * [sql] Allow pid repos in Ecto.Adapters.SQL.table_exists?
14 + * [sql] Accept counter option in `to_sql/4`
15 + * [sql] Support `{:unsafe_fragment, ...}` support to RETURNING clause
16 +
3 17 ## v3.13.5 (2026-03-03)
4 18
5 19 * [postgrex] Map `:restrict_violation` to `:foreign_key` constraint (required by PostgreSQL 18)
  @@ -1,8 +1,8 @@
1 1 {<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-ecto/ecto_sql">>}]}.
2 2 {<<"name">>,<<"ecto_sql">>}.
3 - {<<"version">>,<<"3.13.5">>}.
3 + {<<"version">>,<<"3.14.0">>}.
4 4 {<<"description">>,<<"SQL-based adapters for Ecto and database migrations">>}.
5 - {<<"elixir">>,<<"~> 1.14">>}.
5 + {<<"elixir">>,<<"~> 1.15">>}.
6 6 {<<"files">>,
7 7 [<<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"CHANGELOG.md">>,
8 8 <<"lib">>,<<"lib/ecto">>,<<"lib/ecto/adapter">>,
  @@ -44,17 +44,22 @@
44 44 [[{<<"name">>,<<"ecto">>},
45 45 {<<"app">>,<<"ecto">>},
46 46 {<<"optional">>,false},
47 - {<<"requirement">>,<<"~> 3.13.0">>},
47 + {<<"requirement">>,<<"~> 3.14.0">>},
48 48 {<<"repository">>,<<"hexpm">>}],
49 49 [{<<"name">>,<<"telemetry">>},
50 50 {<<"app">>,<<"telemetry">>},
51 51 {<<"optional">>,false},
52 52 {<<"requirement">>,<<"~> 0.4.0 or ~> 1.0">>},
53 53 {<<"repository">>,<<"hexpm">>}],
54 + [{<<"name">>,<<"decimal">>},
55 + {<<"app">>,<<"decimal">>},
56 + {<<"optional">>,false},
57 + {<<"requirement">>,<<"~> 3.0">>},
58 + {<<"repository">>,<<"hexpm">>}],
54 59 [{<<"name">>,<<"db_connection">>},
55 60 {<<"app">>,<<"db_connection">>},
56 61 {<<"optional">>,false},
57 - {<<"requirement">>,<<"~> 2.5 or ~> 2.4.1">>},
62 + {<<"requirement">>,<<"~> 2.9">>},
58 63 {<<"repository">>,<<"hexpm">>}],
59 64 [{<<"name">>,<<"postgrex">>},
60 65 {<<"app">>,<<"postgrex">>},
  @@ -64,7 +69,7 @@
64 69 [{<<"name">>,<<"myxql">>},
65 70 {<<"app">>,<<"myxql">>},
66 71 {<<"optional">>,true},
67 - {<<"requirement">>,<<"~> 0.7">>},
72 + {<<"requirement">>,<<"~> 0.8">>},
68 73 {<<"repository">>,<<"hexpm">>}],
69 74 [{<<"name">>,<<"tds">>},
70 75 {<<"app">>,<<"tds">>},
  @@ -103,6 +103,55 @@ defmodule Ecto.Adapters.MyXQL do
103 103 automatically commits after some commands like CREATE TABLE.
104 104 Therefore MySQL migrations does not run inside transactions.
105 105
106 + ### Insert Mode
107 +
108 + The `:insert_mode` option controls the type of INSERT statement generated.
109 + When set to `:ignore`, the adapter uses MySQL's `INSERT IGNORE`
110 + syntax:
111 +
112 + Repo.insert_all(Post, posts, insert_mode: :ignore)
113 +
114 + With `INSERT IGNORE`, MySQL silently ignores errors that would normally
115 + cause the statement to fail, such as duplicate key violations and certain
116 + type conversion errors. When a row is ignored, the affected row count
117 + will be 0 instead of 1.
118 +
119 + See [MySQL documentation](https://dev.mysql.com/doc/refman/8.4/en/insert.html) for more details.
120 +
121 + ### Upserts
122 +
123 + When using `on_conflict: :nothing`, the adapter uses the
124 + `ON DUPLICATE KEY UPDATE x = x` workaround to simulate "do nothing"
125 + behavior. This always reports 1 affected row regardless of whether
126 + the row was actually inserted or ignored.
127 +
128 + If you need accurate row counts (0 when ignored, 1 when inserted) at the expense of error handling,
129 + you can combine `on_conflict: :nothing` with [`insert_mode: :ignore`](#module-insert-mode):
130 +
131 + Repo.insert_all(Post, posts,
132 + on_conflict: :nothing,
133 + insert_mode: :ignore)
134 +
135 + When both options are used together, `INSERT IGNORE` handles the conflict
136 + resolution and the `ON DUPLICATE KEY UPDATE` clause is omitted.
137 +
138 + Examples:
139 +
140 + ```elixir
141 + Repo.insert_all(Post, posts,
142 + on_conflict: :nothing)
143 +
144 + # SQL: INSERT INTO `posts` (`title`, `uuid`) VALUES (?,?) ON DUPLICATE KEY UPDATE `id` = VALUES(`id`)
145 + ```
146 +
147 + ```elixir
148 + Repo.insert_all(Post, posts,
149 + on_conflict: :nothing,
150 + insert_mode: :ignore)
151 +
152 + # SQL: INSERT IGNORE INTO `posts` (`title`, `uuid`) VALUES (?,?)
153 + ```
154 +
106 155 ## Old MySQL versions
107 156
108 157 ### JSON support
  @@ -319,7 +368,10 @@ defmodule Ecto.Adapters.MyXQL do
319 368
320 369 key = primary_key!(schema_meta, returning)
321 370 {fields, values} = :lists.unzip(params)
322 - sql = @conn.insert(prefix, source, fields, [fields], on_conflict, [], [])
371 +
372 + # Extract insert_mode and pass it to the connection's insert function
373 + insert_opts = if opts[:insert_mode], do: [insert_mode: opts[:insert_mode]], else: []
374 + sql = @conn.insert(prefix, source, fields, [fields], on_conflict, [], [], insert_opts)
323 375
324 376 opts =
325 377 if is_nil(Keyword.get(opts, :cache_statement)) do
  @@ -330,9 +382,15 @@ defmodule Ecto.Adapters.MyXQL do
330 382
331 383 case Ecto.Adapters.SQL.query(adapter_meta, sql, values ++ query_params, opts) do
332 384 {:ok, %{num_rows: 0}} ->
333 - raise "insert operation failed to insert any row in the database. " <>
334 - "This may happen if you have trigger or other database conditions rejecting operations. " <>
335 - "The emitted SQL was: #{sql}"
385 + # With INSERT IGNORE (insert_mode: :ignore), 0 rows means the row
386 + # was ignored due to a conflict, which is expected behavior
387 + if opts[:insert_mode] == :ignore do
388 + {:ok, []}
389 + else
390 + raise "insert operation failed to insert any row in the database. " <>
391 + "This may happen if you have trigger or other database conditions rejecting operations. " <>
392 + "The emitted SQL was: #{sql}"
393 + end
336 394
337 395 # We were used to check if num_rows was 1 or 2 (in case of upserts)
338 396 # but MariaDB supports tables with System Versioning, and in those
  @@ -530,12 +588,13 @@ defmodule Ecto.Adapters.MyXQL do
530 588 args: args
531 589 ]
532 590
591 + # Trap exits in case mysql dies in the middle of execution so that we can surface the error
592 + old_trap_exit = Process.flag(:trap_exit, true)
533 593 port = Port.open({:spawn_executable, abs_cmd}, port_opts)
534 - Port.command(port, contents)
535 - # Use this as a signal to close the port since we cannot
536 - # send an exit command to mysql in batch mode
537 - Port.command(port, ";SELECT '__ECTO_EOF__';\n")
538 - collect_output(port, "")
594 + Port.command(port, [contents, ";SELECT '__ECTO_EOF__';\n"])
595 + result = collect_output(port, "")
596 + Process.flag(:trap_exit, old_trap_exit)
597 + result
539 598 end
540 599
541 600 defp args_env(opts, opt_args) do
  @@ -595,6 +654,9 @@ defmodule Ecto.Adapters.MyXQL do
595 654 collect_output(port, acc)
596 655 end
597 656
657 + {:EXIT, ^port, _reason} ->
658 + {acc, 1}
659 +
598 660 {^port, {:exit_status, status}} ->
599 661 {acc, status}
600 662 end
  @@ -179,41 +179,61 @@ if Code.ensure_loaded?(MyXQL) do
179 179 end
180 180
181 181 @impl true
182 - def insert(prefix, table, header, rows, on_conflict, [], []) do
182 + def insert(prefix, table, header, rows, on_conflict, returning, placeholders, opts \\ [])
183 +
184 + def insert(prefix, table, header, rows, on_conflict, [], [], opts) do
183 185 fields = quote_names(header)
186 + insert_mode = Keyword.get(opts, :insert_mode)
187 + insert_keyword = insert_keyword(insert_mode)
184 188
185 189 [
186 - "INSERT INTO ",
190 + insert_keyword,
187 191 quote_table(prefix, table),
188 192 " (",
189 193 fields,
190 194 ") ",
191 - insert_all(rows) | on_conflict(on_conflict, header)
195 + insert_all(rows) | on_conflict(on_conflict, header, opts)
192 196 ]
193 197 end
194 198
195 - def insert(_prefix, _table, _header, _rows, _on_conflict, _returning, []) do
199 + def insert(_prefix, _table, _header, _rows, _on_conflict, _returning, [], _opts) do
196 200 error!(nil, ":returning is not supported in insert/insert_all by MySQL")
197 201 end
198 202
199 - def insert(_prefix, _table, _header, _rows, _on_conflict, _returning, _placeholders) do
203 + def insert(_prefix, _table, _header, _rows, _on_conflict, _returning, _placeholders, _opts) do
200 204 error!(nil, ":placeholders is not supported by MySQL")
201 205 end
202 206
203 - defp on_conflict({_, _, [_ | _]}, _header) do
207 + # INSERT IGNORE when insert_mode: :ignore is passed, independent of on_conflict
208 + defp insert_keyword(:ignore) do
209 + "INSERT IGNORE INTO "
210 + end
211 +
212 + defp insert_keyword(_) do
213 + "INSERT INTO "
214 + end
215 +
216 + defp on_conflict({_, _, [_ | _]}, _header, _opts) do
204 217 error!(nil, ":conflict_target is not supported in insert/insert_all by MySQL")
205 218 end
206 219
207 - defp on_conflict({:raise, _, []}, _header) do
220 + defp on_conflict({:raise, _, []}, _header, _opts) do
208 221 []
209 222 end
210 223
211 - defp on_conflict({:nothing, _, []}, [field | _]) do
212 - quoted = quote_name(field)
213 - [" ON DUPLICATE KEY UPDATE ", quoted, " = " | quoted]
224 + # When insert_mode: :ignore is used with on_conflict: :nothing,
225 + # INSERT IGNORE already handles conflicts - no ON DUPLICATE KEY UPDATE needed
226 + defp on_conflict({:nothing, _, []}, [field | _], opts) do
227 + if Keyword.get(opts, :insert_mode) == :ignore do
228 + []
229 + else
230 + # Default :nothing without INSERT IGNORE - uses workaround to simulate "do nothing" behavior
231 + quoted = quote_name(field)
232 + [" ON DUPLICATE KEY UPDATE ", quoted, " = " | quoted]
233 + end
214 234 end
215 235
216 - defp on_conflict({fields, _, []}, _header) when is_list(fields) do
236 + defp on_conflict({fields, _, []}, _header, _opts) when is_list(fields) do
217 237 [
218 238 " ON DUPLICATE KEY UPDATE "
219 239 | Enum.map_intersperse(fields, ?,, fn field ->
  @@ -223,11 +243,11 @@ if Code.ensure_loaded?(MyXQL) do
223 243 ]
224 244 end
225 245
226 - defp on_conflict({%{wheres: []} = query, _, []}, _header) do
246 + defp on_conflict({%{wheres: []} = query, _, []}, _header, _opts) do
227 247 [" ON DUPLICATE KEY " | update_all(query, "UPDATE ")]
228 248 end
229 249
230 - defp on_conflict({_query, _, []}, _header) do
250 + defp on_conflict({_query, _, []}, _header, _opts) do
231 251 error!(
232 252 nil,
233 253 "Using a query with :where in combination with the :on_conflict option is not supported by MySQL"
  @@ -347,7 +367,7 @@ if Code.ensure_loaded?(MyXQL) do
347 367 defp distinct(%ByExpr{expr: false}, _sources, _query), do: []
348 368
349 369 defp distinct(%ByExpr{expr: exprs}, _sources, query) when is_list(exprs) do
350 - error!(query, "DISTINCT with multiple columns is not supported by MySQL")
370 + error!(query, "to apply DISTINCT to multiple columns in MySQL, use distinct: true")
351 371 end
352 372
353 373 defp select([], _sources, _query),
  @@ -735,11 +755,11 @@ if Code.ensure_loaded?(MyXQL) do
735 755 end
736 756
737 757 defp expr({:fragment, _, parts}, sources, query) do
738 - Enum.map(parts, fn
739 - {:raw, part} -> part
740 - {:expr, expr} -> expr(expr, sources, query)
741 - end)
742 - |> parens_for_select
758 + fragment_expr(parts, sources, query)
759 + end
760 +
761 + defp expr({{:fragment, _, parts}, schema}, sources, query) when is_atom(schema) do
762 + fragment_expr(parts, sources, query)
743 763 end
744 764
745 765 defp expr({:values, _, [types, _idx, num_rows]}, _, query) do
  @@ -750,18 +770,6 @@ if Code.ensure_loaded?(MyXQL) do
750 770 quote_name(literal)
751 771 end
752 772
753 - defp expr({:constant, _, [literal]}, _sources, _query) when is_binary(literal) do
754 - [?', escape_string(literal), ?']
755 - end
756 -
757 - defp expr({:constant, _, [literal]}, _sources, _query) when is_number(literal) do
758 - [to_string(literal)]
759 - end
760 -
761 - defp expr({:splice, _, [{:^, _, [_, length]}]}, _sources, _query) do
762 - Enum.intersperse(List.duplicate(??, length), ?,)
763 - end
764 -
765 773 defp expr({:selected_as, _, [name]}, _sources, _query) do
766 774 [quote_name(name)]
767 775 end
  @@ -911,6 +919,14 @@ if Code.ensure_loaded?(MyXQL) do
911 919 end)
912 920 end
913 921
922 + defp fragment_expr(parts, sources, query) do
923 + Enum.map(parts, fn
924 + {:raw, part} -> part
925 + {:expr, expr} -> op_to_binary(expr, sources, query)
926 + end)
927 + |> parens_for_select()
928 + end
929 +
914 930 defp interval(count, "millisecond", sources, query) do
915 931 ["INTERVAL (", expr(count, sources, query) | " * 1000) microsecond"]
916 932 end
  @@ -949,6 +965,9 @@ if Code.ensure_loaded?(MyXQL) do
949 965 {:fragment, _, _} ->
950 966 {nil, as_prefix ++ [?f | Integer.to_string(pos)], nil}
951 967
968 + {{:fragment, _, _}, schema, _} ->
969 + {nil, as_prefix ++ [?f | Integer.to_string(pos)], schema}
970 +
952 971 {:values, _, _} ->
953 972 {nil, as_prefix ++ [?v | Integer.to_string(pos)], nil}
954 973
  @@ -984,7 +1003,9 @@ if Code.ensure_loaded?(MyXQL) do
984 1003
985 1004 [
986 1005 [
987 - "CREATE TABLE ",
1006 + "CREATE ",
1007 + modifiers_expr(table.modifiers),
1008 + "TABLE ",
988 1009 if_do(command == :create_if_not_exists, "IF NOT EXISTS "),
989 1010 quote_table(table.prefix, table.name),
990 1011 table_structure,
  @@ -1365,6 +1386,16 @@ if Code.ensure_loaded?(MyXQL) do
1365 1386 defp engine_expr(storage_engine),
1366 1387 do: [" ENGINE = ", String.upcase(to_string(storage_engine || "INNODB"))]
1367 1388
1389 + defp modifiers_expr(nil), do: []
1390 + defp modifiers_expr(modifiers) when is_binary(modifiers), do: [modifiers, ?\s]
1391 +
1392 + defp modifiers_expr(other),
1393 + do:
1394 + error!(
1395 + nil,
1396 + "MySQL adapter expects :modifiers to be a string or nil, got #{inspect(other)}"
1397 + )
1398 +
1368 1399 defp options_expr(nil),
1369 1400 do: []
1370 1401
  @@ -1462,9 +1493,6 @@ if Code.ensure_loaded?(MyXQL) do
1462 1493 defp drop_constraint_if_exists_expr(%Reference{} = ref, table, name),
1463 1494 do: ["DROP FOREIGN KEY IF EXISTS ", reference_name(ref, table, name), ", "]
1464 1495
1465 - defp drop_constraint_if_exists_expr(_, _, _),
1466 - do: []
1467 -
1468 1496 defp reference_name(%Reference{name: nil}, table, column),
1469 1497 do: quote_name("#{table.name}_#{column}_fkey")
  @@ -228,7 +228,7 @@ defmodule Ecto.Adapters.Postgres do
228 228
229 229 case run_query(create_command, opts) do
230 230 {:ok, _} ->
231 - :ok
231 + storage_up_timezone(database, opts)
232 232
233 233 {:error, %{postgres: %{code: :duplicate_database}}} ->
234 234 {:error, :already_up}
  @@ -239,6 +239,21 @@ defmodule Ecto.Adapters.Postgres do
239 239 end
240 240 end
241 241
242 + defp storage_up_timezone(database, opts) do
243 + timezone = Keyword.get(opts, :timezone, "Etc/UTC")
244 +
245 + if timezone do
246 + alter_command = ~s(ALTER DATABASE "#{database}" SET timezone TO '#{timezone}')
247 +
248 + case run_query(alter_command, opts) do
249 + {:ok, _} -> :ok
250 + {:error, error} -> {:error, Exception.message(error)}
251 + end
252 + else
253 + :ok
254 + end
255 + end
256 +
242 257 defp concat_if(content, nil, _), do: content
243 258 defp concat_if(content, false, _), do: content
244 259 defp concat_if(content, value, fun), do: content <> " " <> fun.(value)
Loading more files…