Javadoc and refactor pandalib-db

This commit is contained in:
Marc Baloup 2022-08-01 22:21:04 +02:00
parent 1c490fdd04
commit 660414424e
Signed by: marcbal
GPG Key ID: BBC0FE3ABC30B893
16 changed files with 2457 additions and 1635 deletions

View File

@ -19,7 +19,75 @@
<artifactId>pandalib-util</artifactId> <artifactId>pandalib-util</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.apache.commons:commons-dbcp2</include>
<include>org.apache.commons:commons-pool2</include>
<include>commons-logging:commons-logging</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>org.apache.commons:commons-dbcp2</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
</excludes>
</filter>
<filter>
<artifact>org.apache.commons:commons-pool2</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
</excludes>
</filter>
<filter>
<artifact>commons-logging:commons-logging</artifact>
<excludes>
<exclude>META-INF/MANIFEST.MF</exclude>
</excludes>
</filter>
</filters>
<relocations>
<relocation>
<pattern>org.apache.commons</pattern>
<shadedPattern>fr.pandacube.lib.db.shaded.commons</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.commons</pattern>
<shadedPattern>fr.pandacube.lib.db.shaded.commons</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer">
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheNoticeResourceTransformer">
<addHeader>false</addHeader>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -1,5 +1,6 @@
package fr.pandacube.lib.db; package fr.pandacube.lib.db;
import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -17,7 +18,7 @@ import fr.pandacube.lib.util.Log;
/** /**
* Static class to handle most of the database operations. * Static class to handle most of the database operations.
* * <p>
* To use this database library, first call {@link #init(DBConnection, String)} with an appropriate {@link DBConnection}, * To use this database library, first call {@link #init(DBConnection, String)} with an appropriate {@link DBConnection},
* then you can initialize every table you need for your application, using {@link #initTable(Class)}. * then you can initialize every table you need for your application, using {@link #initTable(Class)}.
* *
@ -25,370 +26,606 @@ import fr.pandacube.lib.util.Log;
*/ */
public final class DB { public final class DB {
private static final List<Class<? extends SQLElement<?>>> tables = new ArrayList<>(); private static final List<Class<? extends SQLElement<?>>> tables = new ArrayList<>();
private static final Map<Class<? extends SQLElement<?>>, String> tableNames = new HashMap<>(); private static final Map<Class<? extends SQLElement<?>>, String> tableNames = new HashMap<>();
private static DBConnection connection; private static DBConnection connection;
/* package */ static String tablePrefix = ""; /* package */ static String tablePrefix = "";
public static DBConnection getConnection() { /**
return connection; * Gets the {@link DBConnection}.
} * @return the {@link DBConnection}.
*/
public synchronized static void init(DBConnection conn, String tablePrefix) { public static DBConnection getConnection() {
connection = conn; return connection;
DB.tablePrefix = Objects.requireNonNull(tablePrefix); }
}
/**
public static synchronized <E extends SQLElement<E>> void initTable(Class<E> elemClass) throws DBInitTableException { * Initialize with the provided connection.
if (connection == null) { * @param conn the database connection.
throw new DBInitTableException(elemClass, "Database connection is not yet initialized."); * @param tablePrefix determine a prefix for the table that will be initialized.
} */
if (tables.contains(elemClass)) return; public synchronized static void init(DBConnection conn, String tablePrefix) {
try { connection = conn;
tables.add(elemClass); DB.tablePrefix = Objects.requireNonNull(tablePrefix);
Log.debug("[DB] Start Init SQL table "+elemClass.getSimpleName()); }
E instance = elemClass.getConstructor().newInstance();
String tableName = tablePrefix + instance.tableName(); /**
tableNames.put(elemClass, tableName); * Initialialize the table represented by the provided class.
if (!tableExistInDB(tableName)) createTable(instance); * @param elemClass the class representing a table.
Log.debug("[DB] End init SQL table "+elemClass.getSimpleName()); * @param <E> the type representing the table.
} catch (Exception|ExceptionInInitializerError e) { * @throws DBInitTableException if the table failed to initialized.
throw new DBInitTableException(elemClass, e); */
} public static synchronized <E extends SQLElement<E>> void initTable(Class<E> elemClass) throws DBInitTableException {
} if (connection == null) {
throw new DBInitTableException(elemClass, "Database connection is not yet initialized.");
private static <E extends SQLElement<E>> void createTable(E elem) throws SQLException { }
if (tables.contains(elemClass)) return;
String tableName = tablePrefix + elem.tableName(); try {
tables.add(elemClass);
StringBuilder sql = new StringBuilder("CREATE TABLE IF NOT EXISTS " + tableName + " ("); Log.debug("[DB] Start Init SQL table "+elemClass.getSimpleName());
List<Object> params = new ArrayList<>(); E instance = elemClass.getConstructor().newInstance();
String tableName = tablePrefix + instance.tableName();
Collection<SQLField<E, ?>> tableFields = elem.getFields().values(); tableNames.put(elemClass, tableName);
boolean first = true; if (!tableExistInDB(tableName)) createTable(instance);
for (SQLField<E, ?> f : tableFields) { Log.debug("[DB] End init SQL table "+elemClass.getSimpleName());
ParameterizedSQLString statementPart = f.forSQLPreparedStatement(); } catch (Exception|ExceptionInInitializerError e) {
params.addAll(statementPart.parameters()); throw new DBInitTableException(elemClass, e);
}
if (!first) }
sql.append(", ");
first = false; private static <E extends SQLElement<E>> void createTable(E elem) throws SQLException {
sql.append(statementPart.sqlString());
} String tableName = tablePrefix + elem.tableName();
sql.append(", PRIMARY KEY id(id))"); StringBuilder sql = new StringBuilder("CREATE TABLE IF NOT EXISTS " + tableName + " (");
List<Object> params = new ArrayList<>();
try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql.toString())) {
int i = 1; Collection<SQLField<E, ?>> tableFields = elem.getFields().values();
for (Object val : params) boolean first = true;
ps.setObject(i++, val); for (SQLField<E, ?> f : tableFields) {
Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString()); ParameterizedSQLString statementPart = f.forSQLPreparedStatement();
ps.executeUpdate(); params.addAll(statementPart.parameters());
}
} if (!first)
sql.append(", ");
public static <E extends SQLElement<E>> String getTableName(Class<E> elemClass) throws DBException { first = false;
initTable(elemClass); sql.append(statementPart.sqlString());
return tableNames.get(elemClass); }
}
sql.append(", PRIMARY KEY id(id))");
private static boolean tableExistInDB(String tableName) throws SQLException {
try (ResultSet set = connection.getNativeConnection().getMetaData().getTables(null, null, tableName, null)) { try (Connection c = connection.getConnection();
return set.next(); PreparedStatement ps = c.prepareStatement(sql.toString())) {
} int i = 1;
} for (Object val : params)
ps.setObject(i++, val);
@SuppressWarnings("unchecked") Log.info("Creating table " + elem.tableName() + ":\n" + ps.toString());
public static <E extends SQLElement<E>> SQLField<E, Integer> getSQLIdField(Class<E> elemClass) ps.executeUpdate();
throws DBInitTableException { }
initTable(elemClass); }
return (SQLField<E, Integer>) SQLElement.fieldsCache.get(elemClass).get("id");
} /**
* Gets the name of the table in the database.
public static <E extends SQLElement<E>> SQLElementList<E> getByIds(Class<E> elemClass, Integer... ids) throws DBException { * @param elemClass the class representing a table.
return getByIds(elemClass, Arrays.asList(ids)); * @return a table name.
} * @param <E> the type representing the table.
* @throws DBInitTableException if the provided table had to be initialized and it failed to do so.
public static <E extends SQLElement<E>> SQLElementList<E> getByIds(Class<E> elemClass, Collection<Integer> ids) */
throws DBException { public static <E extends SQLElement<E>> String getTableName(Class<E> elemClass) throws DBInitTableException {
return getAll(elemClass, getSQLIdField(elemClass).in(ids), SQLOrderBy.asc(getSQLIdField(elemClass)), 1, null); initTable(elemClass);
} return tableNames.get(elemClass);
}
public static <E extends SQLElement<E>> E getById(Class<E> elemClass, int id) throws DBException {
return getFirst(elemClass, getSQLIdField(elemClass).eq(id)); private static boolean tableExistInDB(String tableName) throws SQLException {
} try (Connection c = connection.getConnection();
ResultSet set = c.getMetaData().getTables(null, null, tableName, null)) {
public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLWhere<E> where) return set.next();
throws DBException { }
return getFirst(elemClass, where, null, null); }
}
/**
public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLOrderBy<E> orderBy) * Gets the {@code id} field of the provided table.
throws DBException { * @param elemClass the class representing a table.
return getFirst(elemClass, null, orderBy, null); * @return the {@code id} field of the provided table.
} * @param <E> the type representing the table.
* @throws DBInitTableException if the provided table had to be initialized and it failed to do so.
public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy) */
throws DBException { @SuppressWarnings("unchecked")
return getFirst(elemClass, where, orderBy, null); public static <E extends SQLElement<E>> SQLField<E, Integer> getSQLIdField(Class<E> elemClass) throws DBInitTableException {
} initTable(elemClass);
return (SQLField<E, Integer>) SQLElement.fieldsCache.get(elemClass).get("id");
public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Integer offset) }
throws DBException {
SQLElementList<E> elts = getAll(elemClass, where, orderBy, 1, offset); /**
return (elts.size() == 0) ? null : elts.get(0); * Fetch the entry from the provided table, that has the specified ids.
} * @param elemClass the class representing a table.
* @param ids the ids of the element entries.
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass) throws DBException { * @return the entry from the provided table, that has the specified ids.
return getAll(elemClass, null, null, null, null); * @param <E> the type representing the table.
} * @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where) throws DBException { public static <E extends SQLElement<E>> SQLElementList<E> getByIds(Class<E> elemClass, Integer... ids) throws DBException {
return getAll(elemClass, where, null, null, null); return getByIds(elemClass, Arrays.asList(ids));
} }
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where, /**
SQLOrderBy<E> orderBy) throws DBException { * Fetch the entry from the provided table, that has the specified ids.
return getAll(elemClass, where, orderBy, null, null); * @param elemClass the class representing a table.
} * @param ids the ids of the element entries.
* @return the entry from the provided table, that has the specified ids.
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where, * @param <E> the type representing the table.
SQLOrderBy<E> orderBy, Integer limit) throws DBException { * @throws DBException if an error occurs when interacting with the database.
return getAll(elemClass, where, orderBy, limit, null); */
} public static <E extends SQLElement<E>> SQLElementList<E> getByIds(Class<E> elemClass, Collection<Integer> ids) throws DBException {
return getAll(elemClass, getSQLIdField(elemClass).in(ids), SQLOrderBy.asc(getSQLIdField(elemClass)), 1, null);
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where, }
SQLOrderBy<E> orderBy, Integer limit, Integer offset) throws DBException {
SQLElementList<E> elmts = new SQLElementList<>(); /**
forEach(elemClass, where, orderBy, limit, offset, elmts::add); * Fetch the entry from the provided table, that has the specified id.
return elmts; * @param elemClass the class representing a table.
} * @param id the id of the element entry.
* @return the entry from the provided table, that has the specified id, or null if none was found.
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, Consumer<E> action) throws DBException { * @param <E> the type representing the table.
forEach(elemClass, null, null, null, null, action); * @throws DBException if an error occurs when interacting with the database.
} */
public static <E extends SQLElement<E>> E getById(Class<E> elemClass, int id) throws DBException {
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, return getFirst(elemClass, getSQLIdField(elemClass).eq(id));
Consumer<E> action) throws DBException { }
forEach(elemClass, where, null, null, null, action);
} /**
* Fetch the entry from the provided table, using the provided {@code WHERE} clause,
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, * and a {@code LIMIT} of 1.
SQLOrderBy<E> orderBy, Consumer<E> action) throws DBException { * @param elemClass the class representing a table.
forEach(elemClass, where, orderBy, null, null, action); * @param where the {@code WHERE} clause of the query.
} * @return the entry from the provided table, or null if none was found.
* @param <E> the type representing the table.
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, * @throws DBException if an error occurs when interacting with the database.
SQLOrderBy<E> orderBy, Integer limit, Consumer<E> action) throws DBException { */
forEach(elemClass, where, orderBy, limit, null, action); public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLWhere<E> where) throws DBException {
} return getFirst(elemClass, where, null, null);
}
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where,
SQLOrderBy<E> orderBy, Integer limit, Integer offset, Consumer<E> action) throws DBException { /**
initTable(elemClass); * Fetch the entry from the provided table, using the provided {@code ORDER BY} clause,
* and a {@code LIMIT} of 1.
try { * @param elemClass the class representing a table.
String sql = "SELECT * FROM " + getTableName(elemClass); * @param orderBy the {@code ORDER BY} clause of the query.
* @return the entry from the provided table, or null if none was found.
List<Object> params = new ArrayList<>(); * @param <E> the type representing the table.
* @throws DBException if an error occurs when interacting with the database.
if (where != null) { */
ParameterizedSQLString ret = where.toSQL(); public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLOrderBy<E> orderBy) throws DBException {
sql += " WHERE " + ret.sqlString(); return getFirst(elemClass, null, orderBy, null);
params.addAll(ret.parameters()); }
}
if (orderBy != null) sql += " ORDER BY " + orderBy.toSQL(); /**
if (limit != null) sql += " LIMIT " + limit; * Fetch the entry from the provided table, using the provided {@code WHERE} and {@code ORDER BY} clauses,
if (offset != null) sql += " OFFSET " + offset; * and a {@code LIMIT} of 1.
sql += ";"; * @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
try (ResultSet set = customQueryStatement(sql, params)) { * @param orderBy the {@code ORDER BY} clause of the query.
while (set.next()) { * @return the entry from the provided table, or null if none was found.
E elm = getElementInstance(set, elemClass); * @param <E> the type representing the table.
action.accept(elm); * @throws DBException if an error occurs when interacting with the database.
} */
} public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy) throws DBException {
} catch (SQLException e) { return getFirst(elemClass, where, orderBy, null);
throw new DBException(e); }
}
/**
} * Fetch the entry from the provided table, using the provided {@code WHERE}, {@code ORDER BY} and {@code OFFSET}
* clauses, and a {@code LIMIT} of 1.
* @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
public static <E extends SQLElement<E>> long count(Class<E> elemClass) throws DBException { * @param orderBy the {@code ORDER BY} clause of the query.
return count(elemClass, null); * @param offset the {@code OFFSET} clause of the query.
} * @return the entry from the provided table, or null if none was found.
* @param <E> the type representing the table.
public static <E extends SQLElement<E>> long count(Class<E> elemClass, SQLWhere<E> where) throws DBException { * @throws DBException if an error occurs when interacting with the database.
initTable(elemClass); */
public static <E extends SQLElement<E>> E getFirst(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Integer offset) throws DBException {
try { SQLElementList<E> elts = getAll(elemClass, where, orderBy, 1, offset);
String sql = "SELECT COUNT(*) as count FROM " + getTableName(elemClass); return (elts.size() == 0) ? null : elts.get(0);
}
List<Object> params = new ArrayList<>();
/**
if (where != null) { * Fetch all the entries from the provided table.
ParameterizedSQLString ret = where.toSQL(); * @param elemClass the class representing a table.
sql += " WHERE " + ret.sqlString(); * @return the entries from the provided table, or empty if none was found.
params.addAll(ret.parameters()); * @param <E> the type representing the table.
} * @throws DBException if an error occurs when interacting with the database.
sql += ";"; */
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass) throws DBException {
try (ResultSet set = customQueryStatement(sql, params)) { return getAll(elemClass, null, null, null, null);
if (set.next()) { }
return set.getLong(1);
} /**
} * Fetch the entries from the provided table, using the provided {@code WHERE} clause.
} catch (SQLException e) { * @param elemClass the class representing a table.
throw new DBException(e); * @param where the {@code WHERE} clause of the query.
} * @return the entries from the provided table, or empty if none was found.
* @param <E> the type representing the table.
throw new DBException("Cant retrieve element count from database (The ResultSet may be empty)"); * @throws DBException if an error occurs when interacting with the database.
*/
} public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where) throws DBException {
return getAll(elemClass, where, null, null, null);
}
/**
public static ResultSet customQueryStatement(String sql, List<Object> params) throws DBException { * Fetch the entries from the provided table, using the provided {@code WHERE} and {@code ORDER BY} clauses.
try { * @param elemClass the class representing a table.
PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql); * @param where the {@code WHERE} clause of the query.
int i = 1; * @param orderBy the {@code ORDER BY} clause of the query.
for (Object val : params) { * @return the entries from the provided table, or empty if none was found.
if (val instanceof Enum<?>) val = ((Enum<?>) val).name(); * @param <E> the type representing the table.
ps.setObject(i++, val); * @throws DBException if an error occurs when interacting with the database.
} */
Log.debug(ps.toString()); public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy) throws DBException {
return getAll(elemClass, where, orderBy, null, null);
ResultSet rs = ps.executeQuery(); }
ps.closeOnCompletion(); /**
* Fetch the entries from the provided table, using the provided {@code WHERE}, {@code ORDER BY} and {@code LIMIT}
return rs; * clauses.
} catch (SQLException e) { * @param elemClass the class representing a table.
throw new DBException(e); * @param where the {@code WHERE} clause of the query.
} * @param orderBy the {@code ORDER BY} clause of the query.
* @param limit the {@code LIMIT} clause of the query.
} * @return the entries from the provided table, or empty if none was found.
* @param <E> the type representing the table.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Integer limit) throws DBException {
public static <E extends SQLElement<E>> SQLUpdate<E> update(Class<E> elemClass, SQLWhere<E> where) { return getAll(elemClass, where, orderBy, limit, null);
return new SQLUpdate<>(elemClass, where); }
}
/**
/* package */ static <E extends SQLElement<E>> int update(Class<E> elemClass, SQLWhere<E> where, Map<SQLField<E, ?>, Object> values) throws DBException { * Fetch the entries from the provided table, using the provided {@code WHERE}, {@code ORDER BY}, {@code LIMIT} and
return new SQLUpdate<>(elemClass, where, values).execute(); * {@code OFFSET} clauses.
} * @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
* @param orderBy the {@code ORDER BY} clause of the query.
/** * @param limit the {@code LIMIT} clause of the query.
* Delete the elements of the table represented by {@code elemClass} which meet the condition {@code where}. * @param offset the {@code OFFSET} clause of the query.
* @param elemClass the SQLElement representing the table. * @return the entries from the provided table, or empty if none was found.
* @param where the condition to meet for an element to be deleted from the table. If null, the table is truncated using {@link #truncateTable(Class)}. * @param <E> the type representing the table.
* @return The return value of {@link PreparedStatement#executeUpdate()}, for an SQL query {@code DELETE}. * @throws DBException if an error occurs when interacting with the database.
*/ */
public static <E extends SQLElement<E>> int delete(Class<E> elemClass, SQLWhere<E> where) throws DBException { public static <E extends SQLElement<E>> SQLElementList<E> getAll(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Integer limit, Integer offset) throws DBException {
initTable(elemClass); SQLElementList<E> elmts = new SQLElementList<>();
forEach(elemClass, where, orderBy, limit, offset, elmts::add);
if (where == null) { return elmts;
return truncateTable(elemClass); }
}
/**
ParameterizedSQLString whereData = where.toSQL(); * Iterate through all the entries from the provided table.
* @param elemClass the class representing a table.
String sql = "DELETE FROM " + getTableName(elemClass) * @param action the action to perform on each entries.
+ " WHERE " + whereData.sqlString() * @param <E> the type representing the table.
+ ";"; * @throws DBException if an error occurs when interacting with the database.
List<Object> params = new ArrayList<>(whereData.parameters()); */
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, Consumer<E> action) throws DBException {
return customUpdateStatement(sql, params); forEach(elemClass, null, null, null, null, action);
}
}
/**
* Iterate through the entries from the provided table, using the provided {@code WHERE} clause.
* @param elemClass the class representing a table.
public static int customUpdateStatement(String sql, List<Object> params) throws DBException { * @param where the {@code WHERE} clause of the query.
try (PreparedStatement ps = connection.getNativeConnection().prepareStatement(sql)) { * @param action the action to perform on each entries.
* @param <E> the type representing the table.
int i = 1; * @throws DBException if an error occurs when interacting with the database.
for (Object val : params) { */
if (val instanceof Enum<?>) val = ((Enum<?>) val).name(); public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, Consumer<E> action) throws DBException {
ps.setObject(i++, val); forEach(elemClass, where, null, null, null, action);
} }
Log.debug(ps.toString());
/**
return ps.executeUpdate(); * Iterate through the entries from the provided table, using the provided {@code WHERE} and {@code ORDER BY}
} catch (SQLException e) { * clauses.
throw new DBException(e); * @param elemClass the class representing a table.
} * @param where the {@code WHERE} clause of the query.
} * @param orderBy the {@code ORDER BY} clause of the query.
* @param action the action to perform on each entries.
* @param <E> the type representing the table.
* @throws DBException if an error occurs when interacting with the database.
public static <E extends SQLElement<E>> int truncateTable(Class<E> elemClass) throws DBException { */
try (Statement stmt = connection.getNativeConnection().createStatement()) { public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Consumer<E> action) throws DBException {
forEach(elemClass, where, orderBy, null, null, action);
}
/**
* Iterate through the entries from the provided table, using the provided {@code WHERE}, {@code ORDER BY} and
* {@code LIMIT} clauses.
* @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
* @param orderBy the {@code ORDER BY} clause of the query.
* @param limit the {@code LIMIT} clause of the query.
* @param action the action to perform on each entries.
* @param <E> the type representing the table.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Integer limit, Consumer<E> action) throws DBException {
forEach(elemClass, where, orderBy, limit, null, action);
}
/**
* Iterate through the entries from the provided table, using the provided {@code WHERE}, {@code ORDER BY},
* {@code LIMIT} and {@code OFFSET} clauses.
* @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
* @param orderBy the {@code ORDER BY} clause of the query.
* @param limit the {@code LIMIT} clause of the query.
* @param offset the {@code OFFSET} clause of the query.
* @param action the action to perform on each entries.
* @param <E> the type representing the table.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> void forEach(Class<E> elemClass, SQLWhere<E> where, SQLOrderBy<E> orderBy, Integer limit, Integer offset, Consumer<E> action) throws DBException {
initTable(elemClass);
String sql = "SELECT * FROM " + getTableName(elemClass);
List<Object> params = new ArrayList<>();
if (where != null) {
ParameterizedSQLString ret = where.toSQL();
sql += " WHERE " + ret.sqlString();
params.addAll(ret.parameters());
}
if (orderBy != null)
sql += " ORDER BY " + orderBy.toSQL();
if (limit != null)
sql += " LIMIT " + limit;
if (offset != null)
sql += " OFFSET " + offset;
sql += ";";
customQueryStatement(sql, params, set -> {
while (set.next()) {
E elm = getElementInstance(set, elemClass);
action.accept(elm);
}
return null;
});
}
/**
* Counts the number of entries in the provided table.
* @param elemClass the class representing a table.
* @param <E> the type representing the table.
* @return the number of entries in the provided table.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> long count(Class<E> elemClass) throws DBException {
return count(elemClass, null);
}
/**
* Counts the number of entries from the provided table, that meet the {@code WHERE} clause conditions.
* @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
* @param <E> the type representing the table.
* @return the number of entries from the provided table, that meet the {@code WHERE} clause conditions.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> long count(Class<E> elemClass, SQLWhere<E> where) throws DBException {
initTable(elemClass);
String sql = "SELECT COUNT(*) AS count FROM " + getTableName(elemClass);
List<Object> params = new ArrayList<>();
if (where != null) {
ParameterizedSQLString ret = where.toSQL();
sql += " WHERE " + ret.sqlString();
params.addAll(ret.parameters());
}
sql += ";";
return customQueryStatement(sql, params, rs -> {
if (rs.next()) {
return rs.getLong(1);
}
throw new DBException("Cant retrieve element count from database (the ResultSet is empty).");
});
}
/**
* Execute a custom SQL query statement with the provided parameters, and passes the produced {@link ResultSet}
* to the {@code rsFunction}.
* @param sql the query in SQL language, passed to {@link Connection#prepareStatement(String)}.
* @param params the parameters to put in the query. Uses {@link PreparedStatement#setObject(int, Object)}.
* @param rsFunction the function executed with the result set as the parameter. Its return value will then be
* returned to the caller of this method.
* @param <R> the return type of {@code rsFunction}.
* @return the value returned by {@code rsFunction}.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <R> R customQueryStatement(String sql, List<Object> params, ResultSetFunction<R> rsFunction) throws DBException {
try (Connection c = connection.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
for (Object val : params) {
if (val instanceof Enum<?>) val = ((Enum<?>) val).name();
ps.setObject(i++, val);
}
Log.debug(ps.toString());
try (ResultSet set = ps.executeQuery()) {
return rsFunction.apply(set);
}
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* A function that takes a {@link ResultSet} as an input and output any value.
* @param <R> the return type.
*/
@FunctionalInterface
public interface ResultSetFunction<R> {
/**
* Reads data into the result set.
* @param resultSet the result set to read.
* @throws SQLException if an error occurs while reading the result set.
* @throws DBException if an error occurs while reading the result set.
* @return data computed from the resultSet.
*/
R apply(ResultSet resultSet) throws SQLException, DBException;
}
/**
* Prepares an UPDATE query to the database.
* Call the {@link SQLUpdateBuilder#set(SQLField, Object)} for any field you want to change the value, then call
* {@link SQLUpdateBuilder#execute()} to send the query.
* @param elemClass the class representing a table.
* @param where the {@code WHERE} clause of the query.
* @param <E> the type representing the table.
* @return an {@link SQLUpdateBuilder} instance.
*/
public static <E extends SQLElement<E>> SQLUpdateBuilder<E> update(Class<E> elemClass, SQLWhere<E> where) {
return new SQLUpdateBuilder<>(elemClass, where);
}
/* package */ static <E extends SQLElement<E>> int update(Class<E> elemClass, SQLWhere<E> where, Map<SQLField<E, ?>, Object> values) throws DBException {
return new SQLUpdateBuilder<>(elemClass, where, values).execute();
}
/**
* Delete the entries from the provided table, using the provided {@code WHERE} clause.
* @param elemClass the class representing a table.
* @param where the condition to meet for an element to be deleted from the table. If null, the table is truncated
* using {@link #truncateTable(Class)}.
* @param <E> the type representing the table.
* @return The return value of {@link PreparedStatement#executeUpdate()}, for an SQL query {@code DELETE}.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> int delete(Class<E> elemClass, SQLWhere<E> where) throws DBException {
initTable(elemClass);
if (where == null) {
return truncateTable(elemClass);
}
ParameterizedSQLString whereData = where.toSQL();
String sql = "DELETE FROM " + getTableName(elemClass)
+ " WHERE " + whereData.sqlString()
+ ";";
List<Object> params = new ArrayList<>(whereData.parameters());
return customUpdateStatement(sql, params);
}
/**
* Execute a custom SQL update statement with the provided parameters.
* @param sql the query in SQL language, passed to {@link Connection#prepareStatement(String)}.
* @param params the parameters to put in the query. Uses {@link PreparedStatement#setObject(int, Object)}.
* @return the value returned by {@link PreparedStatement#executeUpdate()}.
* @throws DBException if an error occurs when interacting with the database.
*/
public static int customUpdateStatement(String sql, List<Object> params) throws DBException {
try (Connection c = connection.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
for (Object val : params) {
if (val instanceof Enum<?>) val = ((Enum<?>) val).name();
ps.setObject(i++, val);
}
Log.debug(ps.toString());
return ps.executeUpdate();
} catch (SQLException e) {
throw new DBException(e);
}
}
/**
* Truncate provided table.
* @param elemClass the class representing a table.
* @param <E> the type representing the table.
* @return The return value of {@link PreparedStatement#executeUpdate()}, for an SQL query {@code DELETE}.
* @throws DBException if an error occurs when interacting with the database.
*/
public static <E extends SQLElement<E>> int truncateTable(Class<E> elemClass) throws DBException {
try (Connection c = connection.getConnection();
Statement stmt = c.createStatement()) {
return stmt.executeUpdate("TRUNCATE `" + getTableName(elemClass) + "`"); return stmt.executeUpdate("TRUNCATE `" + getTableName(elemClass) + "`");
} catch(SQLException e) { } catch(SQLException e) {
throw new DBException(e); throw new DBException(e);
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static <E extends SQLElement<E>> E getElementInstance(ResultSet set, Class<E> elemClass) throws DBException { private static <E extends SQLElement<E>> E getElementInstance(ResultSet set, Class<E> elemClass) throws DBException {
try { try {
E instance = elemClass.getConstructor(int.class).newInstance(set.getInt("id")); E instance = elemClass.getConstructor(int.class).newInstance(set.getInt("id"));
int fieldCount = set.getMetaData().getColumnCount(); int fieldCount = set.getMetaData().getColumnCount();
for (int c = 1; c <= fieldCount; c++) { for (int c = 1; c <= fieldCount; c++) {
String fieldName = set.getMetaData().getColumnLabel(c); String fieldName = set.getMetaData().getColumnLabel(c);
// ignore when field is present in database but not handled by SQLElement instance // ignore when field is present in database but not handled by SQLElement instance
if (!instance.getFields().containsKey(fieldName)) continue; if (!instance.getFields().containsKey(fieldName)) continue;
SQLField<E, Object> sqlField = (SQLField<E, Object>) instance.getFields().get(fieldName); SQLField<E, Object> sqlField = (SQLField<E, Object>) instance.getFields().get(fieldName);
boolean customType = sqlField.type instanceof SQLCustomType; boolean customType = sqlField.type instanceof SQLCustomType;
Object val = set.getObject(c, Object val = set.getObject(c,
(Class<?>)(customType ? ((SQLCustomType<?, ?>)sqlField.type).intermediateJavaType (Class<?>)(customType ? ((SQLCustomType<?, ?>)sqlField.type).intermediateJavaType
: sqlField.type.getJavaType())); : sqlField.type.getJavaType()));
if (val == null || set.wasNull()) { if (val == null || set.wasNull()) {
instance.set(sqlField, null, false); instance.set(sqlField, null, false);
} }
else { else {
if (customType) { if (customType) {
try { try {
val = ((SQLCustomType<Object, Object>)sqlField.type).dbToJavaConv.apply(val); val = ((SQLCustomType<Object, Object>)sqlField.type).dbToJavaConv.apply(val);
} catch (Exception e) { } catch (Exception e) {
throw new DBException("Error while converting value of field '"+sqlField.getName()+"' with SQLCustomType from "+((SQLCustomType<Object, Object>)sqlField.type).intermediateJavaType throw new DBException("Error while converting value of field '"+sqlField.getName()+"' with SQLCustomType from "+((SQLCustomType<Object, Object>)sqlField.type).intermediateJavaType
+"(jdbc source) to "+sqlField.type.getJavaType()+"(java destination). The original value is '"+ val +"'", e); +"(jdbc source) to "+sqlField.type.getJavaType()+"(java destination). The original value is '"+ val +"'", e);
} }
} }
instance.set(sqlField, val, false); /*
// la valeur venant de la BDD est marqué comme "non modifié" * The value from the DB is marked as not-modified in the entry instance since this boolean is set
// dans l'instance car le constructeur de l'instance met * only when the value differs from the DB.
// tout les champs comme modifiés */
instance.modifiedSinceLastSave.remove(sqlField.getName()); instance.set(sqlField, val, false);
instance.modifiedSinceLastSave.remove(sqlField.getName());
} }
} }
if (!instance.isValidForSave()) throw new DBException( if (!instance.isValidForSave()) throw new DBException(
"This SQLElement representing a database entry is not valid for save : " + instance); "This SQLElement representing a database entry is not valid for save : " + instance);
return instance; return instance;
} catch (ReflectiveOperationException | IllegalArgumentException | SecurityException | SQLException e) { } catch (ReflectiveOperationException | IllegalArgumentException | SecurityException | SQLException e) {
throw new DBException("Can't instanciate " + elemClass.getName(), e); throw new DBException("Can't instanciate " + elemClass.getName(), e);
} }
} }
private DB() {} private DB() {}
} }

