Add SQLite to devlok-databases

This commit is contained in:
Weapie 2024-07-08 16:20:10 +02:00
parent aa50c7a2bc
commit 8b557b40c3
9 changed files with 389 additions and 18 deletions

1
.gitignore vendored
View File

@ -45,3 +45,4 @@ bin/
### Weapie ### ### Weapie ###
/**/config /**/config
/**/src/test /**/src/test
/**/tmp

View File

@ -1,6 +1,9 @@
dependencies { dependencies {
implementation(libs.mongodb) implementation(libs.mongodb)
implementation(libs.mysql) implementation(libs.mysql)
implementation("org.xerial:sqlite-jdbc:3.46.0.0")
compileOnly(libs.gson) compileOnly(libs.gson)
api(project(":devlok-utils")) api(project(":devlok-utils"))
api(project(":devlok-files")) api(project(":devlok-files"))

View File

@ -3,9 +3,11 @@ package de.weapie.devlok.database;
import de.weapie.devlok.database.config.DatabaseConfig; import de.weapie.devlok.database.config.DatabaseConfig;
import de.weapie.devlok.database.config.DatabaseType; import de.weapie.devlok.database.config.DatabaseType;
import de.weapie.devlok.database.config.module.MongoDBAuthenticationModule; import de.weapie.devlok.database.config.module.MongoDBAuthenticationModule;
import de.weapie.devlok.database.config.module.SQLiteAuthenticationModule;
import de.weapie.devlok.database.config.module.MySQLAuthenticationModule; import de.weapie.devlok.database.config.module.MySQLAuthenticationModule;
import de.weapie.devlok.database.mongodb.MongoDBDatabase; import de.weapie.devlok.database.mongodb.MongoDBDatabase;
import de.weapie.devlok.database.mysql.MySQLDatabase; import de.weapie.devlok.database.mysql.MySQLDatabase;
import de.weapie.devlok.database.sqlite.SQLiteDatabase;
import de.weapie.devlok.database.utils.BasicDatabase; import de.weapie.devlok.database.utils.BasicDatabase;
import de.weapie.devlok.files.config.DevlokConfig; import de.weapie.devlok.files.config.DevlokConfig;
import lombok.Getter; import lombok.Getter;
@ -15,23 +17,25 @@ public class Database {
private static DevlokConfig.Builder<DatabaseConfig> databaseConfigBuilder = DevlokConfig private static DevlokConfig.Builder<DatabaseConfig> databaseConfigBuilder = DevlokConfig
.builder(DatabaseConfig.class) .builder(DatabaseConfig.class)
.withDefault(() -> .withDefault(() ->
new DatabaseConfig( new DatabaseConfig(
DatabaseType.MONGODB, DatabaseType.MONGODB,
new MySQLAuthenticationModule( new MySQLAuthenticationModule(
"127.0.0.1", "127.0.0.1",
3306, 3306,
"database", "database",
"root", "root",
"password" "password"
), new MongoDBAuthenticationModule( ), new MongoDBAuthenticationModule(
"127.0.0.1", "127.0.0.1",
27017, 27017,
"database", "database",
"root", "root",
"password", "password",
"admin" "admin"
) ), new SQLiteAuthenticationModule(
"/tmp/sqlite.db"
) )
)
); );
private static DevlokConfig<DatabaseConfig> databaseConfig = null; private static DevlokConfig<DatabaseConfig> databaseConfig = null;
@ -46,6 +50,9 @@ public class Database {
databaseConfig.read(); databaseConfig.read();
switch (databaseConfig.value().getType()) { switch (databaseConfig.value().getType()) {
case SQLITE -> database = new SQLiteDatabase(
databaseConfig.value().getSqlite().getFile()
);
case MYSQL -> database = new MySQLDatabase( case MYSQL -> database = new MySQLDatabase(
databaseConfig.value().getMySQL().getHost(), databaseConfig.value().getMySQL().getHost(),
databaseConfig.value().getMySQL().getPort(), databaseConfig.value().getMySQL().getPort(),

View File

@ -1,7 +1,7 @@
package de.weapie.devlok.database.config; package de.weapie.devlok.database.config;
import de.weapie.devlok.database.config.module.BasicAuthenticationModule;
import de.weapie.devlok.database.config.module.MongoDBAuthenticationModule; import de.weapie.devlok.database.config.module.MongoDBAuthenticationModule;
import de.weapie.devlok.database.config.module.SQLiteAuthenticationModule;
import de.weapie.devlok.database.config.module.MySQLAuthenticationModule; import de.weapie.devlok.database.config.module.MySQLAuthenticationModule;
import de.weapie.devlok.files.config.annotations.Config; import de.weapie.devlok.files.config.annotations.Config;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@ -18,5 +18,6 @@ public class DatabaseConfig {
private DatabaseType type; private DatabaseType type;
private MySQLAuthenticationModule mySQL; private MySQLAuthenticationModule mySQL;
private MongoDBAuthenticationModule mongoDB; private MongoDBAuthenticationModule mongoDB;
private SQLiteAuthenticationModule sqlite;
} }

View File

@ -1,6 +1,7 @@
package de.weapie.devlok.database.config; package de.weapie.devlok.database.config;
public enum DatabaseType { public enum DatabaseType {
SQLITE,
MYSQL, MYSQL,
MONGODB; MONGODB;
} }

View File

@ -51,7 +51,7 @@ public class MySQLDatabase extends BasicDatabase {
} }
this.autoReconnect = new AutoReconnect(); this.autoReconnect = new AutoReconnect();
//this.autoReconnect.start(); this.autoReconnect.start();
} }
@Override @Override

View File

@ -0,0 +1,104 @@
package de.weapie.devlok.database.sqlite;
import de.weapie.devlok.database.utils.AutoReconnect;
import de.weapie.devlok.database.utils.BasicDatabase;
import lombok.Getter;
import lombok.SneakyThrows;
import java.io.File;
import java.sql.*;
public class SQLiteDatabase extends BasicDatabase {
@Getter
private Connection connection;
public SQLiteDatabase(String file) {
super(null, 0, null, null, null, null, file);
service = new SQLiteService();
}
@Override
public String getDataSourceName() {
return "jdbc:sqlite:" + this.file;
}
@Override
public boolean isConnected() {
try {
return this.connection != null || this.connection.isValid(1);
} catch (SQLException e) {
return false;
}
}
@Override
public void connect() {
try {
Class.forName("org.sqlite.JDBC");
String dataSourceName = this.getDataSourceName();
System.out.println(dataSourceName);
this.connection = DriverManager.getConnection(dataSourceName);
System.out.println("Successfully connected to SQLite database");
} catch (SQLException | ClassNotFoundException e) {
System.err.println("Unable to connect to SQLite database: " + e.getMessage());
e.printStackTrace();
}
}
@Override
public void disconnect() {
try {
if (this.connection != null) {
this.connection.close();
System.out.println("Successfully disconnected to SQLite database");
}
} catch (SQLException e) {
System.err.println("Error while closing the connection: " + e.getMessage());
}
}
public void update(String qry) {
try {
Statement st = this.connection.createStatement();
st.executeUpdate(qry);
st.close();
} catch (SQLException e) {
connect();
System.err.println(e);
}
}
public ResultSet query(PreparedStatement pst) {
ResultSet rs = null;
try {
rs = pst.executeQuery();
rs.close();
} catch (SQLException e) {
System.err.println(e);
}
return rs;
}
}

View File

@ -0,0 +1,235 @@
package de.weapie.devlok.database.sqlite;
import com.mongodb.client.MongoCollection;
import de.weapie.devlok.database.Database;
import de.weapie.devlok.database.utils.BasicService;
import de.weapie.devlok.utils.data.Pair;
import org.bson.Document;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class SQLiteService implements BasicService {
public SQLiteDatabase database() {
return (SQLiteDatabase) Database.getDatabase();
}
@Deprecated
@Override
public MongoCollection<Document> collection(String collection) { return null; }
@Override
public void table(String collection, Document document) {
if(!this.database().isConnected()) return;
if(!this.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='" + collection + "';").isEmpty()) return;
this.execute("CREATE TABLE " + collection + " (" + this.buildString(document, " ", ", ", "") + ");");
}
@Override
public void insert(String collection, Document document) {
if(!this.database().isConnected()) return;
int i = 0;
AtomicReference<String> resultString = new AtomicReference<>("INSERT INTO " + collection + " (");
AtomicReference<String> keyString = new AtomicReference<>("");
AtomicReference<String> valueString = new AtomicReference<>("");
for(String key : document.keySet()) {
Object value = document.get(key);
if(i == document.size() - 1) {
keyString.set(keyString.get() + key);
valueString.set(valueString.get() + "'" + value + "'");
continue;
}
i++;
keyString.set(keyString.get() + key + ", ");
valueString.set(valueString.get() + "'" + value + "', ");
}
resultString.set(resultString.get() + keyString.get() + ") VALUES (");
resultString.set(resultString.get() + valueString.get() + ");");
this.execute(resultString.get());
}
@Override
public void insertMany(String collection, List<Document> documents) {
if(!this.database().isConnected()) return;
documents.forEach(document -> this.insert(collection, document));
}
@Override
public long count(String collection) {
if(!this.database().isConnected()) return 0;
List<Document> documents = this.executeQuery("SELECT COUNT(*) FROM " + collection + ";");
return (long) documents.get(0).get("COUNT(*)");
}
@Override
public Document findFirst(String collection) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " LIMIT 1;");
return documents.get(0);
}
@Override
public Document findOne(String collection, Document filter) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " WHERE " + this.buildString(filter, " = ", " AND ", "'") + " LIMIT 1;");
return !documents.isEmpty() ? documents.get(0) : null;
}
@Override
public List<Document> findMany(String collection, Document filter) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " WHERE " + this.buildString(filter, " = ", " AND ", "'") + ";");
return !documents.isEmpty() ? documents : new ArrayList<>();
}
@Override
public List<Document> findAll(String collection) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + ";");
return !documents.isEmpty() ? documents : new ArrayList<>();
}
@Override
public boolean exist(String collection, Document filter) {
if(!this.database().isConnected()) return false;
return this.findOne(collection, filter) != null;
}
@Override
public void update(String collection, Document filter, Document update) {
if(!this.database().isConnected()) return;
this.execute("UPDATE " + collection + " SET " + this.buildString(update, " = ", ", ", "'") + " WHERE " + this.buildString(filter, " = ", ", ", "'") + ";");
}
@Override
public void replace(String collection, Document filter, Document replace) {
if(!this.database().isConnected()) return;
this.update(collection, filter, replace);
}
@Override
public void deleteOne(String collection, Document filter) {
if(!this.database().isConnected()) return;
this.execute("DELETE FROM " + collection + " WHERE " + this.buildString(filter, " = ", " AND ", "'") + ";");
}
@Override
public void deleteMany(String collection, Document filter) {
if(!this.database().isConnected()) return;
this.deleteOne(collection, filter);
}
@Override
public void deleteAll(String collection) {
if(!this.database().isConnected()) return;
this.findAll(collection).forEach(document -> this.deleteOne(collection, document));
}
@Override
public List<Document> top(String collection, int maxPlace, String fieldName) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " ORDER BY " + fieldName + " DESC LIMIT " + maxPlace + ";");
return !documents.isEmpty() ? documents : new ArrayList<>();
}
@Override
public long position(String collection, Pair<String, Object> filterPair, String fieldName) {
if(!this.database().isConnected()) return -1;
List<Document> documents = this.executeQuery("SELECT " + filterPair.getKey() + ", FIND_IN_SET(" + fieldName + ", (SELECT GROUP_CONCAT(" + fieldName + " ORDER BY " + fieldName + " DESC) FROM " + collection + ")) AS ranking FROM " + collection + " WHERE " + filterPair.getKey() + " = '" + filterPair.getValue() + "';");
return !documents.isEmpty() ? documents.get(0).getLong("ranking") : -1;
}
private void execute(String sql) {
Statement statement = null;
try {
statement = this.database().getConnection().createStatement();
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private List<Document> executeQuery(String sql) {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = this.database().getConnection().createStatement();
resultSet = statement.executeQuery(sql);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
List<Document> documents = new ArrayList<>();
while(resultSet.next()) {
int i = 1;
boolean bound = true;
Document document = new Document();
while(bound) {
try {
document.append(resultSetMetaData.getColumnName(i), resultSet.getObject(i));
} catch (SQLException ex) {
bound = false;
}
i++;
}
documents.add(document);
}
return documents;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
if(statement != null) {
try {
statement.close();
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private String buildString(Document document, String separator, String between, String aroundValue) {
int i = 0;
AtomicReference<String> resultString = new AtomicReference<>("");
for(String key : document.keySet()) {
Object value = document.get(key);
if(i == document.size() - 1) {
resultString.set(resultString.get() + key + separator + aroundValue + value + aroundValue);
continue;
}
i++;
resultString.set(resultString.get() + key + separator + aroundValue + value + aroundValue + between);
}
return resultString.get();
}
}

View File

@ -1,7 +1,9 @@
package de.weapie.devlok.database.utils; package de.weapie.devlok.database.utils;
import lombok.Getter; import lombok.Getter;
import lombok.SneakyThrows;
import java.io.File;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -13,6 +15,7 @@ public abstract class BasicDatabase {
protected String user; protected String user;
protected String password; protected String password;
protected String authDatabase; protected String authDatabase;
protected String file;
@Getter @Getter
protected BasicService service; protected BasicService service;
@ -25,12 +28,28 @@ public abstract class BasicDatabase {
} }
public BasicDatabase(String host, int port, String database, String user, String password, String authDatabase) { public BasicDatabase(String host, int port, String database, String user, String password, String authDatabase) {
this(host, port, database, user, password, authDatabase, null);
}
@SneakyThrows
public BasicDatabase(String host, int port, String database, String user, String password, String authDatabase, String file) {
this.host = host; this.host = host;
this.port = port; this.port = port;
this.database = database; this.database = database;
this.user = user; this.user = user;
this.password = password; this.password = password;
this.authDatabase = authDatabase; this.authDatabase = authDatabase;
this.file = file;
if(this.file != null) {
File dbFile = new File(this.file);
if(!dbFile.getParentFile().exists()) {
dbFile.getParentFile().mkdirs();
}
if(!dbFile.exists()) {
dbFile.createNewFile();
}
}
this.pool = Executors.newCachedThreadPool(); this.pool = Executors.newCachedThreadPool();