-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMagicSearchHandler.php
More file actions
1678 lines (1489 loc) · 62.8 KB
/
MagicSearchHandler.php
File metadata and controls
1678 lines (1489 loc) · 62.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* MagicMapper Search Handler
*
* This handler provides advanced search capabilities for dynamic schema-based tables.
* It implements sophisticated search functionality including metadata filtering,
* object field searching, full-text search, and complex query building for
* dynamically created tables.
*
* KEY RESPONSIBILITIES:
* - Dynamic table search operations
* - Metadata and object field filtering
* - Full-text search within dynamic tables
* - Query optimization for schema-specific tables
* - Integration with ObjectEntity conversion
*
* SEARCH CAPABILITIES:
* - Metadata searches (register, schema, owner, organization, etc.)
* - Object field searches (JSON property searches)
* - Combined searches with complex boolean logic
* - Optimized counting and sizing operations
* - Support for pagination and sorting
*
* @category Handler
* @package OCA\OpenRegister\Db\MagicMapper
* @author Conduction Development Team <info@conduction.nl>
* @copyright 2024 Conduction B.V.
* @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
* @version GIT: <git_id>
* @link https://www.OpenRegister.app
*
* @since 2.0.0 Initial implementation for MagicMapper search capabilities
*/
declare(strict_types=1);
namespace OCA\OpenRegister\Db\MagicMapper;
use OCA\OpenRegister\Db\ObjectEntity;
use OCA\OpenRegister\Db\Register;
use OCA\OpenRegister\Db\Schema;
use OCA\OpenRegister\Db\MagicMapper\MagicRbacHandler;
use OCA\OpenRegister\Db\MagicMapper\MagicOrganizationHandler;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use Psr\Log\LoggerInterface;
use Exception;
use RuntimeException;
use DateTime;
/**
* Dynamic table search handler for MagicMapper
*
* This class provides comprehensive search functionality for dynamically created
* schema-based tables, optimized for schema-specific table structures.
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.ExcessiveClassLength) Search handler requires many specialized query building methods
* @SuppressWarnings(PHPMD.TooManyMethods) Search requires per-operator and per-type conversion methods
* @SuppressWarnings(PHPMD.CouplingBetweenObjects) Search handler bridges schema, register, and query builder layers
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
class MagicSearchHandler
{
/**
* Tracks filter properties that don't exist in the schema during search.
* Reset at the start of each searchObjects call.
*
* @var array<string>
*/
private array $ignoredFilters = [];
/**
* Cached result of pg_trgm extension availability check.
*
* @var boolean|null
*/
private ?bool $hasPgTrgm = null;
/**
* Constructor for MagicSearchHandler
*
* @param IDBConnection $db Database connection for queries
* @param LoggerInterface $logger Logger for debugging and error reporting
* @param MagicRbacHandler $rbacHandler RBAC handler for access control
* @param MagicOrganizationHandler $organizationHandler Organization handler for multi-tenancy
*/
public function __construct(
private readonly IDBConnection $db,
private readonly LoggerInterface $logger,
private readonly MagicRbacHandler $rbacHandler,
private readonly MagicOrganizationHandler $organizationHandler
) {
}//end __construct()
/**
* Check if PostgreSQL pg_trgm extension is available for fuzzy search.
*
* This extension provides the similarity() function and % operator
* for fuzzy text searching. Result is cached for the request lifetime.
*
* @return bool True if pg_trgm is available, false otherwise.
*/
public function hasPgTrgmExtension(): bool
{
// Return cached result if available.
if ($this->hasPgTrgm !== null) {
return $this->hasPgTrgm;
}
// Not PostgreSQL = no pg_trgm.
$platform = $this->db->getDatabasePlatform();
if (str_contains(get_class($platform), 'PostgreSQL') === false) {
$this->hasPgTrgm = false;
return false;
}
// Check if pg_trgm extension is installed.
try {
$stmt = $this->db->prepare("SELECT COUNT(*) FROM pg_extension WHERE extname = 'pg_trgm'");
$result = $stmt->execute();
$count = (int) $result->fetchOne();
$this->hasPgTrgm = $count > 0;
} catch (Exception $e) {
$this->logger->warning(
message: '[MagicSearchHandler] Failed to check pg_trgm extension availability',
context: ['file' => __FILE__, 'line' => __LINE__, 'error' => $e->getMessage()]
);
$this->hasPgTrgm = false;
}
return $this->hasPgTrgm;
}//end hasPgTrgmExtension()
/**
* Get the list of filter properties that were ignored during the last search.
*
* These are properties that were requested as filters but don't exist in the schema.
*
* @return array<string> List of ignored filter property names
*/
public function getIgnoredFilters(): array
{
return $this->ignoredFilters;
}//end getIgnoredFilters()
/**
* Search objects in a specific register-schema table using clean query structure
*
* This method provides comprehensive search capabilities optimized for
* schema-specific dynamic tables.
*
* @param array $query Search query array with filters and options
* @param Register $register Register context for the search
* @param Schema $schema Schema context for the search
* @param string $tableName Target dynamic table name
*
* @return \OCA\OpenRegister\Db\ObjectEntity[]|int Array of ObjectEntity objects or count if _count=true
*
* @throws \OCP\DB\Exception If a database error occurs
*
* @phpstan-param array<string, mixed> $query
*
* @psalm-param array<string, mixed> $query
*
* @psalm-return int|list<ObjectEntity>
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function searchObjects(array $query, Register $register, Schema $schema, string $tableName): array|int
{
// Reset ignored filters tracking for this search.
$this->ignoredFilters = [];
// Extract options from query (prefixed with _).
$limit = $query['_limit'] ?? null;
$offset = $query['_offset'] ?? null;
$page = $query['_page'] ?? null;
$order = $query['_order'] ?? [];
// The _order parameter may arrive as a JSON string from URL query params.
if (is_string($order) === true) {
$decoded = json_decode($order, true);
$order = [];
if (is_array($decoded) === true) {
$order = $decoded;
}
}
$count = $query['_count'] ?? false;
$search = $query['_search'] ?? null;
// Convert page to offset if page is provided but offset is not.
// Page is 1-indexed, so page 1 = offset 0, page 2 = offset $limit, etc.
if ($page !== null && $offset === null && $limit !== null) {
$offset = ((int) $page - 1) * (int) $limit;
}
// Build filtered query (applies all WHERE conditions).
$queryBuilder = $this->buildFilteredQuery(
query: $query,
schema: $schema,
tableName: $tableName
);
// Check if fuzzy search is enabled for relevance scoring.
$fuzzyEnabled = false;
$searchTerm = null;
if ($search !== null && trim($search) !== '') {
$searchTerm = trim($search);
}
$fuzzyParam = $query['_fuzzy'] ?? null;
if ($fuzzyParam === true || $fuzzyParam === 'true' || $fuzzyParam === '1' || $fuzzyParam === 1) {
$fuzzyEnabled = $this->hasPgTrgmExtension();
}
// Add SELECT clause based on count vs search.
if ($count === true) {
$queryBuilder->selectAlias($queryBuilder->createFunction('COUNT(*)'), 'count');
$result = $queryBuilder->executeQuery();
return (int) $result->fetchOne();
}
$queryBuilder->select('t.*');
// Add relevance score column when fuzzy search is enabled.
// This allows us to return the similarity score as a percentage in @self.relevance.
if ($fuzzyEnabled === true && $searchTerm !== null) {
$searchTermParam = $queryBuilder->createNamedParameter($searchTerm);
$queryBuilder->addSelect(
$queryBuilder->createFunction(
'ROUND(similarity(t._name::text, '."{$searchTermParam}) * 100)::integer AS _relevance"
)
);
}
// Apply sorting BEFORE pagination so the query optimizer can use
// indexes for ORDER BY … LIMIT instead of sorting the full result set.
if (empty($order) === false) {
$this->applySorting(qb: $queryBuilder, order: $order, schema: $schema, searchTerm: $searchTerm);
}
$queryBuilder->setMaxResults($limit)
->setFirstResult($offset);
return $this->executeSearchQuery(qb: $queryBuilder, register: $register, schema: $schema, tableName: $tableName);
}//end searchObjects()
/**
* Build a filtered query with all WHERE conditions applied.
*
* This is the SINGLE SOURCE OF TRUTH for query filtering. Used by:
* - searchObjects() for search results
* - searchObjects() with _count=true for counting
* - getFacetQuery() for facet aggregations
*
* Returns a QueryBuilder with FROM and WHERE clauses, but NO SELECT.
* Caller must add SELECT clause based on their needs.
*
* @param array $query Search parameters including filters.
* @param Schema $schema The schema for property filtering.
* @param string $tableName The table to query.
*
* @return IQueryBuilder QueryBuilder with all filters applied.
*/
public function buildFilteredQuery(array $query, Schema $schema, string $tableName): IQueryBuilder
{
// Extract options from query (prefixed with _).
$search = $query['_search'] ?? null;
$includeDeleted = $query['_includeDeleted'] ?? false;
$ids = $query['_ids'] ?? null;
$_rbac = $query['_rbac'] ?? true;
$_multitenancy = $query['_multitenancy'] ?? true;
$relationsContains = $query['_relations_contains'] ?? null;
// Resolve multitenancy flag based on public schema access and explicit request.
$multitenancyExplicit = $this->isExplicitlyTrue(value: $query['_multitenancy_explicit'] ?? false);
$_multitenancy = $this->resolveMultitenancyFlag(
_multitenancy: $_multitenancy,
multitenancyExplicit: $multitenancyExplicit,
schema: $schema
);
// Extract and clean filters from the query.
$metadataFilters = $query['@self'] ?? [];
$objectFilters = array_filter(
$query,
function ($key) {
return $key !== '@self' && !str_starts_with($key, '_');
},
ARRAY_FILTER_USE_KEY
);
$queryBuilder = $this->db->getQueryBuilder();
$queryBuilder->from($tableName, 't');
// Apply basic filters (deleted, etc.).
$this->applyBasicFilters(qb: $queryBuilder, includeDeleted: $includeDeleted);
// Apply multi-tenancy and RBAC access control filters.
$this->applyAccessControlFilters(
qb: $queryBuilder,
schema: $schema,
_rbac: $_rbac,
_multitenancy: $_multitenancy,
multitenancyExplicit: $multitenancyExplicit
);
// Apply metadata filters.
if (empty($metadataFilters) === false) {
$this->applyMetadataFilters(qb: $queryBuilder, filters: $metadataFilters);
}
// Apply object field filters (schema-specific columns).
if (empty($objectFilters) === false) {
$this->applyObjectFilters(qb: $queryBuilder, filters: $objectFilters, schema: $schema);
}
// Apply ID filtering if provided.
if ($ids !== null && empty($ids) === false) {
$this->applyIdFilters(qb: $queryBuilder, ids: $ids);
}
// Apply full-text search if provided.
// Fuzzy matching is only enabled when _fuzzy=true parameter is explicitly set.
if ($search !== null && trim($search) !== '') {
$fuzzyEnabled = $this->isFuzzySearchEnabled(fuzzyParam: $query['_fuzzy'] ?? null);
$this->applyFullTextSearch(
qb: $queryBuilder,
search: trim($search),
schema: $schema,
fuzzyEnabled: $fuzzyEnabled
);
}
// Apply relations contains filter if provided.
if ($relationsContains !== null && empty($relationsContains) === false) {
$this->applyRelationsContainsFilter(qb: $queryBuilder, uuid: $relationsContains);
}
return $queryBuilder;
}//end buildFilteredQuery()
/**
* Build WHERE conditions as raw SQL for use in UNION queries.
*
* This is the SINGLE SOURCE OF TRUTH for filter conditions used by:
* - UNION search queries (MagicMapper::buildUnionSelectPart)
* - UNION facet queries (MagicFacetHandler::getTermsFacetUnion)
*
* Includes RBAC filtering when enabled (default). Values are quoted inline
* (not parameterized) for UNION query compatibility.
*
* @param array $query Search parameters including filters.
* @param Schema $schema The schema for property filtering.
* @param array|null $existingColumns Optional list of existing column names.
*
* @return string[] Array of SQL WHERE conditions (without leading AND/WHERE).
*/
public function buildWhereConditionsSql(array $query, Schema $schema, ?array $existingColumns=null): array
{
$conditions = [];
// Get connection for value quoting through QueryBuilder.
$qb = $this->db->getQueryBuilder();
$connection = $qb->getConnection();
// Extract options from query.
$search = $query['_search'] ?? null;
$includeDeleted = $query['_includeDeleted'] ?? false;
$_rbac = $query['_rbac'] ?? true;
// 1. Deleted filter.
if ($includeDeleted === false) {
$conditions[] = '_deleted IS NULL';
}
// 2. RBAC filter (role-based access control).
if ($_rbac === true) {
$rbacCondition = $this->buildRbacConditionSql(schema: $schema);
if ($rbacCondition !== null) {
$conditions[] = $rbacCondition;
}
}
// 4. Full-text search filter with optional fuzzy matching.
if ($search !== null && trim($search) !== '') {
$searchCondition = $this->buildSearchConditionSql(
search: trim($search),
schema: $schema,
query: $query,
connection: $connection,
existingColumns: $existingColumns
);
if ($searchCondition !== null) {
$conditions[] = $searchCondition;
}
}
// 5. Object field filters (non-reserved, non-metadata).
$objectConditions = $this->buildObjectFilterConditionsSql(
query: $query,
schema: $schema,
connection: $connection
);
$conditions = array_merge($conditions, $objectConditions);
return $conditions;
}//end buildWhereConditionsSql()
/**
* Build the RBAC SQL condition
*
* @param Schema $schema Schema for RBAC rules
*
* @return string|null SQL condition or null if no RBAC filtering needed
*/
private function buildRbacConditionSql(Schema $schema): ?string
{
$rbacResult = $this->rbacHandler->buildRbacConditionsSql(schema: $schema, action: 'read');
if ($rbacResult['bypass'] === false) {
// User doesn't have unconditional access.
if (empty($rbacResult['conditions']) === true) {
// No access conditions met - deny all.
return '1=0';
}
// OR together all RBAC conditions (access if ANY matches).
return '('.implode(' OR ', $rbacResult['conditions']).')';
}
// If bypass=true, no RBAC filtering needed (user has full access).
return null;
}//end buildRbacConditionSql()
/**
* Build the full-text search SQL condition with optional fuzzy matching
*
* Fuzzy matching (pg_trgm similarity) is only enabled when _fuzzy=true parameter is set.
* This gives users control over the performance vs typo-tolerance trade-off.
* Without _fuzzy=true: ~140ms (ILIKE only)
* With _fuzzy=true: ~160ms (ILIKE + similarity on _name)
*
* @param string $search Trimmed search term
* @param Schema $schema Schema for determining searchable columns
* @param array $query Full query array for extracting _fuzzy param
* @param object $connection Database connection for value quoting
* @param array|null $existingColumns Optional list of existing column names.
*
* @return string|null SQL condition or null if no search conditions generated
*/
private function buildSearchConditionSql(
string $search,
Schema $schema,
array $query,
object $connection,
?array $existingColumns=null
): ?string {
$searchConditions = [];
$likePattern = $connection->quote('%'.$search.'%');
$quotedTerm = $connection->quote($search);
// Check if fuzzy search is explicitly requested via _fuzzy=true parameter.
$fuzzyEnabled = $this->isFuzzySearchEnabled(fuzzyParam: $query['_fuzzy'] ?? null);
// Search in schema string properties (ILIKE only for performance).
$properties = $schema->getProperties() ?? [];
foreach ($properties as $propName => $propDef) {
$type = $propDef['type'] ?? 'string';
if ($type === 'string') {
$columnName = $this->sanitizeColumnName(name: $propName);
// In UNION contexts, only search columns that actually exist in this table.
if ($existingColumns !== null && in_array($columnName, $existingColumns, true) === false) {
continue;
}
$searchConditions[] = "{$columnName}::text ILIKE {$likePattern}";
}
}
// Search in metadata text fields (ILIKE for all).
$searchConditions[] = "_name::text ILIKE {$likePattern}";
$searchConditions[] = "_description::text ILIKE {$likePattern}";
$searchConditions[] = "_summary::text ILIKE {$likePattern}";
// Add fuzzy matching ONLY for _name when explicitly requested via _fuzzy=true.
// This uses pg_trgm similarity() for typo tolerance at ~13% performance cost.
if ($fuzzyEnabled === true) {
$searchConditions[] = "similarity(_name::text, {$quotedTerm}) > 0.1";
}
if (empty($searchConditions) === false) {
return '('.implode(' OR ', $searchConditions).')';
}
return null;
}//end buildSearchConditionSql()
/**
* Build object field filter SQL conditions for non-reserved query parameters
*
* @param array $query Full query array
* @param Schema $schema Schema for property type lookup
* @param object $connection Database connection for value quoting
*
* @return string[] Array of SQL WHERE conditions
*/
private function buildObjectFilterConditionsSql(array $query, Schema $schema, object $connection): array
{
$conditions = [];
$reservedParams = $this->getReservedParams();
$properties = $schema->getProperties() ?? [];
foreach ($query as $key => $value) {
// Skip reserved params, underscore-prefixed params, and @ metadata params.
if (in_array($key, $reservedParams, true) === true
|| str_starts_with($key, '_') === true
|| str_starts_with($key, '@') === true
) {
continue;
}
// Check if this property exists in the schema.
if (isset($properties[$key]) === false) {
// Property doesn't exist - add impossible condition.
$conditions[] = '1=0';
continue;
}
$columnName = $this->sanitizeColumnName(name: $key);
$propertyType = $properties[$key]['type'] ?? 'string';
// Handle array-type properties (JSONB columns) with JSON containment operator.
if ($propertyType === 'array') {
$conditions[] = $this->buildArrayPropertyConditionSql(
columnName: $columnName,
value: $value,
connection: $connection
);
continue;
}
// Handle array filter values with IN clause (for non-array property types).
if (is_array($value) === true) {
if (empty($value) === false) {
$quotedValues = array_map(
fn($v) => $connection->quote((string) $v),
$value
);
$conditions[] = "{$columnName} IN (".implode(', ', $quotedValues).')';
}
continue;
}
// Simple equality filter.
$conditions[] = "{$columnName} = ".$connection->quote((string) $value);
}//end foreach
return $conditions;
}//end buildObjectFilterConditionsSql()
/**
* Build SQL condition for array-type (JSONB) property filtering
*
* Uses PostgreSQL JSONB containment operator (@>) to check if a JSON array
* column contains the specified value(s).
*
* @param string $columnName Sanitized column name
* @param mixed $value Filter value (string or array of strings)
* @param object $connection Database connection for value quoting
*
* @return string SQL condition for the array property filter
*/
private function buildArrayPropertyConditionSql(string $columnName, mixed $value, object $connection): string
{
// Normalize value to array.
$values = [$value];
if (is_array($value) === true) {
$values = $value;
}
if (empty($values) === true || count($values) === 1) {
// Single value (or empty): check if JSON array contains this value.
$singleValue = $values[0] ?? '';
$jsonValue = $connection->quote(json_encode([$singleValue]));
return "COALESCE({$columnName}, '[]')::jsonb @> {$jsonValue}::jsonb";
}
// Multiple values: check if JSON array contains ANY of the values (OR logic).
$orParts = [];
foreach ($values as $v) {
$jsonValue = $connection->quote(json_encode([$v]));
$orParts[] = "COALESCE({$columnName}, '[]')::jsonb @> {$jsonValue}::jsonb";
}
return '('.implode(' OR ', $orParts).')';
}//end buildArrayPropertyConditionSql()
/**
* Get the list of reserved query parameter names
*
* These parameters are used for pagination, sorting, and internal flags
* and should not be treated as object field filters.
*
* @return string[] List of reserved parameter names
*/
private function getReservedParams(): array
{
return [
'_limit',
'_offset',
'_page',
'_order',
'_sort',
'_search',
'_extend',
'_fields',
'_filter',
'_unset',
'_facets',
'_facetable',
'_aggregations',
'_debug',
'_rbac',
'_multitenancy',
'_validation',
'_events',
'_register',
'_schema',
'_schemas',
'_ids',
'_count',
'_includeDeleted',
'_relations_contains',
'_multitenancy_explicit',
'_fuzzy',
'_empty',
'register',
'schema',
'registers',
'schemas',
'extend',
];
}//end getReservedParams()
/**
* Apply basic filters like deleted status
*
* @param IQueryBuilder $qb Query builder to modify
* @param bool $includeDeleted Whether to include deleted objects
*
* @return void
*/
private function applyBasicFilters(IQueryBuilder $qb, bool $includeDeleted): void
{
// Handle deleted filter.
if ($includeDeleted === false) {
$qb->andWhere($qb->expr()->isNull('t._deleted'));
}
}//end applyBasicFilters()
/**
* Check if a mixed value represents an explicit boolean true
*
* Handles string, integer, and boolean representations of true.
*
* @param mixed $value The value to check
*
* @return bool True if the value is explicitly true
*/
private function isExplicitlyTrue(mixed $value): bool
{
return $value === true
|| $value === 'true'
|| $value === '1'
|| $value === 1;
}//end isExplicitlyTrue()
/**
* Resolve the multitenancy flag based on public schema access and explicit request
*
* Public schemas bypass multitenancy by default, UNLESS the user explicitly requests
* multitenancy with _multi=true. This allows public data to be visible across orgs
* while still giving users the option to filter by their own organisation.
*
* @param bool $_multitenancy Current multitenancy flag
* @param bool $multitenancyExplicit Whether multitenancy was explicitly requested
* @param Schema $schema Schema to check for public access
*
* @return bool Resolved multitenancy flag
*/
private function resolveMultitenancyFlag(
bool $_multitenancy,
bool $multitenancyExplicit,
Schema $schema
): bool {
if ($_multitenancy === true) {
$schemaAuth = $schema->getAuthorization();
$readGroups = $schemaAuth['read'] ?? [];
$hasPublic = $this->hasPublicReadAccess(readRules: $readGroups);
// Public schemas bypass multitenancy UNLESS user explicitly set _multi=true.
if ($hasPublic === true && $multitenancyExplicit === false) {
return false;
}
}
return $_multitenancy;
}//end resolveMultitenancyFlag()
/**
* Apply access control filters (multitenancy and RBAC) to the query
*
* Handles the interaction between RBAC and _multitenancy:
* - When user has NO RBAC access: Apply multitenancy as normal (AND restriction)
* - When user HAS RBAC access AND _multi=true: Apply multitenancy AFTER RBAC
* - When user HAS RBAC access AND _multi=false: Skip multitenancy (RBAC handles access)
*
* @param IQueryBuilder $qb Query builder to modify
* @param Schema $schema Schema for access control rules
* @param bool $_rbac Whether RBAC filtering is enabled
* @param bool $_multitenancy Whether multitenancy filtering is enabled
* @param bool $multitenancyExplicit Whether multitenancy was explicitly requested
*
* @return void
*/
private function applyAccessControlFilters(
IQueryBuilder $qb,
Schema $schema,
bool $_rbac,
bool $_multitenancy,
bool $multitenancyExplicit
): void {
// Check if user qualifies for any RBAC rule (simple or conditional).
// When user has RBAC access, multitenancy is bypassed by default (RBAC controls access).
$userHasRbacAccess = false;
if ($_rbac === true) {
$userHasRbacAccess = $this->rbacHandler->hasConditionalRulesBypassingMultitenancy(
schema: $schema,
action: 'read'
);
}
// Apply multitenancy filter based on RBAC access and explicit request.
if ($_multitenancy === true) {
$applyMultitenancy = false;
if ($userHasRbacAccess === false) {
// No RBAC access - apply multitenancy as normal.
$applyMultitenancy = true;
} else if ($multitenancyExplicit === true) {
// User has RBAC access but explicitly requested _multi=true
// Apply multitenancy to further restrict results to their org.
$applyMultitenancy = true;
}
// Otherwise: user has RBAC access and didn't request _multi=true
// Skip multitenancy - let RBAC handle access control.
if ($applyMultitenancy === true) {
$this->organizationHandler->applyOrganizationFilter(
qb: $qb,
adminBypassEnabled: $this->organizationHandler->isAdminOverrideEnabled()
);
}
}//end if
// Apply RBAC filtering if enabled.
if ($_rbac === true) {
$this->rbacHandler->applyRbacFilters(
qb: $qb,
schema: $schema,
action: 'read'
);
}
}//end applyAccessControlFilters()
/**
* Check if fuzzy search should be enabled based on the _fuzzy parameter
*
* Fuzzy matching is only enabled when explicitly requested AND the pg_trgm
* extension is available.
*
* @param mixed $fuzzyParam The raw _fuzzy parameter value
*
* @return bool True if fuzzy search should be enabled
*/
private function isFuzzySearchEnabled(mixed $fuzzyParam): bool
{
if ($this->isExplicitlyTrue(value: $fuzzyParam) === true) {
return $this->hasPgTrgmExtension();
}
return false;
}//end isFuzzySearchEnabled()
/**
* Apply metadata filters to the query
*
* @param IQueryBuilder $qb Query builder to modify
* @param array $filters Metadata filters to apply
*
* @return void
*/
private function applyMetadataFilters(IQueryBuilder $qb, array $filters): void
{
foreach ($filters as $field => $value) {
$columnName = '_'.$field;
// Metadata columns are prefixed with _.
if ($value === 'IS NOT NULL') {
$qb->andWhere($qb->expr()->isNotNull("t.{$columnName}"));
} else if ($value === 'IS NULL') {
$qb->andWhere($qb->expr()->isNull("t.{$columnName}"));
} else if (is_array($value) === true) {
$qb->andWhere(
$qb->expr()->in(
"t.{$columnName}",
$qb->createNamedParameter($value, IQueryBuilder::PARAM_STR_ARRAY)
)
);
continue;
}
$qb->andWhere($qb->expr()->eq("t.{$columnName}", $qb->createNamedParameter($value)));
}
}//end applyMetadataFilters()
/**
* Apply object field filters based on schema properties
*
* @param IQueryBuilder $qb Query builder to modify
* @param array $filters Object field filters to apply
* @param Schema $schema Schema for column mapping
*
* @return void
*/
private function applyObjectFilters(IQueryBuilder $qb, array $filters, Schema $schema): void
{
$properties = $schema->getProperties();
foreach ($filters as $field => $value) {
// Check if this field exists as a column in the schema.
if (($properties[$field] ?? null) === null) {
// Property doesn't exist in this schema but a filter was requested.
// Track the ignored filter for client feedback.
$this->ignoredFilters[] = $field;
// Add a condition that always evaluates to false to return zero results.
// This ensures multi-schema searches don't return unfiltered results
// from schemas that lack the filtered property.
$qb->andWhere('1 = 0');
continue;
}
$columnName = $this->sanitizeColumnName(name: $field);
$propertyType = $properties[$field]['type'] ?? 'string';
if ($value === 'IS NOT NULL') {
$qb->andWhere($qb->expr()->isNotNull("t.{$columnName}"));
continue;
}
if ($value === 'IS NULL') {
$qb->andWhere($qb->expr()->isNull("t.{$columnName}"));
continue;
}
// Handle array type columns (JSON arrays in PostgreSQL).
if ($propertyType === 'array') {
$this->applyJsonArrayFilter(qb: $qb, columnName: $columnName, value: $value);
continue;
}
// Handle object type columns (JSON objects with 'value' key containing UUID).
if ($propertyType === 'object') {
$this->applyJsonObjectFilter(qb: $qb, columnName: $columnName, value: $value);
continue;
}
if (is_array($value) === true) {
$qb->andWhere(
$qb->expr()->in(
"t.{$columnName}",
$qb->createNamedParameter($value, IQueryBuilder::PARAM_STR_ARRAY)
)
);
continue;
}
$qb->andWhere($qb->expr()->eq("t.{$columnName}", $qb->createNamedParameter($value)));
}//end foreach
}//end applyObjectFilters()
/**
* Apply filter for JSON array columns using PostgreSQL jsonb operators
*
* @param IQueryBuilder $qb Query builder to modify
* @param string $columnName Column name to filter
* @param mixed $value Filter value (string or array of strings)
*
* @return void
*/
private function applyJsonArrayFilter(IQueryBuilder $qb, string $columnName, mixed $value): void
{
// Normalize value to array.
$values = [$value];
if (is_array($value) === true) {
$values = $value;
}
if (count($values) === 1) {
// Single value: check if JSON array contains this value.
// Use COALESCE to handle NULL values and avoid type cast issues with QueryBuilder.
$jsonValue = json_encode([$values[0]]);
$qb->andWhere(
"COALESCE(t.{$columnName}, '[]')::jsonb @> ".$qb->createNamedParameter($jsonValue)
);
return;
}
// Multiple values: check if JSON array contains ANY of the values (OR logic).
$orConditions = $qb->expr()->orX();
foreach ($values as $v) {
$jsonValue = json_encode([$v]);
// Use raw SQL with COALESCE to handle NULL values properly.
$orConditions->add(
"COALESCE(t.{$columnName}, '[]')::jsonb @> ".$qb->createNamedParameter($jsonValue)
);
}
$qb->andWhere($orConditions);
}//end applyJsonArrayFilter()
/**
* Apply filter for object columns (related objects)
*
* Handles two storage formats:
* 1. JSON object (jsonb column): {"value": "uuid"} - extracts value key
* 2. Plain string (varchar column): "uuid" - direct comparison
*
* Uses text-based matching to work with both column types safely.
*
* @param IQueryBuilder $qb Query builder to modify
* @param string $columnName Column name to filter
* @param mixed $value Filter value (UUID string or array of UUIDs)
*
* @return void
*/
private function applyJsonObjectFilter(IQueryBuilder $qb, string $columnName, mixed $value): void
{
// Normalize value to array.
$values = [$value];
if (is_array($value) === true) {
$values = $value;
}
if (count($values) === 1) {
// Single value: match both plain UUID and JSON format using text comparison.
// Plain format: column contains exactly "uuid".
// JSON format: column contains "value": "uuid" pattern.
$param = $qb->createNamedParameter($values[0]);
$jsonPattern = $qb->createNamedParameter('%"value": "'.$values[0].'"%');
$qb->andWhere(
"(t.{$columnName}::text = {$param} OR t.{$columnName}::text LIKE {$jsonPattern})"
);
return;
}
// Multiple values: check if value matches ANY of the values (OR logic).
$orConditions = $qb->expr()->orX();
foreach ($values as $v) {
$param = $qb->createNamedParameter($v);
$jsonPattern = $qb->createNamedParameter('%"value": "'.$v.'"%');
$orConditions->add(
"(t.{$columnName}::text = {$param} OR t.{$columnName}::text LIKE {$jsonPattern})"
);
}
$qb->andWhere($orConditions);
}//end applyJsonObjectFilter()
/**
* Apply ID-based filtering (UUID, slug, etc.)
*
* @param IQueryBuilder $qb Query builder to modify
* @param array $ids Array of IDs to filter by
*
* @return void
*/
private function applyIdFilters(IQueryBuilder $qb, array $ids): void
{
$orX = $qb->expr()->orX();
$orX->add($qb->expr()->in('t._uuid', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_STR_ARRAY)));
$orX->add($qb->expr()->in('t._slug', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_STR_ARRAY)));
$qb->andWhere($orX);