diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a982e7..3926a33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **Nested Transactions via Savepoints** - `handle_begin/2`, `handle_commit/2` and `handle_rollback/2` now honour DBConnection's `mode: :savepoint`, so a `Repo.transaction/1` inside an open transaction creates a savepoint instead of failing with `cannot start a transaction within a transaction`. This makes application code that uses transactions testable under `Ecto.Adapters.SQL.Sandbox` (e.g. a `phx.gen.auth` test suite). The adapter's own libSQL transaction modes (`:deferred`, `:immediate`, `:exclusive`, `:read_only`) are unaffected. (Thanks [@BeagleSoftwareUK](https://github.com/BeagleSoftwareUK) for [PR #122](https://github.com/ocean/ecto_libsql/pull/122)!) -- **`datetime_add/3` and `date_add/3` Support** - `ago/2`, `from_now/2`, `datetime_add/3` and `date_add/3` now generate correct SQL. Week, millisecond and microsecond intervals are converted to modifiers SQLite supports, and interpolated counts (`ago(^n, "day")`) are bound as parameters. (Thanks [@BeagleSoftwareUK](https://github.com/BeagleSoftwareUK) for [PR #123](https://github.com/ocean/ecto_libsql/pull/123)!) +- **Nested Transactions via Savepoints** - `handle_begin/2`, `handle_commit/2` and `handle_rollback/2` now honour DBConnection's `mode: :savepoint`, so a `Repo.transaction/1` run inside an `Ecto.Adapters.SQL.Sandbox` test transaction creates a savepoint instead of failing with `cannot start a transaction within a transaction`. This makes application code that uses transactions testable under `Ecto.Adapters.SQL.Sandbox` (e.g. a `phx.gen.auth` test suite). The adapter's own libSQL transaction modes (`:deferred`, `:immediate`, `:exclusive`, `:read_only`) are unaffected. (Thanks [@BeagleSoftwareUK](https://github.com/BeagleSoftwareUK) for [PR #122](https://github.com/ocean/ecto_libsql/pull/122)!) +- **`datetime_add/3` and `date_add/3` Support** - `ago/2`, `from_now/2`, `datetime_add/3` and `date_add/3` now generate correct SQL. Week, millisecond and microsecond intervals are converted to modifiers SQLite supports, and interpolated counts (`ago(^n, "day")`) are bound as parameters. A cutoff compared against a `:naive_datetime` column is rendered without the trailing `Z`, matching how the column is stored, so a row on the cutoff second compares as equal. (Thanks [@BeagleSoftwareUK](https://github.com/BeagleSoftwareUK) for [PR #123](https://github.com/ocean/ecto_libsql/pull/123)!) - **Arithmetic Operators** - `+`, `-`, `*` and `/` are now supported in query expressions (e.g. `where: s.count + 1 > 5`, `select: s.count * 2`), parenthesised so precedence survives nesting. (Thanks [@BeagleSoftwareUK](https://github.com/BeagleSoftwareUK) for [PR #124](https://github.com/ocean/ecto_libsql/pull/124)!) ### Fixed diff --git a/USAGE.md b/USAGE.md index a0965af..2bcbb1f 100644 --- a/USAGE.md +++ b/USAGE.md @@ -162,6 +162,8 @@ Named constraints (`ON CONFLICT ON CONSTRAINT name`) are not supported. {:ok, _, state} = EctoLibSql.handle_commit([], state) ``` +Under Ecto, a `Repo.transaction/1` nested inside another one joins the outer transaction, so a rollback or exception in the inner call rolls back the outer one too. Use the savepoint functions above for partial rollback. `Ecto.Adapters.SQL.Sandbox` is the exception: it runs each test inside its own transaction and opens application transactions as savepoints, so code that uses transactions works in sandboxed tests. + ### Named Parameters SQLite supports three named parameter syntaxes. Pass a map instead of a list: @@ -599,12 +601,12 @@ The following Ecto query features do not work due to SQLite limitations: | Feature | Limitation | |---------|------------| | `selected_as()` with GROUP BY | SQLite doesn't support column aliases in GROUP BY | -| `exists()` with `parent_as()` | Complex nested query correlation unsupported | | `fragment(literal(...))` / `fragment(identifier(...))` | Not supported in SQLite fragments | -| `ago(N, unit)` | Does not work with TEXT-based timestamps | +| `ago/2`, `from_now/2`, `datetime_add/3`, `date_add/3` against `:*_usec` columns | SQLite's date functions stop at millisecond precision. On a schema field this raises `ArgumentError`; a schemaless query (`from "table"`) has no column type to check, so it runs and can return wrong rows within the cutoff second. Compute the cutoff in Elixir and bind it, e.g. `where: t.inserted_at > ^DateTime.add(DateTime.utc_now(), -14, :day)` | | `{:array, _}` type | Not supported - use JSON or separate tables | | Mixed arithmetic (string + float) | SQLite returns TEXT instead of coercing to REAL | | Case-insensitive text comparison | TEXT is case-sensitive by default - use `COLLATE NOCASE` | +| Other expressions the adapter cannot translate | Raise `Ecto.QueryError` at query time instead of generating wrong SQL | **Compatibility summary: ~74% of Ecto features pass (31/42 tests). All failures are SQLite limitations, not adapter bugs.** diff --git a/checksum-Elixir.EctoLibSql.Native.exs b/checksum-Elixir.EctoLibSql.Native.exs index 79fc392..2079728 100644 --- a/checksum-Elixir.EctoLibSql.Native.exs +++ b/checksum-Elixir.EctoLibSql.Native.exs @@ -1,8 +1,8 @@ %{ - "libecto_libsql-v0.10.0-nif-2.15-aarch64-apple-darwin.so.tar.gz" => "sha256:662cfc8e7f69edb8571c8eeaae6a6cc3a0b14b8739d280fba8508131c806dec6", - "libecto_libsql-v0.10.0-nif-2.15-aarch64-unknown-linux-gnu.so.tar.gz" => "sha256:94b294de0c86380893839aa03151832d47274b3e3e92341d1b7c8cf733c16ede", - "libecto_libsql-v0.10.0-nif-2.15-aarch64-unknown-linux-musl.so.tar.gz" => "sha256:2ad43e6ac85cbfdb79ef53557a08084d99f66a6965be5a06853b39859d597439", - "libecto_libsql-v0.10.0-nif-2.15-x86_64-apple-darwin.so.tar.gz" => "sha256:6b3061e16e277f21eb048c7780e4b8855e2711a7913d849335590389e503bfa1", - "libecto_libsql-v0.10.0-nif-2.15-x86_64-unknown-linux-gnu.so.tar.gz" => "sha256:fede8407f76212130473ccc8512a9db5a7ff50652dc201c9adc05f714c4b80a2", - "libecto_libsql-v0.10.0-nif-2.15-x86_64-unknown-linux-musl.so.tar.gz" => "sha256:126cbc4a11866338044e321e72a28339ecf1fe4c26906e4a6b517054ea833091", + "libecto_libsql-v0.10.0-nif-2.15-aarch64-apple-darwin.so.tar.gz" => "sha256:3ad3e7e0a485779f7e5c9f3e71152783cbc1a6f5de52e5c5d63652c070fff8ca", + "libecto_libsql-v0.10.0-nif-2.15-aarch64-unknown-linux-gnu.so.tar.gz" => "sha256:20ff544becc770cb93070e9fba16f715db9932d0a1950dcaee71eadbdfe4c0fb", + "libecto_libsql-v0.10.0-nif-2.15-aarch64-unknown-linux-musl.so.tar.gz" => "sha256:4df2b9ef3d5450abd69f5a3965a2a17ea61b8e4d3b5fdd14e3e869d48c1035e5", + "libecto_libsql-v0.10.0-nif-2.15-x86_64-apple-darwin.so.tar.gz" => "sha256:cdbf277abe1bd62cad5f78f9067061414d1da725ae6b47ee319e72b417d59f32", + "libecto_libsql-v0.10.0-nif-2.15-x86_64-unknown-linux-gnu.so.tar.gz" => "sha256:599a2343b70ec953d7a9db46ce49de14f167ba600976355ecb5403cda7859e0b", + "libecto_libsql-v0.10.0-nif-2.15-x86_64-unknown-linux-musl.so.tar.gz" => "sha256:2def82b3b570c55518385364879fe1b29d107fd99d570b57a5e0c36170c7d597", } diff --git a/lib/ecto/adapters/libsql/connection.ex b/lib/ecto/adapters/libsql/connection.ex index 63c1b2d..fddbb58 100644 --- a/lib/ecto/adapters/libsql/connection.ex +++ b/lib/ecto/adapters/libsql/connection.ex @@ -1246,35 +1246,23 @@ defmodule Ecto.Adapters.LibSql.Connection do end # Comparison operations - defp expr({:==, _, [left, right]}, sources, query) do - reject_unsupported_datetime_precision!(left, right, sources) - [expr(left, sources, query), " = ", expr(right, sources, query)] - end + defp expr({:==, _, [left, right]}, sources, query), + do: comparison(left, " = ", right, sources, query) - defp expr({:!=, _, [left, right]}, sources, query) do - reject_unsupported_datetime_precision!(left, right, sources) - [expr(left, sources, query), " != ", expr(right, sources, query)] - end + defp expr({:!=, _, [left, right]}, sources, query), + do: comparison(left, " != ", right, sources, query) - defp expr({:<, _, [left, right]}, sources, query) do - reject_unsupported_datetime_precision!(left, right, sources) - [expr(left, sources, query), " < ", expr(right, sources, query)] - end + defp expr({:<, _, [left, right]}, sources, query), + do: comparison(left, " < ", right, sources, query) - defp expr({:>, _, [left, right]}, sources, query) do - reject_unsupported_datetime_precision!(left, right, sources) - [expr(left, sources, query), " > ", expr(right, sources, query)] - end + defp expr({:>, _, [left, right]}, sources, query), + do: comparison(left, " > ", right, sources, query) - defp expr({:<=, _, [left, right]}, sources, query) do - reject_unsupported_datetime_precision!(left, right, sources) - [expr(left, sources, query), " <= ", expr(right, sources, query)] - end + defp expr({:<=, _, [left, right]}, sources, query), + do: comparison(left, " <= ", right, sources, query) - defp expr({:>=, _, [left, right]}, sources, query) do - reject_unsupported_datetime_precision!(left, right, sources) - [expr(left, sources, query), " >= ", expr(right, sources, query)] - end + defp expr({:>=, _, [left, right]}, sources, query), + do: comparison(left, " >= ", right, sources, query) # Parenthesised so precedence survives nesting: `(s.count + 2) * 2` has to keep # its grouping rather than being reassociated. @@ -1439,15 +1427,8 @@ defmodule Ecto.Adapters.LibSql.Connection do # is rendered the same way to compare correctly as text. The two formats agree to # the second, so a value carrying sub-second precision can land on the wrong side # of a bound when it ties the cutoff to that exact second - see issue #128. - defp expr({:datetime_add, _, [datetime, count, interval]}, sources, query) do - [ - "strftime('%Y-%m-%dT%H:%M:%SZ', ", - expr(datetime, sources, query), - ", ", - interval_modifier(count, interval, sources, query), - ?) - ] - end + defp expr({:datetime_add, _, [datetime, count, interval]}, sources, query), + do: datetime_add("%Y-%m-%dT%H:%M:%SZ", datetime, count, interval, sources, query) defp expr({:date_add, _, [date, count, interval]}, sources, query) do [ @@ -1467,6 +1448,42 @@ defmodule Ecto.Adapters.LibSql.Connection do message: "unsupported expression #{inspect(expr)}" end + defp datetime_add(format, datetime, count, interval, sources, query) do + [ + "strftime('", + format, + "', ", + expr(datetime, sources, query), + ", ", + interval_modifier(count, interval, sources, query), + ?) + ] + end + + defp comparison(left, operator, right, sources, query) do + reject_unsupported_datetime_precision!(left, right, sources) + + [ + comparison_side(left, right, sources, query), + operator, + comparison_side(right, left, sources, query) + ] + end + + # `datetime_encode/1` stores a naive datetime without the trailing Z, so a cutoff + # compared against one drops it too. Otherwise a value on the cutoff second sorts + # before it as text and `>=` and `==` miss the row. + defp comparison_side({:datetime_add, _, [datetime, count, interval]}, other, sources, query) do + format = + if field_type(other, sources) == :naive_datetime, + do: "%Y-%m-%dT%H:%M:%S", + else: "%Y-%m-%dT%H:%M:%SZ" + + datetime_add(format, datetime, count, interval, sources, query) + end + + defp comparison_side(side, _other, sources, query), do: expr(side, sources, query) + # Builds a SQLite time modifier such as '-14 days'. The count stays an expression # rather than being interpolated, so an interpolated `ago(^n, "day")` still binds # as a parameter. SQLite has no week/millisecond/microsecond modifiers, so those diff --git a/mix.exs b/mix.exs index 762ea47..48905b3 100644 --- a/mix.exs +++ b/mix.exs @@ -81,7 +81,7 @@ defmodule EctoLibSql.MixProject do defp docs do [ main: "EctoLibSql", - source_ref: "v#{@version}", + source_ref: @version, source_url: @source_url, extras: ["README.md", "CHANGELOG.md", "USAGE.md", "ECTO_MIGRATION_GUIDE.md", "SECURITY.md"], groups_for_modules: [ diff --git a/test/ecto_datetime_precision_test.exs b/test/ecto_datetime_precision_test.exs index 43db0b0..3ff5cda 100644 --- a/test/ecto_datetime_precision_test.exs +++ b/test/ecto_datetime_precision_test.exs @@ -125,6 +125,20 @@ defmodule EctoLibSql.EctoDatetimePrecisionTest do assert names == ["recent"] end + + test "naive_datetime matches a cutoff that falls on the same second" do + # A naive value is stored without a trailing Z, so the cutoff must be too. + at = ~N[2026-12-01 10:00:00] + TestRepo.insert!(%Event{name: "edge", at_naive: at}) + + for query <- [ + from(e in Event, where: e.at_naive >= datetime_add(^at, 0, "day"), select: e.name), + from(e in Event, where: e.at_naive == datetime_add(^at, 0, "day"), select: e.name), + from(e in Event, where: datetime_add(^at, 0, "day") <= e.at_naive, select: e.name) + ] do + assert TestRepo.all(query) == ["edge"] + end + end end describe "the guard is scoped to shifted datetimes" do