[DEV] update options and where condition, some normalisation

This commit is contained in:
Edouard DUPIN 2023-11-25 14:13:14 +01:00
parent ed3bfa0604
commit c3d2eff5be
46 changed files with 527 additions and 292 deletions

View File

@ -1,7 +1,7 @@
package org.kar.archidata; package org.kar.archidata;
import org.kar.archidata.db.DBConfig; import org.kar.archidata.db.DBConfig;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
public class GlobalConfiguration { public class GlobalConfiguration {
public static DBConfig dbConfig = null; public static DBConfig dbConfig = null;

View File

@ -1,7 +1,7 @@
package org.kar.archidata; package org.kar.archidata;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.tools.JWTWrapper;
public class UpdateJwtPublicKey extends Thread { public class UpdateJwtPublicKey extends Thread {
boolean kill = false; boolean kill = false;

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.OverrideTableName;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -20,11 +21,9 @@ public class AnnotationTools {
public static String getTableName(final Class<?> clazz, final QueryOptions options) throws Exception { public static String getTableName(final Class<?> clazz, final QueryOptions options) throws Exception {
if (options != null) { if (options != null) {
final Object data = options.get(QueryOptions.OVERRIDE_TABLE_NAME); final OverrideTableName data = options.get(OverrideTableName.class);
if (data instanceof final String optionString) { if (data != null) {
return optionString; return data.getName();
} else if (data != null) {
LOGGER.error("'{}' ==> has not a String value: {}", QueryOptions.SQL_DELETED_DISABLE, data);
} }
} }
return AnnotationTools.getTableName(clazz); return AnnotationTools.getTableName(clazz);

View File

@ -26,7 +26,7 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryCondition; import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.filter.GenericContext; import org.kar.archidata.filter.GenericContext;
import org.kar.archidata.model.Data; import org.kar.archidata.model.Data;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@ -1,16 +1,20 @@
package org.kar.archidata.dataAccess; package org.kar.archidata.dataAccess;
/** Java does not permit to set return data (eg: integer) in the function parameter. This class permit to update a value as in/out function parameters. */
public class CountInOut { public class CountInOut {
// internal value of the stream
public int value = 0; public int value = 0;
public CountInOut() { /** Default constructor */
// TODO Auto-generated constructor stub public CountInOut() {}
}
/** Constructor with the initial value.
* @param i Initial Value */
public CountInOut(final int i) { public CountInOut(final int i) {
this.value = i; this.value = i;
} }
/** Increment by one the value. */
public void inc() { public void inc() {
this.value++; this.value++;
} }

View File

@ -25,9 +25,13 @@ import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany; import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.addOn.AddOnManyToOne; import org.kar.archidata.dataAccess.addOn.AddOnManyToOne;
import org.kar.archidata.dataAccess.addOn.AddOnSQLTableExternalForeinKeyAsList; import org.kar.archidata.dataAccess.addOn.AddOnSQLTableExternalForeinKeyAsList;
import org.kar.archidata.dataAccess.options.AccessDeletedItems;
import org.kar.archidata.dataAccess.options.CheckFunction;
import org.kar.archidata.dataAccess.options.Limit;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.exception.DataAccessException; import org.kar.archidata.exception.DataAccessException;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.kar.archidata.tools.DateTools;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -166,7 +170,7 @@ public class DataAccess {
* @param rs Result Set of the BDD * @param rs Result Set of the BDD
* @param iii Id in the result set * @param iii Id in the result set
* @return The list of Long value * @return The list of Long value
* @throws SQLException if an error is generated in the sql request. */ * @throws SQLException if an error is generated in the SQL request. */
public static List<Long> getListOfIds(final ResultSet rs, final int iii, final String separator) throws SQLException { public static List<Long> getListOfIds(final ResultSet rs, final int iii, final String separator) throws SQLException {
final String trackString = rs.getString(iii); final String trackString = rs.getString(iii);
if (rs.wasNull()) { if (rs.wasNull()) {
@ -278,14 +282,12 @@ public class DataAccess {
iii.inc(); iii.inc();
} }
// TODO: maybe wrap this if the use of sqlite ==> maybe some problems came with sqlite ...
protected static <T> void setValueFromDb(final Class<?> type, final Object data, final CountInOut count, final Field field, final ResultSet rs, final CountInOut countNotNull) throws Exception { protected static <T> void setValueFromDb(final Class<?> type, final Object data, final CountInOut count, final Field field, final ResultSet rs, final CountInOut countNotNull) throws Exception {
if (type == Long.class) { if (type == Long.class) {
final Long tmp = rs.getLong(count.value); final Long tmp = rs.getLong(count.value);
if (rs.wasNull()) { if (rs.wasNull()) {
field.set(data, null); field.set(data, null);
} else { } else {
// logger.debug(" ==> {}", tmp);
field.set(data, tmp); field.set(data, tmp);
countNotNull.inc(); countNotNull.inc();
} }
@ -381,11 +383,12 @@ public class DataAccess {
} catch (final SQLException ex) { } catch (final SQLException ex) {
final String tmp = rs.getString(count.value); final String tmp = rs.getString(count.value);
LOGGER.error("Fail to parse the SQL time !!! {}", tmp); LOGGER.error("Fail to parse the SQL time !!! {}", tmp);
LOGGER.error("Fail to parse the SQL time !!! {}", Date.parse(tmp));
if (rs.wasNull()) { if (rs.wasNull()) {
field.set(data, null); field.set(data, null);
} else { } else {
field.set(data, Date.parse(tmp)); final Date date = DateTools.parseDate(tmp);
LOGGER.error("Fail to parse the SQL time !!! {}", date);
field.set(data, date);
countNotNull.inc(); countNotNull.inc();
} }
} }
@ -418,15 +421,19 @@ public class DataAccess {
if (rs.wasNull()) { if (rs.wasNull()) {
field.set(data, null); field.set(data, null);
} else { } else {
boolean find = false;
final Object[] arr = type.getEnumConstants(); final Object[] arr = type.getEnumConstants();
for (final Object elem : arr) { for (final Object elem : arr) {
if (elem.toString().equals(tmp)) { if (elem.toString().equals(tmp)) {
field.set(data, elem); field.set(data, elem);
countNotNull.inc(); countNotNull.inc();
find = true;
break; break;
} }
} }
// TODO: maybe do something stupid if not exist ??? if (!find) {
throw new DataAccessException("Enum value does not exist in the Model: '" + tmp + "'");
}
} }
} else { } else {
throw new DataAccessException("Unknown Field Type"); throw new DataAccessException("Unknown Field Type");
@ -463,6 +470,14 @@ public class DataAccess {
public static <T> T insert(final T data, final QueryOptions options) throws Exception { public static <T> T insert(final T data, final QueryOptions options) throws Exception {
final Class<?> clazz = data.getClass(); final Class<?> clazz = data.getClass();
// External checker of data:
if (options != null) {
final CheckFunction check = options.get(CheckFunction.class);
if (check != null) {
check.getChecker().check(data, null);
}
}
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
// real add in the BDD: // real add in the BDD:
try { try {
@ -672,6 +687,14 @@ public class DataAccess {
final Class<?> clazz = data.getClass(); final Class<?> clazz = data.getClass();
// public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) { // public static NodeSmall createNode(String typeInNode, String name, String description, Long parentId) {
// External checker of data:
if (options != null) {
final CheckFunction check = options.get(CheckFunction.class);
if (check != null) {
check.getChecker().check(data, filterValue);
}
}
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
// real add in the BDD: // real add in the BDD:
try { try {
@ -803,12 +826,7 @@ public class DataAccess {
throws ExceptionDBInterface { throws ExceptionDBInterface {
boolean exclude_deleted = true; boolean exclude_deleted = true;
if (options != null) { if (options != null) {
final Object data = options.get(QueryOptions.SQL_DELETED_DISABLE); exclude_deleted = !options.exist(AccessDeletedItems.class);
if (data instanceof final Boolean elem) {
exclude_deleted = !elem;
} else if (data != null) {
LOGGER.error("'{}' ==> has not a boolean value: {}", QueryOptions.SQL_DELETED_DISABLE, data);
}
} }
// Check if we have a condition to generate // Check if we have a condition to generate
if (condition == null) { if (condition == null) {
@ -823,7 +841,7 @@ public class DataAccess {
} }
query.append(" WHERE ("); query.append(" WHERE (");
condition.generateQuerry(query, tableName); condition.generateQuerry(query, tableName);
query.append(") "); query.append(") ");
if (exclude_deleted && deletedFieldName != null) { if (exclude_deleted && deletedFieldName != null) {
query.append("AND "); query.append("AND ");
@ -865,8 +883,12 @@ public class DataAccess {
return getWhere(clazz, condition, null); return getWhere(clazz, condition, null);
} }
public static <T> T getWhere(final Class<T> clazz, final QueryItem condition, final QueryOptions options) throws Exception { public static <T> T getWhere(final Class<T> clazz, final QueryItem condition, QueryOptions options) throws Exception {
final List<T> values = getsWhere(clazz, condition, options, 1); if (options == null) {
options = new QueryOptions();
}
options.add(new Limit(1));
final List<T> values = getsWhere(clazz, condition, options);
if (values.size() == 0) { if (values.size() == 0) {
return null; return null;
} }
@ -874,19 +896,15 @@ public class DataAccess {
} }
public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition) throws Exception { public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition) throws Exception {
return getsWhere(clazz, condition, null, null, null); return getsWhere(clazz, condition, null, null);
} }
public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition, final QueryOptions options) throws Exception { public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition, final QueryOptions options) throws Exception {
return getsWhere(clazz, condition, null, options, null); return getsWhere(clazz, condition, null, options);
}
public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition, final QueryOptions options, final Integer linit) throws Exception {
return getsWhere(clazz, condition, null, options, linit);
} }
public static void generateSelectField(final StringBuilder querySelect, final StringBuilder query, final Class<?> clazz, final QueryOptions options, final CountInOut count) throws Exception { public static void generateSelectField(final StringBuilder querySelect, final StringBuilder query, final Class<?> clazz, final QueryOptions options, final CountInOut count) throws Exception {
final boolean readAllfields = QueryOptions.readAllFields(options); final boolean readAllfields = QueryOptions.readAllColomn(options);
final String tableName = AnnotationTools.getTableName(clazz, options); final String tableName = AnnotationTools.getTableName(clazz, options);
boolean firstField = true; boolean firstField = true;
@ -899,7 +917,6 @@ public class DataAccess {
if (addOn != null && !addOn.canRetrieve(elem)) { if (addOn != null && !addOn.canRetrieve(elem)) {
continue; continue;
} }
// TODO: Manage it with AddOn
final boolean notRead = AnnotationTools.isdefaultNotRead(elem); final boolean notRead = AnnotationTools.isdefaultNotRead(elem);
if (!readAllfields && notRead) { if (!readAllfields && notRead) {
continue; continue;
@ -922,9 +939,8 @@ public class DataAccess {
} }
} }
// TODO: set limit as an query Option...
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition, final String orderBy, final QueryOptions options, final Integer linit) throws Exception { public static <T> List<T> getsWhere(final Class<T> clazz, final QueryItem condition, final String orderBy, final QueryOptions options) throws Exception {
final List<LazyGetter> lazyCall = new ArrayList<>(); final List<LazyGetter> lazyCall = new ArrayList<>();
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz); final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
@ -948,10 +964,20 @@ public class DataAccess {
query.append(" ORDER BY "); query.append(" ORDER BY ");
query.append(orderBy); query.append(orderBy);
} }
if (linit != null && linit >= 1) { if (options != null) {
query.append(" LIMIT " + linit); final Limit limit = options.get(Limit.class);
if (limit != null) {
if (limit.getLimit() >= 1) {
query.append(" LIMIT " + limit.getLimit());
} else {
LOGGER.warn("Limit is equal @ {}", limit.getLimit());
entry.close();
entry = null;
return outs;
}
}
} }
LOGGER.debug("generate the query: '{}'", query.toString()); LOGGER.warn("generate the query: '{}'", query.toString());
// prepare the request: // prepare the request:
final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
final CountInOut iii = new CountInOut(1); final CountInOut iii = new CountInOut(1);
@ -983,7 +1009,7 @@ public class DataAccess {
public static Object createObjectFromSQLRequest(final ResultSet rs, final Class<?> clazz, final CountInOut count, final CountInOut countNotNull, final QueryOptions options, public static Object createObjectFromSQLRequest(final ResultSet rs, final Class<?> clazz, final CountInOut count, final CountInOut countNotNull, final QueryOptions options,
final List<LazyGetter> lazyCall) throws Exception { final List<LazyGetter> lazyCall) throws Exception {
final boolean readAllfields = QueryOptions.readAllFields(options); final boolean readAllfields = QueryOptions.readAllColomn(options);
// TODO: manage class that is defined inside a class ==> Not manage for now... // TODO: manage class that is defined inside a class ==> Not manage for now...
final Object data = clazz.getConstructors()[0].newInstance(); final Object data = clazz.getConstructors()[0].newInstance();
for (final Field elem : clazz.getFields()) { for (final Field elem : clazz.getFields()) {
@ -995,7 +1021,6 @@ public class DataAccess {
if (addOn != null && !addOn.canRetrieve(elem)) { if (addOn != null && !addOn.canRetrieve(elem)) {
continue; continue;
} }
// TODO: Manage it with AddOn
final boolean notRead = AnnotationTools.isdefaultNotRead(elem); final boolean notRead = AnnotationTools.isdefaultNotRead(elem);
if (!readAllfields && notRead) { if (!readAllfields && notRead) {
continue; continue;
@ -1009,7 +1034,6 @@ public class DataAccess {
return data; return data;
} }
// TODO : detect the @Id
public static <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id) throws Exception { public static <T, ID_TYPE> T get(final Class<T> clazz, final ID_TYPE id) throws Exception {
return get(clazz, id, null); return get(clazz, id, null);
} }
@ -1030,7 +1054,6 @@ public class DataAccess {
return getsWhere(clazz, null, options); return getsWhere(clazz, null, options);
} }
// TODO : detect the @Id
public static <ID_TYPE> int delete(final Class<?> clazz, final ID_TYPE id) throws Exception { public static <ID_TYPE> int delete(final Class<?> clazz, final ID_TYPE id) throws Exception {
return delete(clazz, id, null); return delete(clazz, id, null);
} }
@ -1142,7 +1165,7 @@ public class DataAccess {
query.append("`=false "); query.append("`=false ");
/* is is needed only for SQLite ??? query.append("`modify_date`="); query.append(getDBNow()); query.append(", "); */ /* is is needed only for SQLite ??? query.append("`modify_date`="); query.append(getDBNow()); query.append(", "); */
// need to disable the deleted false because the model must be unselected to be updated. // need to disable the deleted false because the model must be unselected to be updated.
options.put(QueryOptions.SQL_DELETED_DISABLE, true); options.add(QueryOptions.ACCESS_DELETED_ITEMS);
whereAppendQuery(query, tableName, condition, options, deletedFieldName); whereAppendQuery(query, tableName, condition, options, deletedFieldName);
try { try {
final PreparedStatement ps = entry.connection.prepareStatement(query.toString()); final PreparedStatement ps = entry.connection.prepareStatement(query.toString());

View File

@ -12,8 +12,9 @@ import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.CreationTimestamp; import org.kar.archidata.annotation.CreationTimestamp;
import org.kar.archidata.annotation.DataIfNotExists; import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.annotation.UpdateTimestamp; import org.kar.archidata.annotation.UpdateTimestamp;
import org.kar.archidata.dataAccess.options.CreateDropTable;
import org.kar.archidata.exception.DataAccessException; import org.kar.archidata.exception.DataAccessException;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -23,7 +24,7 @@ import jakarta.persistence.GenerationType;
public class DataFactory { public class DataFactory {
static final Logger LOGGER = LoggerFactory.getLogger(DataFactory.class); static final Logger LOGGER = LoggerFactory.getLogger(DataFactory.class);
public static String convertTypeInSQL(final Class<?> type, final String fieldName) throws Exception { public static String convertTypeInSQL(final Class<?> type, final String fieldName) throws Exception {
if (!"sqlite".equals(ConfigBaseVariable.getDBType())) { if (!"sqlite".equals(ConfigBaseVariable.getDBType())) {
if (type == Long.class || type == long.class) { if (type == Long.class || type == long.class) {
@ -126,21 +127,21 @@ public class DataFactory {
} }
throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName()); throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName());
} }
public static void createTablesSpecificType(final String tableName, final Field elem, final StringBuilder mainTableBuilder, final List<String> preOtherTables, final List<String> postOtherTables, public static void createTablesSpecificType(final String tableName, final Field elem, final StringBuilder mainTableBuilder, final List<String> preOtherTables, final List<String> postOtherTables,
final boolean createIfNotExist, final boolean createDrop, final int fieldId, final Class<?> classModel) throws Exception { final boolean createIfNotExist, final boolean createDrop, final int fieldId, final Class<?> classModel) throws Exception {
final String name = AnnotationTools.getFieldName(elem); final String name = AnnotationTools.getFieldName(elem);
final Integer limitSize = AnnotationTools.getLimitSize(elem); final Integer limitSize = AnnotationTools.getLimitSize(elem);
final boolean notNull = AnnotationTools.getNotNull(elem); final boolean notNull = AnnotationTools.getNotNull(elem);
final boolean primaryKey = AnnotationTools.isPrimaryKey(elem); final boolean primaryKey = AnnotationTools.isPrimaryKey(elem);
final GenerationType strategy = AnnotationTools.getStrategy(elem); final GenerationType strategy = AnnotationTools.getStrategy(elem);
final boolean createTime = elem.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0; final boolean createTime = elem.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0;
final boolean updateTime = elem.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0; final boolean updateTime = elem.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0;
final String comment = AnnotationTools.getComment(elem); final String comment = AnnotationTools.getComment(elem);
final String defaultValue = AnnotationTools.getDefault(elem); final String defaultValue = AnnotationTools.getDefault(elem);
if (fieldId == 0) { if (fieldId == 0) {
mainTableBuilder.append("\n\t\t`"); mainTableBuilder.append("\n\t\t`");
} else { } else {
@ -193,13 +194,13 @@ public class DataFactory {
triggerBuilder.append(tableName); triggerBuilder.append(tableName);
triggerBuilder.append(" SET "); triggerBuilder.append(" SET ");
triggerBuilder.append(name); triggerBuilder.append(name);
//triggerBuilder.append(" = datetime('now') WHERE id = NEW.id; \n"); // triggerBuilder.append(" = datetime('now') WHERE id = NEW.id; \n");
triggerBuilder.append(" = strftime('%Y-%m-%d %H:%M:%f', 'now') WHERE id = NEW.id; \n"); triggerBuilder.append(" = strftime('%Y-%m-%d %H:%M:%f', 'now') WHERE id = NEW.id; \n");
triggerBuilder.append("END;"); triggerBuilder.append("END;");
postOtherTables.add(triggerBuilder.toString()); postOtherTables.add(triggerBuilder.toString());
} }
mainTableBuilder.append(" "); mainTableBuilder.append(" ");
} }
} else { } else {
@ -234,11 +235,11 @@ public class DataFactory {
mainTableBuilder.append("DEFAULT "); mainTableBuilder.append("DEFAULT ");
mainTableBuilder.append(defaultValue); mainTableBuilder.append(defaultValue);
mainTableBuilder.append(" "); mainTableBuilder.append(" ");
} }
if (primaryKey && "sqlite".equals(ConfigBaseVariable.getDBType())) { if (primaryKey && "sqlite".equals(ConfigBaseVariable.getDBType())) {
mainTableBuilder.append("PRIMARY KEY "); mainTableBuilder.append("PRIMARY KEY ");
} }
if (strategy == GenerationType.IDENTITY) { if (strategy == GenerationType.IDENTITY) {
if (!"sqlite".equals(ConfigBaseVariable.getDBType())) { if (!"sqlite".equals(ConfigBaseVariable.getDBType())) {
@ -249,14 +250,14 @@ public class DataFactory {
} else if (strategy != null) { } else if (strategy != null) {
throw new DataAccessException("Can not generate a stategy different of IDENTITY"); throw new DataAccessException("Can not generate a stategy different of IDENTITY");
} }
if (comment != null && !"sqlite".equals(ConfigBaseVariable.getDBType())) { if (comment != null && !"sqlite".equals(ConfigBaseVariable.getDBType())) {
mainTableBuilder.append("COMMENT '"); mainTableBuilder.append("COMMENT '");
mainTableBuilder.append(comment.replace('\'', '\'')); mainTableBuilder.append(comment.replace('\'', '\''));
mainTableBuilder.append("' "); mainTableBuilder.append("' ");
} }
} }
private static boolean isFieldFromSuperClass(final Class<?> model, final String filedName) { private static boolean isFieldFromSuperClass(final Class<?> model, final String filedName) {
final Class<?> superClass = model.getSuperclass(); final Class<?> superClass = model.getSuperclass();
if (superClass == null) { if (superClass == null) {
@ -276,24 +277,19 @@ public class DataFactory {
} }
return false; return false;
} }
public static List<String> createTable(final Class<?> clazz) throws Exception { public static List<String> createTable(final Class<?> clazz) throws Exception {
return createTable(clazz, null); return createTable(clazz, null);
} }
public static List<String> createTable(final Class<?> clazz, final QueryOptions options) throws Exception { public static List<String> createTable(final Class<?> clazz, final QueryOptions options) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz, options); final String tableName = AnnotationTools.getTableName(clazz, options);
boolean createDrop = false; boolean createDrop = false;
if (options != null) { if (options != null) {
final Object data = options.get(QueryOptions.CREATE_DROP_TABLE); createDrop = options.exist(CreateDropTable.class);
if (data instanceof final Boolean optionBoolean) {
createDrop = optionBoolean;
} else if (data != null) {
LOGGER.error("'{}' ==> has not a Boolean value: {}", QueryOptions.CREATE_DROP_TABLE, data);
}
} }
final boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(DataIfNotExists.class).length != 0; final boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(DataIfNotExists.class).length != 0;
final List<String> preActionList = new ArrayList<>(); final List<String> preActionList = new ArrayList<>();
final List<String> postActionList = new ArrayList<>(); final List<String> postActionList = new ArrayList<>();
@ -313,7 +309,7 @@ public class DataFactory {
int fieldId = 0; int fieldId = 0;
LOGGER.debug("===> TABLE `{}`", tableName); LOGGER.debug("===> TABLE `{}`", tableName);
final List<String> primaryKeys = new ArrayList<>(); final List<String> primaryKeys = new ArrayList<>();
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)) {
@ -394,5 +390,5 @@ public class DataFactory {
preActionList.addAll(postActionList); preActionList.addAll(postActionList);
return preActionList; return preActionList;
} }
} }

View File

@ -0,0 +1,47 @@
package org.kar.archidata.dataAccess;
import java.sql.PreparedStatement;
import java.util.List;
public class QueryInList<T> implements QueryItem {
protected final String key;
protected final String comparator;
protected final List<T> value;
protected QueryInList(final String key, final String comparator, final List<T> value) {
this.key = key;
this.comparator = comparator;
this.value = value;
}
public QueryInList(final String key, final List<T> value) {
this(key, "IN", value);
}
@Override
public void generateQuerry(final StringBuilder querry, final String tableName) {
querry.append(tableName);
querry.append(".");
querry.append(this.key);
querry.append(" ");
querry.append(this.comparator);
querry.append(" (");
for (int iii = 0; iii < this.value.size(); iii++) {
if (iii != 0) {
querry.append(",?");
} else {
querry.append("?");
}
}
querry.append(")");
}
@Override
public void injectQuerry(final PreparedStatement ps, final CountInOut iii) throws Exception {
for (final Object elem : this.value) {
DataAccess.addElement(ps, elem, iii);
iii.inc();
}
}
}

View File

@ -0,0 +1,9 @@
package org.kar.archidata.dataAccess;
import java.util.List;
public class QueryNoInList<T> extends QueryInList<T> {
public QueryNoInList(final String key, final List<T> value) {
super(key, "NOT IN", value);
}
}

View File

@ -0,0 +1,3 @@
package org.kar.archidata.dataAccess;
public class QueryOption {}

View File

@ -1,57 +1,61 @@
package org.kar.archidata.dataAccess; package org.kar.archidata.dataAccess;
import java.util.HashMap; import java.util.ArrayList;
import java.util.Map; import java.util.Collections;
import java.util.List;
import org.kar.archidata.dataAccess.options.AccessDeletedItems;
import org.kar.archidata.dataAccess.options.CreateDropTable;
import org.kar.archidata.dataAccess.options.ReadAllColumn;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class QueryOptions { public class QueryOptions {
static final Logger LOGGER = LoggerFactory.getLogger(QueryOptions.class); static final Logger LOGGER = LoggerFactory.getLogger(QueryOptions.class);
public static final String SQL_NOT_READ_DISABLE = "SQLNotRead_disable"; public static final ReadAllColumn READ_ALL_COLOMN = new ReadAllColumn();
public static final String SQL_DELETED_DISABLE = "SQLDeleted_disable"; public static final AccessDeletedItems ACCESS_DELETED_ITEMS = new AccessDeletedItems();
public static final String OVERRIDE_TABLE_NAME = "SQL_OVERRIDE_TABLE_NAME"; public static final CreateDropTable CREATE_DROP_TABLE = new CreateDropTable();
public static final String CREATE_DROP_TABLE = "CREATE_DROP_TABLE";
private final Map<String, Object> options = new HashMap<>(); private final List<QueryOption> options = new ArrayList<>();
public QueryOptions() {
public QueryOptions(final QueryOption... elems) {
Collections.addAll(this.options, elems);
} }
public QueryOptions(final String key, final Object value) { public QueryOptions() {}
this.options.put(key, value);
public void add(final QueryOption option) {
this.options.add(option);
} }
public QueryOptions(final String key, final Object value, final String key2, final Object value2) { public List<QueryOption> getAll() {
this.options.put(key, value); return this.options;
this.options.put(key2, value2);
} }
public QueryOptions(final String key, final Object value, final String key2, final Object value2, final String key3, final Object value3) { @SuppressWarnings("unchecked")
this.options.put(key, value); public <T> T get(final Class<T> type) {
this.options.put(key2, value2); for (final QueryOption elem : this.options) {
this.options.put(key3, value3); if (elem.getClass() == type) {
return (T) elem;
}
}
return null;
} }
public void put(final String key, final Object value) { public boolean exist(final Class<?> type) {
this.options.put(key, value); for (final QueryOption elem : this.options) {
} if (elem.getClass() == type) {
return true;
public Object get(final String value) {
return this.options.get(value);
}
public static boolean readAllFields(final QueryOptions options) {
if (options != null) {
final Object data = options.get(QueryOptions.SQL_NOT_READ_DISABLE);
if (data instanceof final Boolean elem) {
return elem;
} else if (data != null) {
LOGGER.error("'{}' ==> has not a boolean value: {}", QueryOptions.SQL_NOT_READ_DISABLE, data);
} }
} }
return false; return false;
} }
public static boolean readAllColomn(final QueryOptions options) {
if (options != null) {
return options.exist(ReadAllColumn.class);
}
return false;
}
} }

View File

@ -16,12 +16,12 @@ import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.LazyGetter; import org.kar.archidata.dataAccess.LazyGetter;
import org.kar.archidata.dataAccess.QueryAnd; import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition; import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.QueryItem; import org.kar.archidata.dataAccess.QueryInList;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.dataAccess.QueryOr;
import org.kar.archidata.dataAccess.addOn.model.LinkTable; import org.kar.archidata.dataAccess.addOn.model.LinkTable;
import org.kar.archidata.dataAccess.options.OverrideTableName;
import org.kar.archidata.exception.DataAccessException; import org.kar.archidata.exception.DataAccessException;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -166,12 +166,10 @@ public class AddOnManyToMany implements DataAccessAddOn {
final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass)); final String idField = AnnotationTools.getFieldName(AnnotationTools.getIdField(objectClass));
// 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<QueryItem> childs = new ArrayList<>(); final List<Long> childs = new ArrayList<>(idList);
for (final Long elem : idList) {
childs.add(new QueryCondition(idField, "=", elem));
}
// TODO: update to have get with abstract types .... // TODO: update to have get with abstract types ....
final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), new QueryOr(childs), options); @SuppressWarnings("unchecked")
final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), new QueryInList<>(idField, childs), null);
if (foreignData == null) { if (foreignData == null) {
return; return;
} }
@ -187,7 +185,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
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 LinkTable insertElement = new LinkTable(localKey, remoteKey); final LinkTable insertElement = new LinkTable(localKey, remoteKey);
final QueryOptions options = new QueryOptions(QueryOptions.OVERRIDE_TABLE_NAME, linkTableName); final QueryOptions options = new QueryOptions(new OverrideTableName(linkTableName));
DataAccess.insert(insertElement, options); DataAccess.insert(insertElement, options);
} }
@ -195,7 +193,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
public static int removeLink(final Class<?> clazz, final long localKey, final String column, final long remoteKey) throws Exception { public static int removeLink(final Class<?> clazz, final long localKey, final String column, final long remoteKey) throws Exception {
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 QueryOptions options = new QueryOptions(QueryOptions.OVERRIDE_TABLE_NAME, linkTableName); final QueryOptions options = new QueryOptions(new OverrideTableName(linkTableName));
final QueryAnd condition = new QueryAnd(new QueryCondition("object1Id", "=", localKey), new QueryCondition("object2Id", "=", remoteKey)); final QueryAnd condition = new QueryAnd(new QueryCondition("object1Id", "=", localKey), new QueryCondition("object2Id", "=", remoteKey));
return DataAccess.deleteWhere(LinkTable.class, condition, options); return DataAccess.deleteWhere(LinkTable.class, condition, options);
} }
@ -204,7 +202,7 @@ public class AddOnManyToMany implements DataAccessAddOn {
public void createTables(final String tableName, final Field field, final StringBuilder mainTableBuilder, final List<String> preActionList, final List<String> postActionList, public void createTables(final String tableName, 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 { final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
final String linkTableName = generateLinkTableNameField(tableName, field); final String linkTableName = generateLinkTableNameField(tableName, field);
final QueryOptions options = new QueryOptions(QueryOptions.OVERRIDE_TABLE_NAME, linkTableName); final QueryOptions options = new QueryOptions(new OverrideTableName(linkTableName));
final List<String> sqlCommand = DataFactory.createTable(LinkTable.class, options); final List<String> sqlCommand = DataFactory.createTable(LinkTable.class, options);
postActionList.addAll(sqlCommand); postActionList.addAll(sqlCommand);
} }

View File

@ -0,0 +1,8 @@
package org.kar.archidata.dataAccess.options;
import org.kar.archidata.dataAccess.QueryOption;
/** This option permit to access on deleted items of a table */
public class AccessDeletedItems extends QueryOption {
public AccessDeletedItems() {}
}

View File

@ -0,0 +1,16 @@
package org.kar.archidata.dataAccess.options;
import org.kar.archidata.dataAccess.QueryOption;
/** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */
public class CheckFunction extends QueryOption {
private final CheckFunctionInterface checker;
public CheckFunction(final CheckFunctionInterface checker) {
this.checker = checker;
}
public CheckFunctionInterface getChecker() {
return this.checker;
}
}

View File

@ -0,0 +1,13 @@
package org.kar.archidata.dataAccess.options;
import java.util.List;
/** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */
public interface CheckFunctionInterface {
/** This function implementation is design to check if the updated class is valid of not for insertion
* @param data The object that might be injected.
* @param filterValue List of fields that might be check. If null, then all column must be checked.
* @throws Exception Exception is generate if the data are incorrect. */
void check(Object data, List<String> filterValue) throws Exception;
}

View File

@ -0,0 +1,8 @@
package org.kar.archidata.dataAccess.options;
import org.kar.archidata.dataAccess.QueryOption;
/** This option permit to create the DROP `Table` IF EXIST in the generation of structure. */
public class CreateDropTable extends QueryOption {
public CreateDropTable() {}
}

View File

@ -0,0 +1,17 @@
package org.kar.archidata.dataAccess.options;
import org.kar.archidata.dataAccess.QueryOption;
/** Option that permit to access to a table structure with an other name that is define in the structure. Note: Internal use for link tables (see:
* org.kar.archidata.dataAccess.addOn.model.LinkTable). */
public class Limit extends QueryOption {
private final int limit;
public Limit(final int limit) {
this.limit = limit;
}
public int getLimit() {
return this.limit;
}
}

View File

@ -0,0 +1,17 @@
package org.kar.archidata.dataAccess.options;
import org.kar.archidata.dataAccess.QueryOption;
/** Option that permit to access to a table structure with an other name that is define in the structure. Note: Internal use for link tables (see:
* org.kar.archidata.dataAccess.addOn.model.LinkTable). */
public class OverrideTableName extends QueryOption {
private final String name;
public OverrideTableName(final String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}

View File

@ -0,0 +1,8 @@
package org.kar.archidata.dataAccess.options;
import org.kar.archidata.dataAccess.QueryOption;
/** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */
public class ReadAllColumn extends QueryOption {
public ReadAllColumn() {}
}

View File

@ -13,7 +13,7 @@ import java.util.Map.Entry;
import org.kar.archidata.annotation.security.PermitTokenInURI; import org.kar.archidata.annotation.security.PermitTokenInURI;
import org.kar.archidata.catcher.RestErrorResponse; import org.kar.archidata.catcher.RestErrorResponse;
import org.kar.archidata.model.UserByToken; import org.kar.archidata.model.UserByToken;
import org.kar.archidata.util.JWTWrapper; import org.kar.archidata.tools.JWTWrapper;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@ -16,17 +16,17 @@ import org.slf4j.LoggerFactory;
public class MigrationEngine { public class MigrationEngine {
final static Logger LOGGER = LoggerFactory.getLogger(MigrationEngine.class); final static Logger LOGGER = LoggerFactory.getLogger(MigrationEngine.class);
// List of order migrations // List of order migrations
private final List<MigrationInterface> datas; private final List<MigrationInterface> datas;
// initialization of the migration if the DB is not present... // initialization of the migration if the DB is not present...
private MigrationInterface init; private MigrationInterface init;
/** Migration engine constructor (empty). */ /** Migration engine constructor (empty). */
public MigrationEngine() { public MigrationEngine() {
this(new ArrayList<>(), null); this(new ArrayList<>(), null);
} }
/** Migration engine constructor (specific mode). /** Migration engine constructor (specific mode).
* @param datas All the migration ordered. * @param datas All the migration ordered.
* @param init Initialization migration model. */ * @param init Initialization migration model. */
@ -34,19 +34,19 @@ public class MigrationEngine {
this.datas = datas; this.datas = datas;
this.init = init; this.init = init;
} }
/** Add a Migration in the list /** Add a Migration in the list
* @param migration Migration to add. */ * @param migration Migration to add. */
public void add(final MigrationInterface migration) { public void add(final MigrationInterface migration) {
this.datas.add(migration); this.datas.add(migration);
} }
/** Set first initialization class /** Set first initialization class
* @param migration migration class for first init. */ * @param migration migration class for first init. */
public void setInit(final MigrationInterface migration) { public void setInit(final MigrationInterface migration) {
this.init = migration; this.init = migration;
} }
/** Get the current version/migration name /** Get the current version/migration name
* @return Model represent the last migration. If null then no migration has been done. */ * @return Model represent the last migration. If null then no migration has been done. */
public Migration getCurrentVersion() { public Migration getCurrentVersion() {
@ -54,7 +54,7 @@ public class MigrationEngine {
return null; return null;
} }
try { try {
final List<Migration> data = DataAccess.gets(Migration.class, new QueryOptions("SQLNotRead_disable", true)); final List<Migration> data = DataAccess.gets(Migration.class, new QueryOptions(QueryOptions.READ_ALL_COLOMN));
if (data == null) { if (data == null) {
LOGGER.error("Can not collect the migration table in the DB:{}"); LOGGER.error("Can not collect the migration table in the DB:{}");
return null; return null;
@ -74,7 +74,7 @@ public class MigrationEngine {
} }
return null; return null;
} }
/** Process the automatic migration of the system The function wait the Administrator intervention to correct the bug. /** Process the automatic migration of the system The function wait the Administrator intervention to correct the bug.
* @param config SQL connection for the migration. * @param config SQL connection for the migration.
* @throws InterruptedException user interrupt the migration */ * @throws InterruptedException user interrupt the migration */
@ -92,7 +92,7 @@ public class MigrationEngine {
} }
} }
} }
/** Process the automatic migration of the system /** Process the automatic migration of the system
* @param config SQL connection for the migration * @param config SQL connection for the migration
* @throws IOException Error if access on the DB */ * @throws IOException Error if access on the DB */
@ -118,7 +118,7 @@ public class MigrationEngine {
} }
} }
} }
// STEP 1: Check the DB exist: // STEP 1: Check the DB exist:
LOGGER.info("Verify existance of '{}'", config.getDbName()); LOGGER.info("Verify existance of '{}'", config.getDbName());
boolean exist = DataAccess.isDBExist(config.getDbName()); boolean exist = DataAccess.isDBExist(config.getDbName());
@ -230,7 +230,7 @@ public class MigrationEngine {
} }
LOGGER.info("Execute migration ... [ END ]"); LOGGER.info("Execute migration ... [ END ]");
} }
public void migrateSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) throws MigrationException { public void migrateSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) throws MigrationException {
LOGGER.info("---------------------------------------------------------"); LOGGER.info("---------------------------------------------------------");
LOGGER.info("-- Migrate: [{}/{}] {} [BEGIN]", id, count, elem.getName()); LOGGER.info("-- Migrate: [{}/{}] {} [BEGIN]", id, count, elem.getName());
@ -277,7 +277,7 @@ public class MigrationEngine {
} }
LOGGER.info("Migrate: [{}/{}] {} [ END ]", id, count, elem.getName()); LOGGER.info("Migrate: [{}/{}] {} [ END ]", id, count, elem.getName());
} }
public void revertTo(final DBEntry entry, final String migrationName) { public void revertTo(final DBEntry entry, final String migrationName) {
final Migration currentVersion = getCurrentVersion(); final Migration currentVersion = getCurrentVersion();
final List<MigrationInterface> toApply = new ArrayList<>(); final List<MigrationInterface> toApply = new ArrayList<>();
@ -300,10 +300,10 @@ public class MigrationEngine {
revertSingle(entry, elem, id, count); revertSingle(entry, elem, id, count);
} }
} }
public void revertSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) { public void revertSingle(final DBEntry entry, final MigrationInterface elem, final int id, final int count) {
LOGGER.info("Revert migration: {} [BEGIN]", elem.getName()); LOGGER.info("Revert migration: {} [BEGIN]", elem.getName());
LOGGER.info("Revert migration: {} [ END ]", elem.getName()); LOGGER.info("Revert migration: {} [ END ]", elem.getName());
} }
} }

View File

@ -7,20 +7,20 @@ public interface MigrationInterface {
/** Get Name of the migration /** Get Name of the migration
* @return Migration name */ * @return Migration name */
String getName(); String getName();
/** Migrate the system to a new version. /** Migrate the system to a new version.
* @param entry DB interface for the migration. * @param entry DB interface for the migration.
* @param log Stored data in the BDD for the migration progression. * @param log Stored data in the BDD for the migration progression.
* @param migration Migration post data on each step... * @param migration Migration post data on each step...
* @return true if migration is finished. */ * @return true if migration is finished. */
boolean applyMigration(DBEntry entry, StringBuilder log, Migration model) throws Exception; boolean applyMigration(DBEntry entry, StringBuilder log, Migration model) throws Exception;
/** Remove a migration the system to the previous version. /** Remove a migration the system to the previous version.
* @param entry DB interface for the migration. * @param entry DB interface for the migration.
* @param log Stored data in the BDD for the migration progression. * @param log Stored data in the BDD for the migration progression.
* @return true if migration is finished. */ * @return true if migration is finished. */
boolean revertMigration(DBEntry entry, StringBuilder log) throws Exception; boolean revertMigration(DBEntry entry, StringBuilder log) throws Exception;
/** Get the number of step in the migration process. /** Get the number of step in the migration process.
* @return count of SQL access. */ * @return count of SQL access. */
int getNumberOfStep(); int getNumberOfStep();

View File

@ -9,17 +9,15 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.migration.model.Migration; import org.kar.archidata.migration.model.Migration;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
record Action( record Action(String action, List<String> filterDB) {
String action,
List<String> filterDB) {
public Action(final String action) { public Action(final String action) {
this(action, List.of()); this(action, List.of());
} }
public Action(final String action, final String filterDB) { public Action(final String action, final String filterDB) {
this(action, List.of(filterDB)); this(action, List.of(filterDB));
} }
@ -28,27 +26,27 @@ record Action(
public class MigrationSqlStep implements MigrationInterface { public class MigrationSqlStep implements MigrationInterface {
final static Logger LOGGER = LoggerFactory.getLogger(MigrationSqlStep.class); final static Logger LOGGER = LoggerFactory.getLogger(MigrationSqlStep.class);
private final List<Action> actions = new ArrayList<>(); private final List<Action> actions = new ArrayList<>();
@Override @Override
public String getName() { public String getName() {
return getClass().getCanonicalName(); return getClass().getCanonicalName();
} }
public void display() { public void display() {
for (int iii = 0; iii < this.actions.size(); iii++) { for (int iii = 0; iii < this.actions.size(); iii++) {
final Action action = this.actions.get(iii); final Action action = this.actions.get(iii);
LOGGER.info(" >>>> SQL ACTION : {}/{} ==> filter='{}'\n{}", iii, this.actions.size(), action.filterDB(), action.action()); LOGGER.info(" >>>> SQL ACTION : {}/{} ==> filter='{}'\n{}", iii, this.actions.size(), action.filterDB(), action.action());
} }
} }
public void generateStep() throws Exception { public void generateStep() throws Exception {
throw new Exception("Forward is not implemented"); throw new Exception("Forward is not implemented");
} }
public void generateRevertStep() throws Exception { public void generateRevertStep() throws Exception {
throw new Exception("Backward is not implemented"); throw new Exception("Backward is not implemented");
} }
@Override @Override
public boolean applyMigration(final DBEntry entry, final StringBuilder log, final Migration model) throws Exception { public boolean applyMigration(final DBEntry entry, final StringBuilder log, final Migration model) throws Exception {
generateStep(); generateStep();
@ -56,7 +54,7 @@ public class MigrationSqlStep implements MigrationInterface {
log.append("action [" + (iii + 1) + "/" + this.actions.size() + "]\n"); log.append("action [" + (iii + 1) + "/" + this.actions.size() + "]\n");
LOGGER.info(" >>>> SQL ACTION : {}/{}", iii + 1, this.actions.size()); LOGGER.info(" >>>> SQL ACTION : {}/{}", iii + 1, this.actions.size());
final Action action = this.actions.get(iii); final Action action = this.actions.get(iii);
LOGGER.info("SQL request: ```{}``` on '{}' current={}", action.action(), action.filterDB(), ConfigBaseVariable.getDBType()); LOGGER.info("SQL request: ```{}``` on '{}' current={}", action.action(), action.filterDB(), ConfigBaseVariable.getDBType());
log.append("SQL: " + action.action() + " on " + action.filterDB() + "\n"); log.append("SQL: " + action.action() + " on " + action.filterDB() + "\n");
boolean isValid = true; boolean isValid = true;
@ -107,31 +105,31 @@ public class MigrationSqlStep implements MigrationInterface {
} }
return true; return true;
} }
@Override @Override
public boolean revertMigration(final DBEntry entry, final StringBuilder log) throws Exception { public boolean revertMigration(final DBEntry entry, final StringBuilder log) throws Exception {
generateRevertStep(); generateRevertStep();
return false; return false;
} }
public void addAction(final String action) { public void addAction(final String action) {
this.actions.add(new Action(action)); this.actions.add(new Action(action));
} }
public void addAction(final String action, final String filterdBType) { public void addAction(final String action, final String filterdBType) {
this.actions.add(new Action(action, filterdBType)); this.actions.add(new Action(action, filterdBType));
} }
public void addClass(final Class<?> clazz) throws Exception { public void addClass(final Class<?> clazz) throws Exception {
final List<String> tmp = DataFactory.createTable(clazz); final List<String> tmp = DataFactory.createTable(clazz);
for (final String elem : tmp) { for (final String elem : tmp) {
this.actions.add(new Action(elem)); this.actions.add(new Action(elem));
} }
} }
@Override @Override
public int getNumberOfStep() { public int getNumberOfStep() {
return this.actions.size(); return this.actions.size();
} }
} }

View File

@ -1,4 +1,4 @@
package org.kar.archidata.util; package org.kar.archidata.tools;
public class ConfigBaseVariable { public class ConfigBaseVariable {
static public String tmpDataFolder; static public String tmpDataFolder;

View File

@ -1,4 +1,4 @@
package org.kar.archidata.util; package org.kar.archidata.tools;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;

View File

@ -0,0 +1,53 @@
package org.kar.archidata.tools;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DateTools {
static private List<SimpleDateFormat> knownPatterns = new ArrayList<>();
{
// SYSTEM mode
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss.SSS'Z'"));
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"));
// Human mode
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss"));
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSS"));
// date mode
DateTools.knownPatterns.add(new SimpleDateFormat("yyyy-MM-dd"));
// time mode
DateTools.knownPatterns.add(new SimpleDateFormat("HH:mm:ss"));
DateTools.knownPatterns.add(new SimpleDateFormat("HH:mm:ss.SSS"));
}
public static Date parseDate(final String inputDate, final String pattern) throws ParseException {
final SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.parse(inputDate);
}
public static Date parseDate(final String inputDate) throws ParseException {
for (final SimpleDateFormat pattern : DateTools.knownPatterns) {
try {
return pattern.parse(inputDate);
} catch (final ParseException e) {
continue;
}
}
throw new ParseException("Can not parse the date-time format: '" + inputDate + "'", 0);
}
public static String formatDate(final Date date, final String requiredDateFormat) {
final SimpleDateFormat df = new SimpleDateFormat(requiredDateFormat);
final String outputDateFormatted = df.format(date);
return outputDateFormatted;
}
public static String formatDate(final Date date) {
return formatDate(date, "yyyy-MM-dd'T'HH:mm.ss.SSS'Z'");
}
}

View File

@ -1,4 +1,4 @@
package org.kar.archidata.util; package org.kar.archidata.tools;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;

View File

@ -1,4 +1,4 @@
package org.kar.archidata.util; package org.kar.archidata.tools;
public class PublicKey { public class PublicKey {
public String key; public String key;

View File

@ -1,4 +1,4 @@
package org.kar.archidata.util; package org.kar.archidata.tools;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;

View File

@ -15,7 +15,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,11 +29,12 @@ public class TestJson {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -16,7 +16,7 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany; import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -31,11 +31,12 @@ public class TestManyToMany {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -15,7 +15,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -30,11 +30,12 @@ public class TestManyToOne {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -14,7 +14,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,11 +27,12 @@ public class TestOneToMany {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -19,7 +19,7 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,30 +33,31 @@ public class TestSimpleTable {
private static final String DATA_INJECTED_2 = "dsqfsdfqsdfsqdf"; private static final String DATA_INJECTED_2 = "dsqfsdfqsdfsqdf";
private static Long idOfTheObject = null; private static Long idOfTheObject = null;
private static Timestamp startAction = null; private static Timestamp startAction = null;
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Clear the static test: // Clear the static test:
idOfTheObject = null; idOfTheObject = null;
startAction = null; startAction = null;
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();
} }
@AfterAll @AfterAll
public static void removeDataBase() throws IOException { public static void removeDataBase() throws IOException {
LOGGER.info("Remove the test db"); LOGGER.info("Remove the test db");
DBEntry.closeAllForceMode(); DBEntry.closeAllForceMode();
ConfigBaseVariable.clearAllValue(); ConfigBaseVariable.clearAllValue();
} }
@Order(1) @Order(1)
@Test @Test
public void testTableInsertAndRetrieve() throws Exception { public void testTableInsertAndRetrieve() throws Exception {
@ -69,14 +70,14 @@ public class TestSimpleTable {
final SimpleTable test = new SimpleTable(); final SimpleTable test = new SimpleTable();
test.data = TestSimpleTable.DATA_INJECTED; test.data = TestSimpleTable.DATA_INJECTED;
final SimpleTable insertedData = DataAccess.insert(test); final SimpleTable insertedData = DataAccess.insert(test);
Assertions.assertNotNull(insertedData); Assertions.assertNotNull(insertedData);
Assertions.assertNotNull(insertedData.id); Assertions.assertNotNull(insertedData.id);
Assertions.assertTrue(insertedData.id >= 0); Assertions.assertTrue(insertedData.id >= 0);
// Try to retrieve all the data: // Try to retrieve all the data:
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, insertedData.id); final SimpleTable retrieve = DataAccess.get(SimpleTable.class, insertedData.id);
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(insertedData.id, retrieve.id); Assertions.assertEquals(insertedData.id, retrieve.id);
@ -85,13 +86,13 @@ public class TestSimpleTable {
Assertions.assertNull(retrieve.updatedAt); Assertions.assertNull(retrieve.updatedAt);
TestSimpleTable.idOfTheObject = retrieve.id; TestSimpleTable.idOfTheObject = retrieve.id;
} }
@Order(2) @Order(2)
@Test @Test
public void testReadAllValuesUnreadable() throws Exception { public void testReadAllValuesUnreadable() throws Exception {
// check the full values // check the full values
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true)); final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.READ_ALL_COLOMN));
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id);
@ -104,7 +105,7 @@ public class TestSimpleTable {
// Assertions.assertTrue(retrieve.updatedAt.after(this.startAction)); // Assertions.assertTrue(retrieve.updatedAt.after(this.startAction));
Assertions.assertEquals(retrieve.createdAt, retrieve.updatedAt); Assertions.assertEquals(retrieve.createdAt, retrieve.updatedAt);
} }
@Order(3) @Order(3)
@Test @Test
public void testUpdateData() throws Exception { public void testUpdateData() throws Exception {
@ -113,7 +114,7 @@ public class TestSimpleTable {
final SimpleTable test = new SimpleTable(); final SimpleTable test = new SimpleTable();
test.data = TestSimpleTable.DATA_INJECTED_2; test.data = TestSimpleTable.DATA_INJECTED_2;
DataAccess.update(test, TestSimpleTable.idOfTheObject, List.of("data")); DataAccess.update(test, TestSimpleTable.idOfTheObject, List.of("data"));
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true)); final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.READ_ALL_COLOMN));
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTable.idOfTheObject, retrieve.id);
@ -123,7 +124,7 @@ public class TestSimpleTable {
LOGGER.info("created @ {} updated @ {}", retrieve.createdAt, retrieve.updatedAt); LOGGER.info("created @ {} updated @ {}", retrieve.createdAt, retrieve.updatedAt);
Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt)); Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt));
} }
@Order(4) @Order(4)
@Test @Test
public void testDeleteTheObject() throws Exception { public void testDeleteTheObject() throws Exception {
@ -132,24 +133,23 @@ public class TestSimpleTable {
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject); final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject);
Assertions.assertNull(retrieve); Assertions.assertNull(retrieve);
} }
@Order(5) @Order(5)
@Test @Test
public void testReadDeletedObject() throws Exception { public void testReadDeletedObject() throws Exception {
// check if we set get deleted element // check if we set get deleted element
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true)); final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.ACCESS_DELETED_ITEMS));
Assertions.assertNull(retrieve); Assertions.assertNull(retrieve);
} }
@Order(6) @Order(6)
@Test @Test
public void testReadAllValuesUnreadableOfDeletedObject() throws Exception { public void testReadAllValuesUnreadableOfDeletedObject() throws Exception {
// check if we set get deleted element with all data // check if we set get deleted element with all data
final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, final SimpleTable retrieve = DataAccess.get(SimpleTable.class, TestSimpleTable.idOfTheObject, new QueryOptions(QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN));
new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true, QueryOptions.SQL_NOT_READ_DISABLE, true));
Assertions.assertNull(retrieve); Assertions.assertNull(retrieve);
} }
} }

View File

@ -19,7 +19,7 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.QueryOptions; import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,30 +33,31 @@ public class TestSimpleTableSoftDelete {
private static final String DATA_INJECTED_2 = "qsdfqsdfqsdfsqdf"; private static final String DATA_INJECTED_2 = "qsdfqsdfqsdfsqdf";
private static Long idOfTheObject = null; private static Long idOfTheObject = null;
private static Timestamp startAction = null; private static Timestamp startAction = null;
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Clear the static test: // Clear the static test:
idOfTheObject = null; idOfTheObject = null;
startAction = null; startAction = null;
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();
} }
@AfterAll @AfterAll
public static void removeDataBase() throws IOException { public static void removeDataBase() throws IOException {
LOGGER.info("Remove the test db"); LOGGER.info("Remove the test db");
DBEntry.closeAllForceMode(); DBEntry.closeAllForceMode();
ConfigBaseVariable.clearAllValue(); ConfigBaseVariable.clearAllValue();
} }
@Order(1) @Order(1)
@Test @Test
public void testTableInsertAndRetrieve() throws Exception { public void testTableInsertAndRetrieve() throws Exception {
@ -69,14 +70,14 @@ public class TestSimpleTableSoftDelete {
final SimpleTableSoftDelete test = new SimpleTableSoftDelete(); final SimpleTableSoftDelete test = new SimpleTableSoftDelete();
test.data = TestSimpleTableSoftDelete.DATA_INJECTED; test.data = TestSimpleTableSoftDelete.DATA_INJECTED;
final SimpleTableSoftDelete insertedData = DataAccess.insert(test); final SimpleTableSoftDelete insertedData = DataAccess.insert(test);
Assertions.assertNotNull(insertedData); Assertions.assertNotNull(insertedData);
Assertions.assertNotNull(insertedData.id); Assertions.assertNotNull(insertedData.id);
Assertions.assertTrue(insertedData.id >= 0); Assertions.assertTrue(insertedData.id >= 0);
// Try to retrieve all the data: // Try to retrieve all the data:
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, insertedData.id); final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, insertedData.id);
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(insertedData.id, retrieve.id); Assertions.assertEquals(insertedData.id, retrieve.id);
@ -86,13 +87,13 @@ public class TestSimpleTableSoftDelete {
Assertions.assertNull(retrieve.deleted); Assertions.assertNull(retrieve.deleted);
TestSimpleTableSoftDelete.idOfTheObject = retrieve.id; TestSimpleTableSoftDelete.idOfTheObject = retrieve.id;
} }
@Order(2) @Order(2)
@Test @Test
public void testReadAllValuesUnreadable() throws Exception { public void testReadAllValuesUnreadable() throws Exception {
// check the full values // check the full values
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.SQL_NOT_READ_DISABLE, true)); final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.READ_ALL_COLOMN));
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);
@ -107,18 +108,18 @@ public class TestSimpleTableSoftDelete {
Assertions.assertNotNull(retrieve.deleted); Assertions.assertNotNull(retrieve.deleted);
Assertions.assertEquals(false, retrieve.deleted); Assertions.assertEquals(false, retrieve.deleted);
} }
@Order(3) @Order(3)
@Test @Test
public void testUpdateData() throws Exception { public void testUpdateData() throws Exception {
Thread.sleep(Duration.ofMillis(15)); Thread.sleep(Duration.ofMillis(15));
// Delete the entry: // Delete the entry:
final SimpleTableSoftDelete test = new SimpleTableSoftDelete(); final SimpleTableSoftDelete test = new SimpleTableSoftDelete();
test.data = TestSimpleTableSoftDelete.DATA_INJECTED_2; test.data = TestSimpleTableSoftDelete.DATA_INJECTED_2;
DataAccess.update(test, TestSimpleTableSoftDelete.idOfTheObject, List.of("data")); DataAccess.update(test, TestSimpleTableSoftDelete.idOfTheObject, List.of("data"));
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject,
new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true, QueryOptions.SQL_NOT_READ_DISABLE, true)); new QueryOptions(QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN));
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);
@ -130,7 +131,7 @@ public class TestSimpleTableSoftDelete {
Assertions.assertNotNull(retrieve.deleted); Assertions.assertNotNull(retrieve.deleted);
Assertions.assertEquals(false, retrieve.deleted); Assertions.assertEquals(false, retrieve.deleted);
} }
@Order(4) @Order(4)
@Test @Test
public void testSoftDeleteTheObject() throws Exception { public void testSoftDeleteTheObject() throws Exception {
@ -144,13 +145,13 @@ public class TestSimpleTableSoftDelete {
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject); final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject);
Assertions.assertNull(retrieve); Assertions.assertNull(retrieve);
} }
@Order(5) @Order(5)
@Test @Test
public void testReadDeletedObject() throws Exception { public void testReadDeletedObject() throws Exception {
// check if we set get deleted element // check if we set get deleted element
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true)); final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, new QueryOptions(QueryOptions.ACCESS_DELETED_ITEMS));
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);
@ -158,15 +159,15 @@ public class TestSimpleTableSoftDelete {
Assertions.assertNull(retrieve.createdAt); Assertions.assertNull(retrieve.createdAt);
Assertions.assertNull(retrieve.updatedAt); Assertions.assertNull(retrieve.updatedAt);
Assertions.assertNull(retrieve.deleted); Assertions.assertNull(retrieve.deleted);
} }
@Order(6) @Order(6)
@Test @Test
public void testReadAllValuesUnreadableOfDeletedObject() throws Exception { public void testReadAllValuesUnreadableOfDeletedObject() throws Exception {
// check if we set get deleted element with all data // check if we set get deleted element with all data
final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject, final SimpleTableSoftDelete retrieve = DataAccess.get(SimpleTableSoftDelete.class, TestSimpleTableSoftDelete.idOfTheObject,
new QueryOptions(QueryOptions.SQL_DELETED_DISABLE, true, QueryOptions.SQL_NOT_READ_DISABLE, true)); new QueryOptions(QueryOptions.ACCESS_DELETED_ITEMS, QueryOptions.READ_ALL_COLOMN));
Assertions.assertNotNull(retrieve); Assertions.assertNotNull(retrieve);
Assertions.assertNotNull(retrieve.id); Assertions.assertNotNull(retrieve.id);
Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id); Assertions.assertEquals(TestSimpleTableSoftDelete.idOfTheObject, retrieve.id);
@ -177,6 +178,6 @@ public class TestSimpleTableSoftDelete {
Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt)); Assertions.assertTrue(retrieve.updatedAt.after(retrieve.createdAt));
Assertions.assertNotNull(retrieve.deleted); Assertions.assertNotNull(retrieve.deleted);
Assertions.assertEquals(true, retrieve.deleted); Assertions.assertEquals(true, retrieve.deleted);
} }
} }

