[FEAT] add capability to change the name of the field (not full tested but base is working)

This commit is contained in:
Edouard DUPIN 2025-01-02 18:01:02 +01:00
parent 54d3f52bd3
commit 645c8b1364
26 changed files with 436 additions and 1021 deletions

View File

@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.dataAccess.options.OptionRenameColumn;
import org.kar.archidata.dataAccess.options.OverrideTableName; import org.kar.archidata.dataAccess.options.OverrideTableName;
import org.kar.archidata.exception.DataAccessException; import org.kar.archidata.exception.DataAccessException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -236,7 +237,7 @@ public class AnnotationTools {
return false; return false;
} }
public static String getFieldName(final Field element) { public static String getFieldNameRaw(final Field element) {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class); final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class);
if (annotation.length == 0) { if (annotation.length == 0) {
return element.getName(); return element.getName();
@ -248,6 +249,26 @@ public class AnnotationTools {
return name; return name;
} }
public record FieldName(
String inStruct,
String inTable) {};
public static FieldName getFieldName(final Field element, final QueryOptions options) {
final String inStructName = getFieldNameRaw(element);
String inTableName = inStructName;
if (options != null) {
final List<OptionRenameColumn> renamesColumn = options.get(OptionRenameColumn.class);
for (final OptionRenameColumn rename : renamesColumn) {
if (rename.columnName.equals(inStructName)) {
inTableName = rename.colomnNewName;
LOGGER.trace("Detect overwrite of column name '{}' => '{}'", inStructName, inTableName);
break;
}
}
}
return new FieldName(inStructName, inTableName);
}
public static boolean getColumnNotNull(final Field element) { public static boolean getColumnNotNull(final Field element) {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class); final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class);
if (annotation.length == 0) { if (annotation.length == 0) {
@ -333,6 +354,7 @@ public class AnnotationTools {
return element.getDeclaredAnnotationsByType(Id.class).length != 0; return element.getDeclaredAnnotationsByType(Id.class).length != 0;
} }
// Note: delete field can not be renamed with OptionRenameColumn
public static String getDeletedFieldName(final Class<?> clazz) { public static String getDeletedFieldName(final Class<?> clazz) {
try { try {
for (final Field elem : clazz.getFields()) { for (final Field elem : clazz.getFields()) {
@ -341,7 +363,7 @@ public class AnnotationTools {
continue; continue;
} }
if (AnnotationTools.isDeletedField(elem)) { if (AnnotationTools.isDeletedField(elem)) {
return AnnotationTools.getFieldName(elem); return AnnotationTools.getFieldNameRaw(elem);
} }
} }
} catch (final Exception ex) { } catch (final Exception ex) {
@ -350,6 +372,7 @@ public class AnnotationTools {
return null; return null;
} }
// Note: update field can not be renamed with OptionRenameColumn
public static String getUpdatedFieldName(final Class<?> clazz) { public static String getUpdatedFieldName(final Class<?> clazz) {
try { try {
for (final Field elem : clazz.getFields()) { for (final Field elem : clazz.getFields()) {
@ -358,7 +381,7 @@ public class AnnotationTools {
continue; continue;
} }
if (AnnotationTools.isUpdateAtField(elem)) { if (AnnotationTools.isUpdateAtField(elem)) {
return AnnotationTools.getFieldName(elem); return AnnotationTools.getFieldNameRaw(elem);
} }
} }
} catch (final Exception ex) { } catch (final Exception ex) {
@ -390,7 +413,7 @@ public class AnnotationTools {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
if (AnnotationTools.getFieldName(field).equals(name)) { if (AnnotationTools.getFieldNameRaw(field).equals(name)) {
return true; return true;
} }
} }
@ -415,7 +438,7 @@ public class AnnotationTools {
if (!full && AnnotationTools.isGenericField(field)) { if (!full && AnnotationTools.isGenericField(field)) {
continue; continue;
} }
out.add(AnnotationTools.getFieldName(field)); out.add(AnnotationTools.getFieldNameRaw(field));
} }
return out; return out;
} }
@ -444,7 +467,7 @@ public class AnnotationTools {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
if (AnnotationTools.getFieldName(field).equals(name)) { if (AnnotationTools.getFieldNameRaw(field).equals(name)) {
return field; return field;
} }
} }

View File

@ -10,6 +10,7 @@ import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.dataAccess.options.Condition; import org.kar.archidata.dataAccess.options.Condition;
import org.kar.archidata.dataAccess.options.FilterValue; import org.kar.archidata.dataAccess.options.FilterValue;
import org.kar.archidata.dataAccess.options.Limit; import org.kar.archidata.dataAccess.options.Limit;
import org.kar.archidata.dataAccess.options.OptionSpecifyType;
import org.kar.archidata.dataAccess.options.QueryOption; import org.kar.archidata.dataAccess.options.QueryOption;
import org.kar.archidata.dataAccess.options.TransmitKey; import org.kar.archidata.dataAccess.options.TransmitKey;
import org.kar.archidata.db.DbConfig; import org.kar.archidata.db.DbConfig;
@ -80,8 +81,10 @@ public abstract class DBAccess implements Closeable {
throw new InternalServerErrorException("Can Not manage the DB-access"); throw new InternalServerErrorException("Can Not manage the DB-access");
} }
public <ID_TYPE> QueryCondition getTableIdCondition(final Class<?> clazz, final ID_TYPE idKey) public <ID_TYPE> QueryCondition getTableIdCondition(
throws DataAccessException { final Class<?> clazz,
final ID_TYPE idKey,
final QueryOptions options) throws DataAccessException {
// Find the ID field type .... // Find the ID field type ....
final Field idField = AnnotationTools.getIdField(clazz); final Field idField = AnnotationTools.getIdField(clazz);
if (idField == null) { if (idField == null) {
@ -89,10 +92,22 @@ public abstract class DBAccess implements Closeable {
"The class have no annotation @Id ==> can not determine the default type searching"); "The class have no annotation @Id ==> can not determine the default type searching");
} }
// check the compatibility of the id and the declared ID // check the compatibility of the id and the declared ID
final Class<?> typeClass = idField.getType(); Class<?> typeClass = idField.getType();
if (idKey == null) { if (idKey == null) {
throw new DataAccessException("Try to identify the ID type and object was null."); throw new DataAccessException("Try to identify the ID type and object was null.");
} }
final String fieldName = AnnotationTools.getFieldName(idField, options).inTable();
final List<OptionSpecifyType> specificTypes = options.get(OptionSpecifyType.class);
if (typeClass == Object.class) {
for (final OptionSpecifyType specify : specificTypes) {
if (specify.name.equals(fieldName)) {
typeClass = specify.clazz;
LOGGER.trace("Detect overwrite of typing ... '{}' => '{}'", typeClass.getCanonicalName(),
specify.clazz.getCanonicalName());
break;
}
}
}
if (idKey.getClass() != typeClass) { if (idKey.getClass() != typeClass) {
if (idKey.getClass() == Condition.class) { if (idKey.getClass() == Condition.class) {
throw new DataAccessException( throw new DataAccessException(
@ -100,7 +115,7 @@ public abstract class DBAccess implements Closeable {
} }
throw new DataAccessException("Request update with the wrong type ..."); throw new DataAccessException("Request update with the wrong type ...");
} }
return new QueryCondition(AnnotationTools.getFieldName(idField), "=", idKey); return new QueryCondition(fieldName, "=", idKey);
} }
// TODO: manage insert batch... // TODO: manage insert batch...
@ -138,7 +153,7 @@ public abstract class DBAccess implements Closeable {
final String jsonData, final String jsonData,
final QueryOption... option) throws Exception { final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
options.add(new TransmitKey(id)); options.add(new TransmitKey(id));
return updateWhereWithJson(clazz, jsonData, options.getAllArray()); return updateWhereWithJson(clazz, jsonData, options.getAllArray());
} }
@ -177,7 +192,7 @@ public abstract class DBAccess implements Closeable {
final List<String> updateColomn, final List<String> updateColomn,
final QueryOption... option) throws Exception { final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(data.getClass(), id))); options.add(new Condition(getTableIdCondition(data.getClass(), id, options)));
options.add(new FilterValue(updateColomn)); options.add(new FilterValue(updateColomn));
options.add(new TransmitKey(id)); options.add(new TransmitKey(id));
return updateWhere(data, options); return updateWhere(data, options);
@ -240,7 +255,7 @@ public abstract class DBAccess implements Closeable {
public <ID_TYPE> long count(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) throws Exception { public <ID_TYPE> long count(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return countWhere(clazz, options); return countWhere(clazz, options);
} }
@ -253,7 +268,7 @@ public abstract class DBAccess implements Closeable {
public <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id, final QueryOption... option) throws Exception { public <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id, final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return getWhere(clazz, options.getAllArray()); return getWhere(clazz, options.getAllArray());
} }
@ -298,7 +313,7 @@ public abstract class DBAccess implements Closeable {
public <ID_TYPE> long deleteHard(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long deleteHard(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws Exception { throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return deleteHardWhere(clazz, options.getAllArray()); return deleteHardWhere(clazz, options.getAllArray());
} }
@ -307,20 +322,20 @@ public abstract class DBAccess implements Closeable {
public <ID_TYPE> long deleteSoft(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long deleteSoft(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws Exception { throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return deleteSoftWhere(clazz, options.getAllArray()); return deleteSoftWhere(clazz, options.getAllArray());
} }
public abstract long deleteSoftWhere(final Class<?> clazz, final QueryOption... option) throws Exception; public abstract long deleteSoftWhere(final Class<?> clazz, final QueryOption... option) throws Exception;
public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id) throws DataAccessException { public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id) throws DataAccessException {
return unsetDeleteWhere(clazz, new Condition(getTableIdCondition(clazz, id))); return unsetDeleteWhere(clazz, new Condition(getTableIdCondition(clazz, id, new QueryOptions())));
} }
public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws DataAccessException { throws DataAccessException {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return unsetDeleteWhere(clazz, options.getAllArray()); return unsetDeleteWhere(clazz, options.getAllArray());
} }

View File

@ -253,8 +253,9 @@ public class DBAccessMorphia extends DBAccess {
final Object data, final Object data,
final Field field, final Field field,
final Document doc, final Document doc,
final List<LazyGetter> lazyCall) throws Exception { final List<LazyGetter> lazyCall,
final String fieldName = AnnotationTools.getFieldName(field); final QueryOptions options) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field, options).inTable();
if (!doc.containsKey(fieldName)) { if (!doc.containsKey(fieldName)) {
field.set(data, null); field.set(data, null);
return; return;
@ -467,7 +468,7 @@ public class DBAccessMorphia extends DBAccess {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
final String tableFieldName = AnnotationTools.getFieldName(field); final String tableFieldName = AnnotationTools.getFieldName(field, options).inTable();
Object currentInsertValue = field.get(data); Object currentInsertValue = field.get(data);
if (AnnotationTools.isPrimaryKey(field)) { if (AnnotationTools.isPrimaryKey(field)) {
primaryKeyField = field; primaryKeyField = field;
@ -586,7 +587,7 @@ public class DBAccessMorphia extends DBAccess {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
final String fieldName = AnnotationTools.getFieldName(field); final String fieldName = AnnotationTools.getFieldName(field, options).inTable();
// update field is not conditioned by filter: // update field is not conditioned by filter:
final boolean updateTime = field.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0; final boolean updateTime = field.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
if (updateTime) { if (updateTime) {
@ -614,7 +615,7 @@ public class DBAccessMorphia extends DBAccess {
continue; continue;
} }
if (addOn != null) { if (addOn != null) {
addOn.insertData(this, field, data, docSet, docUnSet); addOn.insertData(this, field, data, options, docSet, docUnSet);
} else { } else {
final Class<?> type = field.getType(); final Class<?> type = field.getType();
if (!type.isPrimitive()) { if (!type.isPrimitive()) {
@ -668,7 +669,7 @@ public class DBAccessMorphia extends DBAccess {
if (!readAllfields && notRead) { if (!readAllfields && notRead) {
continue; continue;
} }
final String name = AnnotationTools.getFieldName(elem); final String name = AnnotationTools.getFieldName(elem, options).inTable();
fieldsName.add(name); fieldsName.add(name);
} }
return fieldsName; return fieldsName;
@ -805,7 +806,7 @@ public class DBAccessMorphia extends DBAccess {
LOGGER.error("TODO: Add on not managed .6. "); LOGGER.error("TODO: Add on not managed .6. ");
addOn.fillFromDoc(this, doc, elem, data, options, lazyCall); addOn.fillFromDoc(this, doc, elem, data, options, lazyCall);
} else { } else {
setValueFromDoc(elem.getType(), data, elem, doc, lazyCall); setValueFromDoc(elem.getType(), data, elem, doc, lazyCall, options);
} }
} }
return data; return data;
@ -814,7 +815,7 @@ public class DBAccessMorphia extends DBAccess {
@Override @Override
public <ID_TYPE> long count(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) throws Exception { public <ID_TYPE> long count(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return this.countWhere(clazz, options); return this.countWhere(clazz, options);
} }
@ -846,7 +847,7 @@ public class DBAccessMorphia extends DBAccess {
@Override @Override
public <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id, final QueryOption... option) throws Exception { public <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id, final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return this.getWhere(clazz, options.getAllArray()); return this.getWhere(clazz, options.getAllArray());
} }
@ -854,7 +855,7 @@ public class DBAccessMorphia extends DBAccess {
public <ID_TYPE> long deleteHard(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long deleteHard(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws Exception { throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return deleteHardWhere(clazz, options.getAllArray()); return deleteHardWhere(clazz, options.getAllArray());
} }
@ -879,7 +880,7 @@ public class DBAccessMorphia extends DBAccess {
public <ID_TYPE> long deleteSoft(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long deleteSoft(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws Exception { throws Exception {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return deleteSoftWhere(clazz, options.getAllArray()); return deleteSoftWhere(clazz, options.getAllArray());
} }
@ -899,14 +900,14 @@ public class DBAccessMorphia extends DBAccess {
@Override @Override
public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id) throws DataAccessException { public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id) throws DataAccessException {
return unsetDeleteWhere(clazz, new Condition(getTableIdCondition(clazz, id))); return unsetDeleteWhere(clazz, new Condition(getTableIdCondition(clazz, id, new QueryOptions())));
} }
@Override @Override
public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) public <ID_TYPE> long unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOption... option)
throws DataAccessException { throws DataAccessException {
final QueryOptions options = new QueryOptions(option); final QueryOptions options = new QueryOptions(option);
options.add(new Condition(getTableIdCondition(clazz, id))); options.add(new Condition(getTableIdCondition(clazz, id, options)));
return unsetDeleteWhere(clazz, options.getAllArray()); return unsetDeleteWhere(clazz, options.getAllArray());
} }

View File

@ -22,6 +22,7 @@ import java.util.UUID;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.annotation.CreationTimestamp; import org.kar.archidata.annotation.CreationTimestamp;
import org.kar.archidata.annotation.UpdateTimestamp; import org.kar.archidata.annotation.UpdateTimestamp;
import org.kar.archidata.dataAccess.addOnSQL.AddOnDataJson; import org.kar.archidata.dataAccess.addOnSQL.AddOnDataJson;
@ -902,7 +903,7 @@ public class DBAccessSQL extends DBAccess {
generateOID = true; generateOID = true;
} }
count++; count++;
final String name = AnnotationTools.getFieldName(field); final String name = AnnotationTools.getFieldName(field, options).inTable();
if (firstField) { if (firstField) {
firstField = false; firstField = false;
} else { } else {
@ -944,7 +945,7 @@ public class DBAccessSQL extends DBAccess {
} }
} }
count++; count++;
final String name = AnnotationTools.getFieldName(field); final String name = AnnotationTools.getFieldName(field, options).inTable();
if (firstField) { if (firstField) {
firstField = false; firstField = false;
} else { } else {
@ -1097,11 +1098,11 @@ public class DBAccessSQL extends DBAccess {
for (final Field field : asyncFieldUpdate) { for (final Field field : asyncFieldUpdate) {
final DataAccessAddOn addOn = findAddOnforField(field); final DataAccessAddOn addOn = findAddOnforField(field);
if (uniqueSQLID != null) { if (uniqueSQLID != null) {
addOn.asyncInsert(this, tableName, uniqueSQLID, field, field.get(data), asyncActions); addOn.asyncInsert(this, tableName, uniqueSQLID, field, field.get(data), asyncActions, options);
} else if (uniqueSQLUUID != null) { } else if (uniqueSQLUUID != null) {
addOn.asyncInsert(this, tableName, uniqueSQLUUID, field, field.get(data), asyncActions); addOn.asyncInsert(this, tableName, uniqueSQLUUID, field, field.get(data), asyncActions, options);
} else if (uniqueSQLOID != null) { } else if (uniqueSQLOID != null) {
addOn.asyncInsert(this, tableName, uniqueSQLOID, field, field.get(data), asyncActions); addOn.asyncInsert(this, tableName, uniqueSQLOID, field, field.get(data), asyncActions, options);
} }
} }
for (final LazyGetter action : asyncActions) { for (final LazyGetter action : asyncActions) {
@ -1146,8 +1147,8 @@ public class DBAccessSQL extends DBAccess {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
final String name = AnnotationTools.getFieldName(field); final FieldName name = AnnotationTools.getFieldName(field, options);
if (!filter.getValues().contains(name)) { if (!filter.getValues().contains(name.inStruct())) {
continue; continue;
} else if (AnnotationTools.isGenericField(field)) { } else if (AnnotationTools.isGenericField(field)) {
continue; continue;
@ -1161,7 +1162,7 @@ public class DBAccessSQL extends DBAccess {
"Fail to transmit Key to update the async update... (must have only 1)"); "Fail to transmit Key to update the async update... (must have only 1)");
} }
addOn.asyncUpdate(this, tableName, transmitKey.get(0).getKey(), field, field.get(data), addOn.asyncUpdate(this, tableName, transmitKey.get(0).getKey(), field, field.get(data),
asyncActions); asyncActions, options);
} }
continue; continue;
} }
@ -1177,7 +1178,7 @@ public class DBAccessSQL extends DBAccess {
query.append(","); query.append(",");
} }
query.append(" `"); query.append(" `");
query.append(name); query.append(name.inTable());
query.append("` = ? "); query.append("` = ? ");
} }
query.append(" "); query.append(" ");
@ -1201,7 +1202,7 @@ public class DBAccessSQL extends DBAccess {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue; continue;
} }
final String name = AnnotationTools.getFieldName(field); final String name = AnnotationTools.getFieldName(field, options).inStruct();
if (!filter.getValues().contains(name)) { if (!filter.getValues().contains(name)) {
continue; continue;
} else if (AnnotationTools.isGenericField(field)) { } else if (AnnotationTools.isGenericField(field)) {
@ -1332,7 +1333,7 @@ public class DBAccessSQL extends DBAccess {
if (!readAllfields && notRead) { if (!readAllfields && notRead) {
continue; continue;
} }
final String name = AnnotationTools.getFieldName(elem); final String name = AnnotationTools.getFieldName(elem, options).inTable();
if (firstField) { if (firstField) {
firstField = false; firstField = false;
} else { } else {
@ -1611,7 +1612,7 @@ public class DBAccessSQL extends DBAccess {
} }
final DataAccessAddOn addOn = findAddOnforField(field); final DataAccessAddOn addOn = findAddOnforField(field);
if (addOn != null && !addOn.canInsert(field)) { if (addOn != null && !addOn.canInsert(field)) {
addOn.drop(this, tableName, field); addOn.drop(this, tableName, field, options);
} }
} }
} }
@ -1639,7 +1640,7 @@ public class DBAccessSQL extends DBAccess {
} }
final DataAccessAddOn addOn = findAddOnforField(field); final DataAccessAddOn addOn = findAddOnforField(field);
if (addOn != null && !addOn.canInsert(field)) { if (addOn != null && !addOn.canInsert(field)) {
addOn.cleanAll(this, tableName, field); addOn.cleanAll(this, tableName, field, options);
} }
} }
} }

View File

@ -67,10 +67,12 @@ public class DataAccess {
} }
} }
public static <ID_TYPE> QueryCondition getTableIdCondition(final Class<?> clazz, final ID_TYPE idKey) public static <ID_TYPE> QueryCondition getTableIdCondition(
throws DataAccessException, IOException { final Class<?> clazz,
final ID_TYPE idKey,
final QueryOptions options) throws DataAccessException, IOException {
try (DBAccess db = DBAccess.createInterface()) { try (DBAccess db = DBAccess.createInterface()) {
return db.getTableIdCondition(clazz, idKey); return db.getTableIdCondition(clazz, idKey, options);
} }
} }

View File

@ -167,8 +167,9 @@ public class DataFactory {
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId, final int fieldId,
final Class<?> classModel) throws Exception { final Class<?> classModel,
final String name = AnnotationTools.getFieldName(elem); final QueryOptions options) throws Exception {
final String name = AnnotationTools.getFieldName(elem, options).inTable();
final int limitSize = AnnotationTools.getLimitSize(elem); final int limitSize = AnnotationTools.getLimitSize(elem);
final boolean notNull = AnnotationTools.getColumnNotNull(elem); final boolean notNull = AnnotationTools.getColumnNotNull(elem);
@ -314,7 +315,10 @@ public class DataFactory {
} }
} }
private static boolean isFieldFromSuperClass(final Class<?> model, final String filedName) { private static boolean isFieldFromSuperClass(
final Class<?> model,
final String filedName,
final QueryOptions options) {
final Class<?> superClass = model.getSuperclass(); final Class<?> superClass = model.getSuperclass();
if (superClass == null) { if (superClass == null) {
return false; return false;
@ -322,7 +326,7 @@ public class DataFactory {
for (final Field field : superClass.getFields()) { for (final Field field : superClass.getFields()) {
String name; String name;
try { try {
name = AnnotationTools.getFieldName(field); name = AnnotationTools.getFieldName(field, options).inTable();
if (filedName.equals(name)) { if (filedName.equals(name)) {
return true; return true;
} }
@ -370,7 +374,7 @@ public class DataFactory {
for (final Field elem : clazz.getFields()) { for (final Field elem : clazz.getFields()) {
// DEtect the primary key (support only one primary key right now... // DEtect the primary key (support only one primary key right now...
if (AnnotationTools.isPrimaryKey(elem)) { if (AnnotationTools.isPrimaryKey(elem)) {
primaryKeys.add(AnnotationTools.getFieldName(elem)); primaryKeys.add(AnnotationTools.getFieldName(elem, options).inTable());
} }
} }
// Here we insert the data in the reverse mode ==> the parent class add there parameter at the start (we reorder the field with the parenting). // Here we insert the data in the reverse mode ==> the parent class add there parameter at the start (we reorder the field with the parenting).
@ -387,8 +391,8 @@ public class DataFactory {
if (java.lang.reflect.Modifier.isStatic(elem.getModifiers())) { if (java.lang.reflect.Modifier.isStatic(elem.getModifiers())) {
continue; continue;
} }
final String dataName = AnnotationTools.getFieldName(elem); final String dataName = AnnotationTools.getFieldName(elem, options).inTable();
if (isFieldFromSuperClass(currentClazz, dataName)) { if (isFieldFromSuperClass(currentClazz, dataName, options)) {
LOGGER.trace(" SKIP: '{}'", elem.getName()); LOGGER.trace(" SKIP: '{}'", elem.getName());
continue; continue;
} }
@ -416,19 +420,21 @@ public class DataFactory {
LOGGER.trace(" + '{}'", elem.getName()); LOGGER.trace(" + '{}'", elem.getName());
if (DBAccessSQL.isAddOnField(elem)) { if (DBAccessSQL.isAddOnField(elem)) {
final DataAccessAddOn addOn = DBAccessSQL.findAddOnforField(elem); final DataAccessAddOn addOn = DBAccessSQL.findAddOnforField(elem);
LOGGER.trace("Create type for: {} ==> {} (ADD-ON)", AnnotationTools.getFieldName(elem), basicType); LOGGER.trace("Create type for: {} ==> {} (ADD-ON)",
AnnotationTools.getFieldName(elem, options).inTable(), basicType);
if (addOn != null) { if (addOn != null) {
addOn.createTables(tableName, primaryField, elem, tmpOut, preActionList, postActionList, addOn.createTables(tableName, primaryField, elem, tmpOut, preActionList, postActionList,
createIfNotExist, createDrop, fieldId); createIfNotExist, createDrop, fieldId, options);
} else { } else {
throw new DataAccessException( throw new DataAccessException("Element matked as add-on but add-on does not loaded: table:"
"Element matked as add-on but add-on does not loaded: table:" + tableName + tableName + " field name=" + AnnotationTools.getFieldName(elem, options).inTable()
+ " field name=" + AnnotationTools.getFieldName(elem) + " type=" + basicType); + " type=" + basicType);
} }
} else { } else {
LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldName(elem), basicType); LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldName(elem, options).inTable(),
basicType);
DataFactory.createTablesSpecificType(tableName, tablePrimaryKeyField, elem, tmpOut, preActionList, DataFactory.createTablesSpecificType(tableName, tablePrimaryKeyField, elem, tmpOut, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, basicType); postActionList, createIfNotExist, createDrop, fieldId, basicType, options);
} }
fieldId++; fieldId++;
} }

View File

@ -1,31 +1,21 @@
package org.kar.archidata.dataAccess.addOnMongo; package org.kar.archidata.dataAccess.addOnMongo;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
import org.bson.Document; import org.bson.Document;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.DataJson; import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccess;
import org.kar.archidata.dataAccess.DBAccessMorphia; import org.kar.archidata.dataAccess.DBAccessMorphia;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.LazyGetter; import org.kar.archidata.dataAccess.LazyGetter;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversLongLong;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversLongUUID;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversUUIDLong;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversUUIDUUID;
import org.kar.archidata.dataAccess.options.OverrideTableName;
import org.kar.archidata.exception.DataAccessException; import org.kar.archidata.exception.DataAccessException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonValue;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
@ -38,8 +28,8 @@ public class AddOnDataJson implements DataAccessAddOn {
} }
@Override @Override
public String getSQLFieldType(final Field elem) throws DataAccessException { public String getSQLFieldType(final Field elem, final QueryOptions options) throws DataAccessException {
final String fieldName = AnnotationTools.getFieldName(elem); final String fieldName = AnnotationTools.getFieldName(elem, options).inTable();
return DataFactory.convertTypeInSQL(String.class, fieldName); return DataFactory.convertTypeInSQL(String.class, fieldName);
} }
@ -54,6 +44,7 @@ public class AddOnDataJson implements DataAccessAddOn {
final DBAccessMorphia ioDb, final DBAccessMorphia ioDb,
final Field field, final Field field,
final Object rootObject, final Object rootObject,
final QueryOptions options,
final Document docSet, final Document docSet,
final Document docUnSet) throws Exception { final Document docUnSet) throws Exception {
/* /*
@ -174,284 +165,10 @@ public class AddOnDataJson implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, JsonValue.class); postActionList, createIfNotExist, createDrop, fieldId, JsonValue.class, options);
} }
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final Long remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongLong data = ioDb.get(TableCoversLongLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
/**
* Adds a remoteKey to the covers list of a data entry identified by the given class type and ID.
* If the covers list is null, it initializes it. If the remoteKey already exists in the list,
* the method returns without making any changes.
*
* @param clazz The class type to retrieve the table name from.
* @param id The ID of the data object to fetch.
* @param column The name of the column (currently not used, but may be used for specifying a field name).
* @param remoteKey The UUID to add to the covers list.
* @throws Exception If an error occurs during data retrieval or update.
*/
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
// TODO: Get primary key name
final TableCoversLongUUID data = ioDb.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));// TODO: ,new OverrideFieldName("covers", column));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
/**
* Adds a remoteKey to the covers list of a data entry identified by the given class type and ID.
* If the covers list is null, it initializes it. If the remoteKey already exists in the list,
* the method returns without making any changes.
*
* @param clazz The class type to retrieve the table name from.
* @param id The ID of the data object to fetch.
* @param column The name of the column (currently not used, but may be used for specifying a field name).
* @param remoteKey The UUID to add to the covers list.
* @throws Exception If an error occurs during data retrieval or update.
*/
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDUUID data = ioDb.get(TableCoversUUIDUUID.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final Long remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDLong data = ioDb.get(TableCoversUUIDLong.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final Long remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDLong data = ioDb.get(TableCoversUUIDLong.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<Long> newList = new ArrayList<>();
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDUUID data = ioDb.get(TableCoversUUIDUUID.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final Long remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongLong data = ioDb.get(TableCoversLongLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<Long> newList = new ArrayList<>();
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
ioDb.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessMorphia daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongUUID data = ioDb.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
} else if (ioDb instanceof final DBAccessMorphia dam) {
final String collectionName = AnnotationTools.getCollectionName(clazz);
final Field primaryfield = AnnotationTools.getPrimaryKeyField(clazz);
final String primaryFieldName = AnnotationTools.getFieldName(primaryfield);
final MongoCollection<Document> collection = dam.getInterface().getDatastore().getDatabase()
.getCollection(collectionName);
// retrieve previous value:
final Document ret = collection.find(Filters.eq(primaryFieldName, id)).first();
if (ret == null) {
throw new DataAccessException("Element does not exist ...");
}
final List<UUID> newList = new ArrayList<>();
final List listValues = ret.get(remoteKey, newList.getClass());
/*
final Document actions = new Document();
// update value:
final Document actions = new Document();
if (!docSet.isEmpty()) {
actions.append("$set", docSet);
}
if (!docUnSet.isEmpty()) {
actions.append("$unset", docUnSet);
}
LOGGER.info("update some values: {}", actions.toJson());
final UpdateResult ret = collection.updateMany(filters, actions);
return ret.getModifiedCount();
final TableCoversLongUUID data = ioDb.getDocument(tableName, id);
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
*/
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
} }

View File

@ -8,6 +8,7 @@ import java.util.UUID;
import org.bson.Document; import org.bson.Document;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccess; import org.kar.archidata.dataAccess.DBAccess;
import org.kar.archidata.dataAccess.DBAccessMorphia; import org.kar.archidata.dataAccess.DBAccessMorphia;
@ -38,11 +39,6 @@ public class AddOnManyToMany implements DataAccessAddOn {
return ManyToMany.class; return ManyToMany.class;
} }
@Override
public String getSQLFieldType(final Field elem) {
return null;
}
@Override @Override
public boolean isCompatibleField(final Field elem) { public boolean isCompatibleField(final Field elem) {
final ManyToMany decorators = elem.getDeclaredAnnotation(ManyToMany.class); final ManyToMany decorators = elem.getDeclaredAnnotation(ManyToMany.class);
@ -54,6 +50,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
final DBAccessMorphia ioDb, final DBAccessMorphia ioDb,
final Field field, final Field field,
final Object rootObject, final Object rootObject,
final QueryOptions options,
final Document docSet, final Document docSet,
final Document docUnSet) throws Exception { final Document docUnSet) throws Exception {
@ -84,9 +81,12 @@ public class AddOnManyToMany implements DataAccessAddOn {
return false; return false;
} }
public static String generateLinkTableNameField(final String tableName, final Field field) throws Exception { public static String generateLinkTableNameField(
final String name = AnnotationTools.getFieldName(field); final String tableName,
return generateLinkTableName(tableName, name); final Field field,
final QueryOptions options) throws Exception {
final FieldName name = AnnotationTools.getFieldName(field, options);
return generateLinkTableName(tableName, name.inTable());
} }
public static String generateLinkTableName(final String tableName, final String name) { public static String generateLinkTableName(final String tableName, final String name) {
@ -296,7 +296,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
final Object localKey, final Object localKey,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
if (field.getType() != List.class) { if (field.getType() != List.class) {
LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName()); LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName());
return; return;
@ -307,46 +308,16 @@ public class AddOnManyToMany implements DataAccessAddOn {
throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<" throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<"
+ objectClass.getCanonicalName() + ">"); + objectClass.getCanonicalName() + ">");
} }
final String columnName = AnnotationTools.getFieldName(field); final FieldName columnName = AnnotationTools.getFieldName(field, options);
final String linkTableName = generateLinkTableName(tableName, columnName); final String linkTableName = generateLinkTableName(tableName, columnName.inTable());
if (localKey instanceof final Long localKeyLong) { actions.add(() -> {
if (objectClass == Long.class) { ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName),
actions.add(() -> { new Condition(new QueryCondition("object1Id", "=", localKey)),
ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName), new OptionSpecifyType("object1Id", localKey.getClass()),
new Condition(new QueryCondition("object1Id", "=", localKeyLong)), new OptionSpecifyType("object2Id", objectClass));
new OptionSpecifyType("object1Id", Long.class), });
new OptionSpecifyType("object2Id", Long.class)); asyncInsert(ioDb, tableName, localKey, field, data, actions, options);
});
asyncInsert(ioDb, tableName, localKey, field, data, actions);
} else {
actions.add(() -> {
ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName),
new Condition(new QueryCondition("object1Id", "=", localKeyLong)),
new OptionSpecifyType("object1Id", Long.class),
new OptionSpecifyType("object2Id", UUID.class));
});
asyncInsert(ioDb, tableName, localKey, field, data, actions);
}
} else if (localKey instanceof final UUID localKeyUUID) {
if (objectClass == Long.class) {
actions.add(() -> {
ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName),
new Condition(new QueryCondition("object1Id", "=", localKeyUUID)),
new OptionSpecifyType("object1Id", UUID.class),
new OptionSpecifyType("object2Id", Long.class));
});
asyncInsert(ioDb, tableName, localKey, field, data, actions);
} else {
actions.add(() -> {
ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName),
new Condition(new QueryCondition("object1Id", "=", localKeyUUID)),
new OptionSpecifyType("object1Id", UUID.class),
new OptionSpecifyType("object2Id", UUID.class));
});
asyncInsert(ioDb, tableName, localKey, field, data, actions);
}
}
} }
@Override @Override
@ -361,7 +332,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
final Object localKey, final Object localKey,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
if (data == null) { if (data == null) {
return; return;
} }
@ -375,136 +347,50 @@ public class AddOnManyToMany implements DataAccessAddOn {
throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<" throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<"
+ objectClass.getCanonicalName() + ">"); + objectClass.getCanonicalName() + ">");
} }
final String columnName = AnnotationTools.getFieldName(field); final FieldName columnName = AnnotationTools.getFieldName(field, options);
final String linkTableName = generateLinkTableName(tableName, columnName); final String linkTableName = generateLinkTableName(tableName, columnName.inTable());
if (localKey instanceof final Long localKeyLong) {
if (objectClass == Long.class) {
// ========================================================
// == Link a "Long" primary Key with List<Long>
// ========================================================
@SuppressWarnings("unchecked")
final List<Long> dataCasted = (List<Long>) data;
if (dataCasted.size() == 0) {
return;
}
final List<LinkTableGeneric> insertElements = new ArrayList<>();
for (final Long remoteKey : dataCasted) {
if (remoteKey == null) {
throw new DataAccessException("Try to insert remote key with null value");
}
insertElements.add(new LinkTableGeneric(localKeyLong, remoteKey));
}
if (insertElements.size() == 0) {
LOGGER.warn("Insert multiple link without any value (may have null in the list): {}", dataCasted);
return;
}
actions.add(() -> {
ioDb.insertMultiple(insertElements, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", Long.class),
new OptionSpecifyType("object2Id", Long.class));
});
} else {
// ========================================================
// == Link a "Long" primary Key with List<UUID>
// ========================================================
@SuppressWarnings("unchecked")
final List<UUID> dataCasted = (List<UUID>) data;
if (dataCasted.size() == 0) {
return;
}
final List<LinkTableGeneric> insertElements = new ArrayList<>();
for (final UUID remoteKey : dataCasted) {
if (remoteKey == null) {
throw new DataAccessException("Try to insert remote key with null value");
}
insertElements.add(new LinkTableGeneric(localKeyLong, remoteKey));
}
if (insertElements.size() == 0) {
LOGGER.warn("Insert multiple link without any value (may have null in the list): {}", dataCasted);
return;
}
actions.add(() -> {
ioDb.insertMultiple(insertElements, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", Long.class),
new OptionSpecifyType("object2Id", UUID.class));
});
}
} else if (localKey instanceof final UUID localKeyUUID) {
if (objectClass == Long.class) {
// ========================================================
// == Link a "UUID" primary Key with List<Long>
// ========================================================
@SuppressWarnings("unchecked")
final List<Long> dataCasted = (List<Long>) data;
if (dataCasted.size() == 0) {
return;
}
final List<LinkTableGeneric> insertElements = new ArrayList<>();
for (final Long remoteKey : dataCasted) {
if (remoteKey == null) {
throw new DataAccessException("Try to insert remote key with null value");
}
insertElements.add(new LinkTableGeneric(localKeyUUID, remoteKey));
}
if (insertElements.size() == 0) {
LOGGER.warn("Insert multiple link without any value (may have null in the list): {}", dataCasted);
return;
}
actions.add(() -> {
ioDb.insertMultiple(insertElements, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", UUID.class),
new OptionSpecifyType("object2Id", Long.class));
});
} else {
// ========================================================
// == Link a "UUID" primary Key with List<UUID>
// ========================================================
@SuppressWarnings("unchecked")
final List<UUID> dataCasted = (List<UUID>) data;
if (dataCasted.size() == 0) {
return;
}
final List<LinkTableGeneric> insertElements = new ArrayList<>();
for (final UUID remoteKey : dataCasted) {
if (remoteKey == null) {
throw new DataAccessException("Try to insert remote key with null value");
}
insertElements.add(new LinkTableGeneric(localKeyUUID, remoteKey));
}
if (insertElements.size() == 0) {
LOGGER.warn("Insert multiple link without any value (may have null in the list): {}", dataCasted);
return;
}
actions.add(() -> {
ioDb.insertMultiple(insertElements, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", UUID.class),
new OptionSpecifyType("object2Id", UUID.class));
});
}
} else {
throw new DataAccessException("Not manage access of remte key like ManyToMany other than Long or UUID: "
+ localKey.getClass().getCanonicalName());
}
@SuppressWarnings("unchecked")
final List<Object> dataCasted = (List<Object>) data;
if (dataCasted.size() == 0) {
return;
}
final List<LinkTableGeneric> insertElements = new ArrayList<>();
for (final Object remoteKey : dataCasted) {
if (remoteKey == null) {
throw new DataAccessException("Try to insert remote key with null value");
}
insertElements.add(new LinkTableGeneric(localKey, remoteKey));
}
if (insertElements.size() == 0) {
LOGGER.warn("Insert multiple link without any value (may have null in the list): {}", dataCasted);
return;
}
actions.add(() -> {
ioDb.insertMultiple(insertElements, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", localKey.getClass()),
new OptionSpecifyType("object2Id", objectClass));
});
} }
@Override @Override
public void drop(final DBAccessMorphia ioDb, final String tableName, final Field field) throws Exception { public void drop(final DBAccessMorphia ioDb, final String tableName, final Field field, final QueryOptions options)
final String columnName = AnnotationTools.getFieldName(field); throws Exception {
final String columnName = AnnotationTools.getFieldName(field, options).inTable();
final String linkTableName = generateLinkTableName(tableName, columnName); final String linkTableName = generateLinkTableName(tableName, columnName);
final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]; .getActualTypeArguments()[0];
if (objectClass != Long.class && objectClass != UUID.class) {
throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<"
+ objectClass.getCanonicalName() + ">");
}
ioDb.drop(LinkTableGeneric.class, new OverrideTableName(linkTableName), ioDb.drop(LinkTableGeneric.class, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", Long.class), new OptionSpecifyType("object2Id", Long.class)); new OptionSpecifyType("object1Id", Long.class), new OptionSpecifyType("object2Id", Long.class));
} }
@Override @Override
public void cleanAll(final DBAccessMorphia ioDb, final String tableName, final Field field) throws Exception { public void cleanAll(
final String columnName = AnnotationTools.getFieldName(field); final DBAccessMorphia ioDb,
final String tableName,
final Field field,
final QueryOptions options) throws Exception {
final String columnName = AnnotationTools.getFieldName(field, options).inTable();
final String linkTableName = generateLinkTableName(tableName, columnName); final String linkTableName = generateLinkTableName(tableName, columnName);
final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]; .getActualTypeArguments()[0];
@ -568,49 +454,22 @@ public class AddOnManyToMany implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
final ManyToMany manyToMany = AnnotationTools.getManyToMany(field); final ManyToMany manyToMany = AnnotationTools.getManyToMany(field);
if (manyToMany.mappedBy() != null && manyToMany.mappedBy().length() != 0) { if (manyToMany.mappedBy() != null && manyToMany.mappedBy().length() != 0) {
// not the reference model to create base: // not the reference model to create base:
return; return;
} }
final String linkTableName = generateLinkTableNameField(tableName, field); final String linkTableName = generateLinkTableNameField(tableName, field, options);
final QueryOptions options = new QueryOptions(new OverrideTableName(linkTableName)); final QueryOptions options2 = new QueryOptions(new OverrideTableName(linkTableName));
final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]; .getActualTypeArguments()[0];
if (objectClass != Long.class && objectClass != UUID.class) {
throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<"
+ objectClass.getCanonicalName() + ">");
}
final Class<?> primaryType = primaryField.getType(); final Class<?> primaryType = primaryField.getType();
if (primaryType == Long.class) { options2.add(new OptionSpecifyType("object1Id", primaryType));
if (objectClass == Long.class) { options2.add(new OptionSpecifyType("object2Id", objectClass));
options.add(new OptionSpecifyType("object1Id", Long.class)); final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options2);
options.add(new OptionSpecifyType("object2Id", Long.class)); postActionList.addAll(sqlCommand);
final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options);
postActionList.addAll(sqlCommand);
} else {
options.add(new OptionSpecifyType("object1Id", Long.class));
options.add(new OptionSpecifyType("object2Id", UUID.class));
final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options);
postActionList.addAll(sqlCommand);
}
} else if (primaryType == UUID.class) {
if (objectClass == Long.class) {
options.add(new OptionSpecifyType("object1Id", UUID.class));
options.add(new OptionSpecifyType("object2Id", Long.class));
final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options);
postActionList.addAll(sqlCommand);
} else {
options.add(new OptionSpecifyType("object1Id", UUID.class));
options.add(new OptionSpecifyType("object2Id", UUID.class));
final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options);
postActionList.addAll(sqlCommand);
}
} else {
throw new DataAccessException("Can not ManyToMany with other than primary key type Long or UUID Model: "
+ primaryType.getCanonicalName());
}
} }
} }