View File

@ -1,83 +1,60 @@
package fr.pandacube.lib.db; package fr.pandacube.lib.db;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import fr.pandacube.lib.util.Log; import org.apache.commons.dbcp2.BasicDataSource;
/**
* A class holding the connection to the database.
*/
public class DBConnection { public class DBConnection {
private static final long CONNECTION_CHECK_TIMEOUT = 30000; // in ms
private Connection conn; private final BasicDataSource connSource;
private final String url;
private final String login;
private final String pass;
private long timeOfLastCheck = 0; /**
* Create a new connection with the provided settings.
public DBConnection(String host, int port, String dbname, String l, String p) * @param host the MySQL DB host.
throws SQLException { * @param port the MySQL DB port.
url = "jdbc:mysql://" + host + ":" + port + "/" + dbname * @param dbname the MySQL DB name.
+ "?autoReconnect=true" * @param login the login/username.
+ "&useUnicode=true" * @param password the password.
+ "&useSSL=false" */
+ "&characterEncoding=utf8" public DBConnection(String host, int port, String dbname, String login, String password) {
+ "&characterSetResults=utf8" this("jdbc:mysql://" + host + ":" + port + "/" + dbname
+ "&character_set_server=utf8mb4" + "?useUnicode=true"
+ "&character_set_connection=utf8mb4"; + "&useSSL=false"
login = l; + "&characterEncoding=utf8"
pass = p; + "&characterSetResults=utf8"
connect(); + "&character_set_server=utf8mb4"
} + "&character_set_connection=utf8mb4",
login, password);
private void checkConnection() throws SQLException {
if (!isConnected()) {
Log.info("Connection to the database lost. Trying to reconnect...");
close();
connect();
}
}
private boolean isConnected()
{
try {
if (conn.isClosed())
return false;
// avoid checking the connection everytime we want to do a db request
long now = System.currentTimeMillis();
if (timeOfLastCheck + CONNECTION_CHECK_TIMEOUT > now)
return true;
timeOfLastCheck = now;
if (conn.isValid(1))
return true;
try (ResultSet rs = conn.createStatement().executeQuery("SELECT 1;")) {
return rs != null && rs.next();
}
} catch (Exception e) {
return false;
}
} }
public Connection getNativeConnection() throws SQLException { /**
checkConnection(); * Create a new connection with the provided settings.
return conn; * @param url the JDBC URL.
} * @param login the login/username.
* @param password the password.
*/
public DBConnection(String url, String login, String password) {
connSource = new BasicDataSource();
connSource.setUrl(url);
connSource.setUsername(login);
connSource.setPassword(password);
}
private void connect() throws SQLException { /* package */ Connection getConnection() throws SQLException {
conn = DriverManager.getConnection(url, login, pass); return connSource.getConnection();
timeOfLastCheck = System.currentTimeMillis(); }
}
public void close() { /**
try { * Closes the connection.
conn.close(); */
} catch (Exception ignored) {} public void close() {
} try {
connSource.close();
} catch (SQLException ignored) {}
}
} }

