B
B
BonBon Slick2019-02-07 13:18:13
SQL
BonBon Slick, 2019-02-07 13:18:13

SQL query that works in SQLite and PgSql with json?

Doctrine 2.6 + Postgresql .9.6

$rsm = new ResultSetMapping();
        $rsm->addEntityResult(Notification::class, 'notificationTableAlias');
        $rsm->addFieldResult('notificationTableAlias', 'id', 'id');
        $query = $this->_em->createNativeQuery(
            <<<EOT
            SELECT id,
            COUNT(id)
            FROM  notification
                WHERE statuses_values::jsonb = ?::jsonb
                AND user_id = ?
            GROUP BY notification.id
EOT
            ,
            $rsm
        );
        $query->setParameter(1, '"[]"');
        $query->setParameter(2, $loggedUserId);
        $results = $query->execute();

        return \count($results);

But the tests fail when working with any json data, because it does not support such a request format.
SQL syntax is different for PGsql and SqLite.
Above is the native request code, before that I tried to use a query builder that does not support working with JSON at all, except to create custom methods.
If
WHERE statuses_values = ?
the tests pass, only PGsql will crash
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: json = unknown
LINE 4: WHERE statuses_values = $1
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.").

So far I've used a temporary crutch
if ($this->_em->getConnection()->getDriver() instanceof AbstractSQLiteDriver) {
            return 0;
        }

In theory, there should be common methods for working with JSON, most likely you need some kind of extension, a package than to write an interlayer or your custom json() method .
https://www.sqlite.org/json1.html
https://www.postgresql.org/docs/9.5/functions-json.html
How to make SQLite and PGSQL work at the same time?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question