View File

@ -6,6 +6,7 @@ import java.util.UUID;
import org.bson.Document; import org.bson.Document;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccessMorphia; import org.kar.archidata.dataAccess.DBAccessMorphia;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
@ -26,10 +27,10 @@ public class AddOnManyToOne implements DataAccessAddOn {
} }
@Override @Override
public String getSQLFieldType(final Field field) throws Exception { public String getSQLFieldType(final Field field, final QueryOptions options) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field); final FieldName fieldName = AnnotationTools.getFieldName(field, options);
try { try {
return DataFactory.convertTypeInSQL(field.getType(), fieldName); return DataFactory.convertTypeInSQL(field.getType(), fieldName.inTable());
} catch (final Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -46,35 +47,36 @@ public class AddOnManyToOne implements DataAccessAddOn {
final DBAccessMorphia ioDb, final DBAccessMorphia ioDb,
final Field field, final Field field,
final Object rootObject, final Object rootObject,
final QueryOptions options,
final Document docSet, final Document docSet,
final Document docUnSet) throws Exception { final Document docUnSet) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field); final FieldName fieldName = AnnotationTools.getFieldName(field, options);
final Object data = field.get(rootObject); final Object data = field.get(rootObject);
if (field.get(data) == null) { if (field.get(data) == null) {
docUnSet.append(fieldName, ""); docUnSet.append(fieldName.inTable(), "");
return; return;
} else if (field.getType() == Long.class) { } else if (field.getType() == Long.class) {
final Long dataTyped = (Long) data; final Long dataTyped = (Long) data;
docSet.append(fieldName, dataTyped); docSet.append(fieldName.inTable(), dataTyped);
} else if (field.getType() == Integer.class) { } else if (field.getType() == Integer.class) {
final Integer dataTyped = (Integer) data; final Integer dataTyped = (Integer) data;
docSet.append(fieldName, dataTyped); docSet.append(fieldName.inTable(), dataTyped);
} else if (field.getType() == Short.class) { } else if (field.getType() == Short.class) {
final Short dataTyped = (Short) data; final Short dataTyped = (Short) data;
docSet.append(fieldName, dataTyped); docSet.append(fieldName.inTable(), dataTyped);
} else if (field.getType() == String.class) { } else if (field.getType() == String.class) {
final String dataTyped = (String) data; final String dataTyped = (String) data;
docSet.append(fieldName, dataTyped); docSet.append(fieldName.inTable(), dataTyped);
} else if (field.getType() == UUID.class) { } else if (field.getType() == UUID.class) {
final UUID dataTyped = (UUID) data; final UUID dataTyped = (UUID) data;
docSet.append(fieldName, dataTyped); docSet.append(fieldName.inTable(), dataTyped);
} else { } else {
final Field idField = AnnotationTools.getFieldOfId(field.getType()); final Field idField = AnnotationTools.getFieldOfId(field.getType());
final Object uid = idField.get(data); final Object uid = idField.get(data);
if (uid == null) { if (uid == null) {
docUnSet.append(fieldName, ""); docUnSet.append(fieldName.inTable(), "");
} else { } else {
docSet.append(fieldName, uid); docSet.append(fieldName.inTable(), uid);
} }
} }
} }
@ -150,15 +152,15 @@ public class AddOnManyToOne implements DataAccessAddOn {
final QueryOptions options, final QueryOptions options,
final List<LazyGetter> lazyCall) throws Exception { final List<LazyGetter> lazyCall) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field); final FieldName fieldName = AnnotationTools.getFieldName(field, options);
if (!doc.containsKey(fieldName)) { if (!doc.containsKey(fieldName.inTable())) {
field.set(data, null); field.set(data, null);
return; return;
} }
// local field to manage no remote object to retrieve. // local field to manage no remote object to retrieve.
if (field.getType() == Long.class || field.getType() == Integer.class || field.getType() == Short.class if (field.getType() == Long.class || field.getType() == Integer.class || field.getType() == Short.class
|| field.getType() == String.class || field.getType() == UUID.class) { || field.getType() == String.class || field.getType() == UUID.class) {
ioDb.setValueFromDoc(field.getType(), data, field, doc, lazyCall); ioDb.setValueFromDoc(field.getType(), data, field, doc, lazyCall, options);
return; return;
} }
final Class<?> objectClass = field.getType(); final Class<?> objectClass = field.getType();
@ -215,16 +217,17 @@ public class AddOnManyToOne implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
final Class<?> classType = field.getType(); final Class<?> classType = field.getType();
if (classType == Long.class || classType == Integer.class || classType == Short.class if (classType == Long.class || classType == Integer.class || classType == Short.class
|| classType == String.class || classType == UUID.class) { || classType == String.class || classType == UUID.class) {
DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, classType); postActionList, createIfNotExist, createDrop, fieldId, classType, options);
} else { } else {
LOGGER.error("Support only the Long remote field of ecternal primary keys..."); LOGGER.error("Support only the Long remote field of ecternal primary keys...");
DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, Long.class); postActionList, createIfNotExist, createDrop, fieldId, Long.class, options);
} }
} }
} }