View File

@ -1,17 +1,20 @@
package fr.pandacube.lib.db; package fr.pandacube.lib.db;
/**
* Exception thrown when something bad happends when using the {@link DB} API.
*/
public class DBException extends Exception { public class DBException extends Exception {
public DBException(Throwable initCause) { /* package */ DBException(Throwable initCause) {
super(initCause); super(initCause);
} }
public DBException(String message, Throwable initCause) { /* package */ DBException(String message, Throwable initCause) {
super(message, initCause); super(message, initCause);
} }
public DBException(String message) { /* package */ DBException(String message) {
super(message); super(message);
} }
} }

View File

@ -1,13 +1,16 @@
package fr.pandacube.lib.db; package fr.pandacube.lib.db;
/**
* Exception thrown when something bad happends when initializing a new table using {@link DB#initTable(Class)}.
*/
public class DBInitTableException extends DBException { public class DBInitTableException extends DBException {
/* package */ <E extends SQLElement<E>> DBInitTableException(Class<E> tableElem, Throwable t) { /* package */ <E extends SQLElement<E>> DBInitTableException(Class<E> tableElem, Throwable t) {
super("Error while initializing table " + ((tableElem != null) ? tableElem.getName() : "null"), t); super("Error while initializing table " + ((tableElem != null) ? tableElem.getName() : "null"), t);
} }
/* package */ <E extends SQLElement<E>> DBInitTableException(Class<E> tableElem, String message) { /* package */ <E extends SQLElement<E>> DBInitTableException(Class<E> tableElem, String message) {
super("Error while initializing table " + ((tableElem != null) ? tableElem.getName() : "null") + ": " + message); super("Error while initializing table " + ((tableElem != null) ? tableElem.getName() : "null") + ": " + message);
} }
} }

