de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.tables.StaTableAbstract Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of FROST-Server.SQLjooq Show documentation
Show all versions of FROST-Server.SQLjooq Show documentation
SQL bindings for the FROST-Server.
/*
* Copyright (C) 2024 Fraunhofer Institut IOSB, Fraunhoferstr. 1, D 76131
* Karlsruhe, Germany.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see .
*/
package de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.tables;
import static de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.EntityFactories.CHANGED_MULTIPLE_ROWS;
import static de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPreInsert.Phase.POST_RELATIONS;
import static de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPreInsert.Phase.PRE_RELATIONS;
import de.fraunhofer.iosb.ilt.frostserver.model.DefaultEntity;
import de.fraunhofer.iosb.ilt.frostserver.model.EntityChangedMessage;
import de.fraunhofer.iosb.ilt.frostserver.model.EntityType;
import de.fraunhofer.iosb.ilt.frostserver.model.ModelRegistry;
import de.fraunhofer.iosb.ilt.frostserver.model.core.Entity;
import de.fraunhofer.iosb.ilt.frostserver.model.core.EntitySet;
import de.fraunhofer.iosb.ilt.frostserver.model.core.EntitySetImpl;
import de.fraunhofer.iosb.ilt.frostserver.model.core.PkValue;
import de.fraunhofer.iosb.ilt.frostserver.path.PathElementEntity;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.JooqPersistenceManager;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.bindings.JsonBinding;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.bindings.JsonValue;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.EntityFactories;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPostDelete;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPostInsert;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPostUpdate;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPreDelete;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPreInsert;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.factories.HookPreUpdate;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.fieldwrapper.JsonFieldFactory.JsonFieldWrapper;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.relations.Relation;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.DataSize;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.PropertyFieldRegistry;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.PropertyFieldRegistry.ExpressionFactory;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.PropertyFieldRegistry.PropertyFields;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.QueryState;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.SortingWrapper;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.TableRef;
import de.fraunhofer.iosb.ilt.frostserver.persistence.pgjooq.utils.validator.SecurityTableWrapper;
import de.fraunhofer.iosb.ilt.frostserver.property.EntityPropertyCustomSelect;
import de.fraunhofer.iosb.ilt.frostserver.property.EntityPropertyMain;
import de.fraunhofer.iosb.ilt.frostserver.property.NavigationPropertyMain;
import de.fraunhofer.iosb.ilt.frostserver.property.NavigationPropertyMain.NavigationPropertyEntitySet;
import de.fraunhofer.iosb.ilt.frostserver.service.UpdateMode;
import de.fraunhofer.iosb.ilt.frostserver.util.exception.IncompleteEntityException;
import de.fraunhofer.iosb.ilt.frostserver.util.exception.NoSuchEntityException;
import de.fraunhofer.iosb.ilt.frostserver.util.user.PrincipalExtended;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jooq.Binding;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.DataType;
import org.jooq.Field;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.exception.TooManyRowsException;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author hylke
* @param The exact type of the implementing class.
*/
public abstract class StaTableAbstract> extends TableImpl implements StaMainTable {
private static final Logger LOGGER = LoggerFactory.getLogger(StaTableAbstract.class.getName());
private static final String DO_NOT_KNOW_HOW_TO_JOIN = "Do not know how to join ";
public static final String TYPE_JSONB = "\"pg_catalog\".\"jsonb\"";
public static final String TYPE_GEOMETRY = "\"public\".\"geometry\"";
private transient TableCollection tables;
private transient ModelRegistry modelRegistry;
private transient Map> relations;
private List customFields;
protected transient PropertyFieldRegistry pfReg;
private final DataType> idType;
private SecurityTableWrapper securityWrapper;
private final transient SortedSet> hooksPreInsert;
private final transient SortedSet> hooksPostInsert;
private final transient SortedSet> hooksPreUpdate;
private final transient SortedSet> hooksPostUpdate;
private final transient SortedSet> hooksPreDelete;
private final transient SortedSet> hooksPostDelete;
protected StaTableAbstract(DataType> idType, Name alias, StaTableAbstract aliasedBase, Table updatedSql) {
super(alias, null, updatedSql);
this.idType = idType;
if (aliasedBase == null) {
pfReg = new PropertyFieldRegistry<>(getThis());
relations = new HashMap<>();
hooksPreInsert = new TreeSet<>();
hooksPostInsert = new TreeSet<>();
hooksPreUpdate = new TreeSet<>();
hooksPostUpdate = new TreeSet<>();
hooksPreDelete = new TreeSet<>();
hooksPostDelete = new TreeSet<>();
customFields = new ArrayList<>();
} else {
init(aliasedBase.getModelRegistry(), aliasedBase.getTables());
pfReg = new PropertyFieldRegistry<>(getThis(), aliasedBase.getPropertyFieldRegistry());
relations = aliasedBase.relations;
hooksPreInsert = aliasedBase.hooksPreInsert;
hooksPostInsert = aliasedBase.hooksPostInsert;
hooksPreUpdate = aliasedBase.hooksPreUpdate;
hooksPostUpdate = aliasedBase.hooksPostUpdate;
hooksPreDelete = aliasedBase.hooksPreDelete;
hooksPostDelete = aliasedBase.hooksPostDelete;
customFields = aliasedBase.customFields;
}
}
public DataType> getIdType() {
return idType;
}
@Override
public int registerField(Name name, DataType type, Binding binding) {
customFields.add(new CustomField(name, type, binding));
TableField newField = createField(name, type, "", binding);
return fieldsRow().indexOf(newField);
}
/**
* Must be called directly after creating an alias of this table.
*
* @return this.
*/
protected T initCustomFields() {
for (CustomField customField : customFields) {
createField(customField.name, customField.type, "", customField.binding);
}
return getThis();
}
@Override
public void registerRelation(Relation relation) {
relations.put(relation.getName(), relation);
}
/**
* Add a hook that runs pre-insert.
*
* @param priority The priority. Lower priority hooks run first. This is a
* double to make sure it is always possible to squeeze in between two other
* hooks.
* @param hook The hook
*/
@Override
public void registerHookPreInsert(double priority, HookPreInsert hook) {
hooksPreInsert.add(new SortingWrapper<>(priority, hook));
}
@Override
public void registerHookPostInsert(double priority, HookPostInsert hook) {
hooksPostInsert.add(new SortingWrapper<>(priority, hook));
}
@Override
public void registerHookPreUpdate(double priority, HookPreUpdate hook) {
hooksPreUpdate.add(new SortingWrapper<>(priority, hook));
}
@Override
public void registerHookPostUpdate(double priority, HookPostUpdate hook) {
hooksPostUpdate.add(new SortingWrapper<>(priority, hook));
}
@Override
public void registerHookPreDelete(double priority, HookPreDelete hook) {
hooksPreDelete.add(new SortingWrapper<>(priority, hook));
}
@Override
public void registerHookPostDelete(double priority, HookPostDelete hook) {
hooksPostDelete.add(new SortingWrapper<>(priority, hook));
}
@Override
public SecurityTableWrapper getSecurityWrapper() {
return securityWrapper;
}
@Override
public void setSecurityWrapper(SecurityTableWrapper securityWrapper) {
if (securityWrapper == null) {
return;
}
if (this.securityWrapper != null) {
LOGGER.error("Overwriting security wrapper for table {}, old type: {}", getName(), this.securityWrapper.getClass().getName());
}
LOGGER.info("Applying security wrapper to table {} of type {}", getName(), securityWrapper.getClass().getName());
this.securityWrapper = securityWrapper;
}
@Override
public Relation findRelation(String name) {
Relation relation = relations.get(name);
if (relation == null) {
throw new IllegalStateException(DO_NOT_KNOW_HOW_TO_JOIN + name + " on " + getName() + " " + getEntityType() + " " + getClass().getName());
}
return relation;
}
@Override
public TableRef createJoin(String name, QueryState> queryState, TableRef sourceRef) {
return findRelation(name).join(getThis(), queryState, sourceRef);
}
@Override
public > void createSemiJoin(String name, U targetTable, QueryState queryState) {
findRelation(name).semiJoinTo(getThis(), targetTable, queryState);
}
@Override
public PropertyFieldRegistry getPropertyFieldRegistry() {
if (pfReg == null) {
pfReg = new PropertyFieldRegistry<>(getThis());
}
return pfReg;
}
@Override
public Entity entityFromQuery(Record tuple, QueryState state, DataSize dataSize) {
Entity newEntity = new DefaultEntity(getEntityType());
for (PropertyFields sp : state.getSelectedProperties()) {
sp.converter.convert(state.getMainTable(), tuple, newEntity, dataSize);
}
return newEntity;
}
@Override
public Entity insertIntoDatabase(JooqPersistenceManager pm, Entity entity, UpdateMode updateMode, DataSize dataSize) throws NoSuchEntityException, IncompleteEntityException {
final T thisTable = getThis();
EntityFactories entityFactories = pm.getEntityFactories();
EntityType entityType = entity.getEntityType();
Map insertFields = new HashMap<>();
// First, run the pre-insert hooks in the PRE_RELATION phase.
for (SortingWrapper hookWrapper : hooksPreInsert) {
if (!hookWrapper.getObject().preInsertIntoDatabase(PRE_RELATIONS, pm, entity, insertFields)) {
return null;
}
}
// Second create/validate single-entity navigation links.
// this must happen first so the second step can use these in validation
// TODO: add Priority number, handle priorities < 0 here
for (NavigationPropertyMain np : entityType.getNavigationEntities()) {
if (entity.isSetProperty(np)) {
Entity ne = entity.getProperty(np);
entityFactories.entityExistsOrCreate(pm, ne, updateMode);
PropertyFields registry = pfReg.getSelectFieldsForProperty(np);
registry.converter.convert(thisTable, entity, insertFields);
}
}
// Third, run the pre-insert hooks in POST_RELATION phase.
for (SortingWrapper hookWrapper : hooksPreInsert) {
if (!hookWrapper.getObject().preInsertIntoDatabase(POST_RELATIONS, pm, entity, insertFields)) {
return null;
}
}
// Fourth, deal with the ID, user-defined or not
entityFactories.insertUserDefinedId(pm, insertFields, this.getPkFields(), entity);
// Fifth, deal with the other properties
final Set entityProperties = entityType.getEntityProperties();
final List primaryKeyProperties = entityType.getPrimaryKey().getKeyProperties();
for (EntityPropertyMain ep : entityProperties) {
if (primaryKeyProperties.contains(ep)) {
// EP_ID has already been dealt with above.
continue;
}
if (entity.isSetProperty(ep)) {
pfReg.getSelectFieldsForProperty(ep).converter.convert(thisTable, entity, insertFields);
}
}
// Sixth, do the actual insert.
// This returns the entire inserted row. It may or may not be changed by databse rules or before-triggers.
DSLContext dslContext = pm.getDslContext();
final Set> propertyFields = getPropertyFieldRegistry().getSelectFields(new HashSet<>());
final Set selectFields = QueryState.propertiesToFields(thisTable, propertyFields);
Record result = dslContext.insertInto(thisTable)
.set(insertFields)
.returningResult(selectFields)
.fetchAny();
LOGGER.debug("Inserted {} with id = {}.", entityType, result);
if (result == null) {
return null;
}
Set
© 2015 - 2025 Weber Informatics LLC | Privacy Policy