View File

@ -11,9 +11,9 @@ import java.util.stream.Collectors;
import org.bson.Document; import org.bson.Document;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccessMorphia; import org.kar.archidata.dataAccess.DBAccessMorphia;
import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.LazyGetter; import org.kar.archidata.dataAccess.LazyGetter;
import org.kar.archidata.dataAccess.QueryCondition; import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
@ -63,18 +63,6 @@ public class AddOnOneToMany implements DataAccessAddOn {
return OneToMany.class; return OneToMany.class;
} }
@Override
public String getSQLFieldType(final Field field) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field);
try {
return DataFactory.convertTypeInSQL(Long.class, fieldName);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override @Override
public boolean isCompatibleField(final Field field) { public boolean isCompatibleField(final Field field) {
final OneToMany decorators = field.getDeclaredAnnotation(OneToMany.class); final OneToMany decorators = field.getDeclaredAnnotation(OneToMany.class);
@ -86,6 +74,7 @@ public class AddOnOneToMany implements DataAccessAddOn {
final DBAccessMorphia ioDb, final DBAccessMorphia ioDb,
final Field field, final Field field,
final Object rootObject, final Object rootObject,
final QueryOptions options,
final Document docSet, final Document docSet,
final Document docUnSet) throws Exception { final Document docUnSet) throws Exception {
throw new IllegalAccessException("Can not generate an inset of @OneToMany"); throw new IllegalAccessException("Can not generate an inset of @OneToMany");
@ -136,15 +125,15 @@ public class AddOnOneToMany implements DataAccessAddOn {
final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]; .getActualTypeArguments()[0];
final String remoteTableName = AnnotationTools.getTableName(targetEntity); final String remoteTableName = AnnotationTools.getTableName(targetEntity);
final String remoteTablePrimaryKeyName = AnnotationTools final FieldName remoteTablePrimaryKeyName = AnnotationTools
.getFieldName(AnnotationTools.getPrimaryKeyField(targetEntity)); .getFieldName(AnnotationTools.getPrimaryKeyField(targetEntity), options);
final String tmpRemoteVariable = "tmp_" + Integer.toString(count.value); final String tmpRemoteVariable = "tmp_" + Integer.toString(count.value);
final String remoteDeletedFieldName = AnnotationTools.getDeletedFieldName(targetEntity); final String remoteDeletedFieldName = AnnotationTools.getDeletedFieldName(targetEntity);
querySelect.append(" (SELECT GROUP_CONCAT("); querySelect.append(" (SELECT GROUP_CONCAT(");
querySelect.append(tmpRemoteVariable); querySelect.append(tmpRemoteVariable);
querySelect.append("."); querySelect.append(".");
querySelect.append(remoteTablePrimaryKeyName); querySelect.append(remoteTablePrimaryKeyName.inTable());
querySelect.append(" "); querySelect.append(" ");
if ("sqlite".equals(ConfigBaseVariable.getDBType())) { if ("sqlite".equals(ConfigBaseVariable.getDBType())) {
querySelect.append(", "); querySelect.append(", ");
@ -233,7 +222,7 @@ public class AddOnOneToMany implements DataAccessAddOn {
return; return;
} }
final String fieldName = AnnotationTools.getFieldName(field); final String fieldName = AnnotationTools.getFieldName(field, options).inTable();
if (!doc.containsKey(fieldName)) { if (!doc.containsKey(fieldName)) {
field.set(data, null); field.set(data, null);
return; return;
@ -316,7 +305,8 @@ public class AddOnOneToMany implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
// This is a remote field ==> nothing to generate (it is stored in the remote object // This is a remote field ==> nothing to generate (it is stored in the remote object
} }
} }

View File

@ -20,7 +20,9 @@ public interface DataAccessAddOn {
/** Get the SQL type that is needed to declare for the specific Field Type. /** Get the SQL type that is needed to declare for the specific Field Type.
* @param elem Field to declare. * @param elem Field to declare.
* @return SQL type to create. */ * @return SQL type to create. */
String getSQLFieldType(Field elem) throws Exception; default String getSQLFieldType(final Field elem, final QueryOptions options) throws Exception {
return null;
}
/** Check if the field is manage by the local add-on /** Check if the field is manage by the local add-on
* @param elem Field to inspect. * @param elem Field to inspect.
@ -37,6 +39,7 @@ public interface DataAccessAddOn {
final DBAccessMorphia ioDb, final DBAccessMorphia ioDb,
final Field field, final Field field,
final Object rootObject, final Object rootObject,
final QueryOptions options,
final Document docSet, final Document docSet,
final Document docUnSet) throws Exception; final Document docUnSet) throws Exception;
@ -92,7 +95,8 @@ public interface DataAccessAddOn {
List<String> postActionList, List<String> postActionList,
boolean createIfNotExist, boolean createIfNotExist,
boolean createDrop, boolean createDrop,
int fieldId) throws Exception; int fieldId,
final QueryOptions options) throws Exception;
/** Some action must be done asynchronously for update or remove element /** Some action must be done asynchronously for update or remove element
* @param field * @param field
@ -113,7 +117,8 @@ public interface DataAccessAddOn {
final Object localId, final Object localId,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
} }
@ -136,15 +141,21 @@ public interface DataAccessAddOn {
final Object localId, final Object localId,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
} }
default void drop(final DBAccessMorphia ioDb, final String tableName, final Field field) throws Exception { default void drop(final DBAccessMorphia ioDb, final String tableName, final Field field, final QueryOptions options)
throws Exception {
} }
default void cleanAll(final DBAccessMorphia ioDb, final String tableName, final Field field) throws Exception { default void cleanAll(
final DBAccessMorphia ioDb,
final String tableName,
final Field field,
final QueryOptions options) throws Exception {
} }

View File

@ -10,8 +10,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.bson.Document;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.annotation.DataJson; import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccess; import org.kar.archidata.dataAccess.DBAccess;
@ -20,10 +20,9 @@ import org.kar.archidata.dataAccess.DBAccessSQL;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.LazyGetter; import org.kar.archidata.dataAccess.LazyGetter;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversLongLong; import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversGeneric;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversLongUUID; import org.kar.archidata.dataAccess.options.OptionRenameColumn;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversUUIDLong; import org.kar.archidata.dataAccess.options.OptionSpecifyType;
import org.kar.archidata.dataAccess.addOnSQL.model.TableCoversUUIDUUID;
import org.kar.archidata.dataAccess.options.OverrideTableName; import org.kar.archidata.dataAccess.options.OverrideTableName;
import org.kar.archidata.exception.DataAccessException; import org.kar.archidata.exception.DataAccessException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -35,8 +34,6 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.type.TypeFactory;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
@ -49,9 +46,9 @@ public class AddOnDataJson implements DataAccessAddOn {
} }
@Override @Override
public String getSQLFieldType(final Field elem) throws DataAccessException { public String getSQLFieldType(final Field elem, final QueryOptions options) throws DataAccessException {
final String fieldName = AnnotationTools.getFieldName(elem); final FieldName fieldName = AnnotationTools.getFieldName(elem, options);
return DataFactory.convertTypeInSQL(String.class, fieldName); return DataFactory.convertTypeInSQL(String.class, fieldName.inTable());
} }
@Override @Override
@ -181,284 +178,77 @@ public class AddOnDataJson implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, JsonValue.class); postActionList, createIfNotExist, createDrop, fieldId, JsonValue.class, options);
} }
public static void addLink( public static void addLink(
final DBAccess ioDb, final DBAccess ioDb,
final Class<?> clazz, final Class<?> clazz,
final Long id, final String columnId,
final String column, final Object id,
final Long remoteKey) throws Exception { final String columnList,
final Object remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz); final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongLong data = ioDb.get(TableCoversLongLong.class, id, new OverrideTableName(tableName)); final QueryOptions options = new QueryOptions(new OverrideTableName(tableName),
new OptionSpecifyType("id", id.getClass()),
new OptionSpecifyType("covers", remoteKey.getClass(), true));
if (columnId != null && !columnId.equals("id")) {
options.add(new OptionRenameColumn("id", columnId));
}
if (columnList != null && !columnList.equals("covers")) {
options.add(new OptionRenameColumn("covers", columnList));
}
final TableCoversGeneric data = ioDb.get(TableCoversGeneric.class, id, options.getAllArray());
if (data.covers == null) { if (data.covers == null) {
data.covers = new ArrayList<>(); data.covers = new ArrayList<>();
} }
for (final Long elem : data.covers) { for (final Object elem : data.covers) {
if (elem.equals(remoteKey)) { if (elem.equals(remoteKey)) {
return; return;
} }
} }
data.covers.add(remoteKey); data.covers.add(remoteKey);
ioDb.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); ioDb.update(data, data.id, List.of("covers"), options.getAllArray());
}
/**
* Adds a remoteKey to the covers list of a data entry identified by the given class type and ID.
* If the covers list is null, it initializes it. If the remoteKey already exists in the list,
* the method returns without making any changes.
*
* @param clazz The class type to retrieve the table name from.
* @param id The ID of the data object to fetch.
* @param column The name of the column (currently not used, but may be used for specifying a field name).
* @param remoteKey The UUID to add to the covers list.
* @throws Exception If an error occurs during data retrieval or update.
*/
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
// TODO: Get primary key name
final TableCoversLongUUID data = ioDb.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));// TODO: ,new OverrideFieldName("covers", column));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
/**
* Adds a remoteKey to the covers list of a data entry identified by the given class type and ID.
* If the covers list is null, it initializes it. If the remoteKey already exists in the list,
* the method returns without making any changes.
*
* @param clazz The class type to retrieve the table name from.
* @param id The ID of the data object to fetch.
* @param column The name of the column (currently not used, but may be used for specifying a field name).
* @param remoteKey The UUID to add to the covers list.
* @throws Exception If an error occurs during data retrieval or update.
*/
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDUUID data = ioDb.get(TableCoversUUIDUUID.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void addLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final Long remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDLong data = ioDb.get(TableCoversUUIDLong.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
} }
public static void removeLink( public static void removeLink(
final DBAccess ioDb, final DBAccess ioDb,
final Class<?> clazz, final Class<?> clazz,
final UUID uuid, final String columnId,
final String column, final Object id,
final Long remoteKey) throws Exception { final String columnList,
final Object remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) { if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz); final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDLong data = ioDb.get(TableCoversUUIDLong.class, uuid, final QueryOptions options = new QueryOptions(new OverrideTableName(tableName),
new OverrideTableName(tableName)); new OptionSpecifyType("id", id.getClass()),
new OptionSpecifyType("covers", remoteKey.getClass(), true));
if (columnId != null && !columnId.equals("id")) {
options.add(new OptionRenameColumn("id", columnId));
}
if (columnList != null && !columnList.equals("covers")) {
options.add(new OptionRenameColumn("covers", columnList));
}
final TableCoversGeneric data = ioDb.get(TableCoversGeneric.class, id, options.getAllArray());
if (data.covers == null) { if (data.covers == null) {
return; return;
} }
final List<Long> newList = new ArrayList<>(); final List<Object> newList = new ArrayList<>();
for (final Long elem : data.covers) { for (final Object elem : data.covers) {
if (elem.equals(remoteKey)) { if (elem.equals(remoteKey)) {
continue; continue;
} }
newList.add(elem); newList.add(elem);
} }
data.covers = newList; data.covers = newList;
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName)); ioDb.update(data, data.id, List.of("covers"), options.getAllArray());
} else if (ioDb instanceof final DBAccessMorphia dam) { } else if (ioDb instanceof final DBAccessMorphia dam) {
} else { } else {
throw new DataAccessException("DataAccess Not managed"); throw new DataAccessException("DataAccess Not managed");
} }
} }
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final UUID uuid,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDUUID data = ioDb.get(TableCoversUUIDUUID.class, uuid,
new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
ioDb.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final Long remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongLong data = ioDb.get(TableCoversLongLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<Long> newList = new ArrayList<>();
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
ioDb.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
} else if (ioDb instanceof final DBAccessMorphia dam) {
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
public static void removeLink(
final DBAccess ioDb,
final Class<?> clazz,
final Long id,
final String column,
final UUID remoteKey) throws Exception {
if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongUUID data = ioDb.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
} else if (ioDb instanceof final DBAccessMorphia dam) {
final String collectionName = AnnotationTools.getCollectionName(clazz);
final Field primaryfield = AnnotationTools.getPrimaryKeyField(clazz);
final String primaryFieldName = AnnotationTools.getFieldName(primaryfield);
final MongoCollection<Document> collection = dam.getInterface().getDatastore().getDatabase()
.getCollection(collectionName);
// retrieve previous value:
final Document ret = collection.find(Filters.eq(primaryFieldName, id)).first();
if (ret == null) {
throw new DataAccessException("Element does not exist ...");
}
final List<UUID> newList = new ArrayList<>();
final List listValues = ret.get(remoteKey, newList.getClass());
/*
final Document actions = new Document();
// update value:
final Document actions = new Document();
if (!docSet.isEmpty()) {
actions.append("$set", docSet);
}
if (!docUnSet.isEmpty()) {
actions.append("$unset", docUnSet);
}
LOGGER.info("update some values: {}", actions.toJson());
final UpdateResult ret = collection.updateMany(filters, actions);
return ret.getModifiedCount();
final TableCoversLongUUID data = ioDb.getDocument(tableName, id);
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
*/
} else {
throw new DataAccessException("DataAccess Not managed");
}
}
} }

View File

@ -10,6 +10,7 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccess; import org.kar.archidata.dataAccess.DBAccess;
import org.kar.archidata.dataAccess.DBAccessMorphia; import org.kar.archidata.dataAccess.DBAccessMorphia;
@ -43,11 +44,6 @@ public class AddOnManyToMany implements DataAccessAddOn {
return ManyToMany.class; return ManyToMany.class;
} }
@Override
public String getSQLFieldType(final Field elem) {
return null;
}
@Override @Override
public boolean isCompatibleField(final Field elem) { public boolean isCompatibleField(final Field elem) {
final ManyToMany decorators = elem.getDeclaredAnnotation(ManyToMany.class); final ManyToMany decorators = elem.getDeclaredAnnotation(ManyToMany.class);
@ -89,9 +85,12 @@ public class AddOnManyToMany implements DataAccessAddOn {
return false; return false;
} }
public static String generateLinkTableNameField(final String tableName, final Field field) throws Exception { public static String generateLinkTableNameField(
final String name = AnnotationTools.getFieldName(field); final String tableName,
return generateLinkTableName(tableName, name); final Field field,
final QueryOptions options) throws Exception {
final FieldName name = AnnotationTools.getFieldName(field, options);
return generateLinkTableName(tableName, name.inTable());
} }
public static String generateLinkTableName(final String tableName, final String name) { public static String generateLinkTableName(final String tableName, final String name) {
@ -249,14 +248,15 @@ public class AddOnManyToMany implements DataAccessAddOn {
// field.set(data, idList); // field.set(data, idList);
count.inc(); count.inc();
if (idList != null && idList.size() > 0) { if (idList != null && idList.size() > 0) {
final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass)); final FieldName idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass),
options);
// In the lazy mode, the request is done in asynchronous mode, they will be done after... // In the lazy mode, the request is done in asynchronous mode, they will be done after...
final LazyGetter lambda = () -> { final LazyGetter lambda = () -> {
final List<Long> childs = new ArrayList<>(idList); final List<Long> childs = new ArrayList<>(idList);
// TODO: update to have get with abstract types .... // TODO: update to have get with abstract types ....
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Object foreignData = ioDb.getsWhere(decorators.targetEntity(), final Object foreignData = ioDb.getsWhere(decorators.targetEntity(),
new Condition(new QueryInList<>(idField, childs))); new Condition(new QueryInList<>(idField.inTable(), childs)));
if (foreignData == null) { if (foreignData == null) {
return; return;
} }
@ -269,14 +269,15 @@ public class AddOnManyToMany implements DataAccessAddOn {
// field.set(data, idList); // field.set(data, idList);
count.inc(); count.inc();
if (idList != null && idList.size() > 0) { if (idList != null && idList.size() > 0) {
final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass)); final FieldName idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass),
options);
// In the lazy mode, the request is done in asynchronous mode, they will be done after... // In the lazy mode, the request is done in asynchronous mode, they will be done after...
final LazyGetter lambda = () -> { final LazyGetter lambda = () -> {
final List<UUID> childs = new ArrayList<>(idList); final List<UUID> childs = new ArrayList<>(idList);
// TODO: update to have get with abstract types .... // TODO: update to have get with abstract types ....
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Object foreignData = ioDb.getsWhere(decorators.targetEntity(), final Object foreignData = ioDb.getsWhere(decorators.targetEntity(),
new Condition(new QueryInList<>(idField, childs))); new Condition(new QueryInList<>(idField.inTable(), childs)));
if (foreignData == null) { if (foreignData == null) {
return; return;
} }
@ -300,7 +301,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
final Object localKey, final Object localKey,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
if (field.getType() != List.class) { if (field.getType() != List.class) {
LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName()); LOGGER.error("Can not ManyToMany with other than List Model: {}", field.getType().getCanonicalName());
return; return;
@ -311,8 +313,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<" throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<"
+ objectClass.getCanonicalName() + ">"); + objectClass.getCanonicalName() + ">");
} }
final String columnName = AnnotationTools.getFieldName(field); final FieldName columnName = AnnotationTools.getFieldName(field, options);
final String linkTableName = generateLinkTableName(tableName, columnName); final String linkTableName = generateLinkTableName(tableName, columnName.inTable());
actions.add(() -> { actions.add(() -> {
ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName), ioDb.deleteWhere(LinkTableGeneric.class, new OverrideTableName(linkTableName),
@ -320,7 +322,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
new OptionSpecifyType("object1Id", localKey.getClass()), new OptionSpecifyType("object1Id", localKey.getClass()),
new OptionSpecifyType("object2Id", objectClass)); new OptionSpecifyType("object2Id", objectClass));
}); });
asyncInsert(ioDb, tableName, localKey, field, data, actions); asyncInsert(ioDb, tableName, localKey, field, data, actions, options);
} }
@Override @Override
@ -335,7 +337,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
final Object localKey, final Object localKey,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
if (data == null) { if (data == null) {
return; return;
} }
@ -349,8 +352,8 @@ public class AddOnManyToMany implements DataAccessAddOn {
throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<" throw new DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<"
+ objectClass.getCanonicalName() + ">"); + objectClass.getCanonicalName() + ">");
} }
final String columnName = AnnotationTools.getFieldName(field); final FieldName columnName = AnnotationTools.getFieldName(field, options);
final String linkTableName = generateLinkTableName(tableName, columnName); final String linkTableName = generateLinkTableName(tableName, columnName.inTable());
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final List<Long> dataCasted = (List<Long>) data; final List<Long> dataCasted = (List<Long>) data;
if (dataCasted.size() == 0) { if (dataCasted.size() == 0) {
@ -375,16 +378,18 @@ public class AddOnManyToMany implements DataAccessAddOn {
} }
@Override @Override
public void drop(final DBAccessSQL ioDb, final String tableName, final Field field) throws Exception { public void drop(final DBAccessSQL ioDb, final String tableName, final Field field, final QueryOptions options)
final String columnName = AnnotationTools.getFieldName(field); throws Exception {
final String linkTableName = generateLinkTableName(tableName, columnName); final FieldName columnName = AnnotationTools.getFieldName(field, options);
final String linkTableName = generateLinkTableName(tableName, columnName.inTable());
ioDb.drop(LinkTableGeneric.class, new OverrideTableName(linkTableName)); ioDb.drop(LinkTableGeneric.class, new OverrideTableName(linkTableName));
} }
@Override @Override
public void cleanAll(final DBAccessSQL ioDb, final String tableName, final Field field) throws Exception { public void cleanAll(final DBAccessSQL ioDb, final String tableName, final Field field, final QueryOptions options)
final String columnName = AnnotationTools.getFieldName(field); throws Exception {
final String linkTableName = generateLinkTableName(tableName, columnName); final FieldName columnName = AnnotationTools.getFieldName(field, options);
final String linkTableName = generateLinkTableName(tableName, columnName.inTable());
ioDb.cleanAll(LinkTableGeneric.class, new OverrideTableName(linkTableName)); ioDb.cleanAll(LinkTableGeneric.class, new OverrideTableName(linkTableName));
} }
@ -397,8 +402,6 @@ public class AddOnManyToMany implements DataAccessAddOn {
if (ioDb instanceof final DBAccessSQL daSQL) { if (ioDb instanceof final DBAccessSQL daSQL) {
final String tableName = AnnotationTools.getTableName(clazz); final String tableName = AnnotationTools.getTableName(clazz);
final String linkTableName = generateLinkTableName(tableName, column); final String linkTableName = generateLinkTableName(tableName, column);
/* final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (objectClass != Long.class && objectClass != UUID.class) { throw new
* DataAccessException("Can not ManyToMany with other than List<Long> or List<UUID> Model: List<" + objectClass.getCanonicalName() + ">"); } */
final LinkTableGeneric insertElement = new LinkTableGeneric(localKey, remoteKey); final LinkTableGeneric insertElement = new LinkTableGeneric(localKey, remoteKey);
daSQL.insert(insertElement, new OverrideTableName(linkTableName), daSQL.insert(insertElement, new OverrideTableName(linkTableName),
new OptionSpecifyType("object1Id", localKey.getClass()), new OptionSpecifyType("object1Id", localKey.getClass()),
@ -442,20 +445,21 @@ public class AddOnManyToMany implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
final ManyToMany manyToMany = AnnotationTools.getManyToMany(field); final ManyToMany manyToMany = AnnotationTools.getManyToMany(field);
if (manyToMany.mappedBy() != null && manyToMany.mappedBy().length() != 0) { if (manyToMany.mappedBy() != null && manyToMany.mappedBy().length() != 0) {
// not the reference model to create base: // not the reference model to create base:
return; return;
} }
final String linkTableName = generateLinkTableNameField(tableName, field); final String linkTableName = generateLinkTableNameField(tableName, field, options);
final QueryOptions options = new QueryOptions(new OverrideTableName(linkTableName)); final QueryOptions options2 = new QueryOptions(new OverrideTableName(linkTableName));
final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]; .getActualTypeArguments()[0];
final Class<?> primaryType = primaryField.getType(); final Class<?> primaryType = primaryField.getType();
options.add(new OptionSpecifyType("object1Id", primaryType)); options2.add(new OptionSpecifyType("object1Id", primaryType));
options.add(new OptionSpecifyType("object2Id", objectClass)); options2.add(new OptionSpecifyType("object2Id", objectClass));
final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options); final List<String> sqlCommand = DataFactory.createTable(LinkTableGeneric.class, options2);
postActionList.addAll(sqlCommand); postActionList.addAll(sqlCommand);
} }
} }