View File

@ -15,7 +15,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,11 +29,12 @@ public class TestTypeEnum1 {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -15,7 +15,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,11 +29,12 @@ public class TestTypeEnum2 {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -20,7 +20,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory; import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,11 +33,12 @@ public class TestTypes {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -5,16 +5,16 @@ import org.kar.archidata.migration.MigrationSqlStep;
import test.kar.archidata.migration.model.TypesMigrationInitialisationCurrent; import test.kar.archidata.migration.model.TypesMigrationInitialisationCurrent;
class InitializationCurrent extends MigrationSqlStep { class InitializationCurrent extends MigrationSqlStep {
@Override @Override
public String getName() { public String getName() {
return "Initialization"; return "Initialization";
} }
public InitializationCurrent() { public InitializationCurrent() {
} }
@Override @Override
public void generateStep() throws Exception { public void generateStep() throws Exception {
addClass(TypesMigrationInitialisationCurrent.class); addClass(TypesMigrationInitialisationCurrent.class);

View File

@ -5,16 +5,16 @@ import org.kar.archidata.migration.MigrationSqlStep;
import test.kar.archidata.migration.model.TypesMigrationInitialisationFirst; import test.kar.archidata.migration.model.TypesMigrationInitialisationFirst;
class InitializationFirst extends MigrationSqlStep { class InitializationFirst extends MigrationSqlStep {
@Override @Override
public String getName() { public String getName() {
return "Initialization"; return "Initialization";
} }
public InitializationFirst() { public InitializationFirst() {
} }
@Override @Override
public void generateStep() throws Exception { public void generateStep() throws Exception {
addClass(TypesMigrationInitialisationFirst.class); addClass(TypesMigrationInitialisationFirst.class);

View File

@ -3,24 +3,24 @@ package test.kar.archidata.migration;
import org.kar.archidata.migration.MigrationSqlStep; import org.kar.archidata.migration.MigrationSqlStep;
class Migration1 extends MigrationSqlStep { class Migration1 extends MigrationSqlStep {
@Override @Override
public String getName() { public String getName() {
return "first migratiion"; return "first migratiion";
} }
public Migration1() { public Migration1() {
} }
@Override @Override
public void generateStep() throws Exception { public void generateStep() throws Exception {
addAction(""" addAction("""
ALTER TABLE `TestTableMigration` ALTER TABLE `TestTableMigration`
RENAME COLUMN `testData` TO `testDataMigration1` RENAME COLUMN `testData` TO `testDataMigration1`
"""); """);
display(); display();
} }
} }

View File

@ -3,24 +3,24 @@ package test.kar.archidata.migration;
import org.kar.archidata.migration.MigrationSqlStep; import org.kar.archidata.migration.MigrationSqlStep;
class Migration2 extends MigrationSqlStep { class Migration2 extends MigrationSqlStep {
@Override @Override
public String getName() { public String getName() {
return "Second migration"; return "Second migration";
} }
public Migration2() { public Migration2() {
} }
@Override @Override
public void generateStep() throws Exception { public void generateStep() throws Exception {
addAction(""" addAction("""
ALTER TABLE `TestTableMigration` ALTER TABLE `TestTableMigration`
RENAME COLUMN `testDataMigration1` TO `testDataMigration2` RENAME COLUMN `testDataMigration1` TO `testDataMigration2`
"""); """);
display(); display();
} }
} }

View File

@ -3,24 +3,24 @@ package test.kar.archidata.migration;
import org.kar.archidata.migration.MigrationSqlStep; import org.kar.archidata.migration.MigrationSqlStep;
class MigrationFail extends MigrationSqlStep { class MigrationFail extends MigrationSqlStep {
@Override @Override
public String getName() { public String getName() {
return "Fail migration Test"; return "Fail migration Test";
} }
public MigrationFail() { public MigrationFail() {
} }
@Override @Override
public void generateStep() throws Exception { public void generateStep() throws Exception {
addAction(""" addAction("""
ALTER TABLE `TestTableMigrationqs` ALTER TABLE `TestTableMigrationqs`
RENAME COLUMN `testDataMisqdgration1` TO `testDataMiqsdgration2` RENAME COLUMN `testDataMisqdgration1` TO `testDataMiqsdgration2`
"""); """);
display(); display();
} }
} }

View File

@ -15,7 +15,7 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.migration.MigrationEngine; import org.kar.archidata.migration.MigrationEngine;
import org.kar.archidata.migration.MigrationException; import org.kar.archidata.migration.MigrationException;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,10 +29,12 @@ public class TestMigrationFail {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -14,7 +14,7 @@ import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess; import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.migration.MigrationEngine; import org.kar.archidata.migration.MigrationEngine;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,10 +29,12 @@ public class TestMigrationFirstInit {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();

View File

@ -16,7 +16,7 @@ import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.db.DBEntry; import org.kar.archidata.db.DBEntry;
import org.kar.archidata.migration.MigrationEngine; import org.kar.archidata.migration.MigrationEngine;
import org.kar.archidata.migration.model.Migration; import org.kar.archidata.migration.model.Migration;
import org.kar.archidata.util.ConfigBaseVariable; import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -30,10 +30,12 @@ public class TestMigrationFirstInitWithMigration {
@BeforeAll @BeforeAll
public static void configureWebServer() throws Exception { public static void configureWebServer() throws Exception {
ConfigBaseVariable.dbType = "sqlite"; if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbHost = "memory"; ConfigBaseVariable.dbType = "sqlite";
// for test we need to connect all time the DB ConfigBaseVariable.dbHost = "memory";
ConfigBaseVariable.dbKeepConnected = "true"; // for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase... // Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig); final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect(); entry.connect();