Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: support sqlite contains path queries #274

Merged

Conversation

jiazheng2
Copy link
Contributor

@jiazheng2 jiazheng2 commented Oct 16, 2024

Checks

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

Support using path for SQLite JSON array contains queries.

This addresses issue #216 to some extent.

Use case description

If we have

| json_column   |
|---------------|
| {"a": [1, 2]} |

For SQLite databases, we can now do

JSONArrayQuery("json_column", "a").Contains(1)

This gets translated to

EXISTS(
    SELECT 1 FROM json_each(`json_column`, "$.a") WHERE value=1
) AND json_array_length(`json_column`, "$.a") > 0

Note the additional json_array_length check compared to the previous implementation.

This fixes the inconsistency in the behaviour between the MySQL and SQLite dialects.

Previously, if we have

| json_column |
|-------------|
| {"a": 1}    |

When we do

JSONArrayQuery("json_column").Contains(1)

The where condition is translated to

EXISTS(
    SELECT 1 FROM json_each(`json_column`) WHERE value=1
) 

This returns the row {"a": 1} because the for_each function iterates over the map as well. And
the key-value pair "a" and 1 fulfils the query criteria WHERE value=1. This behaviour is
different from the MySQL implementation.

With this change, the where condition gets translated to

EXISTS(
    SELECT 1 FROM json_each(`json_column`) WHERE value=1
) AND json_array_length(`json_column`) > 0

json_array_length for a non-array object is 0, and therefore the second where clause is false. Additionally,
any contains query should return false for an empty target array.

@jiazheng2 jiazheng2 marked this pull request as ready for review October 17, 2024 03:07
@jiazheng2
Copy link
Contributor Author

@jinzhu 麻烦review一下 🙏

@jinzhu jinzhu merged commit e2e91b3 into go-gorm:master Oct 18, 2024
27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants