Skip to content

Commit

Permalink
Update convertor script for inserting and updating values
Browse files Browse the repository at this point in the history
  • Loading branch information
apik007 committed Mar 26, 2024
1 parent d834e4b commit e70bfd7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>cz.foresttech</groupId>
<artifactId>ForestDatabase</artifactId>
<version>1.0.2</version>
<version>1.0.3</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
Expand Down
44 changes: 42 additions & 2 deletions src/main/java/cz/foresttech/database/DatabaseEntityConvertor.java
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,15 @@ public <T> String insertOrUpdateScript(Class<T> clazz, T object) throws IllegalA
return null;
}

String columns = processFieldsForScript(clazz, object, false);
String columns = getColumnsFromField(clazz);
String values = getValuesFromField(clazz, object);

String updateSetValues = processFieldsForScript(clazz, object, false);

String conflictPolicy = getConflictPolicy(clazz);

return String.format("INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO UPDATE SET (%s);",
tableName, columns, columns, conflictPolicy, columns);
tableName, columns, values, conflictPolicy, updateSetValues);
}

/**
Expand Down Expand Up @@ -260,6 +264,42 @@ private <T> String processFieldsForScript(Class<T> clazz, T object, boolean forD
return keys + " = " + values;
}

private <T> String getValuesFromField(Class<T> clazz, T object) throws IllegalAccessException {
StringBuilder values = new StringBuilder();

for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
Column column = field.getAnnotation(Column.class);
if (column == null) continue;
String dbName = getDbName(field, column);
Object fieldValue = field.get(object);
DatabaseValueProcessor valueProcessor = databaseAPI.getProcessor(field.getType());

String processedValue = processFieldValue(fieldValue, valueProcessor);
values.append(processedValue).append(",");
}

if (!values.isEmpty()) values.setLength(values.length() - 1);

return values.toString();
}

private <T> String getColumnsFromField(Class<T> clazz) {
StringBuilder keys = new StringBuilder();

for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
Column column = field.getAnnotation(Column.class);
if (column == null) continue;
String dbName = getDbName(field, column);
keys.append(dbName).append(",");
}

if (!keys.isEmpty()) keys.setLength(keys.length() - 1);

return keys.toString();
}

/**
* Processes the value of a field for inclusion in an SQL script.
*
Expand Down

0 comments on commit e70bfd7

Please sign in to comment.