Skip to content

Commit

Permalink
New SQLite function to decode struct JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
annda committed Jan 18, 2024
1 parent 6335bc4 commit cdd1649
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
22 changes: 22 additions & 0 deletions helper/db.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ protected function init()
// register our JSON function with variable parameters
$this->sqlite->getPdo()->sqliteCreateFunction('STRUCT_JSON', [$this, 'STRUCT_JSON'], -1);

// register our JSON decode function with variable parameters
$this->sqlite->getPdo()->sqliteCreateFunction('STRUCT_LOOKUP', [$this, 'STRUCT_LOOKUP'], -1);

// this function is meant to be overwritten by plugins
$this->sqlite->getPdo()->sqliteCreateFunction('IS_PUBLISHER', [$this, 'IS_PUBLISHER'], -1);
}
Expand Down Expand Up @@ -83,6 +86,25 @@ public function STRUCT_JSON(...$args) // phpcs:ignore PSR1.Methods.CamelCapsMeth
return json_encode($args, JSON_THROW_ON_ERROR);
}

/**
* Decodes a struct JSON structure and returns the requested value
*
* @param ...$args
* @return mixed|null
*/
public function STRUCT_LOOKUP(...$args) // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps
{
$json = $args[0];
$field = $args[1];

try {
$vals = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
return null;
}
return $vals[$field];
}

/**
* This dummy implementation can be overwritten by a plugin
*
Expand Down
3 changes: 2 additions & 1 deletion types/Lookup.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,8 @@ public function select(QueryBuilder $QB, $tablealias, $colname, $alias)
$tablealias,
$schema,
$rightalias,
"$tablealias.$colname = STRUCT_JSON($rightalias.pid, CAST($rightalias.rid AS DECIMAL)) " .
"STRUCT_LOOKUP($tablealias.$colname, 0) = $rightalias.pid " .
"AND STRUCT_LOOKUP($tablealias.$colname, 1) = $rightalias.rid " .
"AND $rightalias.latest = 1"
);
$column->getType()->select($QB, $rightalias, $field, $alias);
Expand Down

0 comments on commit cdd1649

Please sign in to comment.