[DEV] add raw query

This commit is contained in:
Edouard DUPIN 2024-02-03 18:47:11 +01:00
parent 29402fc27e
commit 7ae948bb79
3 changed files with 369 additions and 50 deletions

View File

@ -364,4 +364,17 @@ public class AnnotationTools {
return null;
}
public static Field getFieldNamed(final Class<?> clazz, final String name) throws Exception {
for (final Field field : clazz.getFields()) {
// static field is only for internal global declaration ==> remove it ..
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue;
}
if (AnnotationTools.getFieldName(field).equals(name)) {
return field;
}
}
return null;
}
}

View File

@ -446,6 +446,196 @@ public class DataAccess {
count.inc();
}
// TODO: this function will replace the previous one !!!
protected static RetreiveFromDB createSetValueFromDbCallback(final int count, final Field field) throws Exception {
Class<?> type = field.getType();
if (type == Long.class) {
return (final ResultSet rs, Object obj) -> {
final Long tmp = rs.getLong(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type == long.class) {
return (final ResultSet rs, Object obj) -> {
final Long tmp = rs.getLong(count);
if (rs.wasNull()) {
// field.set(data, null);
} else {
field.setLong(obj, tmp);
}
};
}
if (type == Integer.class) {
return (final ResultSet rs, Object obj) -> {
final Integer tmp = rs.getInt(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type == int.class) {
return (final ResultSet rs, Object obj) -> {
final Integer tmp = rs.getInt(count);
if (rs.wasNull()) {
// field.set(obj, null);
} else {
field.setInt(obj, tmp);
}
};
}
if (type == Float.class) {
return (final ResultSet rs, Object obj) -> {
final Float tmp = rs.getFloat(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type == float.class) {
return (final ResultSet rs, Object obj) -> {
final Float tmp = rs.getFloat(count);
if (rs.wasNull()) {
// field.set(obj, null);
} else {
field.setFloat(obj, tmp);
}
};
}
if (type == Double.class) {
return (final ResultSet rs, Object obj) -> {
final Double tmp = rs.getDouble(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type == double.class) {
return (final ResultSet rs, Object obj) -> {
final Double tmp = rs.getDouble(count);
if (rs.wasNull()) {
// field.set(obj, null);
} else {
field.setDouble(obj, tmp);
}
};
}
if (type == Boolean.class) {
return (final ResultSet rs, Object obj) -> {
final Boolean tmp = rs.getBoolean(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type == boolean.class) {
return (final ResultSet rs, Object obj) -> {
final Boolean tmp = rs.getBoolean(count);
if (rs.wasNull()) {
// field.set(obj, null);
} else {
field.setBoolean(obj, tmp);
}
};
}
if (type == Timestamp.class) {
return (final ResultSet rs, Object obj) -> {
final Timestamp tmp = rs.getTimestamp(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type == Date.class) {
return (final ResultSet rs, Object obj) -> {
try {
final Timestamp tmp = rs.getTimestamp(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, Date.from(tmp.toInstant()));
}
} catch (final SQLException ex) {
final String tmp = rs.getString(count);
LOGGER.error("Fail to parse the SQL time !!! {}", tmp);
if (rs.wasNull()) {
field.set(obj, null);
} else {
final Date date = DateTools.parseDate(tmp);
LOGGER.error("Fail to parse the SQL time !!! {}", date);
field.set(obj, date);
}
}
};
}
if (type == LocalDate.class) {
return (final ResultSet rs, Object obj) -> {
final java.sql.Date tmp = rs.getDate(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp.toLocalDate());
}
};
}
if (type == LocalTime.class) {
return (final ResultSet rs, Object obj) -> {
final java.sql.Time tmp = rs.getTime(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp.toLocalTime());
}
};
}
if (type == String.class) {
return (final ResultSet rs, Object obj) -> {
final String tmp = rs.getString(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
field.set(obj, tmp);
}
};
}
if (type.isEnum()) {
return (final ResultSet rs, Object obj) -> {
final String tmp = rs.getString(count);
if (rs.wasNull()) {
field.set(obj, null);
} else {
boolean find = false;
final Object[] arr = type.getEnumConstants();
for (final Object elem : arr) {
if (elem.toString().equals(tmp)) {
field.set(obj, elem);
find = true;
break;
}
}
if (!find) {
throw new DataAccessException("Enum value does not exist in the Model: '" + tmp + "'");
}
}
};
}
throw new DataAccessException("Unknown Field Type");
}
public static boolean isAddOnField(final Field field) {
return findAddOnforField(field) != null;
}
@ -1322,10 +1512,10 @@ public class DataAccess {
- useful code to manage external query: List<T> query<T>(class<T> clazz, );
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
*/
public static <TYPE> List<TYPE> querry(final Class<TYPE> clazz, String query, List<Object> parameters, final QueryOption... option) throws Exception {
public static <TYPE> List<TYPE> query(final Class<TYPE> clazz, String query, List<Object> parameters, final QueryOption... option) throws Exception {
final QueryOptions options = new QueryOptions(option);
final List<LazyGetter> lazyCall = new ArrayList<>();
final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
// TODO ... final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz);
final DBEntry entry = DBInterfaceOption.getAutoEntry(options);
final List<TYPE> outs = new ArrayList<>();
// real add in the BDD:
@ -1336,32 +1526,27 @@ public class DataAccess {
final PreparedStatement ps = entry.connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
final CountInOut iii = new CountInOut(1);
if (parameters != null) {
for (Object elem : parameters)
for (Object elem : parameters) {
DataAccess.addElement(ps, elem, iii);
}
iii.inc();
}
// execute the request
final ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
List<RetreiveFromDB> actionToRetreive = new ArrayList<>();
for (int jjj = 0; jjj < rsmd.getColumnCount(); jjj++) {
String name = rsmd.getColumnName(jjj);
String name = rsmd.getColumnName(jjj + 1);
// find field name ...
Field field = AnnotationTools.getFieldNamed(clazz, name);
if (field == null) {
throw new DataAccessException("Querry with unknown field: '" + name + "'");
}
// create the callback...
// TODO ...
RetreiveFromDB element = createSetValueFromDbCallback(jjj + 1, field);
actionToRetreive.add(element);
}
/*
*
*
* j'en suis ici
*
*
*
*/
while (rs.next()) {
count.value = 1;
final CountInOut countNotNull = new CountInOut(0);

View File

@ -0,0 +1,121 @@
package test.kar.archidata;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.kar.archidata.GlobalConfiguration;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.db.DBEntry;
import org.kar.archidata.tools.ConfigBaseVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.kar.archidata.model.TypesTable;
@ExtendWith(StepwiseExtension.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestRawQuery {
final static private Logger LOGGER = LoggerFactory.getLogger(TestTypes.class);
@BeforeAll
public static void configureWebServer() throws Exception {
if (!"true".equalsIgnoreCase(System.getenv("TEST_E2E_MODE"))) {
ConfigBaseVariable.dbType = "sqlite";
ConfigBaseVariable.dbHost = "memory";
// for test we need to connect all time the DB
ConfigBaseVariable.dbKeepConnected = "true";
}
// Connect the dataBase...
final DBEntry entry = DBEntry.createInterface(GlobalConfiguration.dbConfig);
entry.connect();
}
@AfterAll
public static void removeDataBase() throws IOException {
LOGGER.info("Remove the test db");
DBEntry.closeAllForceMode();
ConfigBaseVariable.clearAllValue();
}
@Order(1)
@Test
public void testCreateTable() throws Exception {
final List<String> sqlCommand = DataFactory.createTable(TypesTable.class);
for (final String elem : sqlCommand) {
LOGGER.debug("request: '{}'", elem);
DataAccess.executeSimpleQuerry(elem);
}
}
@Order(2)
@Test
public void testGet() throws Exception {
final TypesTable test = new TypesTable();
test.intData = 95;
test.floatData = 1.0F;
DataAccess.insert(test);
test.intData = 96;
test.floatData = 2.0F;
DataAccess.insert(test);
test.intData = 97;
test.floatData = 3.0F;
DataAccess.insert(test);
test.intData = 98;
test.floatData = 4.0F;
DataAccess.insert(test);
test.intData = 99;
test.floatData = 5.0F;
DataAccess.insert(test);
test.intData = 99;
test.floatData = 6.0F;
DataAccess.insert(test);
test.intData = 99;
test.floatData = 7.0F;
DataAccess.insert(test);
{
String querry = """
SELECT *
FROM TypesTable
WHERE `intData` = ?
ORDER BY id DESC
""";
List<Object> parameters = List.of(Integer.valueOf(99));
// Try to retrieve all the data:
final List<TypesTable> retrieve = DataAccess.query(TypesTable.class, querry, parameters);
Assertions.assertNotNull(retrieve);
Assertions.assertEquals(3, retrieve.size());
Assertions.assertEquals(99, retrieve.get(0).intData);
Assertions.assertEquals(7.0F, retrieve.get(0).floatData);
Assertions.assertEquals(6.0F, retrieve.get(1).floatData);
Assertions.assertEquals(5.0F, retrieve.get(2).floatData);
}
{
String querry = """
SELECT DISTINCT intData
FROM TypesTable
WHERE `intData` = ?
ORDER BY id DESC
""";
List<Object> parameters = List.of(Integer.valueOf(99));
// Try to retrieve all the data:
final List<TypesTable> retrieve = DataAccess.query(TypesTable.class, querry, parameters);
Assertions.assertNotNull(retrieve);
Assertions.assertEquals(1, retrieve.size());
Assertions.assertEquals(99, retrieve.get(0).intData);
}
}
}