View File

@ -8,6 +8,7 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccessSQL; import org.kar.archidata.dataAccess.DBAccessSQL;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
@ -31,10 +32,10 @@ public class AddOnManyToOne implements DataAccessAddOn {
} }
@Override @Override
public String getSQLFieldType(final Field field) throws Exception { public String getSQLFieldType(final Field field, final QueryOptions options) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field); final FieldName fieldName = AnnotationTools.getFieldName(field, options);
try { try {
return DataFactory.convertTypeInSQL(field.getType(), fieldName); return DataFactory.convertTypeInSQL(field.getType(), fieldName.inTable());
} catch (final Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -161,11 +162,11 @@ public class AddOnManyToOne implements DataAccessAddOn {
query.append("` ON "); query.append("` ON ");
query.append(subTableName); query.append(subTableName);
query.append("."); query.append(".");
query.append(AnnotationTools.getFieldName(idField)); query.append(AnnotationTools.getFieldName(idField, options).inTable());
query.append(" = "); query.append(" = ");
query.append(tableName); query.append(tableName);
query.append("."); query.append(".");
query.append(AnnotationTools.getFieldName(field)); query.append(AnnotationTools.getFieldName(field, options).inTable());
} else { } else {
querySelect.append(" "); querySelect.append(" ");
querySelect.append(tableName); querySelect.append(tableName);
@ -293,16 +294,17 @@ public class AddOnManyToOne implements DataAccessAddOn {
final List<String> postActionList, final List<String> postActionList,
final boolean createIfNotExist, final boolean createIfNotExist,
final boolean createDrop, final boolean createDrop,
final int fieldId) throws Exception { final int fieldId,
final QueryOptions options) throws Exception {
final Class<?> classType = field.getType(); final Class<?> classType = field.getType();
if (classType == Long.class || classType == Integer.class || classType == Short.class if (classType == Long.class || classType == Integer.class || classType == Short.class
|| classType == String.class || classType == UUID.class) { || classType == String.class || classType == UUID.class) {
DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, classType); postActionList, createIfNotExist, createDrop, fieldId, classType, options);
} else { } else {
LOGGER.error("Support only the Long remote field of ecternal primary keys..."); LOGGER.error("Support only the Long remote field of ecternal primary keys...");
DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList,
postActionList, createIfNotExist, createDrop, fieldId, Long.class); postActionList, createIfNotExist, createDrop, fieldId, Long.class, options);
} }
} }
} }

