circles-learning-labs / ecto_adapters_dynamodb

DynamoDB adapter for Elixir's Ecto Database layer.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Compilation error: begins_with

sheshankkodam opened this issue · comments

Query with begins_with on primary key or sort key gives compilation error

# id is the partition key
TestRepo.all(from p in Person, where: p.id begins_with "person-")

or 
# id is the partition key and email is sort key 
TestRepo.all(from p in Person, where: p.id == "John" and p.email begins_with "john@")

Result

** (Ecto.Query.CompileError) `p.id(begins_with("person-"))` is not a valid query expression
    (ecto) expanding macro: Ecto.Query.where/3
    (ecto) expanding macro: Ecto.Query.from/2

** (Ecto.Query.CompileError) `p.email(begins_with("john@"))` is not a valid query expression
    (ecto) expanding macro: Ecto.Query.where/3
    (ecto) expanding macro: Ecto.Query.from/2

If you want to use begins_with in your query, you'll need to use a fragment. Here's an excerpt from README.md:

### DynamoDB `between` and Ecto `:fragment`

We currently only support the Ecto fragments of the form:

`from(m in Model, where: fragment("? between ? and ?", m.attribute, ^range_start, ^range_end))`

`from(m in Model, where: fragment("begins_with(?, ?)", m.attribute, ^prefix))`

Note that the range value must be provided as a "pinned" variable... so you'd want to do something like

email_fragment = "john@"
query = from(p in Person, where: p.id == "John" and fragment("begins_with(?, ?)", p.email, ^email_fragment))

TestRepo.all(query)

You should note that this behavior is not yet fully-implemented - if you are using this against a composite-keyed global secondary index, it will work just fine. However, if you intend to use this against a composite primary key, it won't work... referring to the example above, it would end up just querying for where p.id == "John" and p.email == "john@". This issue was actually raised in #21 - we are aware of the problem, and may try to resolve it in the next week or so.

I intend to run the query on the primary key.
Thanks for the detailed response.

@sheshankkodam My colleague has been working on the primary key issue, we'll hopefully have a fix out for that in the next few days.

@sheshankkodam Ok, the adapter has been updated to support this kind of fragment query on a composite primary key - see the latest release, version 1.1.1.

Thank you