View File

@ -2,5 +2,5 @@ package fr.pandacube.lib.db;
import java.util.List; import java.util.List;
public record ParameterizedSQLString(String sqlString, List<Object> parameters) { /* package */ record ParameterizedSQLString(String sqlString, List<Object> parameters) {
} }

View File

@ -3,23 +3,45 @@ package fr.pandacube.lib.db;
import java.util.function.Function; import java.util.function.Function;
/** /**
* @param <IT> intermediate type, the type of the value transmitted to the JDBC * Represents a SQL type that needs conversion from and to the JDBC values.
* @param <JT> Java type * <p>
* For instance, if there is a UUID field in a table, its possible to create a new type as follows:
* <pre>{@code
* SQLType<UUID> UUID = new SQLCustomType<>(SQLElement.CHAR(36), UUID.class, UUID::fromString, UUID::toString);
* }</pre>
* @param <IT> intermediate Java type, the type of the value transmitted to the JDBC.
* @param <JT> the final Java type.
*/ */
public class SQLCustomType<IT, JT> extends SQLType<JT> { public class SQLCustomType<IT, JT> extends SQLType<JT> {
public final Class<IT> intermediateJavaType; /* package */ final Class<IT> intermediateJavaType;
public final Function<IT, JT> dbToJavaConv; /* package */ final Function<IT, JT> dbToJavaConv;
public final Function<JT, IT> javaToDbConv; /* package */ final Function<JT, IT> javaToDbConv;
/* package */ SQLCustomType(SQLType<IT> type, Class<JT> javaT, Function<IT, JT> dbToJava, Function<JT, IT> javaToDb) { /**
this(type.sqlDeclaration, type.getJavaType(), javaT, dbToJava, javaToDb); * Creates a new custom type, using a type that is already managed by JDBC and already has a {@link SQLType}
} * instance, like {@link SQLElement#VARCHAR(int)}.
* @param type the raw {@link SQLType} instance.
* @param javaT the class of the Java type.
* @param dbToJava a function that converts from the JDBC value to Java value.
* @param javaToDb a function that converts from Java value to JDBC value.
*/
public SQLCustomType(SQLType<IT> type, Class<JT> javaT, Function<IT, JT> dbToJava, Function<JT, IT> javaToDb) {
this(type.sqlDeclaration, type.getJavaType(), javaT, dbToJava, javaToDb);
}
/* package */ SQLCustomType(String sqlD, Class<IT> intermediateJavaT, Class<JT> javaT, Function<IT, JT> dbToJava, Function<JT, IT> javaToDb) { /**
super(sqlD, javaT); * Creates a new custom type.
intermediateJavaType = intermediateJavaT; * @param sqlD the name of the type in SQL (like {@code BLOB} or {@code BIGINT}).
dbToJavaConv = dbToJava; * @param intermediateJavaT the class of the JDBC value type.
javaToDbConv = javaToDb; * @param javaT the class of the Java value type.
} * @param dbToJava a function that converts from the JDBC value to Java value.
* @param javaToDb a function that converts from Java value to JDBC value.
*/
public SQLCustomType(String sqlD, Class<IT> intermediateJavaT, Class<JT> javaT, Function<IT, JT> dbToJava, Function<JT, IT> javaToDb) {
super(sqlD, javaT);
intermediateJavaType = intermediateJavaT;
dbToJavaConv = dbToJava;
javaToDbConv = javaToDb;
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,7 @@
package fr.pandacube.lib.db; package fr.pandacube.lib.db;
import java.sql.PreparedStatement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -11,179 +10,199 @@ import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import fr.pandacube.lib.util.Log;
/** /**
* * An {@link ArrayList} that provides special operations for the table entries it contains.
* @param <E> * @param <E> the table type.
*/ */
public class SQLElementList<E extends SQLElement<E>> extends ArrayList<E> { public class SQLElementList<E extends SQLElement<E>> extends ArrayList<E> {
private final Map<SQLField<E, ?>, Object> modifiedValues = new LinkedHashMap<>(); /**
* Stores all the values modified by {@link #setCommon(SQLField, Object)}.
*/
private final Map<SQLField<E, ?>, Object> modifiedValues = new LinkedHashMap<>();
@Override @Override
public synchronized boolean add(E e) { public synchronized boolean add(E e) {
if (e == null || !e.isStored()) return false; if (e == null || !e.isStored()) return false;
return super.add(e); return super.add(e);
} }
/** /**
* Défini une valeur à un champ qui sera appliquée dans la base de données à * Sets the value of a field for all the entries.
* tous les * The changed value is stored in this {@link SQLElementList} itself, and does not modify the content of the entries.
* entrées présente dans cette liste lors de l'appel à {@link #saveCommon()} * To apply the modification into the database and into the entries themselves, call {@link #saveCommon()}.
* . * @param field the field to set.
* Les valeurs stockés dans chaque élément de cette liste ne seront affectés * @param value the new value for this field.
* que lors de * @param <T> the Java type of the field.
* l'appel à {@link #saveCommon()} */
* public synchronized <T> void setCommon(SQLField<E, T> field, T value) {
* @param field le champs à modifier if (field == null)
* @param value la valeur à lui appliquer throw new IllegalArgumentException("field can't be null");
*/ if (Objects.equals(field.getName(), "id"))
public synchronized <T> void setCommon(SQLField<E, T> field, T value) { throw new IllegalArgumentException("Can't modify id field in a SQLElementList");
if (field == null)
throw new IllegalArgumentException("field can't be null");
if (Objects.equals(field.getName(), "id"))
throw new IllegalArgumentException("Can't modify id field in a SQLElementList");
Class<E> elemClass = field.getSQLElementType(); Class<E> elemClass = field.getSQLElementType();
try { try {
E emptyElement = elemClass.getConstructor().newInstance(); E emptyElement = elemClass.getConstructor().newInstance();
emptyElement.set(field, value, false); emptyElement.set(field, value, false);
} catch (Exception e) { } catch (Exception e) {
throw new IllegalArgumentException("Illegal field or value or can't instanciante an empty instance of " throw new IllegalArgumentException("Illegal field or value or can't instanciante an empty instance of "
+ elemClass.getName() + ". (the instance is only created to test validity of field and value)", e); + elemClass.getName() + ". (the instance is only created to test validity of field and value)", e);
} }
// ici, la valeur est bonne // ici, la valeur est bonne
modifiedValues.put(field, value); modifiedValues.put(field, value);
} }
/** /**
* Applique toutes les valeurs défini avec * Apply all the changes made with {@link #setCommon(SQLField, Object)} to the entries currently present in this
* {@link #setCommon(SQLField, Object)} à toutes * list.
* les entrées dans la base de données correspondants aux entrées de cette * The change is applied in the database and into the entries in this list (except the fields that has already been
* liste. Les nouvelles * modified in an entry (checked using {@link SQLElement#isModified(SQLField)})).
* valeurs sont aussi mises à jour dans les objets contenus dans cette * The entries of this list that are not stored in database (using {@link SQLElement#isStored()}) are ignored.
* liste, si la valeur n'a pas été modifiée individuellement avec * @return the value returned by {@link PreparedStatement#executeUpdate()}.
* {@link SQLElement#set(SQLField, Object)}.<br/> * @throws DBException if an error occurs when interacting with the database.
* Les objets de cette liste qui n'ont pas leur données en base de données */
* sont ignorées. public synchronized int saveCommon() throws DBException {
*/ List<E> storedEl = getStoredEl();
public synchronized int saveCommon() throws DBException { if (storedEl.isEmpty()) return 0;
List<E> storedEl = getStoredEl();
if (storedEl.isEmpty()) return 0;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Class<E> classEl = (Class<E>)storedEl.get(0).getClass(); Class<E> classEl = (Class<E>)storedEl.get(0).getClass();
int ret = DB.update(classEl, int ret = DB.update(classEl,
storedEl.get(0).getFieldId().in(storedEl.stream().map(SQLElement::getId).collect(Collectors.toList()) storedEl.get(0).getIdField().in(storedEl.stream().map(SQLElement::getId).collect(Collectors.toList())
), ),
modifiedValues); modifiedValues);
applyNewValuesToElements(storedEl); applyNewValuesToElements(storedEl);
return ret; return ret;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void applyNewValuesToElements(List<E> storedEl) { private void applyNewValuesToElements(List<E> storedEl) {
// applique les valeurs dans chaques objets de la liste // applique les valeurs dans chaques objets de la liste
for (E el : storedEl) for (E el : storedEl) {
for (@SuppressWarnings("rawtypes") for (@SuppressWarnings("rawtypes") SQLField entry : modifiedValues.keySet()) {
SQLField entry : modifiedValues.keySet()) if (!el.isModified(entry)) {
if (!el.isModified(entry)) el.set(entry, modifiedValues.get(entry), false); el.set(entry, modifiedValues.get(entry), false);
} }
}
}
}
private List<E> getStoredEl() { private List<E> getStoredEl() {
return stream().filter(SQLElement::isStored).collect(Collectors.toCollection(ArrayList::new)); return stream().filter(SQLElement::isStored).collect(Collectors.toCollection(ArrayList::new));
} }
/** /**
* @deprecated please use {@link DB#delete(Class, SQLWhere)} instead, * Removes all the entries of this list from the database.
* except if you really want to fetch the data before removing them from database. * This method has the same effect as calling the {@link SQLElement#delete()} method individually on each element,
*/ * but with only one SQL query to delete all of the entries.
@Deprecated * <p>
public synchronized void removeFromDB() { * If you intend to remove the entries from the database just after fetching them, call directly the
List<E> storedEl = getStoredEl(); * {@link DB#delete(Class, SQLWhere)} method instead.
if (storedEl.isEmpty()) return; * @throws DBException if an error occurs when interacting with the database.
*/
public synchronized void deleteFromDB() throws DBException {
List<E> storedEl = getStoredEl();
if (storedEl.isEmpty()) return;
try { @SuppressWarnings("unchecked")
@SuppressWarnings("unchecked") Class<E> classEl = (Class<E>)storedEl.get(0).getClass();
Class<E> classEl = (Class<E>)storedEl.get(0).getClass();
DB.delete(classEl, DB.delete(classEl,
storedEl.get(0).getFieldId().in(storedEl.stream().map(SQLElement::getId).collect(Collectors.toList())) storedEl.get(0).getIdField().in(storedEl.stream().map(SQLElement::getId).collect(Collectors.toList()))
); );
for (E el : storedEl) for (E el : storedEl)
el.markAsNotStored(); el.markAsNotStored();
} catch (DBException e) {
Log.severe(e);
}
} }
/**
public <T, P extends SQLElement<P>> SQLElementList<P> getReferencedEntries(SQLFKField<E, T, P> foreignKey, SQLOrderBy<P> orderBy) throws DBException { * Get all the entries targeted by the foreign key of all the entries in this list.
Set<T> values = new HashSet<>(); * @param foreignKey a foreignkey of this table.
forEach(v -> { * @param orderBy the {@code ORDER BY} clause of the query.
T val = v.get(foreignKey); * @return a list of foreign table entries targeted by the provided foreignkey of this table.
if (val != null) * @param <T> the fields Java type.
values.add(val); * @param <P> the target table type.
}); * @throws DBException if an error occurs when interacting with the database.
*/
if (values.isEmpty()) { public <T, P extends SQLElement<P>> SQLElementList<P> getReferencedEntries(SQLFKField<E, T, P> foreignKey, SQLOrderBy<P> orderBy) throws DBException {
return new SQLElementList<>(); Set<T> values = stream()
} .map(v -> v.get(foreignKey))
.filter(Objects::nonNull)
return DB.getAll(foreignKey.getForeignElementClass(), foreignKey.getPrimaryField().in(values), orderBy, null, null); .collect(Collectors.toSet());
return values.isEmpty()
} ? new SQLElementList<>()
: DB.getAll(foreignKey.getForeignElementClass(), foreignKey.getPrimaryField().in(values), orderBy, null, null);
}
public <T, P extends SQLElement<P>> Map<T, P> getReferencedEntriesInGroups(SQLFKField<E, T, P> foreignKey) throws DBException { /**
SQLElementList<P> foreignElemts = getReferencedEntries(foreignKey, null); * Get all the entries targeted by the foreign key of all the entries in this list, mapped from the foreign key value.
* @param foreignKey a foreignkey of this table.
return foreignElemts.stream() * @return a map of the foreign key values, mapped to the foreign tables entries.
.collect(Collectors.toMap( * @param <T> the fields Java type.
foreignVal -> foreignVal.get(foreignKey.getPrimaryField()), * @param <P> the target table type.
Function.identity(), (a, b) -> b) * @throws DBException if an error occurs when interacting with the database.
); */
} public <T, P extends SQLElement<P>> Map<T, P> getReferencedEntriesInGroups(SQLFKField<E, T, P> foreignKey) throws DBException {
return getReferencedEntries(foreignKey, null).stream()
.collect(Collectors.toMap(
foreignVal -> foreignVal.get(foreignKey.getPrimaryField()),
Function.identity(),
(a, b) -> b)
);
}
/**
public <T, F extends SQLElement<F>> SQLElementList<F> getReferencingForeignEntries(SQLFKField<F, T, E> foreignKey, SQLOrderBy<F> orderBy, Integer limit, Integer offset) throws DBException { * Gets all the original tables entries which the provided foreign key is targeting the entries of this list, and
Set<T> values = new HashSet<>(); * following the provided {@code ORDER BY}, {@code LIMIT} and {@code OFFSET} clauses.
forEach(v -> { * @param foreignKey a foreignkey in the original table.
T val = v.get(foreignKey.getPrimaryField()); * @param orderBy the {@code ORDER BY} clause of the query.
if (val != null) * @param limit the {@code LIMIT} clause of the query.
values.add(val); * @param offset the {@code OFFSET} clause of the query.
}); * @param <T> the type of the foreignkey field.
* @param <F> the table class of the foreign key that reference a field of this entry.
if (values.isEmpty()) { * @return the original tables entries which the provided foreign key is targeting the entries of this list.
return new SQLElementList<>(); * @throws DBException if an error occurs when interacting with the database.
} */
public <T, F extends SQLElement<F>> SQLElementList<F> getReferencingForeignEntries(SQLFKField<F, T, E> foreignKey, SQLOrderBy<F> orderBy, Integer limit, Integer offset) throws DBException {
return DB.getAll(foreignKey.getSQLElementType(), foreignKey.in(values), orderBy, limit, offset); Set<T> values = stream()
.map(v -> v.get(foreignKey.getPrimaryField()))
} .filter(Objects::nonNull)
.collect(Collectors.toSet());
return values.isEmpty()
? new SQLElementList<>()
: DB.getAll(foreignKey.getSQLElementType(), foreignKey.in(values), orderBy, limit, offset);
}
public <T, F extends SQLElement<F>> Map<T, SQLElementList<F>> getReferencingForeignEntriesInGroups(SQLFKField<F, T, E> foreignKey, SQLOrderBy<F> orderBy, Integer limit, Integer offset) throws DBException { /**
SQLElementList<F> foreignElements = getReferencingForeignEntries(foreignKey, orderBy, limit, offset); * Gets all the original tables entries which the provided foreign key is targeting the entries of this list,
* following the provided {@code ORDER BY}, {@code LIMIT} and {@code OFFSET} clauses, and mapped from the foreign
Map<T, SQLElementList<F>> map = new HashMap<>(); * key value.
foreignElements.forEach(foreignVal -> { * @param foreignKey a foreignkey in the original table.
SQLElementList<F> subList = map.getOrDefault(foreignVal.get(foreignKey), new SQLElementList<>()); * @param orderBy the {@code ORDER BY} clause of the query.
subList.add(foreignVal); * @param limit the {@code LIMIT} clause of the query.
map.put(foreignVal.get(foreignKey), subList); * @param offset the {@code OFFSET} clause of the query.
}); * @param <T> the type of the foreignkey field.
* @param <F> the table class of the foreign key that reference a field of this entry.
return map; * @return a map of the foreign key values, mapped to the orignal tables entries.
} * @throws DBException if an error occurs when interacting with the database.
*/
public <T, F extends SQLElement<F>> Map<T, SQLElementList<F>> getReferencingForeignEntriesInGroups(SQLFKField<F, T, E> foreignKey, SQLOrderBy<F> orderBy, Integer limit, Integer offset) throws DBException {
return getReferencingForeignEntries(foreignKey, orderBy, limit, offset).stream()
.collect(Collectors.groupingBy(
e -> e.get(foreignKey),
Collectors.toCollection(SQLElementList::new)
));
}

View File

@ -3,67 +3,73 @@ package fr.pandacube.lib.db;
import fr.pandacube.lib.util.Log; import fr.pandacube.lib.util.Log;
/** /**
* * A foreign key field in a SQL table.
* @author Marc
*
* @param <F> the table class of this current foreign key field * @param <F> the table class of this current foreign key field
* @param <T> the Java type of this field * @param <T> the Java type of this field
* @param <P> the table class of the targeted primary key * @param <P> the table class of the targeted primary key
*/ */
public class SQLFKField<F extends SQLElement<F>, T, P extends SQLElement<P>> extends SQLField<F, T> { public class SQLFKField<F extends SQLElement<F>, T, P extends SQLElement<P>> extends SQLField<F, T> {
private SQLField<P, T> sqlPrimaryKeyField; private SQLField<P, T> sqlPrimaryKeyField;
private Class<P> sqlForeignKeyElemClass; private Class<P> sqlForeignKeyElemClass;
protected SQLFKField(SQLType<T> t, boolean nul, T deflt, Class<P> fkEl, SQLField<P, T> fkF) { /* package */ SQLFKField(SQLType<T> t, boolean nul, T deflt, Class<P> fkEl, SQLField<P, T> fkF) {
super(t, nul, deflt); super(t, nul, deflt);
construct(fkEl, fkF); construct(fkEl, fkF);
} }
/* package */ static <E extends SQLElement<E>, F extends SQLElement<F>> SQLFKField<E, Integer, F> idFK(boolean nul, Class<F> fkEl) { /* package */ static <E extends SQLElement<E>, F extends SQLElement<F>> SQLFKField<E, Integer, F> idFK(boolean nul, Class<F> fkEl) {
return idFK(nul, null, fkEl); return idFK(nul, null, fkEl);
} }
/* package */ static <E extends SQLElement<E>, F extends SQLElement<F>> SQLFKField<E, Integer, F> idFK(boolean nul, Integer deflt, Class<F> fkEl) { /* package */ static <E extends SQLElement<E>, F extends SQLElement<F>> SQLFKField<E, Integer, F> idFK(boolean nul, Integer deflt, Class<F> fkEl) {
if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null");
try { try {
SQLField<F, Integer> f = DB.getSQLIdField(fkEl); SQLField<F, Integer> f = DB.getSQLIdField(fkEl);
return new SQLFKField<>(f.type, nul, deflt, fkEl, f); return new SQLFKField<>(f.type, nul, deflt, fkEl, f);
} catch (DBInitTableException e) { } catch (DBInitTableException e) {
Log.severe("Can't create Foreign key Field targetting id field of '"+fkEl+"'", e); Log.severe("Can't create Foreign key Field targetting id field of '"+fkEl+"'", e);
return null; return null;
} }
} }
/* package */ static <E extends SQLElement<E>, T, F extends SQLElement<F>> SQLFKField<E, T, F> customFK(boolean nul, Class<F> fkEl, SQLField<F, T> fkF) { /* package */ static <E extends SQLElement<E>, T, F extends SQLElement<F>> SQLFKField<E, T, F> customFK(boolean nul, Class<F> fkEl, SQLField<F, T> fkF) {
return customFK(nul, null, fkEl, fkF); return customFK(nul, null, fkEl, fkF);
} }
/* package */ static <E extends SQLElement<E>, T, F extends SQLElement<F>> SQLFKField<E, T, F> customFK(boolean nul, T deflt, Class<F> fkEl, SQLField<F, T> fkF) { /* package */ static <E extends SQLElement<E>, T, F extends SQLElement<F>> SQLFKField<E, T, F> customFK(boolean nul, T deflt, Class<F> fkEl, SQLField<F, T> fkF) {
if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null");
return new SQLFKField<>(fkF.type, nul, deflt, fkEl, fkF); return new SQLFKField<>(fkF.type, nul, deflt, fkEl, fkF);
} }
private void construct(Class<P> fkEl, SQLField<P, T> fkF) { private void construct(Class<P> fkEl, SQLField<P, T> fkF) {
if (fkF == null) throw new IllegalArgumentException("foreignKeyField can't be null"); if (fkF == null) throw new IllegalArgumentException("foreignKeyField can't be null");
try { try {
DB.initTable(fkEl); DB.initTable(fkEl);
} catch (DBInitTableException e) { } catch (DBInitTableException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if (fkF.getSQLElementType() == null) if (fkF.getSQLElementType() == null)
throw new RuntimeException("Can't initialize foreign key. The primary key in the table " + fkEl.getName() + " is not properly initialized and can't be targetted by a forein key"); throw new RuntimeException("Can't initialize foreign key. The primary key in the table " + fkEl.getName() + " is not properly initialized and can't be targetted by a forein key");
sqlPrimaryKeyField = fkF; sqlPrimaryKeyField = fkF;
sqlForeignKeyElemClass = fkEl; sqlForeignKeyElemClass = fkEl;
} }
public SQLField<P, T> getPrimaryField() { /**
return sqlPrimaryKeyField; * Gets the targeted field of this foreign key.
} * @return the targeted field of this foreign key.
*/
public SQLField<P, T> getPrimaryField() {
return sqlPrimaryKeyField;
}
public Class<P> getForeignElementClass() { /**
return sqlForeignKeyElemClass; * Gets the type of the table containing the targeted field of this foreign key.
} * @return the type of the table containing the targeted field of this foreign key.
*/
public Class<P> getForeignElementClass() {
return sqlForeignKeyElemClass;
}
} }

View File

@ -10,131 +10,225 @@ import fr.pandacube.lib.db.SQLWhere.SQLWhereIn;
import fr.pandacube.lib.db.SQLWhere.SQLWhereLike; import fr.pandacube.lib.db.SQLWhere.SQLWhereLike;
import fr.pandacube.lib.db.SQLWhere.SQLWhereNull; import fr.pandacube.lib.db.SQLWhere.SQLWhereNull;
/**
* A field in a SQL table.
* @param <E> the table type.
* @param <T> the Java type of this field.
*/
public class SQLField<E extends SQLElement<E>, T> { public class SQLField<E extends SQLElement<E>, T> {
private Class<E> sqlElemClass; private Class<E> sqlElemClass;
private String name = null; private String name = null;
public final SQLType<T> type; /* package */ final SQLType<T> type;
public final boolean canBeNull; /* package */ final boolean nullable;
public final boolean autoIncrement; /* package */ final boolean autoIncrement;
/* package */ final T defaultValue; /* package */ final T defaultValue;
/* package */ SQLField(SQLType<T> t, boolean nul, boolean autoIncr, T deflt) { /* package */ SQLField(SQLType<T> type, boolean nullable, boolean autoIncr, T deflt) {
type = t; this.type = type;
canBeNull = nul; this.nullable = nullable;
autoIncrement = autoIncr; autoIncrement = autoIncr;
defaultValue = deflt; defaultValue = deflt;
} }
/* package */ SQLField(SQLType<T> t, boolean nul) { /* package */ SQLField(SQLType<T> type, boolean nullable) {
this(t, nul, false, null); this(type, nullable, false, null);
} }
/* package */ SQLField(SQLType<T> t, boolean nul, boolean autoIncr) { /* package */ SQLField(SQLType<T> type, boolean nullable, boolean autoIncr) {
this(t, nul, autoIncr, null); this(type, nullable, autoIncr, null);
} }
/* package */ SQLField(SQLType<T> t, boolean nul, T deflt) { /* package */ SQLField(SQLType<T> type, boolean nullable, T deflt) {
this(t, nul, false, deflt); this(type, nullable, false, deflt);
} }
/* package */ ParameterizedSQLString forSQLPreparedStatement() { /* package */ ParameterizedSQLString forSQLPreparedStatement() {
List<Object> params = new ArrayList<>(1); List<Object> params = new ArrayList<>(1);
if (defaultValue != null && !autoIncrement) params.add(defaultValue); if (defaultValue != null && !autoIncrement)
return new ParameterizedSQLString("`" + getName() + "` " + type.toString() + (canBeNull ? " NULL" : " NOT NULL") params.add(defaultValue);
+ (autoIncrement ? " AUTO_INCREMENT" : "") return new ParameterizedSQLString("`" + getName() + "` " + type.toString() + (nullable ? " NULL" : " NOT NULL")
+ ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), params); + (autoIncrement ? " AUTO_INCREMENT" : "")
} + ((defaultValue == null || autoIncrement) ? "" : " DEFAULT ?"), params);
}
/* package */ void setSQLElementType(Class<E> elemClass) { /* package */ void setSQLElementType(Class<E> elemClass) {
sqlElemClass = elemClass; sqlElemClass = elemClass;
} }
public Class<E> getSQLElementType() { /**
return sqlElemClass; * Gets the type representing the table containing this field.
} * @return the type representing the table containing this field.
*/
public Class<E> getSQLElementType() {
return sqlElemClass;
}
/* package */ void setName(String n) { // only for internal usage, the name determined after the name of the static field holding this instance.
name = n; /* package */ void setName(String n) {
} name = n;
}
public String getName() { /**
return name; * Gets the name of this field.
} * It is automatically determined by the name of the static field holding this instance.
* @return the name of this field.
*/
public String getName() {
return name;
}
/** /**
* <b>Don't use this {@code toString()} method in a SQL query, because * Gets the type of this field.
* the default value is not escaped correctly</b> * @return the type of this field.
* */
* @see java.lang.Object#toString() public SQLType<T> getType() {
*/ return type;
@Override }
public String toString() {
return forSQLPreparedStatement().sqlString().replaceFirst("\\?",
(defaultValue != null && !autoIncrement) ? defaultValue.toString() : "");
}
@Override /**
public boolean equals(Object obj) { * Tells if this field accepts null values.
return obj instanceof SQLField<?, ?> f * @return true if this field is {@code NULL}, false if its {@code NOT NULL}.
&& f.getName().equals(getName()) */
&& f.sqlElemClass.equals(sqlElemClass); public boolean isNullable() {
} return nullable;
}
@Override /**
public int hashCode() { * Tells if this field is auto incremented by the database on insertion.
return getName().hashCode() + sqlElemClass.hashCode(); * @return true if this field is {@code AUTO_INCREMENT}, false otherwise.
} */
public boolean isAutoIncrement() {
return autoIncrement;
}
/**
* Gets the default value of this field.
* @return the default value of this field, or null if there is none.
*/
public T getDefaultValue() {
return defaultValue;
}
/* Don't use this {@code toString()} method in a SQL query, because the default value is not escaped correctly. */
@Override
public String toString() {
return forSQLPreparedStatement().sqlString().replaceFirst("\\?",
(defaultValue != null && !autoIncrement) ? defaultValue.toString() : "");
}
@Override
public boolean equals(Object obj) {
return obj instanceof SQLField<?, ?> f
&& f.getName().equals(getName())
&& f.sqlElemClass.equals(sqlElemClass);
}
@Override
public int hashCode() {
return getName().hashCode() ^ sqlElemClass.hashCode();
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code =} operator.
* @param r the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> eq(T r) {
return comp(SQLComparator.EQ, r);
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code >=} operator.
* @param r the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> geq(T r) {
return comp(SQLComparator.GEQ, r);
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code >} operator.
* @param r the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> gt(T r) {
return comp(SQLComparator.GT, r);
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code <=} operator.
* @param r the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> leq(T r) {
return comp(SQLComparator.LEQ, r);
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code <} operator.
* @param r the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> lt(T r) {
return comp(SQLComparator.LT, r);
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code !=} operator.
* @param r the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> neq(T r) {
return comp(SQLComparator.NEQ, r);
}
private fr.pandacube.lib.db.SQLWhere<E> comp(SQLComparator c, T r) {
if (r == null)
throw new IllegalArgumentException("The value cannot be null. Use SQLField#isNull(value) or SQLField#isNotNull(value) to check for null values");
return new SQLWhereComp<>(this, c, r);
}
/**
* Create a SQL {@code WHERE} expression comparing this field with the provided value using the {@code LIKE}
* keyword.
* @param like the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> like(String like) {
return new SQLWhereLike<>(this, like);
}
/**
* Create a SQL {@code WHERE} expression testing the presence of this field in the provided collection of value
* using the {@code IN} keyword.
* @param v the value to compare with.
* @return a SQL {@code WHERE} expression.
*/
public fr.pandacube.lib.db.SQLWhere<E> in(Collection<T> v) {
return new SQLWhereIn<>(this, v);
}
public fr.pandacube.lib.db.SQLWhere<E> eq(T r) { /**
return comp(SQLComparator.EQ, r); * Create a SQL {@code WHERE} expression testing the nullity of this field using the {@code IS NULL} keyword.
} * @return a SQL {@code WHERE} expression.
public fr.pandacube.lib.db.SQLWhere<E> geq(T r) { */
return comp(SQLComparator.GEQ, r); public fr.pandacube.lib.db.SQLWhere<E> isNull() {
} return new SQLWhereNull<>(this, true);
public fr.pandacube.lib.db.SQLWhere<E> gt(T r) { }
return comp(SQLComparator.GT, r);
}
public fr.pandacube.lib.db.SQLWhere<E> leq(T r) {
return comp(SQLComparator.LEQ, r);
}
public fr.pandacube.lib.db.SQLWhere<E> lt(T r) {
return comp(SQLComparator.LT, r);
}
public fr.pandacube.lib.db.SQLWhere<E> neq(T r) {
return comp(SQLComparator.NEQ, r);
}
private fr.pandacube.lib.db.SQLWhere<E> comp(SQLComparator c, T r) { /**
if (r == null) * Create a SQL {@code WHERE} expression testing the non-nullity of this field using the {@code IS NOT NULL}
throw new IllegalArgumentException("The value cannot be null. Use SQLField#isNull(value) or SQLField#isNotNull(value) to check for null values"); * keyword.
return new SQLWhereComp<>(this, c, r); * @return a SQL {@code WHERE} expression.
} */
public fr.pandacube.lib.db.SQLWhere<E> isNotNull() {
return new SQLWhereNull<>(this, false);
public fr.pandacube.lib.db.SQLWhere<E> like(String like) { }
return new SQLWhereLike<>(this, like);
}
public fr.pandacube.lib.db.SQLWhere<E> in(Collection<T> v) {
return new SQLWhereIn<>(this, v);
}
public fr.pandacube.lib.db.SQLWhere<E> isNull() {
return new SQLWhereNull<>(this, true);
}
public fr.pandacube.lib.db.SQLWhere<E> isNotNull() {
return new SQLWhereNull<>(this, false);
}
} }

View File

@ -4,72 +4,74 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/**
* A SQL {@code ORDER BY} expression builder.
* @param <E> the table type.
*/
public class SQLOrderBy<E extends SQLElement<E>> { public class SQLOrderBy<E extends SQLElement<E>> {
private final List<OBField> orderByFields = new ArrayList<>(); /**
* Creates a new SQL {@code ORDER BY} expression builder with the provided field to sort in the ascending order.
* @param field le field to order.
* @return a new SQL {@code ORDER BY} expression builder.
* @param <E> the type of the table declaring the field.
*/
public static <E extends SQLElement<E>> SQLOrderBy<E> asc(SQLField<E, ?> field) {
return new SQLOrderBy<E>().thenAsc(field);
}
/** /**
* Construit une nouvelle clause ORDER BY * Creates a new SQL {@code ORDER BY} expression builder with the provided field to sort in the descending order.
*/ * @param field le field to order.
private SQLOrderBy() {} * @return a new SQL {@code ORDER BY} expression builder.
* @param <E> the type of the table declaring the field.
*/
public static <E extends SQLElement<E>> SQLOrderBy<E> desc(SQLField<E, ?> field) {
return new SQLOrderBy<E>().thenDesc(field);
}
/**
* Ajoute un champ dans la clause ORDER BY en construction
*
* @param field le champ SQL à ordonner
* @param d le sens de tri (croissant ASC ou décroissant DESC)
* @return l'objet courant (permet de chainer les ajouts de champs)
*/
private SQLOrderBy<E> add(SQLField<E, ?> field, Direction d) {
orderByFields.add(new OBField(field, d));
return this;
}
/**
* Ajoute un champ dans la clause ORDER BY en construction avec pour direction ASC
*
* @param field le champ SQL à ordonner
* @return l'objet courant (permet de chainer les ajouts de champs)
*/
public SQLOrderBy<E> thenAsc(SQLField<E, ?> field) {
return add(field, Direction.ASC);
}
/**
* Ajoute un champ dans la clause ORDER BY en construction avec pour direction DESC
*
* @param field le champ SQL à ordonner
* @return l'objet courant (permet de chainer les ajouts de champs)
*/
public SQLOrderBy<E> thenDesc(SQLField<E, ?> field) {
return add(field, Direction.DESC);
}
/* package */ String toSQL() {
return orderByFields.stream()
.map(f -> "`" + f.field.getName() + "` " + f.direction.name())
.collect(Collectors.joining(", "));
}
@Override
public String toString() {
return toSQL();
}
private class OBField { private final List<OBField<E>> orderByFields = new ArrayList<>();
public final SQLField<E, ?> field;
public final Direction direction;
public OBField(SQLField<E, ?> f, Direction d) { private SQLOrderBy() {}
field = f;
direction = d;
}
} private SQLOrderBy<E> add(SQLField<E, ?> field, Direction d) {
orderByFields.add(new OBField<>(field, d));
return this;
}
private enum Direction { /**
ASC, DESC * Adds the provided field to sort in the ascending order, in this {@code ORDER BY} expression builder.
} * @param field le field to order.
* @return this.
*/
public SQLOrderBy<E> thenAsc(SQLField<E, ?> field) {
return add(field, Direction.ASC);
}
/**
* Adds the provided field to sort in the descending order, in this {@code ORDER BY} expression builder.
* @param field le field to order.
* @return this.
*/
public SQLOrderBy<E> thenDesc(SQLField<E, ?> field) {
return add(field, Direction.DESC);
}
/* package */ String toSQL() {
return orderByFields.stream()
.map(f -> "`" + f.field.getName() + "` " + f.direction.name())
.collect(Collectors.joining(", "));
}
@Override
public String toString() {
return toSQL();
}
@ -79,15 +81,13 @@ public class SQLOrderBy<E extends SQLElement<E>> {
public static <E extends SQLElement<E>> SQLOrderBy<E> asc(SQLField<E, ?> field) {
return new SQLOrderBy<E>().thenAsc(field);
}
public static <E extends SQLElement<E>> SQLOrderBy<E> desc(SQLField<E, ?> field) {
return new SQLOrderBy<E>().thenDesc(field);
}
private record OBField<E extends SQLElement<E>>(SQLField<E, ?> field, Direction direction) { }
private enum Direction {
ASC, DESC
}
} }

View File

@ -1,38 +1,58 @@
package fr.pandacube.lib.db; package fr.pandacube.lib.db;
/**
* Represents a SQL type.
* <p>
* The most common types are already declared as static values in {@link SQLElement} class.
* @param <T> the Java type.
*/
public class SQLType<T> { public class SQLType<T> {
protected final String sqlDeclaration; /* package */ final String sqlDeclaration;
private final Class<T> javaTypes; private final Class<T> javaTypes;
/* package */ SQLType(String sqlD, Class<T> javaT) { /**
sqlDeclaration = sqlD; * Create a new type.
javaTypes = javaT; * @param sqlD the name of the data type in SQL (like {@code "BIGINT"} or {@code "CHAR(16)"}).
} * @param javaT the corresponding java type.
*/
public SQLType(String sqlD, Class<T> javaT) {
sqlDeclaration = sqlD;
javaTypes = javaT;
}
@Override @Override
public String toString() { public String toString() {
return sqlDeclaration; return sqlDeclaration;
} }
public boolean isInstance(Object val) { /**
return javaTypes.isInstance(val); * Check if the provided object can be used as a possible value for this type.
} * @param val the objet to check.
* @return true if the provided object can be used as a possible value for this type, false otherwise.
*/
public boolean isInstance(Object val) {
return javaTypes.isInstance(val);
}
@Override @Override
public int hashCode() { public int hashCode() {
return toString().hashCode(); return toString().hashCode();
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
return obj instanceof SQLType o return obj instanceof SQLType o
&& toString().equals(o.toString()); && toString().equals(o.toString());
} }
public Class<T> getJavaType() { /**
return javaTypes; * Gets the corresponding Java type of this type.
} * @return the corresponding Java type of this type.
*/
public Class<T> getJavaType() {
return javaTypes;
}
} }

View File

@ -1,68 +0,0 @@
package fr.pandacube.lib.db;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import fr.pandacube.lib.util.Log;
public class SQLUpdate<E extends SQLElement<E>> {
private final Class<E> elemClass;
private final SQLWhere<E> where;
private final Map<SQLField<E, ?>, Object> values;
/* package */ SQLUpdate(Class<E> el, SQLWhere<E> w) {
elemClass = el;
where = w;
values = new HashMap<>();
}
/* package */ SQLUpdate(Class<E> el, SQLWhere<E> w, Map<SQLField<E, ?>, Object> v) {
elemClass = el;
where = w;
values = v;
}
public <T> SQLUpdate<E> set(SQLField<E, T> field, T value) {
values.put(field, value);
return this;
}
public SQLUpdate<E> setUnsafe(SQLField<E, ?> field, Object value) {
values.put(field, value);
return this;
}
public int execute() throws DBException {
if (values.isEmpty()) {
Log.warning(new DBException("Trying to do an UPDATE with no values to SET. Query aborted."));
return 0;
}
StringBuilder sql = new StringBuilder("UPDATE " + DB.getTableName(elemClass) + " SET ");
List<Object> params = new ArrayList<>();
boolean first = true;
for (Map.Entry<SQLField<E, ?>, Object> entry : values.entrySet()) {
if (!first)
sql.append(", ");
sql.append("`").append(entry.getKey().getName()).append("` = ? ");
SQLElement.addValueToSQLObjectList(params, entry.getKey(), entry.getValue());
first = false;
}
if (where != null) {
ParameterizedSQLString ret = where.toSQL();
sql.append(" WHERE ").append(ret.sqlString());
params.addAll(ret.parameters());
}
sql.append(";");
return DB.customUpdateStatement(sql.toString(), params);
}
}

View File

@ -0,0 +1,92 @@
package fr.pandacube.lib.db;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import fr.pandacube.lib.util.Log;
/**
* Builder for a SQL {@code UPDATE} query.
* @param <E> the type of te table affected by this update.
*/
public class SQLUpdateBuilder<E extends SQLElement<E>> {
private final Class<E> elemClass;
private final SQLWhere<E> where;
private final Map<SQLField<E, ?>, Object> values;
/* package */ SQLUpdateBuilder(Class<E> el, SQLWhere<E> w) {
elemClass = el;
where = w;
values = new HashMap<>();
}
/* package */ SQLUpdateBuilder(Class<E> el, SQLWhere<E> w, Map<SQLField<E, ?>, Object> v) {
elemClass = el;
where = w;
values = v;
}
/**
* Sets the value for the specified field.
* @param field the field to set.
* @param value the value to put in the field.
* @return this.
* @param <T> the type of the value
*/
public <T> SQLUpdateBuilder<E> set(SQLField<E, T> field, T value) {
values.put(field, value);
return this;
}
/**
* Sets the value for the specified field, without statically checking the value type.
* This method is not safe to use. Use {@link #set(SQLField, Object)} instead when possible.
* @param field the field to set.
* @param value the value to put in the field.
* @return this.
*/
public SQLUpdateBuilder<E> setUnsafe(SQLField<E, ?> field, Object value) {
values.put(field, value);
return this;
}
/**
* Executes the SQL {@code UPDATE} query.
* @return the value returned by {@link PreparedStatement#executeUpdate()}.
* @throws DBException if an error occurs when interacting with the database.
*/
public int execute() throws DBException {
if (values.isEmpty()) {
Log.warning(new DBException("Trying to do an UPDATE with no values to SET. Query aborted."));
return 0;
}
StringBuilder sql = new StringBuilder("UPDATE " + DB.getTableName(elemClass) + " SET ");
List<Object> params = new ArrayList<>();
boolean first = true;
for (Map.Entry<SQLField<E, ?>, Object> entry : values.entrySet()) {
if (!first)
sql.append(", ");
sql.append("`").append(entry.getKey().getName()).append("` = ? ");
SQLElement.addValueToSQLObjectList(params, entry.getKey(), entry.getValue());
first = false;
}
if (where != null) {
ParameterizedSQLString ret = where.toSQL();
sql.append(" WHERE ").append(ret.sqlString());
params.addAll(ret.parameters());
}
sql.append(";");
return DB.customUpdateStatement(sql.toString(), params);
}
}

View File

@ -6,236 +6,299 @@ import java.util.List;
import fr.pandacube.lib.util.Log; import fr.pandacube.lib.util.Log;
/**
* A SQL {@code WHERE} expression.
* @param <E> the table type.
*/
public abstract class SQLWhere<E extends SQLElement<E>> { public abstract class SQLWhere<E extends SQLElement<E>> {
public abstract ParameterizedSQLString toSQL() throws DBException; /* package */ abstract ParameterizedSQLString toSQL() throws DBException;
@Override
public String toString() {
try {
return toSQL().sqlString();
} catch (DBException e) {
Log.warning(e);
return "[SQLWhere.toString() error (see logs)]";
}
}
/**
* Create a SQL {@code WHERE} expression that is true when this expression {@code AND} the provided expression is
* true.
* @param other the other expression.
* @return a SQL {@code WHERE} expression.
*/
public SQLWhere<E> and(SQLWhere<E> other) {
return SQLWhere.<E>and().and(this).and(other);
}
/**
* Create a SQL {@code WHERE} expression that is true when this expression {@code OR} the provided expression is
* true.
* @param other the other expression.
* @return a SQL {@code WHERE} expression.
*/
public SQLWhere<E> or(SQLWhere<E> other) {
return SQLWhere.<E>or().or(this).or(other);
}
/**
* Create a SQL {@code WHERE} expression builder joining multiple expressions with the {@code AND} operator.
* @return a SQL {@code WHERE} expression.
* @param <E> the table type.
*/
public static <E extends SQLElement<E>> SQLWhereAndBuilder<E> and() {
return new SQLWhereAndBuilder<>();
}
/**
* Create a SQL {@code WHERE} expression builder joining multiple expressions with the {@code OR} operator.
* @return a SQL {@code WHERE} expression.
* @param <E> the table type.
*/
public static <E extends SQLElement<E>> SQLWhereOrBuilder<E> or() {
return new SQLWhereOrBuilder<>();
}
@Override
public String toString() {
try {
return toSQL().sqlString();
} catch (DBException e) {
Log.warning(e);
return "[SQLWhere.toString() error (see logs)]";
}
}
public SQLWhereAnd<E> and(SQLWhere<E> other) { /**
return new SQLWhereAnd<E>().and(this).and(other); * A SQL {@code WHERE} expression builder joining multiple expressions with the {@code AND} or {@code OR} operator.
} * @param <E> the table type.
*/
public static abstract class SQLWhereChainBuilder<E extends SQLElement<E>> extends SQLWhere<E> {
public SQLWhereOr<E> or(SQLWhere<E> other) { private final SQLBoolOp operator;
return new SQLWhereOr<E>().or(this).or(other); private final List<SQLWhere<E>> conditions = new ArrayList<>();
}
public static <E extends SQLElement<E>> SQLWhereAnd<E> and() { private SQLWhereChainBuilder(SQLBoolOp op) {
return new SQLWhereAnd<>(); if (op == null) throw new IllegalArgumentException("op can't be null");
} operator = op;
}
public static <E extends SQLElement<E>> SQLWhereOr<E> or() { /* package */ void add(SQLWhere<E> sqlWhere) {
return new SQLWhereOr<>(); if (sqlWhere == null) throw new IllegalArgumentException("sqlWhere can't be null");
} conditions.add(sqlWhere);
}
public static String escapeLike(String str) { /**
return str.replace("\\", "\\\\").replace("_", "\\_").replace("%", "\\%"); * Tells if this expression builder is empty.
} * The builder must not be empty
* @return true if this expression builder is empty, false otherwise.
*/
public boolean isEmpty() {
return conditions.isEmpty();
}
@Override
/* package */ ParameterizedSQLString toSQL() throws DBException {
if (conditions.isEmpty()) {
throw new DBException("SQLWhereChainBuilder needs at least one element inside !");
}
StringBuilder sql = new StringBuilder();
List<Object> params = new ArrayList<>();
boolean first = true;
for (SQLWhere<E> w : conditions) {
if (!first)
sql.append(" ").append(operator.sql).append(" ");
first = false;
ParameterizedSQLString ret = w.toSQL();
sql.append("(").append(ret.sqlString()).append(")");
params.addAll(ret.parameters());
}
return new ParameterizedSQLString(sql.toString(), params);
}
/* package */ enum SQLBoolOp {
/** Equivalent to SQL {@code "AND"}. */
AND("AND"),
/** Equivalent to SQL {@code "OR"}. */
OR("OR");
/* package */ final String sql;
SQLBoolOp(String s) {
sql = s;
}
public static abstract class SQLWhereChain<E extends SQLElement<E>> extends SQLWhere<E> { }
private final SQLBoolOp operator; }
private final List<SQLWhere<E>> conditions = new ArrayList<>();
private SQLWhereChain(SQLBoolOp op) {
if (op == null) throw new IllegalArgumentException("op can't be null");
operator = op;
}
protected void add(SQLWhere<E> sqlWhere) {
if (sqlWhere == null) throw new IllegalArgumentException("sqlWhere can't be null");
conditions.add(sqlWhere);
}
public boolean isEmpty() {
return conditions.isEmpty();
}
@Override
public ParameterizedSQLString toSQL() throws DBException {
if (conditions.isEmpty()) {
throw new DBException("SQLWhereChain needs at least one element inside !");
}
StringBuilder sql = new StringBuilder();
List<Object> params = new ArrayList<>();
boolean first = true;
for (SQLWhere<E> w : conditions) {
if (!first)
sql.append(" ").append(operator.sql).append(" ");
first = false;
ParameterizedSQLString ret = w.toSQL();
sql.append("(").append(ret.sqlString()).append(")");
params.addAll(ret.parameters());
}
return new ParameterizedSQLString(sql.toString(), params); /**
} * A SQL {@code WHERE} expression builder joining multiple expressions with the {@code AND} operator.
* @param <E> the table type.
*/
public static class SQLWhereAndBuilder<E extends SQLElement<E>> extends SQLWhereChainBuilder<E> {
protected enum SQLBoolOp { private SQLWhereAndBuilder() {
/** Equivalent to SQL "<code>AND</code>" */ super(SQLBoolOp.AND);
AND("AND"), }
/** Equivalent to SQL "<code>OR</code>" */
OR("OR");
/* package */ final String sql;
SQLBoolOp(String s) { @Override
sql = s; public SQLWhereAndBuilder<E> and(SQLWhere<E> other) {
} add(other);
return this;
}
} }
}
/**
* A SQL {@code WHERE} expression builder joining multiple expressions with the {@code OR} operator.
* @param <E> the table type.
*/
public static class SQLWhereOrBuilder<E extends SQLElement<E>> extends SQLWhereChainBuilder<E> {
private SQLWhereOrBuilder() {
super(SQLBoolOp.OR);
}
@Override
public SQLWhereOrBuilder<E> or(SQLWhere<E> other) {
add(other);
return this;
}
public static class SQLWhereAnd<E extends SQLElement<E>> extends SQLWhereChain<E> { }
private SQLWhereAnd() {
super(SQLBoolOp.AND);
}
@Override
public SQLWhereAnd<E> and(SQLWhere<E> other) {
add(other);
return this;
}
}
/* package */ static class SQLWhereComp<E extends SQLElement<E>> extends SQLWhere<E> {
private final SQLField<E, ?> left;
private final SQLComparator comp;
private final Object right;
/**
* Compare a field with a value.
*
* @param l the field at left of the comparison operator. Can't be null
* @param c the comparison operator, can't be null
* @param r the value at right of the comparison operator. Can't be null
*/
/* package */ <T> SQLWhereComp(SQLField<E, T> l, SQLComparator c, T r) {
if (l == null || r == null || c == null)
throw new IllegalArgumentException("All arguments for SQLWhereComp constructor can't be null");
left = l;
comp = c;
right = r;
}
public static class SQLWhereOr<E extends SQLElement<E>> extends SQLWhereChain<E> { @Override
/* package */ ParameterizedSQLString toSQL() throws DBException {
List<Object> params = new ArrayList<>();
SQLElement.addValueToSQLObjectList(params, left, right);
return new ParameterizedSQLString("`" + left.getName() + "` " + comp.sql + " ? ", params);
}
private SQLWhereOr() { /* package */ enum SQLComparator {
super(SQLBoolOp.OR); /** Equivalent to SQL {@code "="}. */
} EQ("="),
/** Equivalent to SQL {@code ">"}. */
GT(">"),
/** Equivalent to SQL {@code ">="}. */
GEQ(">="),
/** Equivalent to SQL {@code "<"}. */
LT("<"),
/** Equivalent to SQL {@code "<="}. */
LEQ("<="),
/** Equivalent to SQL {@code "!="}. */
NEQ("!=");
@Override /* package */ final String sql;
public SQLWhereOr<E> or(SQLWhere<E> other) {
add(other);
return this;
}
} SQLComparator(String s) {
sql = s;
}
}
}
/* package */ static class SQLWhereComp<E extends SQLElement<E>> extends SQLWhere<E> {
private final SQLField<E, ?> left;
private final SQLComparator comp;
private final Object right;
/** /* package */ static class SQLWhereIn<E extends SQLElement<E>> extends SQLWhere<E> {
* Compare a field with a value
*
* @param l the field at left of the comparison operator. Can't be null
* @param c the comparison operator, can't be null
* @param r the value at right of the comparison operator. Can't be null
*/
/* package */ <T> SQLWhereComp(SQLField<E, T> l, SQLComparator c, T r) {
if (l == null || r == null || c == null)
throw new IllegalArgumentException("All arguments for SQLWhereComp constructor can't be null");
left = l;
comp = c;
right = r;
}
@Override private final SQLField<E, ?> field;
public ParameterizedSQLString toSQL() throws DBException { private final Collection<?> values;
List<Object> params = new ArrayList<>();
SQLElement.addValueToSQLObjectList(params, left, right);
return new ParameterizedSQLString("`" + left.getName() + "` " + comp.sql + " ? ", params);
}
/* package */ enum SQLComparator { /* package */ <T> SQLWhereIn(SQLField<E, T> f, Collection<T> v) {
/** Equivalent to SQL "<code>=</code>" */ if (f == null || v == null)
EQ("="), throw new IllegalArgumentException("All arguments for SQLWhereIn constructor can't be null");
/** Equivalent to SQL "<code>></code>" */ field = f;
GT(">"), values = v;
/** Equivalent to SQL "<code>>=</code>" */ }
GEQ(">="),
/** Equivalent to SQL "<code>&lt;</code>" */
LT("<"),
/** Equivalent to SQL "<code>&lt;=</code>" */
LEQ("<="),
/** Equivalent to SQL "<code>!=</code>" */
NEQ("!=");
/* package */ final String sql; @Override
/* package */ ParameterizedSQLString toSQL() throws DBException {
List<Object> params = new ArrayList<>();
SQLComparator(String s) { if (values.isEmpty())
sql = s; return new ParameterizedSQLString(" 1=0 ", params);
}
} for (Object v : values)
SQLElement.addValueToSQLObjectList(params, field, v);
} char[] questions = new char[values.size() == 0 ? 0 : (values.size() * 2 - 1)];
for (int i = 0; i < questions.length; i++)
questions[i] = i % 2 == 0 ? '?' : ',';
return new ParameterizedSQLString("`" + field.getName() + "` IN (" + new String(questions) + ") ", params);
}
}
/* package */ static class SQLWhereIn<E extends SQLElement<E>> extends SQLWhere<E> {
private final SQLField<E, ?> field;
private final Collection<?> values;
/* package */ <T> SQLWhereIn(SQLField<E, T> f, Collection<T> v) {
if (f == null || v == null)
throw new IllegalArgumentException("All arguments for SQLWhereIn constructor can't be null");
field = f;
values = v;
}
@Override
public ParameterizedSQLString toSQL() throws DBException {
List<Object> params = new ArrayList<>();
if (values.isEmpty()) /* package */ static class SQLWhereLike<E extends SQLElement<E>> extends SQLWhere<E> {
return new ParameterizedSQLString(" 1=0 ", params);
for (Object v : values) private final SQLField<E, ?> field;
SQLElement.addValueToSQLObjectList(params, field, v); private final String likeExpr;
char[] questions = new char[values.size() == 0 ? 0 : (values.size() * 2 - 1)]; /* package */ SQLWhereLike(SQLField<E, ?> f, String like) {
for (int i = 0; i < questions.length; i++) if (f == null || like == null)
questions[i] = i % 2 == 0 ? '?' : ','; throw new IllegalArgumentException("All arguments for SQLWhereLike constructor can't be null");
field = f;
likeExpr = like;
}
return new ParameterizedSQLString("`" + field.getName() + "` IN (" + new String(questions) + ") ", params); @Override
} /* package */ ParameterizedSQLString toSQL() {
ArrayList<Object> params = new ArrayList<>();
params.add(likeExpr);
return new ParameterizedSQLString("`" + field.getName() + "` LIKE ? ", params);
}
} }
@ -243,33 +306,28 @@ public abstract class SQLWhere<E extends SQLElement<E>> {
/* package */ static class SQLWhereNull<E extends SQLElement<E>> extends SQLWhere<E> {
/* package */ static class SQLWhereLike<E extends SQLElement<E>> extends SQLWhere<E> { private final SQLField<E, ?> field;
private final boolean isNull;
private final SQLField<E, ?> field; /* package */ SQLWhereNull(SQLField<E, ?> field, boolean isNull) {
private final String likeExpr; if (field == null)
throw new IllegalArgumentException("field can't be null");
if (!field.nullable)
Log.warning("Useless : Trying to check IS [NOT] NULL on the field " + field.getSQLElementType().getName()
+ "#" + field.getName() + " which is declared in the ORM as 'can't be null'");
this.field = field;
this.isNull = isNull;
}
/** @Override
* Compare a field with a value /* package */ ParameterizedSQLString toSQL() {
* return new ParameterizedSQLString("`" + field.getName() + "` IS " + ((isNull) ? "NULL" : "NOT NULL"), new ArrayList<>());
* @param f the field at left of the LIKE keyword. Can't be null }
* @param like the like expression.
*/
/* package */ SQLWhereLike(SQLField<E, ?> f, String like) {
if (f == null || like == null)
throw new IllegalArgumentException("All arguments for SQLWhereLike constructor can't be null");
field = f;
likeExpr = like;
}
@Override }
public ParameterizedSQLString toSQL() {
ArrayList<Object> params = new ArrayList<>();
params.add(likeExpr);
return new ParameterizedSQLString("`" + field.getName() + "` LIKE ? ", params);
}
}
@ -277,33 +335,16 @@ public abstract class SQLWhere<E extends SQLElement<E>> {
/* package */ static class SQLWhereNull<E extends SQLElement<E>> extends SQLWhere<E> {
private final SQLField<E, ?> field; /**
private final boolean isNull; * Escapes the {@code \}, {@code _} and {@code %} in the string to be used in a {@code WHERE ... LIKE} expression.
* @param str the string to escape.
/** * @return the escaped string.
* Init a IS NULL / IS NOT NULL expression for a SQL WHERE condition. */
* public static String escapeLike(String str) {
* @param field the field to check null / not null state return str.replace("\\", "\\\\")
* @param isNull true if we want to ckeck if "IS NULL", or false to check if .replace("_", "\\_")
* "IS NOT NULL" .replace("%", "\\%");
*/ }
/* package */ SQLWhereNull(SQLField<E, ?> field, boolean isNull) {
if (field == null)
throw new IllegalArgumentException("field can't be null");
if (!field.canBeNull)
Log.warning("Useless : Trying to check IS [NOT] NULL on the field " + field.getSQLElementType().getName()
+ "#" + field.getName() + " which is declared in the ORM as 'can't be null'");
this.field = field;
this.isNull = isNull;
}
@Override
public ParameterizedSQLString toSQL() {
return new ParameterizedSQLString("`" + field.getName() + "` IS " + ((isNull) ? "NULL" : "NOT NULL"), new ArrayList<>());
}
}
} }