View File

@ -11,6 +11,7 @@ import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.kar.archidata.annotation.AnnotationTools; import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.AnnotationTools.FieldName;
import org.kar.archidata.dataAccess.CountInOut; import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DBAccessSQL; import org.kar.archidata.dataAccess.DBAccessSQL;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
@ -64,10 +65,10 @@ public class AddOnOneToMany implements DataAccessAddOn {
} }
@Override @Override
public String getSQLFieldType(final Field field) throws Exception { public String getSQLFieldType(final Field field, final QueryOptions options) throws Exception {
final String fieldName = AnnotationTools.getFieldName(field); final FieldName fieldName = AnnotationTools.getFieldName(field, options);
try { try {
return DataFactory.convertTypeInSQL(Long.class, fieldName); return DataFactory.convertTypeInSQL(Long.class, fieldName.inTable());
} catch (final Exception e) { } catch (final Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -136,15 +137,15 @@ public class AddOnOneToMany implements DataAccessAddOn {
final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType())
.getActualTypeArguments()[0]; .getActualTypeArguments()[0];
final String remoteTableName = AnnotationTools.getTableName(targetEntity); final String remoteTableName = AnnotationTools.getTableName(targetEntity);
final String remoteTablePrimaryKeyName = AnnotationTools final FieldName remoteTablePrimaryKeyName = AnnotationTools
.getFieldName(AnnotationTools.getPrimaryKeyField(targetEntity)); .getFieldName(AnnotationTools.getPrimaryKeyField(targetEntity), options);
final String tmpRemoteVariable = "tmp_" + Integer.toString(count.value); final String tmpRemoteVariable = "tmp_" + Integer.toString(count.value);
final String remoteDeletedFieldName = AnnotationTools.getDeletedFieldName(targetEntity); final String remoteDeletedFieldName = AnnotationTools.getDeletedFieldName(targetEntity);
querySelect.append(" (SELECT GROUP_CONCAT("); querySelect.append(" (SELECT GROUP_CONCAT(");
querySelect.append(tmpRemoteVariable); querySelect.append(tmpRemoteVariable);
querySelect.append("."); querySelect.append(".");
querySelect.append(remoteTablePrimaryKeyName); querySelect.append(remoteTablePrimaryKeyName.inTable());
querySelect.append(" "); querySelect.append(" ");
if ("sqlite".equals(ConfigBaseVariable.getDBType())) { if ("sqlite".equals(ConfigBaseVariable.getDBType())) {
querySelect.append(", "); querySelect.append(", ");
@ -307,18 +308,4 @@ public class AddOnOneToMany implements DataAccessAddOn {
} }
} }
// TODO : refacto this table to manage a generic table with dynamic name to be serialize with the default system
@Override
public void createTables(
final String tableName,
final Field primaryField,
final Field field,
final StringBuilder mainTableBuilder,
final List<String> preActionList,
final List<String> postActionList,
final boolean createIfNotExist,
final boolean createDrop,
final int fieldId) throws Exception {
// This is a remote field ==> nothing to generate (it is stored in the remote object
}
} }

View File

@ -21,7 +21,9 @@ public interface DataAccessAddOn {
/** Get the SQL type that is needed to declare for the specific Field Type. /** Get the SQL type that is needed to declare for the specific Field Type.
* @param elem Field to declare. * @param elem Field to declare.
* @return SQL type to create. */ * @return SQL type to create. */
String getSQLFieldType(Field elem) throws Exception; default String getSQLFieldType(final Field elem, final QueryOptions options) throws Exception {
return null;
}
/** Check if the field is manage by the local add-on /** Check if the field is manage by the local add-on
* @param elem Field to inspect. * @param elem Field to inspect.
@ -81,16 +83,19 @@ public interface DataAccessAddOn {
* @param createDrop * @param createDrop
* @param fieldId * @param fieldId
* @throws Exception */ * @throws Exception */
void createTables( default void createTables(
String tableName, final String tableName,
final Field primaryField, final Field primaryField,
Field field, final Field field,
StringBuilder mainTableBuilder, final StringBuilder mainTableBuilder,
List<String> preActionList, final List<String> preActionList,
List<String> postActionList, final List<String> postActionList,
boolean createIfNotExist, final boolean createIfNotExist,
boolean createDrop, final boolean createDrop,
int fieldId) throws Exception; final int fieldId,
final QueryOptions options) throws Exception {
}
/** Some action must be done asynchronously for update or remove element /** Some action must be done asynchronously for update or remove element
* @param field * @param field
@ -111,7 +116,8 @@ public interface DataAccessAddOn {
final Object localId, final Object localId,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
} }
@ -134,15 +140,18 @@ public interface DataAccessAddOn {
final Object localId, final Object localId,
final Field field, final Field field,
final Object data, final Object data,
final List<LazyGetter> actions) throws Exception { final List<LazyGetter> actions,
final QueryOptions options) throws Exception {
} }
default void drop(final DBAccessSQL ioDb, final String tableName, final Field field) throws Exception { default void drop(final DBAccessSQL ioDb, final String tableName, final Field field, final QueryOptions options)
throws Exception {
} }
default void cleanAll(final DBAccessSQL ioDb, final String tableName, final Field field) throws Exception { default void cleanAll(final DBAccessSQL ioDb, final String tableName, final Field field, final QueryOptions options)
throws Exception {
} }

View File

@ -6,20 +6,20 @@ import org.kar.archidata.annotation.DataJson;
import jakarta.persistence.Id; import jakarta.persistence.Id;
public class TableCoversLongLong { public class TableCoversGeneric {
public TableCoversLongLong() { public TableCoversGeneric() {
// nothing to do... // nothing to do...
} }
public TableCoversLongLong(final Long id, final List<Long> covers) { public TableCoversGeneric(final Object id, final List<Object> covers) {
this.id = id; this.id = id;
this.covers = covers; this.covers = covers;
} }
@Id @Id
public Long id; public Object id;
@DataJson() @DataJson()
public List<Long> covers; public List<Object> covers;
} }

View File

@ -1,27 +0,0 @@
package org.kar.archidata.dataAccess.addOnSQL.model;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import jakarta.persistence.Id;
public class TableCoversLongUUID {
public TableCoversLongUUID() {
// nothing to do...
}
public TableCoversLongUUID(final Long id, final List<UUID> covers) {
this.id = id;
this.covers = new ArrayList<>(covers);
}
@Id
public Long id;
@DataJson()
public List<UUID> covers;
}

View File

@ -1,26 +0,0 @@
package org.kar.archidata.dataAccess.addOnSQL.model;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import jakarta.persistence.Id;
public class TableCoversUUIDLong {
public TableCoversUUIDLong() {
// nothing to do...
}
public TableCoversUUIDLong(final UUID uuid, final List<Long> covers) {
this.uuid = uuid;
this.covers = new ArrayList<>(covers);
}
@Id
public UUID uuid;
@DataJson()
public List<Long> covers;
}

View File

@ -1,25 +0,0 @@
package org.kar.archidata.dataAccess.addOnSQL.model;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import jakarta.persistence.Id;
public class TableCoversUUIDUUID {
public TableCoversUUIDUUID() {
// nothing to do...
}
public TableCoversUUIDUUID(final UUID uuid, final List<UUID> covers) {
this.uuid = uuid;
this.covers = covers;
}
@Id
public UUID uuid;
@DataJson()
public List<UUID> covers;
}

View File

@ -0,0 +1,12 @@
package org.kar.archidata.dataAccess.options;
public class OptionRenameColumn extends QueryOption {
public final String columnName;
public final String colomnNewName;
public OptionRenameColumn(final String name, final String newName) {
this.columnName = name;
this.colomnNewName = newName;
}
}

View File

@ -3,10 +3,18 @@ package org.kar.archidata.dataAccess.options;
public class OptionSpecifyType extends QueryOption { public class OptionSpecifyType extends QueryOption {
public final String name; public final String name;
public final Class<?> clazz; public final Class<?> clazz;
public final boolean isList;
// To specify the type of an element if the model is a Object. // To specify the type of an element if the model is a Object.
public OptionSpecifyType(final String name, final Class<?> clazz) { public OptionSpecifyType(final String name, final Class<?> clazz) {
this.clazz = clazz; this.clazz = clazz;
this.name = name; this.name = name;
this.isList = false;
}
public OptionSpecifyType(final String name, final Class<?> clazz, final boolean isList) {
this.clazz = clazz;
this.name = name;
this.isList = isList;
} }
} }

View File

@ -44,7 +44,7 @@ public class ClassObjectModel extends ClassModel {
for (final Field field : superClass.getFields()) { for (final Field field : superClass.getFields()) {
String name; String name;
try { try {
name = AnnotationTools.getFieldName(field); name = AnnotationTools.getFieldNameRaw(field);
if (filedName.equals(name)) { if (filedName.equals(name)) {
return true; return true;
} }
@ -217,7 +217,7 @@ public class ClassObjectModel extends ClassModel {
} }
alreadyAdded.add(dataName); alreadyAdded.add(dataName);
LOGGER.trace(" + '{}'", elem.getName()); LOGGER.trace(" + '{}'", elem.getName());
LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldName(elem), elem.getType()); LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldNameRaw(elem), elem.getType());
final FieldProperty porperty = new FieldProperty(elem, previous); final FieldProperty porperty = new FieldProperty(elem, previous);
for (final ClassModel depModel : porperty.model().getAlls()) { for (final ClassModel depModel : porperty.model().getAlls()) {
if (!this.dependencyModels.contains(depModel)) { if (!this.dependencyModels.contains(depModel)) {

View File

@ -345,13 +345,7 @@ public class DataTools {
} }
// Fist step: retrieve all the Id of each parents:... // Fist step: retrieve all the Id of each parents:...
LOGGER.info("Find typeNode"); LOGGER.info("Find typeNode");
if (id instanceof final Long idLong) { AddOnDataJson.addLink(ioDb, clazz, null, id, null, data.uuid);
AddOnDataJson.addLink(ioDb, clazz, idLong, "covers", data.uuid);
} else if (id instanceof final UUID idUUID) {
AddOnDataJson.addLink(ioDb, clazz, idUUID, "covers", data.uuid);
} else {
throw new IOException("Fail to add Cover can not detect type...");
}
} }
public static <CLASS_TYPE, ID_TYPE> void uploadCover( public static <CLASS_TYPE, ID_TYPE> void uploadCover(
@ -397,12 +391,6 @@ public class DataTools {
} }
// Fist step: retrieve all the Id of each parents:... // Fist step: retrieve all the Id of each parents:...
LOGGER.info("Find typeNode"); LOGGER.info("Find typeNode");
if (id instanceof final Long idLong) { AddOnDataJson.addLink(ioDb, clazz, null, id, null, data.uuid);
AddOnDataJson.addLink(ioDb, clazz, idLong, "covers", data.uuid);
} else if (id instanceof final UUID idUUID) {
AddOnDataJson.addLink(ioDb, clazz, idUUID, "covers", data.uuid);
} else {
throw new IOException("Fail to add Cover can not detect type...");
}
} }
} }

View File

@ -14,6 +14,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.kar.archidata.dataAccess.DBAccessSQL; import org.kar.archidata.dataAccess.DBAccessSQL;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.addOnSQL.AddOnDataJson;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -87,4 +88,54 @@ public class TestListJson {
Assertions.assertEquals(test.data.get(4), retrieve.data.get(4)); Assertions.assertEquals(test.data.get(4), retrieve.data.get(4));
} }
@Order(3)
@Test
public void testToolInsert() throws Exception {
final SerializeListAsJson test = new SerializeListAsJson();
test.data = new ArrayList<>();
final SerializeListAsJson insertedData = ConfigureDb.da.insert(test);
Assertions.assertNotNull(insertedData);
Assertions.assertNotNull(insertedData.id);
Assertions.assertTrue(insertedData.id >= 0);
Assertions.assertNotNull(insertedData.data);
Assertions.assertEquals(0, insertedData.data.size());
final Integer firstDataInserted1 = 111;
final Integer firstDataInserted2 = 222;
final Integer firstDataInserted3 = 333;
AddOnDataJson.addLink(ConfigureDb.da, SerializeListAsJson.class, null, insertedData.id, "data",
firstDataInserted1);
AddOnDataJson.addLink(ConfigureDb.da, SerializeListAsJson.class, null, insertedData.id, "data",
firstDataInserted2);
AddOnDataJson.addLink(ConfigureDb.da, SerializeListAsJson.class, null, insertedData.id, "data",
firstDataInserted3);
// Try to retrieve all the data:
SerializeListAsJson retrieve = ConfigureDb.da.get(SerializeListAsJson.class, insertedData.id);
Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id);
Assertions.assertTrue(retrieve.id >= 0);
Assertions.assertNotNull(retrieve.data);
Assertions.assertEquals(3, retrieve.data.size());
Assertions.assertEquals(firstDataInserted1, retrieve.data.get(0));
Assertions.assertEquals(firstDataInserted2, retrieve.data.get(1));
Assertions.assertEquals(firstDataInserted3, retrieve.data.get(2));
AddOnDataJson.removeLink(ConfigureDb.da, SerializeListAsJson.class, null, insertedData.id, "data",
firstDataInserted2);
// Try to retrieve all the data:
retrieve = ConfigureDb.da.get(SerializeListAsJson.class, insertedData.id);
Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id);
Assertions.assertTrue(retrieve.id >= 0);
Assertions.assertNotNull(retrieve.data);
Assertions.assertEquals(2, retrieve.data.size());
Assertions.assertEquals(firstDataInserted1, retrieve.data.get(0));
Assertions.assertEquals(firstDataInserted3, retrieve.data.get(1));
}
} }

View File

@ -0,0 +1,14 @@
package test.kar.archidata.dataAccess.model;
import java.util.List;
import org.bson.types.ObjectId;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData;
public class DataJsonList extends GenericData {
@DataJson()
public List<Long> covers;
@DataJson()
public List<ObjectId> coversObjectId;
}