/
SqaleRepositoryService.java
839 lines (728 loc) · 35.3 KB
/
SqaleRepositoryService.java
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
/*
* Copyright (C) 2010-2021 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.repo.sqale;
import java.util.Objects;
import java.util.*;
import java.util.function.Consumer;
import javax.annotation.PreDestroy;
import com.google.common.base.Strings;
import com.querydsl.core.Tuple;
import com.querydsl.sql.dml.SQLUpdateClause;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.evolveum.midpoint.common.crypto.CryptoUtil;
import com.evolveum.midpoint.prism.ConsistencyCheckScope;
import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ItemDeltaCollectionsUtil;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.equivalence.EquivalenceStrategy;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.repo.api.*;
import com.evolveum.midpoint.repo.api.perf.PerformanceMonitor;
import com.evolveum.midpoint.repo.api.query.ObjectFilterExpressionEvaluator;
import com.evolveum.midpoint.repo.sqale.operations.AddObjectOperation;
import com.evolveum.midpoint.repo.sqale.qmodel.SqaleTableMapping;
import com.evolveum.midpoint.repo.sqale.qmodel.object.MObject;
import com.evolveum.midpoint.repo.sqale.qmodel.object.ObjectSqlTransformer;
import com.evolveum.midpoint.repo.sqale.qmodel.object.QObject;
import com.evolveum.midpoint.repo.sqlbase.*;
import com.evolveum.midpoint.repo.sqlbase.perfmon.SqlPerformanceMonitorImpl;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.schema.internals.InternalMonitor;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
/**
* Repository implementation based on SQL, JDBC and Querydsl without any ORM.
* WORK IN PROGRESS:
* It will be PostgreSQL only or at least PG optimized with generic SQL support for other unsupported DB.
* Possible Oracle support is in play.
*/
public class SqaleRepositoryService implements RepositoryService {
private static final Trace LOGGER = TraceManager.getTrace(SqaleRepositoryService.class);
/**
* Class name prefix for operation names, including the dot separator.
* Use with various `RepositoryService.OP_*` constants, not with constants without `OP_`
* prefix because they already contain class name of the service interface.
*/
private static final String OP_NAME_PREFIX = SqaleRepositoryService.class.getSimpleName() + '.';
private static final int MAX_CONFLICT_WATCHERS = 10;
private final SqaleRepoContext sqlRepoContext;
private final SchemaHelper schemaService;
private final SqlQueryExecutor sqlQueryExecutor;
private final SqaleTransformerContext transformerContext;
private final SqlPerformanceMonitorsCollection sqlPerformanceMonitorsCollection;
private final ThreadLocal<List<ConflictWatcherImpl>> conflictWatchersThreadLocal =
ThreadLocal.withInitial(ArrayList::new);
private SqlPerformanceMonitorImpl performanceMonitor; // set to null in destroy
public SqaleRepositoryService(
SqaleRepoContext sqlRepoContext,
SchemaHelper schemaService,
SqlPerformanceMonitorsCollection sqlPerformanceMonitorsCollection) {
this.sqlRepoContext = sqlRepoContext;
this.schemaService = schemaService;
this.sqlQueryExecutor = new SqlQueryExecutor(sqlRepoContext);
this.transformerContext = new SqaleTransformerContext(schemaService, sqlRepoContext);
this.sqlPerformanceMonitorsCollection = sqlPerformanceMonitorsCollection;
// monitor initialization and registration
JdbcRepositoryConfiguration config = sqlRepoContext.getJdbcRepositoryConfiguration();
performanceMonitor = new SqlPerformanceMonitorImpl(
config.getPerformanceStatisticsLevel(), config.getPerformanceStatisticsFile());
sqlPerformanceMonitorsCollection.register(performanceMonitor);
}
@Override
public @NotNull <T extends ObjectType> PrismObject<T> getObject(Class<T> type, String oid,
Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
Objects.requireNonNull(type, "Object type must not be null.");
UUID oidUuid = checkOid(oid);
Objects.requireNonNull(parentResult, "Operation result must not be null.");
LOGGER.debug("Getting object '{}' with oid '{}': {}",
type.getSimpleName(), oid, parentResult.getOperation());
InternalMonitor.recordRepositoryRead(type, oid);
OperationResult operationResult = parentResult.subresult(GET_OBJECT)
.addQualifier(type.getSimpleName())
.setMinor()
.addParam("type", type.getName())
.addParam("oid", oid)
.build();
PrismObject<T> object;
try {
//noinspection unchecked
object = (PrismObject<T>) readByOid(type, oidUuid, options).asPrismObject();
// TODO what's with all the conflict watchers?
// "objectLocal" is here just to provide effectively final variable for the lambda below
// PrismObject<T> objectLocal = executeAttempts(oid, OP_GET_OBJECT, type, "getting",
// subResult, () -> objectRetriever.getObjectAttempt(type, oid, options, operationResult));
// object = objectLocal;
// invokeConflictWatchers((w) -> w.afterGetObject(objectLocal));
} catch (RuntimeException e) { // TODO what else to catch?
handleGeneralException(e, operationResult);
throw new SystemException(e);
} catch (Throwable t) {
operationResult.recordFatalError(t);
throw t;
} finally {
operationResult.computeStatusIfUnknown();
// OperationLogger.logGetObject(type, oid, options, object, operationResult);
// TODO some logging
}
return object;
}
private UUID checkOid(String oid) {
Objects.requireNonNull(oid, "Oid must not be null");
try {
return UUID.fromString(oid);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("OID " + oid + " is invalid", e);
}
}
/**
* Read object with shortest possible read-only transaction.
* Not intended as part of more complex transactional scenarios, only for {@link #getObject}.
*/
private <S extends ObjectType, Q extends QObject<R>, R extends MObject> S readByOid(
@NotNull Class<S> schemaType,
@NotNull UUID oid,
Collection<SelectorOptions<GetOperationOptions>> options)
throws SchemaException, ObjectNotFoundException {
// context.processOptions(options); TODO how to process option, is setting of select expressions enough?
SqaleTableMapping<S, Q, R> rootMapping =
sqlRepoContext.getMappingBySchemaType(schemaType);
final Q root = rootMapping.defaultAlias();
Tuple result;
try (JdbcSession jdbcSession = sqlRepoContext.newJdbcSession().startReadOnlyTransaction()) {
result = sqlRepoContext.newQuery(jdbcSession.connection())
.from(root)
.select(rootMapping.selectExpressions(root, options))
.where(root.oid.eq(oid))
.fetchOne();
}
if (result == null || result.get(root.fullObject) == null) {
// TODO is there a case when fullObject can be null?
String oidString = oid.toString();
throw new ObjectNotFoundException("Object of type '" + schemaType.getSimpleName()
+ "' with oid '" + oidString + "' was not found.", oidString);
}
return rootMapping.createTransformer(transformerContext)
.toSchemaObject(result, root, options);
}
/** Read object using provided {@link JdbcSession} as a part of already running transaction. */
private <S extends ObjectType, Q extends QObject<R>, R extends MObject> S readByOid(
@NotNull JdbcSession jdbcSession,
@NotNull Class<S> schemaType,
@NotNull UUID oid,
Collection<SelectorOptions<GetOperationOptions>> options)
throws SchemaException {
// context.processOptions(options); TODO how to process option, is setting of select expressions enough?
SqaleTableMapping<S, Q, R> rootMapping =
sqlRepoContext.getMappingBySchemaType(schemaType);
final Q root = rootMapping.defaultAlias();
Tuple result = sqlRepoContext.newQuery(jdbcSession.connection())
.from(root)
.select(rootMapping.selectExpressions(root, options))
.where(root.oid.eq(oid))
.fetchOne();
return rootMapping.createTransformer(transformerContext)
.toSchemaObject(result, root, options);
}
@Override
public <T extends ObjectType> String getVersion(
Class<T> type, String oid, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
return null;
// TODO
}
// Add/modify/delete
@Override
@NotNull
public <T extends ObjectType> String addObject(
@NotNull PrismObject<T> object,
@Nullable RepoAddOptions options,
@NotNull OperationResult parentResult)
throws ObjectAlreadyExistsException, SchemaException {
Objects.requireNonNull(object, "Object must not be null.");
PolyString name = object.getName();
if (name == null || Strings.isNullOrEmpty(name.getOrig())) {
// TODO this throws exception but leaves the result unchanged, is it OK?
throw new SchemaException("Attempt to add object without name.");
}
Objects.requireNonNull(parentResult, "Operation result must not be null.");
if (options == null) {
options = new RepoAddOptions();
}
//noinspection ConstantConditions
LOGGER.debug(
"Adding object type '{}', overwrite={}, allowUnencryptedValues={}, name={} - {}",
object.getCompileTimeClass().getSimpleName(), options.isOverwrite(),
options.isAllowUnencryptedValues(), name.getOrig(), name.getNorm());
if (InternalsConfig.encryptionChecks && !RepoAddOptions.isAllowUnencryptedValues(options)) {
CryptoUtil.checkEncrypted(object);
}
if (InternalsConfig.consistencyChecks) {
object.checkConsistence(ConsistencyCheckScope.THOROUGH);
} else {
object.checkConsistence(ConsistencyCheckScope.MANDATORY_CHECKS_ONLY);
}
OperationResult operationResult = parentResult.subresult(ADD_OBJECT)
.addQualifier(object.asObjectable().getClass().getSimpleName())
.addParam("object", object)
.addParam("options", options.toString())
.build();
// SqlPerformanceMonitorImpl pm = getPerformanceMonitor();
// long opHandle = pm.registerOperationStart(OP_ADD_OBJECT, object.getCompileTimeClass());
// int attempt = 1;
// int restarts = 0;
// boolean noFetchExtensionValueInsertionForbidden = false;
try {
// TODO use executeAttempts
final String operation = "adding";
if (object.getVersion() == null) {
object.setVersion("1");
}
String oid = new AddObjectOperation<>(object, options, operationResult)
.execute(transformerContext);
return oid;
/*
String proposedOid = object.getOid();
while (true) {
try {
String createdOid = objectUpdater.addObjectAttempt(object, options, noFetchExtensionValueInsertionForbidden, subResult);
invokeConflictWatchers((w) -> w.afterAddObject(createdOid, object));
return createdOid;
} catch (RestartOperationRequestedException ex) {
// special case: we want to restart but we do not want to count these
LOGGER.trace("Restarting because of {}", ex.getMessage());
restarts++;
if (restarts > RESTART_LIMIT) {
throw new IllegalStateException("Too many operation restarts");
}
} catch (RuntimeException ex) {
attempt = baseHelper.logOperationAttempt(proposedOid, operation, attempt, ex, subResult);
// pm.registerOperationNewAttempt(opHandle, attempt);
}
noFetchExtensionValueInsertionForbidden = true; // todo This is a temporary measure; needs better handling.
}
} finally {
// pm.registerOperationFinish(opHandle, attempt);
// OperationLogger.logAdd(object, options, subResult); TODO logging
}
*/
} catch (Throwable t) {
operationResult.recordFatalError(t);
throw t;
} finally {
operationResult.computeStatusIfUnknown();
}
}
@Override
@NotNull
public <T extends ObjectType> ModifyObjectResult<T> modifyObject(
@NotNull Class<T> type,
@NotNull String oid,
@NotNull Collection<? extends ItemDelta<?, ?>> modifications,
@NotNull OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
return modifyObject(type, oid, modifications, null, parentResult);
}
@Override
@NotNull
public <T extends ObjectType> ModifyObjectResult<T> modifyObject(
@NotNull Class<T> type,
@NotNull String oid,
@NotNull Collection<? extends ItemDelta<?, ?>> modifications,
@Nullable RepoModifyOptions options,
@NotNull OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
try {
return modifyObject(type, oid, modifications, null, options, parentResult);
} catch (PreconditionViolationException e) {
throw new AssertionError(e); // with null precondition we couldn't get this exception
}
}
@Override
@NotNull
public <T extends ObjectType> ModifyObjectResult<T> modifyObject(
@NotNull Class<T> type,
@NotNull String oid,
@NotNull Collection<? extends ItemDelta<?, ?>> modifications,
@Nullable ModificationPrecondition<T> precondition,
@Nullable RepoModifyOptions options,
@NotNull OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, PreconditionViolationException {
Objects.requireNonNull(modifications, "Modifications must not be null.");
Objects.requireNonNull(type, "Object class in delta must not be null.");
UUID oidUuid = checkOid(oid);
Objects.requireNonNull(parentResult, "Operation result must not be null.");
OperationResult operationResult = parentResult.subresult(MODIFY_OBJECT)
.addQualifier(type.getSimpleName())
.addParam("type", type.getName())
.addParam("oid", oid)
.addArbitraryObjectCollectionAsParam("modifications", modifications)
.build();
try {
if (modifications.isEmpty() && !RepoModifyOptions.isForceReindex(options)) {
LOGGER.debug("Modification list is empty, nothing was modified.");
operationResult.recordStatus(OperationResultStatus.SUCCESS,
"Modification list is empty, nothing was modified.");
return new ModifyObjectResult<>(modifications);
}
if (InternalsConfig.encryptionChecks) {
CryptoUtil.checkEncrypted(modifications);
}
if (InternalsConfig.consistencyChecks) {
ItemDeltaCollectionsUtil.checkConsistence(modifications, ConsistencyCheckScope.THOROUGH);
} else {
ItemDeltaCollectionsUtil.checkConsistence(modifications, ConsistencyCheckScope.MANDATORY_CHECKS_ONLY);
}
logTraceModifications(modifications);
try (JdbcSession jdbcSession = sqlRepoContext.newJdbcSession().startTransaction()) {
GetOperationOptionsBuilder getOptionsBuilder = schemaService.getOperationOptionsBuilder();
T object = readByOid(jdbcSession, type, oidUuid, getOptionsBuilder.build());
//noinspection unchecked
PrismObject<T> prismObject = (PrismObject<T>) object.asPrismObject();
if (precondition != null && !precondition.holds(prismObject)) {
throw new PreconditionViolationException("Modification precondition does not hold for " + prismObject);
}
// invokeConflictWatchers(w -> w.beforeModifyObject(prismObject)); TODO
PrismObject<T> originalObject = prismObject.clone();
modifyObjectAttempt(jdbcSession, prismObject, modifications);
/*
RObject rObject = objectDeltaUpdater.modifyObject(type, oid, modifications, prismObject, modifyOptions, session, attemptContext);
LOGGER.trace("OBJECT after:\n{}", prismObject.debugDumpLazily());
// Continuing the photo treatment: should we remove the (now obsolete) focus photo?
// We have to test prismObject at this place, because updateFullObject (below) removes photo property from the prismObject.
shouldPhotoBeRemoved =
containsFocusPhotoModification && ((FocusType) prismObject.asObjectable()).getJpegPhoto() == null;
updateFullObject(rObject, prismObject);
LOGGER.trace("Starting save.");
session.save(rObject);
LOGGER.trace("Save finished.");
*/
// TODO is modifications cloning unavoidable? see the clone at the start of ObjectUpdater.modifyObjectAttempt
// If cloning will be necessary, do it at the beginning of modifyObjectAttempt,
// especially if called potentially multiple times.
return new ModifyObjectResult<>(originalObject, prismObject, modifications);
}
} catch (Throwable t) {
operationResult.recordFatalError(t);
throw t;
} finally {
operationResult.computeStatusIfUnknown();
}
}
/**
* @param <S> schema type
* @param <Q> type of entity path
* @param <R> row type related to the {@link Q}
*/
private <S extends ObjectType, Q extends QObject<R>, R extends MObject>
void modifyObjectAttempt(
JdbcSession jdbcSession,
PrismObject<S> prismObject,
Collection<? extends ItemDelta<?, ?>> modifications) throws SchemaException {
Collection<? extends ItemDelta<?, ?>> narrowedModifications =
prismObject.narrowModifications(modifications, EquivalenceStrategy.DATA,
EquivalenceStrategy.REAL_VALUE_CONSIDER_DIFFERENT_IDS, true);
LOGGER.trace("Narrowed modifications:\n{}", DebugUtil.debugDumpLazily(narrowedModifications));
SqaleTableMapping<S, Q, R> rootMapping =
sqlRepoContext.getMappingBySchemaType(prismObject.getCompileTimeClass());
Q root = rootMapping.defaultAlias();
// TODO update will probably be replaced by some "update context" to be able to update multiple tables (+insert/delete of details)
SQLUpdateClause update = jdbcSession.newUpdate(root)
.where(root.oid.eq(UUID.fromString(prismObject.getOid())));
// TODO taken from "legacy" branch, how is this worse/different from ObjectDeltaUpdater.handleObjectCommonAttributes()?
ItemDeltaCollectionsUtil.applyTo(modifications, prismObject);
ObjectTypeUtil.normalizeAllRelations(prismObject, schemaService.relationRegistry());
// TODO generate missing container IDs? is it needed? doesn't model do it? see old repo PrismIdentifierGenerator
int newVersion = SqaleUtils.objectVersionAsInt(prismObject) + 1;
prismObject.setVersion(String.valueOf(newVersion));
ObjectSqlTransformer<S, Q, R> transformer = (ObjectSqlTransformer<S, Q, R>)
rootMapping.createTransformer(transformerContext);
update.set(root.fullObject, transformer.createFullObject(prismObject.asObjectable()));
update.set(root.version, newVersion);
update.execute();
}
private void logTraceModifications(@NotNull Collection<? extends ItemDelta<?, ?>> modifications) {
if (LOGGER.isTraceEnabled()) {
for (ItemDelta<?, ?> modification : modifications) {
if (modification instanceof PropertyDelta<?>) {
PropertyDelta<?> propDelta = (PropertyDelta<?>) modification;
if (propDelta.getPath().equivalent(ObjectType.F_NAME)) {
Collection<PrismPropertyValue<PolyString>> values = propDelta.getValues(PolyString.class);
for (PrismPropertyValue<PolyString> pval : values) {
PolyString value = pval.getValue();
LOGGER.trace("NAME delta: {} - {}", value.getOrig(), value.getNorm());
}
}
}
}
}
}
@Override
public @NotNull <T extends ObjectType> DeleteObjectResult deleteObject(
Class<T> type, String oid, OperationResult parentResult)
throws ObjectNotFoundException {
return null;
// TODO
}
// Counting/searching
@Override
public <T extends ObjectType> int countObjects(Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult)
throws SchemaException {
Objects.requireNonNull(type, "Object type must not be null.");
Objects.requireNonNull(parentResult, "Operation result must not be null.");
OperationResult operationResult = parentResult.subresult(OP_NAME_PREFIX + OP_COUNT_OBJECTS)
.addQualifier(type.getSimpleName())
.addParam("type", type.getName())
.addParam("query", query)
.build();
try {
var queryContext = SqaleQueryContext.from(type, transformerContext, sqlRepoContext);
return sqlQueryExecutor.count(queryContext, query, options);
} catch (QueryException | RuntimeException e) {
handleGeneralException(e, operationResult);
throw new SystemException(e);
} catch (Throwable t) {
operationResult.recordFatalError(t);
throw t;
} finally {
operationResult.computeStatusIfUnknown();
}
}
@Override
public @NotNull <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjects(
@NotNull Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options,
@NotNull OperationResult parentResult)
throws SchemaException {
Objects.requireNonNull(type, "Object type must not be null.");
Objects.requireNonNull(parentResult, "Operation result must not be null.");
OperationResult operationResult = parentResult.subresult(OP_NAME_PREFIX + OP_SEARCH_OBJECTS)
.addQualifier(type.getSimpleName())
.addParam("type", type.getName())
.addParam("query", query)
.build();
try {
var queryContext = SqaleQueryContext.from(type, transformerContext, sqlRepoContext);
SearchResultList<T> result =
sqlQueryExecutor.list(queryContext, query, options);
// TODO see the commented code from old repo lower, problems for each object must be caught
//noinspection unchecked
return result.map(
o -> (PrismObject<T>) o.asPrismObject());
} catch (QueryException | RuntimeException e) {
handleGeneralException(e, operationResult);
throw new SystemException(e);
} catch (Throwable t) {
operationResult.recordFatalError(t);
throw t;
} finally {
operationResult.computeStatusIfUnknown();
}
}
/*
TODO from ObjectRetriever, how to do this per-object Throwable catch + record result?
should we smuggle the OperationResult all the way to the transformer call?
@NotNull
private <T extends ObjectType> List<PrismObject<T>> queryResultToPrismObjects(
List<T> objects, Class<T> type,
Collection<SelectorOptions<GetOperationOptions>> options,
OperationResult result) throws SchemaException {
List<PrismObject<T>> rv = new ArrayList<>();
if (objects == null) {
return rv;
}
for (T object : objects) {
String oid = object.getOid();
Holder<PrismObject<T>> partialValueHolder = new Holder<>();
PrismObject<T> prismObject;
try {
prismObject = createPrismObject(object, type, oid, options, partialValueHolder);
} catch (Throwable t) {
if (!partialValueHolder.isEmpty()) {
prismObject = partialValueHolder.getValue();
} else {
prismObject = prismContext.createObject(type);
prismObject.setOid(oid);
prismObject.asObjectable().setName(PolyStringType.fromOrig("Unreadable object"));
}
result.recordFatalError("Couldn't retrieve " + type + " " + oid + ": " + t.getMessage(), t);
prismObject.asObjectable().setFetchResult(result.createOperationResultType());
}
rv.add(prismObject);
}
return rv;
}
*/
@Override
public <T extends ObjectType> SearchResultMetadata searchObjectsIterative(
Class<T> type, ObjectQuery query, ResultHandler<T> handler,
Collection<SelectorOptions<GetOperationOptions>> options, boolean strictlySequential,
OperationResult parentResult) throws SchemaException {
return null;
// TODO
}
@Override
public <T extends Containerable> int countContainers(Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult) {
return 0;
}
@Override
public <T extends Containerable> SearchResultList<T> searchContainers(
Class<T> type, ObjectQuery query,
Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult)
throws SchemaException {
Objects.requireNonNull(type, "Container type must not be null.");
Objects.requireNonNull(parentResult, "Operation result must not be null.");
OperationResult operationResult = parentResult.subresult(OP_NAME_PREFIX + SEARCH_CONTAINERS)
.addQualifier(type.getSimpleName())
.addParam("type", type.getName())
.addParam("query", query)
.build();
try {
var queryContext = SqaleQueryContext.from(type, transformerContext, sqlRepoContext);
SearchResultList<T> result =
sqlQueryExecutor.list(queryContext, query, options);
return result;
} catch (QueryException | RuntimeException e) {
handleGeneralException(e, operationResult);
throw new SystemException(e);
} catch (Throwable t) {
operationResult.recordFatalError(t);
throw t;
} finally {
operationResult.computeStatusIfUnknown();
}
}
@Override
public boolean isAnySubordinate(String upperOrgOid, Collection<String> lowerObjectOids)
throws SchemaException {
return false;
// TODO
}
@Override
public <O extends ObjectType> boolean isDescendant(PrismObject<O> object, String orgOid)
throws SchemaException {
return false;
// TODO
}
@Override
public <O extends ObjectType> boolean isAncestor(PrismObject<O> object, String oid)
throws SchemaException {
return false;
// TODO
}
@Override
public <F extends FocusType> PrismObject<F> searchShadowOwner(String shadowOid,
Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult) {
return null;
// TODO
}
@Override
public long advanceSequence(String oid, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
return 0;
// TODO
}
@Override
public void returnUnusedValuesToSequence(
String oid, Collection<Long> unusedValues, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException {
// TODO
}
@Override
public RepositoryDiag getRepositoryDiag() {
return null;
// TODO
}
@Override
public void repositorySelfTest(OperationResult parentResult) {
// TODO
}
@Override
public void testOrgClosureConsistency(boolean repairIfNecessary, OperationResult testResult) {
// TODO
}
@Override
public RepositoryQueryDiagResponse executeQueryDiagnostics(
RepositoryQueryDiagRequest request, OperationResult result) {
// TODO search like containers + dry run?
RepositoryQueryDiagResponse response = new RepositoryQueryDiagResponse(
null, null, Map.of());
// objects, implementationLevelQuery, implementationLevelQueryParameters);
return response;
}
@Override
public <O extends ObjectType> boolean selectorMatches(
ObjectSelectorType objectSelector, PrismObject<O> object,
ObjectFilterExpressionEvaluator filterEvaluator, Trace logger, String logMessagePrefix)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException,
CommunicationException, ConfigurationException, SecurityViolationException {
return false;
// TODO
}
@Override
public void applyFullTextSearchConfiguration(FullTextSearchConfigurationType fullTextSearch) {
// TODO
}
@Override
public FullTextSearchConfigurationType getFullTextSearchConfiguration() {
return null;
// TODO
}
@Override
public void postInit(OperationResult result) throws SchemaException {
// TODO
}
// TODO use internally in various operations (see old repo)
private void invokeConflictWatchers(Consumer<ConflictWatcherImpl> consumer) {
conflictWatchersThreadLocal.get().forEach(consumer);
}
@Override
public ConflictWatcher createAndRegisterConflictWatcher(@NotNull String oid) {
List<ConflictWatcherImpl> watchers = conflictWatchersThreadLocal.get();
if (watchers.size() >= MAX_CONFLICT_WATCHERS) {
throw new IllegalStateException("Conflicts watchers leaking: reached limit of "
+ MAX_CONFLICT_WATCHERS + ": " + watchers);
}
ConflictWatcherImpl watcher = new ConflictWatcherImpl(oid);
watchers.add(watcher);
return watcher;
}
@Override
public void unregisterConflictWatcher(ConflictWatcher watcher) {
ConflictWatcherImpl watcherImpl = (ConflictWatcherImpl) watcher;
List<ConflictWatcherImpl> watchers = conflictWatchersThreadLocal.get();
// change these exceptions to logged errors, eventually
if (watchers == null) {
throw new IllegalStateException(
"No conflict watchers registered for current thread; tried to unregister " + watcher);
} else if (!watchers.remove(watcherImpl)) { // expecting there's only one
throw new IllegalStateException(
"Tried to unregister conflict watcher " + watcher + " that was not registered");
}
}
@Override
public boolean hasConflict(ConflictWatcher watcher, OperationResult parentResult) {
OperationResult result = parentResult.subresult(HAS_CONFLICT)
.setMinor()
.addParam("oid", watcher.getOid())
.addParam("watcherClass", watcher.getClass().getName())
.build();
try {
boolean rv;
if (watcher.hasConflict()) {
rv = true;
} else {
try {
getVersion(ObjectType.class, watcher.getOid(), result);
} catch (ObjectNotFoundException | SchemaException e) {
// just ignore this
}
rv = watcher.hasConflict();
}
result.addReturn("hasConflict", rv);
return rv;
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
@Override
public <T extends ObjectType> void addDiagnosticInformation(Class<T> type, String oid,
DiagnosticInformationType information, OperationResult parentResult)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
// TODO
}
@Override
public PerformanceMonitor getPerformanceMonitor() {
return performanceMonitor;
}
@PreDestroy
public void destroy() {
if (performanceMonitor != null) {
performanceMonitor.shutdown();
sqlPerformanceMonitorsCollection.deregister(performanceMonitor);
performanceMonitor = null;
}
}
/**
* Handles exception outside of transaction - this does not handle transactional problems.
*/
private void handleGeneralException(@NotNull Throwable ex, OperationResult result) {
LOGGER.error("General checked exception occurred.", ex);
recordException(ex, result,
sqlRepoContext.getJdbcRepositoryConfiguration().isFatalException(ex));
throw ex instanceof SystemException
? (SystemException) ex
: new SystemException(ex.getMessage(), ex);
}
private void recordException(@NotNull Throwable ex, OperationResult result, boolean fatal) {
String message = Strings.isNullOrEmpty(ex.getMessage()) ? ex.getMessage() : "null";
if (Strings.isNullOrEmpty(message)) {
message = ex.getMessage();
}
// non-fatal errors will NOT be put into OperationResult, not to confuse the user
if (result != null && fatal) {
result.recordFatalError(message, ex);
}
}
}