Skip to content

Commit

Permalink
refactor: Working JSONB internal seach
Browse files Browse the repository at this point in the history
  • Loading branch information
khalwat committed Feb 24, 2024
1 parent f5dd1e3 commit 9fd8f81
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/services/Assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ protected function updateContent(string $value, CantoFieldData $cantoFieldData,
// Get any existing Canto Assets fields that contain the asset ID we're updating
$cantoIdFieldName = ElementHelper::fieldColumnFromField($cantoDamAssetField, self::CONTENT_COLUMN_KEY_MAPPINGS['cantoId']);
$cantoAssetDataFieldName = ElementHelper::fieldColumnFromField($cantoDamAssetField, self::CONTENT_COLUMN_KEY_MAPPINGS['cantoAssetData']);
$jsonSearchNeedle = ['id' => $cantoFieldData->cantoId];
$jsonSearchNeedle[] = ['id' => $cantoFieldData->cantoId];
$jsonSearchSql = '';
if ($db->getIsMysql()) {
$jsonSearchSql = $this->mySqlJsonContains($cantoAssetDataFieldName, $jsonSearchNeedle);
Expand All @@ -201,12 +201,12 @@ protected function updateContent(string $value, CantoFieldData $cantoFieldData,
->select(['id', $cantoAssetDataFieldName])
->from([$table])
->where([$cantoIdFieldName => 0])
->addParams([$jsonSearchSql])
->andWhere($jsonSearchSql)
->all();
// Iterate through each row, the field data as appropriate
foreach ($rows as $row) {
$rowCollection = new Collection($row[$cantoAssetDataFieldName]);
$rowCollection->transform(function ($item) use ($cantoFieldData) {
$rowCollection = new Collection(Json::decodeIfJson($row[$cantoAssetDataFieldName]));
$rowCollection->transform(function($item) use ($cantoFieldData) {
if ($item['id'] === $cantoFieldData->cantoId) {
$item = $cantoFieldData->cantoAssetData[0];
}
Expand All @@ -231,7 +231,10 @@ protected function updateContent(string $value, CantoFieldData $cantoFieldData,
*/
private function mySqlJsonContains(string $targetSql, mixed $value): string
{
$value = Craft::$app->getDb()->quoteValue(Json::encode($value));
$db = Craft::$app->getDb();
$value = $db->quoteValue(Json::encode($value));
$targetSql = $db->quoteColumnName($targetSql);

return "JSON_CONTAINS($targetSql, $value)";
}

Expand All @@ -244,7 +247,10 @@ private function mySqlJsonContains(string $targetSql, mixed $value): string
*/
private function pgSqlJsonContains(string $targetSql, mixed $value): string
{
$db = Craft::$app->getDb();
$value = Craft::$app->getDb()->quoteValue(Json::encode($value));
$targetSql = $db->quoteColumnName($targetSql);

return "($targetSql @> $value::jsonb)";
}

Expand Down

0 comments on commit 9fd8f81

Please sign in to comment.