diff --git a/core/src/main/resources/config.yml b/.doc/example-config.yml
similarity index 88%
rename from core/src/main/resources/config.yml
rename to .doc/example-config.yml
index b8d0dfb..3d0096c 100644
--- a/core/src/main/resources/config.yml
+++ b/.doc/example-config.yml
@@ -19,7 +19,7 @@ properties:
enable: true
# 文件夹路径,将读取该文件夹下的所有 .properties 文件,并以文件名为数据管理器名称。
# 读取时,将排除以 “.” 开头的文件与非 .properties 文件。
- # 默认为 "db-properties/" 相对路径,指向“plugins/EasySQL-Plugin/db-properties/”;
+ # 默认为 "db-properties/" 相对路径,指向“plugins/MineSQL/db-properties/”;
# 该选项也支持绝对路径,但使用绝对路径时,请务必注意权限问题。
folder: "db-properties/"
@@ -38,7 +38,4 @@ databases:
"example-h2": # 数据库源名称 不可包含“.” 以“example-”开头的数据源不会被加载
driver-type: h2 #数据库驱动类型,目前支持 mariadb, mysql, h2
- file: "example.db" #数据库文件路径,相对于“plugins/EasySQL-Plugin/db-files/”
- username: minecraft # 数据库用户名
- password: password #数据库连接密码
- database: minecraft #数据库名
\ No newline at end of file
+ file: "example.db" #数据库文件路径,相对于“plugins/MineSQL/db-files/”
\ No newline at end of file
diff --git a/.documentation/JAVADOC-README.md b/.doc/javadoc/JAVADOC-README.md
similarity index 74%
rename from .documentation/JAVADOC-README.md
rename to .doc/javadoc/JAVADOC-README.md
index 91e82dc..c80aa99 100644
--- a/.documentation/JAVADOC-README.md
+++ b/.doc/javadoc/JAVADOC-README.md
@@ -1,9 +1,9 @@
-# EasySQL Plugin Javadoc
+# MineSQL _(EasySQL Plugin)_ Javadoc
-基于 [Github Pages](https://pages.github.com/) 搭建,请访问 [JavaDoc](https://carmjos.github.io/EasySQL-Plugin) 。
+基于 [Github Pages](https://pages.github.com/) 搭建,请访问 [JavaDoc](https://carmjos.github.io/MineSQL) 。
## 如何实现?
-若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
+若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
自动部署项目的Javadoc到 [Github Pages](https://pages.github.com/) ,
可以参考我的文章 [《自动部署Javadoc到Github Pages》](https://pages.carm.cc/doc/javadoc-in-github.html) 。
\ No newline at end of file
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index df533b7..d1da139 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -1,7 +1,4 @@
-# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
-# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
-
-name: Deploy & Upload
+name: "Deploy & Publish"
on:
# 支持手动触发构建
@@ -11,8 +8,8 @@ on:
types: [ published ]
jobs:
- build:
-
+ gh-deploy:
+ name: "Deploy Project (GitHub)"
runs-on: ubuntu-latest
steps:
@@ -26,65 +23,36 @@ jobs:
server-id: github
server-username: MAVEN_USERNAME
server-password: MAVEN_TOKEN
+ gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
+ gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- name: "Maven Deploy"
- run: mvn -B deploy --file pom.xml -DskipTests
+ run: mvn -B -Pgithub deploy --file pom.xml -DskipTests
env:
MAVEN_USERNAME: ${{ github.repository_owner }}
MAVEN_TOKEN: ${{secrets.GITHUB_TOKEN}}
+ MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
- - name: "Release Asset Upload"
- id: upload-release-asset
- uses: shogo82148/actions-upload-release-asset@v1
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ central-deploy:
+ name: "Deploy Project (Central)"
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: "Set up JDK"
+ uses: actions/setup-java@v2
with:
- upload_url: ${{ github.event.release.upload_url }}
- asset_path: asset/*.jar
- asset_content_type: application/java-archive
+ java-version: '11'
+ distribution: 'adopt'
+ cache: maven
+ server-id: ossrh
+ server-username: MAVEN_USERNAME
+ server-password: MAVEN_PASSWORD
+ gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
+ gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
- - name: "Javadoc Deploy Staging"
- run: |
- rm -rf docs
- mkdir -vp docs
- cp -vrf api-docs/* docs/
- cp -vrf .documentation/JAVADOC-README.md docs/README.md
-
- - name: "Generate the Javadoc sitemap"
- id: sitemap
- uses: cicirello/generate-sitemap@v1
- with:
- base-url-path: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}
- path-to-root: docs
-
- - name: "Output Javadoc stats"
- run: |
- echo "sitemap-path = ${{ steps.sitemap.outputs.sitemap-path }}"
- echo "url-count = ${{ steps.sitemap.outputs.url-count }}"
- echo "excluded-count = ${{ steps.sitemap.outputs.excluded-count }}"
-
- - name: "Configure Git"
+ - name: "Central Deploy"
+ run: mvn -B -Possrh deploy --file pom.xml -DskipTests
env:
- DEPLOY_PRI: ${{secrets.DEPLOY_PRI}}
- run: |
- sudo timedatectl set-timezone "Asia/Shanghai"
- mkdir -p ~/.ssh/
- echo "$DEPLOY_PRI" > ~/.ssh/id_rsa
- chmod 600 ~/.ssh/id_rsa
- ssh-keyscan github.com >> ~/.ssh/known_hosts
- git config --global user.name 'CarmJos'
- git config --global user.email 'carm@carm.cc'
-
- - name: "Commit Javadocs"
- run: |
- cd docs
- git init
- git remote add origin git@github.com:${{ github.repository }}.git
- git checkout -b gh-pages
- git add -A
- git commit -m "API Document generated."
-
- - name: "Push javadocs"
- run: |
- cd docs
- git push origin HEAD:gh-pages --force
\ No newline at end of file
+ MAVEN_USERNAME: ${{ secrets.OSSRH_USER }}
+ MAVEN_PASSWORD: ${{ secrets.OSSRH_PASS }}
+ MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
diff --git a/.github/workflows/javadoc.yml b/.github/workflows/javadoc.yml
new file mode 100644
index 0000000..52507cf
--- /dev/null
+++ b/.github/workflows/javadoc.yml
@@ -0,0 +1,74 @@
+name: "Publish Javadoc"
+
+on:
+ # 支持手动触发构建
+ workflow_dispatch:
+ release:
+ # 创建release的时候触发
+ types: [ published ]
+
+
+jobs:
+
+ javadoc-deploy:
+ name: "Deploy Javadoc (Github Pages)"
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: "Set up JDK"
+ uses: actions/setup-java@v2
+ with:
+ java-version: '8'
+ distribution: 'adopt'
+ cache: maven
+
+ - name: "Generate Javadoc"
+ run: mvn -B javadoc:javadoc -pl api --file pom.xml -DskipTests
+
+ - name: "Copy Javadoc"
+ run: |
+ rm -rf docs
+ mkdir -vp docs
+ cp -vrf api/target/site/apidocs/* docs/
+ cp -vrf .doc/javadoc/JAVADOC-README.md docs/README.md
+
+ - name: "Generate Sitemap"
+ id: sitemap
+ uses: cicirello/generate-sitemap@v1
+ with:
+ base-url-path: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}
+ path-to-root: docs
+
+ - name: Output stats
+ run: |
+ echo "sitemap-path = ${{ steps.sitemap.outputs.sitemap-path }}"
+ echo "url-count = ${{ steps.sitemap.outputs.url-count }}"
+ echo "excluded-count = ${{ steps.sitemap.outputs.excluded-count }}"
+ ls -l docs
+
+ - name: Configure Git
+ env:
+ DEPLOY_PRI: ${{secrets.DEPLOY_PRI}}
+ run: |
+ sudo timedatectl set-timezone "Asia/Shanghai"
+ mkdir -p ~/.ssh/
+ echo "$DEPLOY_PRI" > ~/.ssh/id_rsa
+ chmod 600 ~/.ssh/id_rsa
+ ssh-keyscan github.com >> ~/.ssh/known_hosts
+ git config --global user.name '${{ github.repository_owner }}'
+ git config --global user.email '${{ github.repository_owner }}@users.noreply.github.com'
+
+ - name: Commit documentation changes
+ run: |
+ echo "Committing changes to git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git ..."
+ cd docs
+ git init
+ git remote add origin git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git
+ git checkout -b gh-pages
+ git add -A
+ git commit -m "API Document generated."
+
+ - name: Javadoc Website Push
+ run: |
+ cd docs
+ git push origin HEAD:gh-pages --force
\ No newline at end of file
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
index 95c030e..a959a23 100644
--- a/.github/workflows/maven.yml
+++ b/.github/workflows/maven.yml
@@ -6,7 +6,12 @@ name: Build & Tests
on:
# 支持手动触发构建
workflow_dispatch:
+ pull_request:
push:
+ paths-ignore:
+ - ".github/**"
+ - "README.md"
+ - "LICENCE"
jobs:
build:
@@ -20,19 +25,12 @@ jobs:
with:
java-version: '11'
distribution: 'adopt'
- cache: maven
- server-id: github
- server-username: MAVEN_USERNAME
- server-password: MAVEN_TOKEN
- name: "Package"
- run: mvn -B package --file pom.xml -Dmaven.javadoc.skip=true
- env:
- MAVEN_USERNAME: ${{ github.repository_owner }}
- MAVEN_TOKEN: ${{secrets.GITHUB_TOKEN}}
+ run: mvn -B package --file pom.xml -Dgpg.skip
- name: "Target Stage"
- run: mkdir -vp staging && ls -l asset/ && cp -vrf asset/*.jar staging
+ run: mkdir staging && cp */target/*.jar staging
- name: "Upload artifact"
uses: actions/upload-artifact@v2
with:
name: Artifact
- path: staging
+ path: staging
\ No newline at end of file
diff --git a/README.md b/README.md
index e20b22d..fb50351 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,14 @@
```text
- ______ _____ ____ _ _____ _ _
-| ____| / ____|/ __ \| | | __ \| | (_)
-| |__ __ _ ___ _ _| (___ | | | | | | |__) | |_ _ __ _ _ _ __
-| __| / _` / __| | | |\___ \| | | | | | ___/| | | | |/ _` | | '_ \
-| |___| (_| \__ \ |_| |____) | |__| | |____ | | | | |_| | (_| | | | | |
-|______\__,_|___/\__, |_____/ \___\_\______| |_| |_|\__,_|\__, |_|_| |_|
- __/ | __/ |
- |___/ |___/
+ __ ____ ________ __
+ / |/ (_)__ ___ / __/ __ \ / /
+ / /|_/ / / _ \/ -_)\ \/ /_/ / / /__
+/_/ /_/_/_//_/\__/___/\___\_\/____/
+#MineSQL (EasySQL-Plugin)
```
注意:该项目仍在开发中!
-# EasySQL-Plugin
+# MineSQL (EasySQL-Plugin)
轻松(用)SQL的独立运行库插件,支持多种服务端,适用于MineCraft全版本。
@@ -27,9 +24,9 @@
## 配置
-### 插件配置文件 [`config.yml`](easysql-plugin-core/src/main/resources/config.yml)
+### 插件配置文件 [`config.yml`](minesql-core/src/main/resources/config.yml)
-完整示例配置请见 [源文件](easysql-plugin-core/src/main/resources/config.yml)。
+完整示例配置请见 [源文件](minesql-core/src/main/resources/config.yml)。
#### MySQL/MariaDB 数据源详细配置示例
@@ -60,9 +57,9 @@ databases:
file-path: "db-files/minecraft"
```
-### Properties 配置文件 [`<插件目录>/db-properties/*.properties`](easysql-plugin-core/src/main/resources/db-properties/.example-mysql.properties)
+### Properties 配置文件 [`<插件目录>/db-properties/*.properties`](minesql-core/src/main/resources/db-properties/.example-mysql.properties)
-示例配置请见 [示例MySQL数据源Properties](easysql-plugin-core/src/main/resources/db-properties/.example-mysql.properties)。
+示例配置请见 [示例MySQL数据源Properties](minesql-core/src/main/resources/db-properties/.example-mysql.properties)。
Properties 文件的文件名几位数据源的ID,允许为英文、数字、下划线、短横线;请不要包含中文、其他特殊符号与空格,以`.`开头的文件将被忽略。
@@ -91,9 +88,9 @@ Properties 文件的文件名几位数据源的ID,允许为英文、数字、
- EasySQL-Plugin
+ MineSQL
GitHub Packages
- https://maven.pkg.github.com/CarmJos/EasySQL-Plugin
+ https://maven.pkg.github.com/CarmJos/MineSQL
@@ -109,7 +106,7 @@ Properties 文件的文件名几位数据源的ID,允许为英文、数字、
cc.carm.plugin
- easysql-plugin-api
+ minesql-api
[LATEST RELEASE]
provided
@@ -130,14 +127,14 @@ repositories {
mavenCentral()
// 采用github依赖库,安全稳定,但需要配置 (推荐)
- maven { url 'https://maven.pkg.github.com/CarmJos/EasySQL-Plugin' }
+ maven { url 'https://maven.pkg.github.com/CarmJos/MineSQL' }
// 采用我的私人依赖库,简单方便,但可能因为变故而无法使用
maven { url 'https://repo.carm.cc/repository/maven-public/' }
}
dependencies {
- compileOnly "cc.carm.plugin:easysql-plugin-api:[LATEST RELEASE]"
+ compileOnly "cc.carm.plugin:minesql-api:[LATEST RELEASE]"
}
```
diff --git a/api/pom.xml b/api/pom.xml
index 75e03e4..b5fa4be 100644
--- a/api/pom.xml
+++ b/api/pom.xml
@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- easysql-plugin
+ minesql-parent
cc.carm.plugin
0.0.3-SNAPSHOT
@@ -16,12 +16,12 @@
UTF-8
- easysql-plugin-api
+ minesql-api
jar
- EasySQL-Plugin-API
+ MineSQL-API
轻松(用)SQL的独立运行库插件的公用API接口部分。
- https://github.com/CarmJos/EasySQL-Plugin
+ https://github.com/CarmJos/MineSQL
@@ -45,12 +45,12 @@
GitHub Issues
- https://github.com/CarmJos/EasySQL-Plugin/issues
+ https://github.com/CarmJos/MineSQL/issues
GitHub Actions
- https://github.com/CarmJos/EasySQL-Plugin/actions/workflows/maven.yml
+ https://github.com/CarmJos/MineSQL/actions/workflows/maven.yml
@@ -61,6 +61,12 @@
compile
+
+ cc.carm.lib
+ easyconfiguration-core
+ provided
+
+
@@ -92,7 +98,6 @@
true
cc.carm.lib:easysql-api
cc.carm.plugin:*
- ${project.parent.basedir}/api-docs/
diff --git a/api/src/main/java/cc/carm/plugin/minesql/IMineSQL.java b/api/src/main/java/cc/carm/plugin/minesql/IMineSQL.java
new file mode 100644
index 0000000..331e2e4
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/IMineSQL.java
@@ -0,0 +1,21 @@
+package cc.carm.plugin.minesql;
+
+import cc.carm.plugin.minesql.api.SQLRegistry;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.File;
+import java.util.logging.Logger;
+
+interface IMineSQL {
+
+ @NotNull SQLRegistry getRegistry();
+
+ @NotNull File getPluginFolder();
+
+ default @NotNull File getSourceFolder() {
+ return new File(getPluginFolder(), "db-files");
+ }
+
+ @NotNull Logger getLogger();
+
+}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/MineSQL.java b/api/src/main/java/cc/carm/plugin/minesql/MineSQL.java
index 873fa63..ae04f83 100644
--- a/api/src/main/java/cc/carm/plugin/minesql/MineSQL.java
+++ b/api/src/main/java/cc/carm/plugin/minesql/MineSQL.java
@@ -2,16 +2,30 @@ package cc.carm.plugin.minesql;
import cc.carm.plugin.minesql.api.SQLRegistry;
+import java.io.File;
+import java.util.logging.Logger;
+
public class MineSQL {
- protected static SQLRegistry api;
+ private static IMineSQL instance;
- protected static void initializeAPI(SQLRegistry api) {
- MineSQL.api = api;
+ protected static void initializeAPI(IMineSQL api) {
+ MineSQL.instance = api;
}
- public static SQLRegistry get() {
- return api;
+ public static Logger getLogger() {
+ return instance.getLogger();
+ }
+
+ public static SQLRegistry getRegistry() {
+ return instance.getRegistry();
+ }
+
+ /**
+ * @return 数据库源文件所在目录,非插件数据目录。
+ */
+ public static File getDataSourceFolder() {
+ return instance.getSourceFolder();
}
}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/DBConfiguration.java b/api/src/main/java/cc/carm/plugin/minesql/api/DBConfiguration.java
deleted file mode 100644
index 96952a0..0000000
--- a/api/src/main/java/cc/carm/plugin/minesql/api/DBConfiguration.java
+++ /dev/null
@@ -1,226 +0,0 @@
-package cc.carm.plugin.minesql.api;
-
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DBConfiguration {
-
- public static DBConfiguration create(@NotNull SQLDriverType sourceType, @NotNull String url) {
- return new DBConfiguration(sourceType.getDriverClass(), sourceType.getUrlPrefix(), url, sourceType.getInitializeSQLs());
- }
-
- private final @NotNull String driverClassName;
- private final @NotNull String urlPrefix;
- private final @NotNull List initializeSQLs;
-
- private @NotNull String url;
-
- private @Nullable String username;
- private @Nullable String password;
-
- private @Nullable String connectionInitSql;
-
- private @Nullable String poolName;
- private @Nullable Integer maxPoolSize;
- private @Nullable Integer maxActive;
-
- private @Nullable Integer maxHoldTime;
-
- private @Nullable Long idleTimeout;
-
- private @Nullable Long maxWaitTime;
-
-
- private @Nullable String schema;
- private @Nullable Boolean autoCommit;
- private @Nullable Boolean readOnly;
-
- private @Nullable String validationSQL;
- private @Nullable Integer validationTimeout;
- private @Nullable Long validationInterval;
-
-
- private DBConfiguration(@NotNull String driverClass, @NotNull String urlPrefix,
- @NotNull String url, @NotNull String[] initializeSQLs) {
- this.driverClassName = driverClass;
- this.urlPrefix = urlPrefix;
- this.url = url;
- this.initializeSQLs = Arrays.asList(initializeSQLs);
- }
-
- public @NotNull String getDriverClassName() {
- return driverClassName;
- }
-
- public @NotNull String getUrlPrefix() {
- return urlPrefix;
- }
-
- public @NotNull List getInitializeSQLs() {
- return initializeSQLs;
- }
-
- public DBConfiguration setInitializeSQLs(@Nullable String[] initializeSQLs) {
- this.initializeSQLs.clear();
- this.initializeSQLs.addAll(Arrays.asList(initializeSQLs));
- return this;
- }
-
- public DBConfiguration addInitializeSQL(@NotNull String initializeSQL) {
- this.initializeSQLs.add(initializeSQL);
- return this;
- }
-
- public DBConfiguration clearExtraSettings() {
- this.initializeSQLs.clear();
- return this;
- }
-
- public @NotNull String getUrl() {
- return url;
- }
-
- public DBConfiguration setUrl(String url) {
- this.url = url;
- return this;
- }
-
- public @Nullable String getUsername() {
- return username;
- }
-
- public DBConfiguration setUsername(String username) {
- this.username = username;
- return this;
- }
-
- public @Nullable String getPassword() {
- return password;
- }
-
- public DBConfiguration setPassword(String password) {
- this.password = password;
- return this;
- }
-
- public @Nullable String getConnectionInitSql() {
- return connectionInitSql;
- }
-
- public DBConfiguration setConnectionInitSql(String connectionInitSql) {
- this.connectionInitSql = connectionInitSql;
- return this;
- }
-
- public @Nullable String getValidationSQL() {
- return validationSQL;
- }
-
- public DBConfiguration setValidationSQL(String validationSQL) {
- this.validationSQL = validationSQL;
- return this;
- }
-
- public @Nullable Long getValidationInterval() {
- return validationInterval;
- }
-
- public DBConfiguration setValidationInterval(@Nullable Long validationInterval) {
- this.validationInterval = validationInterval;
- return this;
- }
-
- public @Nullable String getPoolName() {
- return poolName;
- }
-
- public DBConfiguration setPoolName(String poolName) {
- this.poolName = poolName;
- return this;
- }
-
- public @Nullable String getSchema() {
- return schema;
- }
-
- public DBConfiguration setSchema(String schema) {
- this.schema = schema;
- return this;
- }
-
- public @Nullable Boolean getAutoCommit() {
- return autoCommit;
- }
-
- public DBConfiguration setAutoCommit(Boolean autoCommit) {
- this.autoCommit = autoCommit;
- return this;
- }
-
- public @Nullable Boolean getReadOnly() {
- return readOnly;
- }
-
- public DBConfiguration setReadOnly(Boolean readOnly) {
- this.readOnly = readOnly;
- return this;
- }
-
- public @Nullable Integer getMaxHoldTime() {
- return maxHoldTime;
- }
-
- public DBConfiguration setMaxHoldTime(@Nullable Integer maxHoldTime) {
- this.maxHoldTime = maxHoldTime;
- return this;
- }
-
- public @Nullable Integer getValidationTimeout() {
- return validationTimeout;
- }
-
- public DBConfiguration setValidationTimeout(Integer validationTimeout) {
- this.validationTimeout = validationTimeout;
- return this;
- }
-
- public @Nullable Long getIdleTimeout() {
- return idleTimeout;
- }
-
- public DBConfiguration setIdleTimeout(Long idleTimeout) {
- this.idleTimeout = idleTimeout;
- return this;
- }
-
- public @Nullable Integer getMaxActive() {
- return maxActive;
- }
-
- public DBConfiguration setMaxActive(Integer maxActive) {
- this.maxActive = maxActive;
- return this;
- }
-
- public @Nullable Integer getMaxPoolSize() {
- return maxPoolSize;
- }
-
- public DBConfiguration setMaxPoolSize(@Nullable Integer maxPoolSize) {
- this.maxPoolSize = maxPoolSize;
- return this;
- }
-
- public @Nullable Long getMaxWaitTime() {
- return maxWaitTime;
- }
-
- public DBConfiguration setMaxWaitTime(Long maxWaitTime) {
- this.maxWaitTime = maxWaitTime;
- return this;
- }
-
-}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/SQLDriverType.java b/api/src/main/java/cc/carm/plugin/minesql/api/SQLDriverType.java
index 4671040..7e57d6e 100644
--- a/api/src/main/java/cc/carm/plugin/minesql/api/SQLDriverType.java
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/SQLDriverType.java
@@ -1,37 +1,54 @@
package cc.carm.plugin.minesql.api;
+import cc.carm.lib.easysql.api.SQLManager;
+import cc.carm.lib.easysql.api.function.SQLHandler;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
+import java.util.Optional;
public enum SQLDriverType {
- MARIADB("org.mariadb.jdbc.Driver", "jdbc:mariadb://",
- new String[]{"mariadb", "maria-db"}, new String[]{}
+ MARIADB(
+ "org.mariadb.jdbc.Driver", "jdbc:mariadb://",
+ new String[]{"maria-db"}, null
),
- MYSQL("com.mysql.jdbc.Driver", "jdbc:mysql://",
- new String[]{"mysql"}, new String[]{}
+
+ MYSQL("com.mysql.jdbc.Driver", "jdbc:mysql://", null, null),
+
+ H2_FILE("org.h2.Driver", "jdbc:h2:file:",
+ new String[]{"h2"},
+ (manager) -> {
+ manager.executeSQL("SET MODE=MySQL");
+ manager.executeSQL("SET DB_CLOSE_DELAY=-1");
+ manager.executeSQL("SET DB_CLOSE_ON_EXIT=FALSE");
+ }
),
- H2("org.h2.Driver", "jdbc:h2:",
- new String[]{"h2", "h2-db", "h2-database"},
- new String[]{"SET MODE=MySQL", "SET DB_CLOSE_DELAY=-1"}
+
+ H2_MEM("org.h2.Driver", "jdbc:h2:mem:",
+ new String[]{"h2-memory", "h2-temp"},
+ (manager) -> {
+ manager.executeSQL("SET MODE=MySQL");
+ manager.executeSQL("SET DB_CLOSE_DELAY=-1");
+ manager.executeSQL("SET DB_CLOSE_ON_EXIT=FALSE");
+ }
);
private final @NotNull String driverClass;
- private final @NotNull String urlPrefix;
+ private final @NotNull String jdbcPrefix;
private final @NotNull String[] databaseAlias;
- private final @NotNull String[] initializeSQLs;
+ private final @Nullable SQLHandler initializer;
- SQLDriverType(@NotNull String driverClass, @NotNull String urlPrefix,
- @NotNull String[] databaseAlias,
- @NotNull String[] initializeSQLs) {
+ SQLDriverType(@NotNull String driverClass, @NotNull String jdbcPrefix,
+ @Nullable String[] databaseAlias,
+ @Nullable SQLHandler initializer) {
this.driverClass = driverClass;
- this.urlPrefix = urlPrefix;
- this.databaseAlias = databaseAlias;
- this.initializeSQLs = initializeSQLs;
+ this.jdbcPrefix = jdbcPrefix;
+ this.databaseAlias = Optional.ofNullable(databaseAlias).orElse(new String[0]);
+ this.initializer = initializer;
}
public @NotNull String[] getDatabaseAlias() {
@@ -42,24 +59,24 @@ public enum SQLDriverType {
return driverClass;
}
- public @NotNull String getUrlPrefix() {
- return urlPrefix;
+ public @NotNull String getJdbcPrefix() {
+ return jdbcPrefix;
}
- public @NotNull String[] getInitializeSQLs() {
- return initializeSQLs;
+ public @Nullable SQLHandler getInitializer() {
+ return initializer;
}
@Contract("null->null")
public static @Nullable SQLDriverType parse(@Nullable String driverString) {
if (driverString == null) return null;
return Arrays.stream(values())
- .filter(value -> value.name().equalsIgnoreCase(driverString) || has(value.getDatabaseAlias(), driverString))
+ .filter(value -> value.name().equalsIgnoreCase(driverString) || anyMatch(value.getDatabaseAlias(), driverString))
.findFirst().orElse(null);
}
-
- private static boolean has(String[] array, String value) {
+ private static boolean anyMatch(String[] array, String value) {
return Arrays.stream(array).anyMatch(s -> s.equalsIgnoreCase(value));
}
+
}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/SQLRegistry.java b/api/src/main/java/cc/carm/plugin/minesql/api/SQLRegistry.java
index ab86c66..ef707f7 100644
--- a/api/src/main/java/cc/carm/plugin/minesql/api/SQLRegistry.java
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/SQLRegistry.java
@@ -2,6 +2,7 @@ package cc.carm.plugin.minesql.api;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
@@ -52,7 +53,7 @@ public interface SQLRegistry {
* @throws Exception 若创建失败则抛出异常
*/
@NotNull SQLManager create(@NotNull String name,
- @NotNull DBConfiguration configuration) throws Exception;
+ @NotNull SQLSourceConfig configuration) throws Exception;
/**
* 创建并注册一个新的 SQLManager 实例
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/conf/SQLDriverConfig.java b/api/src/main/java/cc/carm/plugin/minesql/api/conf/SQLDriverConfig.java
new file mode 100644
index 0000000..d948904
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/conf/SQLDriverConfig.java
@@ -0,0 +1,25 @@
+package cc.carm.plugin.minesql.api.conf;
+
+import cc.carm.plugin.minesql.api.SQLDriverType;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Map;
+
+public abstract class SQLDriverConfig {
+
+ protected final @NotNull SQLDriverType type;
+
+ public SQLDriverConfig(@NotNull SQLDriverType type) {
+ this.type = type;
+ }
+
+ public abstract SQLSourceConfig createSource();
+
+ public @NotNull SQLDriverType getType() {
+ return type;
+ }
+
+ public abstract @NotNull Map serialize();
+
+}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/conf/drivers/H2MemConfig.java b/api/src/main/java/cc/carm/plugin/minesql/api/conf/drivers/H2MemConfig.java
new file mode 100644
index 0000000..4b3ee3b
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/conf/drivers/H2MemConfig.java
@@ -0,0 +1,45 @@
+package cc.carm.plugin.minesql.api.conf.drivers;
+
+import cc.carm.plugin.minesql.api.SQLDriverType;
+import cc.carm.plugin.minesql.api.conf.SQLDriverConfig;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Optional;
+
+public class H2MemConfig extends SQLDriverConfig {
+
+ protected final @Nullable String database;
+
+ public H2MemConfig(@Nullable String database) {
+ super(SQLDriverType.H2_MEM);
+ this.database = database;
+ }
+
+ public @Nullable String getDatabase() {
+ return database;
+ }
+
+ @Override
+ public SQLSourceConfig createSource() {
+ return SQLSourceConfig.create(getType().getDriverClass(), buildJDBC(), getType().getInitializer());
+ }
+
+ protected String buildJDBC() {
+ return getType().getJdbcPrefix() + Optional.ofNullable(getDatabase()).orElse("");
+ }
+
+ @Override
+ public @NotNull Map serialize() {
+ Map values = new LinkedHashMap<>();
+
+ values.put("type", getType().name());
+ if (getDatabase() != null) values.put("database", getDatabase());
+
+ return values;
+ }
+
+}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/conf/impl/FileBasedConfig.java b/api/src/main/java/cc/carm/plugin/minesql/api/conf/impl/FileBasedConfig.java
new file mode 100644
index 0000000..568f9f5
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/conf/impl/FileBasedConfig.java
@@ -0,0 +1,45 @@
+package cc.carm.plugin.minesql.api.conf.impl;
+
+import cc.carm.plugin.minesql.MineSQL;
+import cc.carm.plugin.minesql.api.SQLDriverType;
+import cc.carm.plugin.minesql.api.conf.SQLDriverConfig;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.File;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class FileBasedConfig extends SQLDriverConfig {
+
+ protected final @NotNull String filePath;
+
+ public FileBasedConfig(@NotNull SQLDriverType type,
+ @NotNull String filePath) {
+ super(type);
+ this.filePath = filePath;
+ }
+
+ public @NotNull String getFilePath() {
+ return filePath;
+ }
+
+ @Override
+ public SQLSourceConfig createSource() {
+ File file = new File(MineSQL.getDataSourceFolder(), filePath);
+ return SQLSourceConfig.create(getType().getDriverClass(), file.getAbsolutePath(), getType().getInitializer());
+ }
+
+ @Override
+ public @NotNull Map serialize() {
+ Map values = new LinkedHashMap<>();
+
+ values.put("type", getType().name());
+ values.put("file", getFilePath());
+
+ return values;
+ }
+
+
+}
+
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/conf/impl/RemoteAuthConfig.java b/api/src/main/java/cc/carm/plugin/minesql/api/conf/impl/RemoteAuthConfig.java
new file mode 100644
index 0000000..1a6a2c2
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/conf/impl/RemoteAuthConfig.java
@@ -0,0 +1,87 @@
+package cc.carm.plugin.minesql.api.conf.impl;
+
+import cc.carm.plugin.minesql.api.SQLDriverType;
+import cc.carm.plugin.minesql.api.conf.SQLDriverConfig;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class RemoteAuthConfig extends SQLDriverConfig {
+
+ protected final @NotNull String host;
+ protected final int port;
+ protected final @NotNull String database;
+ protected final @Nullable String username;
+ protected final @Nullable String password;
+
+ protected final @Nullable String extraSettings;
+
+ public RemoteAuthConfig(@NotNull SQLDriverType type,
+ @NotNull String host, int port, @NotNull String database,
+ @Nullable String username, @Nullable String password,
+ @Nullable String extraSettings) {
+ super(type);
+ this.host = host;
+ this.port = port;
+ this.database = database;
+ this.username = username;
+ this.password = password;
+ this.extraSettings = extraSettings;
+ }
+
+ @Override
+ public SQLSourceConfig createSource() {
+ return SQLSourceConfig.create(
+ getType().getDriverClass(), buildJDBC(), getType().getInitializer()
+ ).setUsername(getUsername()).setPassword(getPassword());
+ }
+
+ public @NotNull String getHost() {
+ return host;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public @NotNull String getDatabase() {
+ return database;
+ }
+
+ public @Nullable String getUsername() {
+ return username;
+ }
+
+
+ public @Nullable String getPassword() {
+ return password;
+ }
+
+ public @Nullable String getExtraSettings() {
+ return extraSettings;
+ }
+
+ protected String buildJDBC() {
+ return String.format("%s%s:%s/%s%s", getType().getJdbcPrefix(), getHost(), getPort(), getDatabase(), getExtraSettings());
+ }
+
+ @Override
+ public @NotNull Map serialize() {
+ Map values = new LinkedHashMap<>();
+
+ values.put("type", getType().name());
+
+ values.put("host", getHost());
+ values.put("port", getPort());
+ values.put("database", getDatabase());
+ if (getUsername() != null) values.put("username", username);
+ if (getPassword() != null) values.put("password", password);
+ if (getExtraSettings() != null) values.put("extra", extraSettings);
+
+ return values;
+ }
+
+}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/source/SQLPoolSettings.java b/api/src/main/java/cc/carm/plugin/minesql/api/source/SQLPoolSettings.java
new file mode 100644
index 0000000..0964383
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/source/SQLPoolSettings.java
@@ -0,0 +1,134 @@
+package cc.carm.plugin.minesql.api.source;
+
+import org.jetbrains.annotations.Nullable;
+
+public class SQLPoolSettings {
+
+ private @Nullable String poolName;
+ private @Nullable Integer maxPoolSize;
+ private @Nullable Integer maxActive;
+
+ private @Nullable Integer maxHoldTime;
+
+ private @Nullable Long idleTimeout;
+
+ private @Nullable Long maxWaitTime;
+
+ private @Nullable String schema;
+ private @Nullable Boolean autoCommit;
+ private @Nullable Boolean readOnly;
+
+ private @Nullable String validationSQL;
+ private @Nullable Integer validationTimeout;
+ private @Nullable Long validationInterval;
+
+ public @Nullable String getValidationSQL() {
+ return validationSQL;
+ }
+
+ public SQLPoolSettings setValidationSQL(String validationSQL) {
+ this.validationSQL = validationSQL;
+ return this;
+ }
+
+ public @Nullable Long getValidationInterval() {
+ return validationInterval;
+ }
+
+ public SQLPoolSettings setValidationInterval(@Nullable Long validationInterval) {
+ this.validationInterval = validationInterval;
+ return this;
+ }
+
+ public @Nullable String getPoolName() {
+ return poolName;
+ }
+
+ public SQLPoolSettings setPoolName(String poolName) {
+ this.poolName = poolName;
+ return this;
+ }
+
+ public @Nullable String getSchema() {
+ return schema;
+ }
+
+ public SQLPoolSettings setSchema(String schema) {
+ this.schema = schema;
+ return this;
+ }
+
+ public @Nullable Boolean getAutoCommit() {
+ return autoCommit;
+ }
+
+ public SQLPoolSettings setAutoCommit(Boolean autoCommit) {
+ this.autoCommit = autoCommit;
+ return this;
+ }
+
+ public @Nullable Boolean getReadOnly() {
+ return readOnly;
+ }
+
+ public SQLPoolSettings setReadOnly(Boolean readOnly) {
+ this.readOnly = readOnly;
+ return this;
+ }
+
+ public @Nullable Integer getMaxHoldTime() {
+ return maxHoldTime;
+ }
+
+ public SQLPoolSettings setMaxHoldTime(@Nullable Integer maxHoldTime) {
+ this.maxHoldTime = maxHoldTime;
+ return this;
+ }
+
+ public @Nullable Integer getValidationTimeout() {
+ return validationTimeout;
+ }
+
+ public SQLPoolSettings setValidationTimeout(Integer validationTimeout) {
+ this.validationTimeout = validationTimeout;
+ return this;
+ }
+
+ public @Nullable Long getIdleTimeout() {
+ return idleTimeout;
+ }
+
+ public SQLPoolSettings setIdleTimeout(Long idleTimeout) {
+ this.idleTimeout = idleTimeout;
+ return this;
+ }
+
+ public @Nullable Integer getMaxActive() {
+ return maxActive;
+ }
+
+ public SQLPoolSettings setMaxActive(Integer maxActive) {
+ this.maxActive = maxActive;
+ return this;
+ }
+
+ public @Nullable Integer getMaxPoolSize() {
+ return maxPoolSize;
+ }
+
+ public SQLPoolSettings setMaxPoolSize(@Nullable Integer maxPoolSize) {
+ this.maxPoolSize = maxPoolSize;
+ return this;
+ }
+
+ public @Nullable Long getMaxWaitTime() {
+ return maxWaitTime;
+ }
+
+ public SQLPoolSettings setMaxWaitTime(Long maxWaitTime) {
+ this.maxWaitTime = maxWaitTime;
+ return this;
+ }
+
+
+}
diff --git a/api/src/main/java/cc/carm/plugin/minesql/api/source/SQLSourceConfig.java b/api/src/main/java/cc/carm/plugin/minesql/api/source/SQLSourceConfig.java
new file mode 100644
index 0000000..6705fdf
--- /dev/null
+++ b/api/src/main/java/cc/carm/plugin/minesql/api/source/SQLSourceConfig.java
@@ -0,0 +1,135 @@
+package cc.carm.plugin.minesql.api.source;
+
+import cc.carm.lib.easysql.api.SQLManager;
+import cc.carm.lib.easysql.api.function.SQLHandler;
+import cc.carm.plugin.minesql.api.SQLDriverType;
+import cc.carm.plugin.minesql.api.conf.drivers.H2MemConfig;
+import cc.carm.plugin.minesql.api.conf.impl.FileBasedConfig;
+import cc.carm.plugin.minesql.api.conf.impl.RemoteAuthConfig;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.File;
+import java.util.Optional;
+import java.util.function.Consumer;
+
+public class SQLSourceConfig {
+
+ public static SQLSourceConfig createMySQL(@NotNull String host, int port, @NotNull String database,
+ @NotNull String username, @Nullable String password,
+ @Nullable String extraSettings) {
+ return new RemoteAuthConfig(SQLDriverType.MYSQL, host, port, database, username, password, extraSettings).createSource();
+ }
+
+ public static SQLSourceConfig createMariaDB(@NotNull String host, int port, @NotNull String database,
+ @NotNull String username, @Nullable String password,
+ @Nullable String extraSettings) {
+ return new RemoteAuthConfig(SQLDriverType.MARIADB, host, port, database, username, password, extraSettings).createSource();
+ }
+
+ public static SQLSourceConfig createH2File(@NotNull File file) {
+ return create(SQLDriverType.H2_FILE, file.getAbsolutePath());
+ }
+
+ public static SQLSourceConfig createH2File(@NotNull String filePath) {
+ return new FileBasedConfig(SQLDriverType.H2_FILE, filePath).createSource();
+ }
+
+ public static SQLSourceConfig createH2Mem(@Nullable String databaseName) {
+ return new H2MemConfig(databaseName).createSource();
+ }
+
+ public static SQLSourceConfig create(@NotNull SQLDriverType sourceType, @NotNull String url) {
+ return create(sourceType.getDriverClass(), sourceType.getJdbcPrefix() + url, sourceType.getInitializer());
+ }
+
+ public static SQLSourceConfig create(@NotNull String driverClass, @NotNull String jdbcURL) {
+ return create(driverClass, jdbcURL, null);
+ }
+
+ public static SQLSourceConfig create(@NotNull String driverClassName, @NotNull String jdbcURL,
+ @Nullable SQLHandler initializer) {
+ return new SQLSourceConfig(driverClassName, jdbcURL, initializer, null);
+ }
+
+ public static SQLSourceConfig create(@NotNull String driverClassName, @NotNull String jdbcURL,
+ @Nullable SQLHandler initializer, @Nullable SQLPoolSettings settings) {
+ return new SQLSourceConfig(driverClassName, jdbcURL, initializer, settings);
+ }
+
+ private @NotNull String driverClassName;
+ private @NotNull String jdbcURL;
+ private @Nullable String username;
+ private @Nullable String password;
+
+ private @Nullable SQLHandler initializer;
+ private @NotNull SQLPoolSettings settings;
+
+ public SQLSourceConfig(@NotNull String driverClassName, @NotNull String jdbcURL,
+ @Nullable SQLHandler initializer, @Nullable SQLPoolSettings settings) {
+ this.driverClassName = driverClassName;
+ this.jdbcURL = jdbcURL;
+ this.initializer = initializer;
+ this.settings = Optional.ofNullable(settings).orElse(new SQLPoolSettings());
+ }
+
+ public @NotNull String getDriverClassName() {
+ return driverClassName;
+ }
+
+ public SQLSourceConfig setDriverClassName(String driverClassName) {
+ this.driverClassName = driverClassName;
+ return this;
+ }
+
+ public @NotNull String getJdbcURL() {
+ return jdbcURL;
+ }
+
+ public SQLSourceConfig setJdbcURL(String jdbcURL) {
+ this.jdbcURL = jdbcURL;
+ return this;
+ }
+
+ public @Nullable String getUsername() {
+ return username;
+ }
+
+ public SQLSourceConfig setUsername(String username) {
+ this.username = username;
+ return this;
+ }
+
+ public @Nullable String getPassword() {
+ return password;
+ }
+
+ public SQLSourceConfig setPassword(String password) {
+ this.password = password;
+ return this;
+ }
+
+ public @Nullable SQLHandler getInitializer() {
+ return initializer;
+ }
+
+ public SQLSourceConfig setInitializer(SQLHandler initializer) {
+ this.initializer = initializer;
+ return this;
+ }
+
+ public @NotNull SQLPoolSettings getSettings() {
+ return settings;
+ }
+
+ public SQLSourceConfig setSettings(SQLPoolSettings settings) {
+ this.settings = settings;
+ return this;
+ }
+
+ public SQLSourceConfig editSettings(Consumer consumer) {
+ consumer.accept(settings);
+ return this;
+ }
+
+}
diff --git a/core/pom.xml b/core/pom.xml
index 41c0526..b39bf64 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -3,12 +3,11 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- easysql-plugin
+ minesql-parent
cc.carm.plugin
0.0.3-SNAPSHOT
4.0.0
-
${project.jdk.version}
${project.jdk.version}
@@ -17,11 +16,11 @@
true
true
- easysql-plugin-core
+ minesql-core
- EasySQL-Plugin-Core
+ MineSQL-Core
轻松(用)SQL的独立运行库插件的主要实现部分。
- https://github.com/CarmJos/EasySQL-Plugin
+ https://github.com/CarmJos/MineSQL
@@ -45,19 +44,19 @@
GitHub Issues
- https://github.com/CarmJos/EasySQL-Plugin/issues
+ https://github.com/CarmJos/MineSQL/issues
GitHub Actions
- https://github.com/CarmJos/EasySQL-Plugin/actions/workflows/maven.yml
+ https://github.com/CarmJos/MineSQL/actions/workflows/maven.yml
${project.parent.groupId}
- easysql-plugin-api
+ minesql-api
${project.parent.version}
compile
@@ -87,6 +86,18 @@
compile
+
+ cc.carm.lib
+ easyplugin-utils
+ compile
+
+
+
+ cc.carm.lib
+ easyconfiguration-yaml
+ compile
+
+
cc.carm.lib
githubreleases4j
@@ -105,6 +116,7 @@
compile
+
com.h2database
h2
@@ -133,10 +145,6 @@
org.apache.maven.plugins
maven-jar-plugin
-
- org.apache.maven.plugins
- maven-javadoc-plugin
-
diff --git a/core/src/main/java/cc/carm/plugin/minesql/MineSQLCore.java b/core/src/main/java/cc/carm/plugin/minesql/MineSQLCore.java
new file mode 100644
index 0000000..ec15a58
--- /dev/null
+++ b/core/src/main/java/cc/carm/plugin/minesql/MineSQLCore.java
@@ -0,0 +1,144 @@
+package cc.carm.plugin.minesql;
+
+import cc.carm.lib.configuration.EasyConfiguration;
+import cc.carm.lib.configuration.yaml.YAMLConfigProvider;
+import cc.carm.lib.easyplugin.utils.JarResourceUtils;
+import cc.carm.lib.easysql.api.SQLManager;
+import cc.carm.lib.githubreleases4j.GithubReleases4J;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
+import cc.carm.plugin.minesql.command.EasySQLCommand;
+import cc.carm.plugin.minesql.command.EasySQLHelpFormatter;
+import cc.carm.plugin.minesql.conf.PluginConfiguration;
+import cc.carm.plugin.minesql.conf.SQLSourceGroup;
+import cc.carm.plugin.minesql.util.DBPropertiesUtil;
+import co.aikar.commands.CommandManager;
+import co.aikar.commands.InvalidCommandArgument;
+import co.aikar.commands.Locales;
+import com.google.common.collect.ImmutableList;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.logging.Logger;
+
+public class MineSQLCore implements IMineSQL {
+
+ public static final String REPO_OWNER = "CarmJos";
+ public static final String REPO_NAME = "MineSQL";
+
+ protected final MineSQLPlatform platform;
+
+ protected final MineSQLRegistry registry;
+ protected final YAMLConfigProvider configProvider;
+ protected final PluginConfiguration config;
+
+ public MineSQLCore(MineSQLPlatform platform) {
+ this.platform = platform;
+
+ getLogger().info("加载配置文件...");
+ this.configProvider = EasyConfiguration.from(new File(platform.getPluginFolder(), "config.yml"));
+ this.config = new PluginConfiguration();
+ this.configProvider.initialize(this.config);
+
+ getLogger().info("初始化注册池...");
+ this.registry = new MineSQLRegistry(this);
+
+ }
+
+ public MineSQLPlatform getPlatform() {
+ return platform;
+ }
+
+ @Override
+ public @NotNull MineSQLRegistry getRegistry() {
+ return this.registry;
+ }
+
+ @Override
+ public @NotNull File getPluginFolder() {
+ return getPlatform().getPluginFolder();
+ }
+
+ @Override
+ public @NotNull Logger getLogger() {
+ return getPlatform().getLogger();
+ }
+
+ public PluginConfiguration getConfig() {
+ return config;
+ }
+
+ public YAMLConfigProvider getConfigProvider() {
+ return configProvider;
+ }
+
+ public @NotNull Map readConfigurations() {
+ SQLSourceGroup group = getConfig().SOURCES.getNotNull();
+ Map sources = new LinkedHashMap<>();
+ group.getSources().forEach((k, v) -> sources.put(k, v.createSource()));
+ return sources;
+ }
+
+ public @NotNull Map readProperties() {
+ if (!getConfig().PROPERTIES.ENABLE.getNotNull()) return new HashMap<>();
+
+ String propertiesFolder = getConfig().PROPERTIES.FOLDER.get();
+ if (propertiesFolder == null || propertiesFolder.length() == 0) return new HashMap<>();
+
+ File file = new File(getPluginFolder(), propertiesFolder);
+ if (!file.exists() || !file.isDirectory()) {
+ try {
+ JarResourceUtils.copyFolderFromJar(
+ "db-properties", file, JarResourceUtils.CopyOption.COPY_IF_NOT_EXIST
+ );
+ } catch (Exception ex) {
+ getLogger().severe("初始化properties示例文件失败:" + ex.getMessage());
+ }
+ }
+
+ return DBPropertiesUtil.readFromFolder(file);
+ }
+
+ @SuppressWarnings("deprecation")
+ protected void initializeCommands(CommandManager, ?, ?, ?, ?, ?> commandManager) {
+ commandManager.enableUnstableAPI("help");
+ commandManager.setHelpFormatter(new EasySQLHelpFormatter(commandManager));
+ commandManager.getLocales().setDefaultLocale(Locales.SIMPLIFIED_CHINESE);
+ commandManager.getCommandContexts().registerContext(SQLManager.class, c -> {
+ String name = c.popFirstArg();
+ try {
+ return getRegistry().get(name);
+ } catch (NullPointerException exception) {
+ throw new InvalidCommandArgument("不存在名为 " + name + " 的数据库管理器。");
+ }
+ });
+ commandManager.getCommandCompletions().registerCompletion("sql-managers", c -> {
+ if (c.getIssuer().isPlayer()) return ImmutableList.of();
+ else return ImmutableList.copyOf(getRegistry().list().keySet());
+ });
+ commandManager.registerCommand(new EasySQLCommand(this));
+ }
+
+ public void checkUpdate(String currentVersion) {
+ Logger logger = getLogger();
+
+ Integer behindVersions = GithubReleases4J.getVersionBehind(REPO_OWNER, REPO_NAME, currentVersion);
+ String downloadURL = GithubReleases4J.getReleasesURL(REPO_OWNER, REPO_NAME);
+ if (behindVersions == null) {
+ logger.severe("检查更新失败,请您定期查看插件是否更新,避免安全问题。");
+ logger.severe("下载地址 " + downloadURL);
+ } else if (behindVersions < 0) {
+ logger.severe("检查更新失败! 当前版本未知,请您使用原生版本以避免安全问题。");
+ logger.severe("最新版下载地址 " + downloadURL);
+ } else if (behindVersions > 0) {
+ logger.warning("发现新版本! 目前已落后 " + behindVersions + " 个版本。");
+ logger.warning("最新版下载地址 " + downloadURL);
+ } else {
+ logger.info("检查完成,当前已是最新版本。");
+ }
+ }
+
+}
diff --git a/core/src/main/java/cc/carm/plugin/minesql/MineSQLPlatform.java b/core/src/main/java/cc/carm/plugin/minesql/MineSQLPlatform.java
index 4a01837..d1e531a 100644
--- a/core/src/main/java/cc/carm/plugin/minesql/MineSQLPlatform.java
+++ b/core/src/main/java/cc/carm/plugin/minesql/MineSQLPlatform.java
@@ -1,52 +1,17 @@
package cc.carm.plugin.minesql;
-import cc.carm.lib.easysql.api.SQLManager;
-import cc.carm.plugin.minesql.api.DBConfiguration;
-import cc.carm.plugin.minesql.api.SQLRegistry;
-import cc.carm.plugin.minesql.command.EasySQLCommand;
-import cc.carm.plugin.minesql.command.EasySQLHelpFormatter;
import co.aikar.commands.CommandManager;
-import co.aikar.commands.InvalidCommandArgument;
-import co.aikar.commands.Locales;
-import com.google.common.collect.ImmutableList;
import org.jetbrains.annotations.NotNull;
-import java.util.Map;
-import java.util.Properties;
+import java.io.File;
import java.util.logging.Logger;
public interface MineSQLPlatform {
- @NotNull SQLRegistry getRegistry();
+ @NotNull File getPluginFolder();
- @NotNull Map readConfigurations();
+ @NotNull Logger getLogger();
- @NotNull Map readProperties();
-
- Logger getLogger();
-
- default void initializeAPI(SQLRegistry registry) {
- MineSQL.initializeAPI(registry);
- }
-
- @SuppressWarnings("deprecation")
- default void initializeCommands(CommandManager, ?, ?, ?, ?, ?> commandManager) {
- commandManager.enableUnstableAPI("help");
- commandManager.setHelpFormatter(new EasySQLHelpFormatter(commandManager));
- commandManager.getLocales().setDefaultLocale(Locales.SIMPLIFIED_CHINESE);
- commandManager.getCommandContexts().registerContext(SQLManager.class, c -> {
- String name = c.popFirstArg();
- try {
- return getRegistry().get(name);
- } catch (NullPointerException exception) {
- throw new InvalidCommandArgument("不存在名为 " + name + " 的数据库管理器。");
- }
- });
- commandManager.getCommandCompletions().registerCompletion("sql-managers", c -> {
- if (c.getIssuer().isPlayer()) return ImmutableList.of();
- else return ImmutableList.copyOf(getRegistry().list().keySet());
- });
- commandManager.registerCommand(new EasySQLCommand());
- }
+ @NotNull CommandManager, ?, ?, ?, ?, ?> getCommandManager();
}
diff --git a/core/src/main/java/cc/carm/plugin/minesql/MineSQLRegistry.java b/core/src/main/java/cc/carm/plugin/minesql/MineSQLRegistry.java
index d3d1414..cc8ba40 100644
--- a/core/src/main/java/cc/carm/plugin/minesql/MineSQLRegistry.java
+++ b/core/src/main/java/cc/carm/plugin/minesql/MineSQLRegistry.java
@@ -3,9 +3,8 @@ package cc.carm.plugin.minesql;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
import cc.carm.lib.easysql.manager.SQLManagerImpl;
-import cc.carm.lib.githubreleases4j.GithubReleases4J;
-import cc.carm.plugin.minesql.api.DBConfiguration;
import cc.carm.plugin.minesql.api.SQLRegistry;
+import cc.carm.plugin.minesql.api.source.SQLSourceConfig;
import cn.beecp.BeeDataSource;
import cn.beecp.BeeDataSourceConfig;
import com.google.common.collect.ImmutableMap;
@@ -18,40 +17,38 @@ import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
-import java.util.logging.Logger;
public class MineSQLRegistry implements SQLRegistry {
- public static final String REPO_OWNER = "CarmJos";
- public static final String REPO_NAME = "EasySQL-Plugin";
private static MineSQLRegistry instance;
protected ExecutorService executorPool;
- protected MineSQLPlatform platform;
- private final HashMap sqlManagerRegistry = new HashMap<>();
+ protected MineSQLCore core;
+ private final HashMap managers = new HashMap<>();
- protected MineSQLRegistry(@NotNull MineSQLPlatform platform) {
- this.platform = platform;
+ protected MineSQLRegistry(@NotNull MineSQLCore core) {
+ this.core = core;
MineSQLRegistry.instance = this;
this.executorPool = Executors.newFixedThreadPool(2, (r) -> {
Thread thread = new Thread(r, "EasySQLRegistry");
thread.setDaemon(true);
return thread;
});
- Map dbProperties = platform.readProperties();
- Map dbConfigurations = platform.readConfigurations();
+
+ Map dbProperties = core.readProperties();
+ Map dbConfigurations = core.readConfigurations();
if (dbProperties.isEmpty() && dbConfigurations.isEmpty()) {
- platform.getLogger().warning("未检测到任何数据库配置,将不会创建任何SQLManager。");
+ core.getLogger().warning("未检测到任何数据库配置,将不会预创建任何SQLManager。");
return;
}
dbProperties.forEach((id, properties) -> {
try {
SQLManagerImpl sqlManager = create(id, properties);
- this.sqlManagerRegistry.put(id, sqlManager);
+ this.managers.put(id, sqlManager);
} catch (Exception exception) {
- platform.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
+ core.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
exception.printStackTrace();
}
});
@@ -59,54 +56,86 @@ public class MineSQLRegistry implements SQLRegistry {
dbConfigurations.forEach((id, configuration) -> {
try {
SQLManagerImpl sqlManager = create(id, configuration);
- this.sqlManagerRegistry.put(id, sqlManager);
+ this.managers.put(id, sqlManager);
} catch (Exception exception) {
- platform.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
+ core.getLogger().warning("初始化SQLManager(#" + id + ") 出错,请检查配置文件.");
exception.printStackTrace();
}
});
}
+ public void shutdownAll() {
+ this.managers.forEach((k, manager) -> {
+ getCore().getLogger().info(" 正在关闭数据库 " + k + "...");
+ shutdown(manager, activeQueries -> {
+ getCore().getLogger().info(" 数据库 " + k + " 仍有有 " + activeQueries + " 条活动查询");
+ if (manager.getDataSource() instanceof BeeDataSource
+ && this.core.getConfig().SETTINGS.FORCE_CLOSE.getNotNull()) {
+ getCore().getLogger().info(" 将强制关闭全部活跃链接...");
+ BeeDataSource dataSource = (BeeDataSource) manager.getDataSource();
+ dataSource.close(); //Close bee connection pool
+ }
+ });
+ });
+ this.managers.clear();
+ }
+
+ protected HashMap getManagers() {
+ return managers;
+ }
+
+ public ExecutorService getExecutor() {
+ return executorPool;
+ }
+
+ public static MineSQLRegistry getInstance() {
+ return instance;
+ }
+
+ public MineSQLCore getCore() {
+ return core;
+ }
+
@Override
public @NotNull SQLManagerImpl get(@Nullable String id) throws NullPointerException {
- return Objects.requireNonNull(this.sqlManagerRegistry.get(id), "并不存在ID为 #" + id + " 的SQLManager.");
+ return Objects.requireNonNull(this.managers.get(id), "并不存在ID为 #" + id + " 的SQLManager.");
}
@Override
public @NotNull Optional<@Nullable SQLManagerImpl> getOptional(@Nullable String id) {
- return Optional.of(this.sqlManagerRegistry.get(id));
+ return Optional.of(this.managers.get(id));
}
@Override
@Unmodifiable
public @NotNull Map list() {
- return ImmutableMap.copyOf(this.sqlManagerRegistry);
+ return ImmutableMap.copyOf(this.managers);
}
@Override
- public @NotNull SQLManagerImpl create(@NotNull String name, @NotNull DBConfiguration configuration) throws Exception {
+ public @NotNull SQLManagerImpl create(@NotNull String name, @NotNull SQLSourceConfig conf) {
BeeDataSourceConfig config = new BeeDataSourceConfig();
- config.setDriverClassName(configuration.getDriverClassName());
- config.setJdbcUrl(configuration.getUrlPrefix() + configuration.getUrl());
- Optional.ofNullable(configuration.getUsername()).ifPresent(config::setUsername);
- Optional.ofNullable(configuration.getPassword()).ifPresent(config::setPassword);
+ config.setDriverClassName(conf.getDriverClassName());
+ config.setJdbcUrl(conf.getJdbcURL());
+ Optional.ofNullable(conf.getUsername()).ifPresent(config::setUsername);
+ Optional.ofNullable(conf.getPassword()).ifPresent(config::setPassword);
- Optional.ofNullable(configuration.getPoolName()).ifPresent(config::setPoolName);
- Optional.ofNullable(configuration.getMaxPoolSize()).ifPresent(config::setMaxActive);
- Optional.ofNullable(configuration.getMaxActive()).ifPresent(config::setMaxActive);
+ Optional.ofNullable(conf.getSettings().getPoolName()).ifPresent(config::setPoolName);
+ Optional.ofNullable(conf.getSettings().getMaxPoolSize()).ifPresent(config::setMaxActive);
+ Optional.ofNullable(conf.getSettings().getMaxActive()).ifPresent(config::setMaxActive);
- Optional.ofNullable(configuration.getIdleTimeout()).ifPresent(config::setIdleTimeout);
- Optional.ofNullable(configuration.getMaxWaitTime()).ifPresent(config::setMaxWait);
- Optional.ofNullable(configuration.getMaxHoldTime()).ifPresent(config::setHoldTimeout);
+ Optional.ofNullable(conf.getSettings().getIdleTimeout()).ifPresent(config::setIdleTimeout);
+ Optional.ofNullable(conf.getSettings().getMaxWaitTime()).ifPresent(config::setMaxWait);
+ Optional.ofNullable(conf.getSettings().getMaxHoldTime()).ifPresent(config::setHoldTimeout);
- Optional.ofNullable(configuration.getAutoCommit()).ifPresent(config::setDefaultAutoCommit);
- Optional.ofNullable(configuration.getReadOnly()).ifPresent(config::setDefaultReadOnly);
- Optional.ofNullable(configuration.getSchema()).ifPresent(config::setDefaultSchema);
+ Optional.ofNullable(conf.getSettings().getAutoCommit()).ifPresent(config::setDefaultAutoCommit);
+ Optional.ofNullable(conf.getSettings().getReadOnly()).ifPresent(config::setDefaultReadOnly);
+ Optional.ofNullable(conf.getSettings().getSchema()).ifPresent(config::setDefaultSchema);
- Optional.ofNullable(configuration.getValidationSQL()).ifPresent(config::setValidTestSql);
- Optional.ofNullable(configuration.getValidationTimeout()).ifPresent(config::setValidTestTimeout);
- Optional.ofNullable(configuration.getValidationInterval()).ifPresent(config::setValidAssumeTime);
+ Optional.ofNullable(conf.getSettings().getValidationSQL()).ifPresent(config::setValidTestSql);
+ Optional.ofNullable(conf.getSettings().getValidationTimeout()).ifPresent(config::setValidTestTimeout);
+ Optional.ofNullable(conf.getSettings().getValidationInterval()).ifPresent(config::setValidAssumeTime);
return create(name, config);
}
@@ -135,39 +164,4 @@ public class MineSQLRegistry implements SQLRegistry {
}
}
- protected HashMap getManagers() {
- return sqlManagerRegistry;
- }
-
- public ExecutorService getExecutor() {
- return executorPool;
- }
-
- public static MineSQLRegistry getInstance() {
- return instance;
- }
-
- public MineSQLPlatform getPlatform() {
- return platform;
- }
-
- public void checkUpdate(String currentVersion) {
- Logger logger = getInstance().getPlatform().getLogger();
- getExecutor().execute(() -> {
- Integer behindVersions = GithubReleases4J.getVersionBehind(REPO_OWNER, REPO_NAME, currentVersion);
- String downloadURL = GithubReleases4J.getReleasesURL(REPO_OWNER, REPO_NAME);
- if (behindVersions == null) {
- logger.severe("检查更新失败,请您定期查看插件是否更新,避免安全问题。");
- logger.severe("下载地址 " + downloadURL);
- } else if (behindVersions < 0) {
- logger.severe("检查更新失败! 当前版本未知,请您使用原生版本以避免安全问题。");
- logger.severe("最新版下载地址 " + downloadURL);
- } else if (behindVersions > 0) {
- logger.warning("发现新版本! 目前已落后 " + behindVersions + " 个版本。");
- logger.warning("最新版下载地址 " + downloadURL);
- } else {
- logger.info("检查完成,当前已是最新版本。");
- }
- });
- }
}
diff --git a/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLCommand.java b/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLCommand.java
index c04bfb1..1f6b9c1 100644
--- a/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLCommand.java
+++ b/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLCommand.java
@@ -2,6 +2,7 @@ package cc.carm.plugin.minesql.command;
import cc.carm.lib.easysql.api.SQLManager;
import cc.carm.lib.easysql.api.SQLQuery;
+import cc.carm.plugin.minesql.MineSQLCore;
import cc.carm.plugin.minesql.MineSQLRegistry;
import cc.carm.plugin.minesql.util.VersionReader;
import co.aikar.commands.BaseCommand;
@@ -15,9 +16,15 @@ import java.util.UUID;
@SuppressWarnings("unused")
@CommandAlias("EasySQL")
-@Description("EasySQL-Plugin的主指令,用于开发者进行调试,只允许后台执行。")
+@Description("MineSQL的主指令,用于开发者进行调试,只允许后台执行。")
public class EasySQLCommand extends BaseCommand {
+ protected final MineSQLCore core;
+
+ public EasySQLCommand(MineSQLCore core) {
+ this.core = core;
+ }
+
@HelpCommand
@Syntax("&9[页码或子指令名称]")
@Description("查看指定数据源的统计信息与当前仍未关闭的查询。")
@@ -49,7 +56,7 @@ public class EasySQLCommand extends BaseCommand {
issuer.sendMessage("§8 - &f数据库驱动 h2-database §9" + reader.get("h2-driver"));
issuer.sendMessage("§r正在检查插件更新,请稍候...");
- MineSQLRegistry.getInstance().checkUpdate(pluginVersion);
+ core.checkUpdate(pluginVersion);
}
@Subcommand("list")
diff --git a/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLHelpFormatter.java b/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLHelpFormatter.java
index f962cba..f194b78 100644
--- a/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLHelpFormatter.java
+++ b/core/src/main/java/cc/carm/plugin/minesql/command/EasySQLHelpFormatter.java
@@ -10,7 +10,7 @@ public class EasySQLHelpFormatter extends CommandHelpFormatter {
@Override
public void printHelpHeader(CommandHelp help, CommandIssuer issuer) {
- issuer.sendMessage("§3§lEasySQL-Plugin §7指令帮助");
+ issuer.sendMessage("§3§lMineSQL §7指令帮助");
}
@Override
@@ -27,7 +27,7 @@ public class EasySQLHelpFormatter extends CommandHelpFormatter {
@Override
public void printSearchHeader(CommandHelp help, CommandIssuer issuer) {
- issuer.sendMessage("§3§lEasySQL-Plugin §7指令帮助查询");
+ issuer.sendMessage("§3§lMineSQL §7指令帮助查询");
}
@Override
@@ -41,7 +41,7 @@ public class EasySQLHelpFormatter extends CommandHelpFormatter {
@Override
public void printDetailedHelpHeader(CommandHelp help, CommandIssuer issuer, HelpEntry entry) {
- issuer.sendMessage("§3§lEasySQL-Plugin §7指令帮助 §8(§f" + entry.getCommand() + "§8)");
+ issuer.sendMessage("§3§lMineSQL §7指令帮助 §8(§f" + entry.getCommand() + "§8)");
}
@Override
diff --git a/core/src/main/java/cc/carm/plugin/minesql/conf/PluginConfiguration.java b/core/src/main/java/cc/carm/plugin/minesql/conf/PluginConfiguration.java
new file mode 100644
index 0000000..8d42ba2
--- /dev/null
+++ b/core/src/main/java/cc/carm/plugin/minesql/conf/PluginConfiguration.java
@@ -0,0 +1,70 @@
+package cc.carm.plugin.minesql.conf;
+
+import cc.carm.lib.configuration.core.ConfigurationRoot;
+import cc.carm.lib.configuration.core.annotation.HeaderComment;
+import cc.carm.lib.configuration.core.value.ConfigValue;
+import cc.carm.lib.configuration.core.value.type.ConfiguredValue;
+
+public class PluginConfiguration extends ConfigurationRoot {
+
+ @HeaderComment("排错模式,一般留给开发者检查问题,平常使用无需开启。")
+ public ConfigValue DEBUG = ConfiguredValue.of(Boolean.class, false);
+
+ @HeaderComment({
+ "统计数据设定",
+ "该选项用于帮助开发者统计插件版本与使用情况,且绝不会影响性能与使用体验。",
+ "当然,您也可以选择在这里关闭,或在plugins/bStats下的配置文件中关闭所有插件的统计信息。"
+ })
+ public ConfigValue METRICS = ConfiguredValue.of(Boolean.class, true);
+
+ @HeaderComment({
+ "检查更新设定",
+ "该选项用于插件判断是否要检查更新,若您不希望插件检查更新并提示您,可以选择关闭。",
+ "检查更新为异步操作,绝不会影响性能与使用体验。"
+ })
+ public ConfigValue UPDATE_CHECKER = ConfiguredValue.of(Boolean.class, true);
+
+ @HeaderComment({"插件注册池配置"})
+ public SettingsConfig SETTINGS = new SettingsConfig();
+
+ @HeaderComment({
+ "Properties 数据库配置文件配置",
+ "相关配置介绍(BeeCP) https://github.com/Chris2018998/BeeCP/wiki/Configuration--List#配置列表"
+ })
+ public PropertiesConfig PROPERTIES = new PropertiesConfig();
+
+ @HeaderComment({
+ "数据库源配置",
+ "目前支持的驱动类型(type)有 mariadb、mysql、h2-file(文件数据库) 与 h2-mem(内存临时数据库)。",
+ "详细配置介绍请查看 https://github.com/CarmJos/MineSQL/.doc/README.md"
+ })
+ public ConfigValue SOURCES = ConfigValue.builder()
+ .asValue(SQLSourceGroup.class).fromSection()
+ .parseValue((w, d) -> SQLSourceGroup.parse(w))
+ .serializeValue(SQLSourceGroup::serialize)
+ .build();
+
+ public static class PropertiesConfig extends ConfigurationRoot {
+
+ @HeaderComment("该选项用于启用 Properties 配置读取,若您不希望插件启用 Properties 文件配置,可以选择关闭。")
+ public ConfigValue ENABLE = ConfiguredValue.of(Boolean.class, true);
+
+ @HeaderComment({
+ "文件夹路径,将读取该文件夹下的所有 .properties 文件,并以文件名为数据管理器名称。",
+ "读取时,将排除以 “.” 开头的文件与非 .properties 文件。",
+ "默认为 \"db-properties/\" 相对路径,指向“plugins/MineSQL/db-properties/”;",
+ "该选项也支持绝对路径,但使用绝对路径时,请务必注意权限问题。"
+ })
+ public ConfigValue FOLDER = ConfiguredValue.of(String.class, "db-properties/");
+
+ }
+
+ public static class SettingsConfig extends ConfigurationRoot {
+
+ @HeaderComment({"在插件卸载时是否强制关闭活跃链接"})
+ public ConfigValue FORCE_CLOSE = ConfiguredValue.of(Boolean.class, true);
+
+ }
+
+
+}
diff --git a/core/src/main/java/cc/carm/plugin/minesql/conf/SQLSourceGroup.java b/core/src/main/java/cc/carm/plugin/minesql/conf/SQLSourceGroup.java
new file mode 100644
index 0000000..2874e49
--- /dev/null
+++ b/core/src/main/java/cc/carm/plugin/minesql/conf/SQLSourceGroup.java
@@ -0,0 +1,88 @@
+package cc.carm.plugin.minesql.conf;
+
+import cc.carm.lib.configuration.core.source.ConfigurationWrapper;
+import cc.carm.plugin.minesql.MineSQL;
+import cc.carm.plugin.minesql.api.SQLDriverType;
+import cc.carm.plugin.minesql.api.conf.SQLDriverConfig;
+import cc.carm.plugin.minesql.api.conf.drivers.H2MemConfig;
+import cc.carm.plugin.minesql.api.conf.impl.FileBasedConfig;
+import cc.carm.plugin.minesql.api.conf.impl.RemoteAuthConfig;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class SQLSourceGroup {
+
+ protected final LinkedHashMap sources;
+
+ public SQLSourceGroup(LinkedHashMap sources) {
+ this.sources = sources;
+ }
+
+ public Map getSources() {
+ return Collections.unmodifiableMap(sources);
+ }
+
+ public @NotNull Map serialize() {
+ Map data = new LinkedHashMap<>();
+ this.sources.forEach((k, v) -> data.put(k, v.serialize()));
+ return data;
+ }
+
+ public static @NotNull SQLSourceGroup parse(ConfigurationWrapper> rootSection) {
+ LinkedHashMap configs = new LinkedHashMap<>();
+ for (String name : rootSection.getKeys(false)) {
+ if (!rootSection.isConfigurationSection(name)) continue;
+ ConfigurationWrapper> section = rootSection.getConfigurationSection(name);
+ if (section == null) continue;
+ SQLDriverConfig conf = parse(name, section);
+ if (conf != null) configs.put(name, conf);
+ }
+ return new SQLSourceGroup(configs);
+ }
+
+ public static @Nullable SQLDriverConfig parse(String name, ConfigurationWrapper> section) {
+ @Nullable String driverString = section.getString("type");
+ @Nullable SQLDriverType driverType = SQLDriverType.parse(driverString);
+ if (driverType == null) {
+ MineSQL.getLogger().severe("驱动类型 " + driverString + " 不存在于预设中," + " 请检查配置文件 sources." + name + "。");
+ return null;
+ }
+
+ switch (driverType) {
+ case MYSQL:
+ case MARIADB: {
+ String host = section.getString("host");
+ int port = section.getInt("port", 0);
+ String database = section.getString("database");
+ if (host == null || database == null || !(port > 0 && port <= 65535)) {
+ MineSQL.getLogger().severe("数据库连接配置有误," + " 请检查配置文件 sources." + name + "。");
+ return null;
+ }
+
+ String username = section.getString("username");
+ String password = section.getString("password");
+ String extra = section.getString("extra");
+ return new RemoteAuthConfig(driverType, host, port, database, username, password, extra);
+ }
+ case H2_MEM: {
+ return new H2MemConfig(section.getString("database"));
+ }
+ case H2_FILE: {
+ String filePath = section.getString("file");
+ if (filePath == null) {
+ MineSQL.getLogger().severe("数据库文件地址配置有误," + " 请检查配置文件 sources." + name + "。");
+ return null;
+ }
+ return new FileBasedConfig(SQLDriverType.H2_FILE, filePath);
+ }
+ }
+
+ return null;
+ }
+
+
+}
diff --git a/core/src/main/java/cc/carm/plugin/minesql/configuration/PluginConfiguration.java b/core/src/main/java/cc/carm/plugin/minesql/configuration/PluginConfiguration.java
deleted file mode 100644
index fde8c0f..0000000
--- a/core/src/main/java/cc/carm/plugin/minesql/configuration/PluginConfiguration.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package cc.carm.plugin.minesql.configuration;
-
-import cc.carm.plugin.minesql.api.DBConfiguration;
-import org.jetbrains.annotations.NotNull;
-
-import java.util.Map;
-
-public interface PluginConfiguration {
-
- boolean isDebugEnabled();
-
- boolean isMetricsEnabled();
-
- boolean isUpdateCheckerEnabled();
-
- boolean isPropertiesEnabled();
-
- String getPropertiesFolder();
-
- @NotNull Map getDBConfigurations();
-
-}
diff --git a/core/src/main/java/cc/carm/plugin/minesql/util/JarResourceUtils.java b/core/src/main/java/cc/carm/plugin/minesql/util/JarResourceUtils.java
deleted file mode 100644
index c7b4e7f..0000000
--- a/core/src/main/java/cc/carm/plugin/minesql/util/JarResourceUtils.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package cc.carm.plugin.minesql.util;
-
-import org.jetbrains.annotations.Nullable;
-
-import java.io.*;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Scanner;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-@SuppressWarnings("ResultOfMethodCallIgnored")
-public class JarResourceUtils {
- public static final char JAR_SEPARATOR = '/';
-
- public static @Nullable String[] readResource(@Nullable InputStream resourceStream) {
- if (resourceStream == null) return null;
- try (Scanner scanner = new Scanner(resourceStream, "UTF-8")) {
- List contents = new ArrayList<>();
- while (scanner.hasNextLine()) {
- contents.add(scanner.nextLine());
- }
- return contents.toArray(new String[0]);
- } catch (Exception e) {
- return null;
- }
- }
-
- public static void copyFolderFromJar(String folderName, File destFolder, CopyOption option)
- throws IOException {
- copyFolderFromJar(folderName, destFolder, option, null);
- }
-
- public static void copyFolderFromJar(String folderName, File destFolder,
- CopyOption option, PathTrimmer trimmer) throws IOException {
- if (!destFolder.exists())
- destFolder.mkdirs();
-
- byte[] buffer = new byte[1024];
-
- File fullPath;
- String path = JarResourceUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
- if (trimmer != null)
- path = trimmer.trim(path);
- try {
- if (!path.startsWith("file"))
- path = "file://" + path;
-
- fullPath = new File(new URI(path));
- } catch (URISyntaxException e) {
- e.printStackTrace();
- return;
- }
-
- ZipInputStream zis = new ZipInputStream(new FileInputStream(fullPath));
-
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null) {
- if (!entry.getName().startsWith(folderName + JAR_SEPARATOR))
- continue;
-
- String fileName = entry.getName();
-
- if (fileName.charAt(fileName.length() - 1) == JAR_SEPARATOR) {
- File file = new File(destFolder + File.separator + fileName);
- if (file.isFile()) {
- file.delete();
- }
- file.mkdirs();
- continue;
- }
-
- File file = new File(destFolder + File.separator + fileName);
- if (option == CopyOption.COPY_IF_NOT_EXIST && file.exists())
- continue;
-
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
-
- if (!file.exists())
- file.createNewFile();
- FileOutputStream fos = new FileOutputStream(file);
-
- int len;
- while ((len = zis.read(buffer)) > 0) {
- fos.write(buffer, 0, len);
- }
- fos.close();
- }
-
- zis.closeEntry();
- zis.close();
- }
-
- public enum CopyOption {
- COPY_IF_NOT_EXIST, REPLACE_IF_EXIST
- }
-
- @FunctionalInterface
- public interface PathTrimmer {
- String trim(String original);
- }
-}
\ No newline at end of file
diff --git a/core/src/main/resources/PLUGIN_INFO b/core/src/main/resources/PLUGIN_INFO
index bc7a729..b984f0e 100644
--- a/core/src/main/resources/PLUGIN_INFO
+++ b/core/src/main/resources/PLUGIN_INFO
@@ -1,11 +1,6 @@
-
-&3 ______ _____ ____ _ &f_____ _ _
-&3| ____| / ____|/ __ \| | &f| __ \| | (_)
-&3| |__ __ _ ___ _ _| (___ | | | | | &f| |__) | |_ _ __ _ _ _ __
-&3| __| / _` / __| | | |\___ \| | | | | &f| ___/| | | | |/ _` | | '_ \
-&3| |___| (_| \__ \ |_| |____) | |__| | |____ &f| | | | |_| | (_| | | | | |
-&3|______\__,_|___/\__, |_____/ \___\_\______| &f|_| |_|\__,_|\__, |_|_| |_|
-&3 __/ | &f __/ |
-&3 |___/ &f|___/
-
-&f 查看更多信息请访问项目主页&f https://github.com/CarmJos/EasySQL-Plugin
\ No newline at end of file
+&d __ ____ &f________ __
+&d / |/ (_)__ ___ &f/ __/ __ \ / /
+&d / /|_/ / / _ \/ -_)&f\ \/ /_/ / / /__
+&d/_/ /_/_/_//_/\__/&f___/\___\_\/____/
+&8# &dMine&fSQL &8&o(EasySQL-Plugin) &7v&f${project.version}
+&8- &7查看更多信息请访问项目主页&f https://github.com/CarmJos/MineSQL
\ No newline at end of file
diff --git a/core/src/main/resources/versions.properties b/core/src/main/resources/versions.properties
index 31b3885..0137059 100644
--- a/core/src/main/resources/versions.properties
+++ b/core/src/main/resources/versions.properties
@@ -1,11 +1,11 @@
# suppress inspection "SpellCheckingInspection" for whole file
plugin=${project.version}
-api=${easysql.version}
+api=${deps.easysql.version}
-beecp=${beecp.version}
+beecp=${deps.beecp.version}
-mysql-driver=${mysql-driver.version}
-mariadb-driver=${mariadb-driver.version}
-h2-driver=${h2-driver.version}
+mysql-driver=${deps.mysql-driver.version}
+mariadb-driver=${deps.mariadb-driver.version}
+h2-driver=${deps.h2-driver.version}
diff --git a/platforms/bukkit/pom.xml b/platforms/bukkit/pom.xml
index d6d363d..331855a 100644
--- a/platforms/bukkit/pom.xml
+++ b/platforms/bukkit/pom.xml
@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- easysql-plugin
+ minesql-parent
cc.carm.plugin
0.0.3-SNAPSHOT
../../pom.xml
@@ -19,12 +19,12 @@
true
- easysql-plugin-bukkit
+ minesql-bukkit
jar
- EasySQL-Plugin-Bukkit
+ MineSQL-Bukkit
轻松(用)SQL的独立运行库Bukkit版本插件。
- https://github.com/CarmJos/EasySQL-Plugin
+ https://github.com/CarmJos/MineSQL
@@ -48,19 +48,19 @@
GitHub Issues
- https://github.com/CarmJos/EasySQL-Plugin/issues
+ https://github.com/CarmJos/MineSQL/issues
GitHub Actions
- https://github.com/CarmJos/EasySQL-Plugin/actions/workflows/maven.yml
+ https://github.com/CarmJos/MineSQL/actions/workflows/maven.yml
${project.parent.groupId}
- easysql-plugin-core
+ minesql-core
${project.parent.version}
compile
@@ -68,7 +68,7 @@
cc.carm.lib
easyplugin-main
- ${easyplugin.version}
+ ${deps.easyplugin.version}
true
compile
@@ -102,66 +102,15 @@
org.apache.maven.plugins
- maven-shade-plugin
- 3.2.3
-
-
- package
-
- shade
-
-
-
-
-
- ${project.name}-${project.version}
- ${project.parent.basedir}/asset/
- false
-
-
- org.bstats
- cc.carm.plugin.minesql.lib.bstats
-
-
- org.json
- cc.carm.plugin.minesql.lib.json
-
-
- cc.carm.lib.easyplugin
- cc.carm.plugin.minesql.lib.easyplugin
-
-
- cc.carm.lib.githubreleases4j
- cc.carm.plugin.minesql.lib.githubreleases4j
-
-
- co.aikar.commands
- cc.carm.plugin.minesql.lib.acf
-
-
- co.aikar.locales
- cc.carm.plugin.minesql.lib.locales
-
-
-
-
- co.aikar:*
-
- META-INF/MANIFEST.MF
- META-INF/*.txt
- acf-core*.properties
- acf-minecraft*.properties
-
-
-
- *:*
-
- META-INF/MANIFEST.MF
- META-INF/*.txt
-
-
-
-
+ maven-source-plugin
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
diff --git a/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/BukkitConfiguration.java b/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/BukkitConfiguration.java
deleted file mode 100644
index e601d2e..0000000
--- a/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/BukkitConfiguration.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package cc.carm.plugin.minesql;
-
-import cc.carm.plugin.minesql.api.DBConfiguration;
-import cc.carm.plugin.minesql.api.SQLDriverType;
-import cc.carm.plugin.minesql.configuration.PluginConfiguration;
-import org.bukkit.configuration.ConfigurationSection;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.jetbrains.annotations.NotNull;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-public class BukkitConfiguration implements PluginConfiguration {
-
- private final @NotNull FileConfiguration configuration;
-
- protected BukkitConfiguration(@NotNull FileConfiguration configuration) {
- this.configuration = configuration;
- }
-
- public @NotNull FileConfiguration getConfiguration() {
- return configuration;
- }
-
- @Override
- public boolean isDebugEnabled() {
- return getConfiguration().getBoolean("debug", false);
- }
-
- @Override
- public boolean isMetricsEnabled() {
- return getConfiguration().getBoolean("metrics", true);
- }
-
- @Override
- public boolean isUpdateCheckerEnabled() {
- return getConfiguration().getBoolean("check-update", true);
- }
-
- @Override
- public boolean isPropertiesEnabled() {
- return getConfiguration().getBoolean("properties.enable", true);
- }
-
- @Override
- public String getPropertiesFolder() {
- return getConfiguration().getString("properties.folder", "db-properties/");
- }
-
- @Override
- public @NotNull Map getDBConfigurations() {
- Map dbConfigurations = new LinkedHashMap<>();
- ConfigurationSection dbConfigurationsSection = getConfiguration().getConfigurationSection("databases");
- if (dbConfigurationsSection != null) {
- for (String dbName : dbConfigurationsSection.getKeys(false)) {
- if (dbName.startsWith("example-")) continue;
- ConfigurationSection dbSection = dbConfigurationsSection.getConfigurationSection(dbName);
- if (dbSection == null) continue;
-
- String driverString = dbSection.getString("driver-type");
- SQLDriverType driverType = SQLDriverType.parse(driverString);
- if (driverType == null) {
- MineSQLBukkit.getInstance().error("不存在预设的驱动类型 " + driverString + "," + " 请检查配置文件 databases." + dbName + "。");
- continue;
- }
- String host = dbSection.getString("host");
- if (host == null) {
- MineSQLBukkit.getInstance().error("地址配置不得为空," + " 请检查配置文件 databases." + dbName + "。");
- continue;
- }
-
- int port = dbSection.getInt("port", -1);
- if (port < 0) {
- MineSQLBukkit.getInstance().error("端口未配置正确," + " 请检查配置文件 databases." + dbName + "。");
- continue;
- }
- DBConfiguration dbConfiguration = DBConfiguration.create(driverType, host + ":" + port);
-
- String username = dbSection.getString("username");
- String password = dbSection.getString("password");
-
- dbConfiguration.setUsername(username);
- dbConfiguration.setPassword(password);
-
- dbConfigurations.put(dbName, dbConfiguration);
- }
- }
- return dbConfigurations;
- }
-}
diff --git a/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/MineSQLBukkit.java b/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/MineSQLBukkit.java
index f86b238..6fc5aa1 100644
--- a/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/MineSQLBukkit.java
+++ b/platforms/bukkit/src/main/java/cc/carm/plugin/minesql/MineSQLBukkit.java
@@ -1,147 +1,88 @@
package cc.carm.plugin.minesql;
import cc.carm.lib.easyplugin.EasyPlugin;
-import cc.carm.lib.easyplugin.i18n.EasyPluginMessageProvider;
-import cc.carm.lib.easysql.api.SQLManager;
-import cc.carm.plugin.minesql.api.DBConfiguration;
-import cc.carm.plugin.minesql.util.DBPropertiesUtil;
-import cc.carm.plugin.minesql.util.JarResourceUtils;
-import cn.beecp.BeeDataSource;
+import cc.carm.plugin.minesql.conf.PluginConfiguration;
import co.aikar.commands.PaperCommandManager;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.SimplePie;
import org.jetbrains.annotations.NotNull;
import java.io.File;
-import java.util.*;
public class MineSQLBukkit extends EasyPlugin implements MineSQLPlatform {
- public MineSQLBukkit() {
- super(new EasyPluginMessageProvider.zh_CN());
- }
-
protected static MineSQLBukkit instance;
- private BukkitConfiguration configuration;
- private MineSQLRegistry registry;
-
- private PaperCommandManager commandManager;
+ protected MineSQLCore core;
+ protected PaperCommandManager commandManager;
@Override
protected void load() {
MineSQLBukkit.instance = this;
- log("加载配置文件...");
- getInstance().saveDefaultConfig();
- this.configuration = new BukkitConfiguration(getInstance().getConfig());
+ log("加载基础核心...");
+ this.core = new MineSQLCore(this);
- log("初始化EasySQL注册器...");
- this.registry = new MineSQLRegistry(this);
-
- log("初始化EasySQLAPI...");
- initializeAPI(getRegistry()); // 尽快地初始化接口,方便其他插件调用
+ log("初始化MineSQL API...");
+ MineSQL.initializeAPI(this.core);
}
@Override
protected boolean initialize() {
log("初始化指令管理器...");
this.commandManager = new PaperCommandManager(this);
- log("注册相关指令...");
- initializeCommands(getCommandManager());
- if (getConfiguration().isMetricsEnabled()) {
+ log("注册相关指令...");
+ this.core.initializeCommands(getCommandManager());
+
+ if (getConfiguration().METRICS.getNotNull()) {
log("启用统计数据...");
Metrics metrics = new Metrics(this, 14075);
metrics.addCustomChart(new SimplePie("update_check",
- () -> getConfiguration().isUpdateCheckerEnabled() ? "ENABLED" : "DISABLED")
+ () -> getConfiguration().UPDATE_CHECKER.getNotNull() ? "ENABLED" : "DISABLED")
);
metrics.addCustomChart(new SimplePie("properties_configuration",
- () -> getConfiguration().isPropertiesEnabled() ? "ENABLED" : "DISABLED")
+ () -> getConfiguration().PROPERTIES.ENABLE.getNotNull() ? "ENABLED" : "DISABLED")
);
}
- if (getConfiguration().isUpdateCheckerEnabled()) {
- log("开始检查更新...");
- getRegistry().checkUpdate(getDescription().getVersion());
+ if (getConfiguration().PROPERTIES.ENABLE.getNotNull()) {
+ log("开始检查更新,可能需要一小段时间...");
+ log(" 如不希望检查更新,可在配置文件中关闭。");
+ getScheduler().runAsync(() -> this.core.checkUpdate(getDescription().getVersion()));
} else {
log("已禁用检查更新,跳过。");
}
+
return true;
}
@Override
protected void shutdown() {
log("终止全部数据库连接...");
- for (String dbName : new HashSet<>(getRegistry().list().keySet())) {
- log(" 正在关闭数据库 " + dbName + "...");
- SQLManager manager = getRegistry().get(dbName);
- getRegistry().shutdown(manager, activeQueries -> {
- log(" 数据库 " + dbName + " 仍有有 " + activeQueries + " 条活动查询,强制关闭中...");
- if (manager.getDataSource() instanceof BeeDataSource) {
- BeeDataSource dataSource = (BeeDataSource) manager.getDataSource();
- dataSource.close(); //Close bee connection pool
- }
- });
- }
- getRegistry().getManagers().clear(); // release all managers
+ this.core.getRegistry().shutdownAll();
}
@Override
public boolean isDebugging() {
- return getConfiguration().isDebugEnabled();
+ return getConfiguration().DEBUG.getNotNull();
}
- @Override
- @NotNull
- public MineSQLRegistry getRegistry() {
- return this.registry;
- }
-
- @Override
- public @NotNull
- Map readConfigurations() {
- return getConfiguration().getDBConfigurations();
- }
-
- @Override
- public @NotNull
- Map readProperties() {
- if (!getConfiguration().isPropertiesEnabled()) return new HashMap<>();
- String propertiesFolder = getConfiguration().getPropertiesFolder();
- if (propertiesFolder == null || propertiesFolder.length() == 0) return new HashMap<>();
-
- File file = new File(getDataFolder(), propertiesFolder);
- if (!file.exists() || !file.isDirectory()) {
- try {
- JarResourceUtils.copyFolderFromJar(
- "db-properties", file,
- JarResourceUtils.CopyOption.COPY_IF_NOT_EXIST
- );
- } catch (Exception ex) {
- error("初始化properties示例文件失败:" + ex.getMessage());
- }
- }
-
- return DBPropertiesUtil.readFromFolder(file);
- }
-
- @Override
- public void outputInfo() {
- Optional.ofNullable(JarResourceUtils.readResource(this.getResource("PLUGIN_INFO"))).ifPresent(this::log);
- }
-
- public static MineSQLBukkit getInstance() {
+ public static @NotNull MineSQLBukkit getInstance() {
return MineSQLBukkit.instance;
}
- protected BukkitConfiguration getConfiguration() {
- return configuration;
+ public @NotNull PluginConfiguration getConfiguration() {
+ return this.core.getConfig();
}
- protected PaperCommandManager getCommandManager() {
+ public @NotNull PaperCommandManager getCommandManager() {
return commandManager;
}
+ @Override
+ public @NotNull File getPluginFolder() {
+ return getDataFolder();
+ }
}
diff --git a/platforms/bukkit/src/main/resources/plugin.yml b/platforms/bukkit/src/main/resources/plugin.yml
index 97387cf..3d30872 100644
--- a/platforms/bukkit/src/main/resources/plugin.yml
+++ b/platforms/bukkit/src/main/resources/plugin.yml
@@ -1,7 +1,8 @@
-main: cc.carm.plugin.easysql.EasySQLBukkit
+main: cc.carm.plugin.minesql.MineSQLBukkit
version: ${project.version}
-prefix: EasySQL-Plugin
-name: EasySQL-Plugin
+
+prefix: MineSQL
+name: MineSQL
load: STARTUP
website: ${project.url}
diff --git a/platforms/bungee/pom.xml b/platforms/bungee/pom.xml
index 774498b..e57f171 100644
--- a/platforms/bungee/pom.xml
+++ b/platforms/bungee/pom.xml
@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- easysql-plugin
+ minesql-parent
cc.carm.plugin
0.0.3-SNAPSHOT
../../pom.xml
@@ -19,12 +19,12 @@
true
- easysql-plugin-bungee
+ minesql-bungee
jar
- EasySQL-Plugin-Bungee
+ MineSQL-Bungee
轻松(用)SQL的独立运行库Bungee版本插件。
- https://github.com/CarmJos/EasySQL-Plugin
+ https://github.com/CarmJos/MineSQL
@@ -48,12 +48,12 @@
GitHub Issues
- https://github.com/CarmJos/EasySQL-Plugin/issues
+ https://github.com/CarmJos/MineSQL/issues
GitHub Actions
- https://github.com/CarmJos/EasySQL-Plugin/actions/workflows/maven.yml
+ https://github.com/CarmJos/MineSQL/actions/workflows/maven.yml
@@ -69,7 +69,7 @@
${project.parent.groupId}
- easysql-plugin-core
+ minesql-core
${project.parent.version}
compile
@@ -108,7 +108,6 @@
-
@@ -123,60 +122,6 @@
org.apache.maven.plugins
maven-jar-plugin
-
- org.apache.maven.plugins
- maven-javadoc-plugin
-
-
- org.apache.maven.plugins
- maven-shade-plugin
- 3.2.3
-
-
- package
-
- shade
-
-
-
-
- ${project.name}-${project.version}
- ${project.parent.basedir}/asset/
- false
-
-
- *:*
-
- META-INF/MANIFEST.MF
- META-INF/*.txt
- acf-minecraft*.properties
-
-
-
-
-
- org.bstats
- cc.carm.plugin.minesql.lib.bstats
-
-
- org.json
- cc.carm.plugin.minesql.lib.json
-
-
- cc.carm.lib.githubreleases4j
- cc.carm.plugin.minesql.lib.githubreleases4j
-
-
- co.aikar.commands
- cc.carm.plugin.minesql.lib.acf
-
-
- co.aikar.locales
- cc.carm.plugin.minesql.lib.locales
-
-
-
-
diff --git a/platforms/bungee/src/main/java/cc/carm/plugin/minesql/EasySQLBungee.java b/platforms/bungee/src/main/java/cc/carm/plugin/minesql/EasySQLBungee.java
deleted file mode 100644
index 3800621..0000000
--- a/platforms/bungee/src/main/java/cc/carm/plugin/minesql/EasySQLBungee.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package cc.carm.plugin.minesql;
-
-import net.md_5.bungee.api.plugin.Plugin;
-import net.md_5.bungee.config.Configuration;
-import net.md_5.bungee.config.ConfigurationProvider;
-import net.md_5.bungee.config.YamlConfiguration;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-
-public class EasySQLBungee extends Plugin {
-
- private boolean setup = false;
-
- private void saveDefaultConfig() {
- if (!getDataFolder().exists())
- getDataFolder().mkdir();
-
- File file = new File(getDataFolder(), "config.yml");
-
-
- if (!file.exists()) {
- try (InputStream in = getResourceAsStream("config.yml")) {
- Files.copy(in, file.toPath());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void setup() {
- if (setup) return;
- saveDefaultConfig();
- // 读取配置文件 - 预注册 instance
- Configuration configuration;
- try {
- configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(new File(getDataFolder(), "config.yml"));
- } catch (IOException e) {
- e.printStackTrace();
- return;
- }
- Configuration instancesConfig = configuration.getSection("instances");
- if (instancesConfig != null) {
- }
- setup = true;
- }
-
- @Override
- public void onLoad() {
- setup();
- }
-
- @Override
- public void onEnable() {
- setup();
- }
-
- @Override
- public void onDisable() {
- getLogger().info("Shutting down...");
- }
-
-}
diff --git a/platforms/bungee/src/main/java/cc/carm/plugin/minesql/MineSQLBungee.java b/platforms/bungee/src/main/java/cc/carm/plugin/minesql/MineSQLBungee.java
new file mode 100644
index 0000000..7737d9c
--- /dev/null
+++ b/platforms/bungee/src/main/java/cc/carm/plugin/minesql/MineSQLBungee.java
@@ -0,0 +1,93 @@
+package cc.carm.plugin.minesql;
+
+import cc.carm.plugin.minesql.conf.PluginConfiguration;
+import co.aikar.commands.BungeeCommandManager;
+import co.aikar.commands.CommandManager;
+import net.md_5.bungee.api.ProxyServer;
+import net.md_5.bungee.api.plugin.Plugin;
+import org.bstats.bungeecord.Metrics;
+import org.bstats.charts.SimplePie;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.File;
+import java.util.logging.Logger;
+
+public class MineSQLBungee extends Plugin implements MineSQLPlatform {
+
+ protected static MineSQLBungee instance;
+
+ protected MineSQLCore core;
+ protected BungeeCommandManager commandManager;
+
+ @Override
+ public void onLoad() {
+ MineSQLBungee.instance = this;
+
+ getLogger().info("加载基础核心...");
+ this.core = new MineSQLCore(this);
+
+ getLogger().info("初始化MineSQL API...");
+ MineSQL.initializeAPI(this.core);
+ }
+
+ @Override
+ public void onEnable() {
+ getLogger().info("初始化指令管理器...");
+ this.commandManager = new BungeeCommandManager(this);
+
+ getLogger().info("注册相关指令...");
+ this.core.initializeCommands(getCommandManager());
+
+ if (getConfiguration().METRICS.getNotNull()) {
+ getLogger().info("启用统计数据...");
+ Metrics metrics = new Metrics(this, 14076);
+ metrics.addCustomChart(new SimplePie("update_check",
+ () -> getConfiguration().UPDATE_CHECKER.getNotNull() ? "ENABLED" : "DISABLED")
+ );
+ metrics.addCustomChart(new SimplePie("properties_configuration",
+ () -> getConfiguration().PROPERTIES.ENABLE.getNotNull() ? "ENABLED" : "DISABLED")
+ );
+ }
+
+ if (getConfiguration().PROPERTIES.ENABLE.getNotNull()) {
+ getLogger().info("开始检查更新,可能需要一小段时间...");
+ getLogger().info(" 如不希望检查更新,可在配置文件中关闭。");
+ ProxyServer.getInstance().getScheduler().runAsync(
+ this, () -> this.core.checkUpdate(getDescription().getVersion())
+ );
+ } else {
+ getLogger().info("已禁用检查更新,跳过。");
+ }
+ }
+
+ @Override
+ public void onDisable() {
+ getLogger().info("终止全部数据库连接...");
+ this.core.getRegistry().shutdownAll();
+ }
+
+ public static MineSQLBungee getInstance() {
+ return instance;
+ }
+
+ @Override
+ public @NotNull Logger getLogger() {
+ return super.getLogger();
+ }
+
+ public @NotNull PluginConfiguration getConfiguration() {
+ return this.core.getConfig();
+ }
+
+ @Override
+ public @NotNull File getPluginFolder() {
+ return getDataFolder();
+ }
+
+ @Override
+ public @NotNull CommandManager, ?, ?, ?, ?, ?> getCommandManager() {
+ return this.commandManager;
+ }
+
+
+}
diff --git a/platforms/bungee/src/main/resources/bungee.yml b/platforms/bungee/src/main/resources/bungee.yml
new file mode 100644
index 0000000..026fed3
--- /dev/null
+++ b/platforms/bungee/src/main/resources/bungee.yml
@@ -0,0 +1,8 @@
+main: cc.carm.plugin.minesql.MineSQLBungee
+name: MineSQL
+version: ${project.version}
+
+website: ${project.url}
+description: ${project.description}
+
+author: "CarmJos"
\ No newline at end of file
diff --git a/platforms/sponge/src/main/java/cc/carm/plugin/minesql/MineSQLSponge.java b/platforms/sponge/src/main/java/cc/carm/plugin/minesql/MineSQLSponge.java
deleted file mode 100644
index 48f1ed2..0000000
--- a/platforms/sponge/src/main/java/cc/carm/plugin/minesql/MineSQLSponge.java
+++ /dev/null
@@ -1,184 +0,0 @@
-package cc.carm.plugin.minesql;
-
-import cc.carm.lib.easysql.api.SQLManager;
-import cc.carm.plugin.minesql.api.DBConfiguration;
-import cc.carm.plugin.minesql.configuration.PluginConfiguration;
-import cc.carm.plugin.minesql.util.DBPropertiesUtil;
-import cc.carm.plugin.minesql.util.JarResourceUtils;
-import cn.beecp.BeeDataSource;
-import com.google.common.io.MoreFiles;
-import com.google.inject.Inject;
-import org.apache.logging.log4j.Logger;
-import org.bstats.charts.SimplePie;
-import org.bstats.sponge.Metrics;
-import org.jetbrains.annotations.NotNull;
-import org.spongepowered.api.Server;
-import org.spongepowered.api.config.ConfigDir;
-import org.spongepowered.api.event.Listener;
-import org.spongepowered.api.event.lifecycle.StoppingEngineEvent;
-import org.spongepowered.configurate.ConfigurateException;
-import org.spongepowered.configurate.ConfigurationNode;
-import org.spongepowered.configurate.hocon.HoconConfigurationLoader;
-import org.spongepowered.plugin.PluginContainer;
-import org.spongepowered.plugin.builtin.jvm.Plugin;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * 2022/6/20
- * MineSQL
- *
- * @author huanmeng_qwq
- */
-@Plugin("easysql-plugin")
-public class MineSQLSponge implements MineSQLPlatform {
- @Inject
- @ConfigDir(sharedRoot = false)
- private Path configDirectory;
- @Inject
- private org.apache.logging.log4j.Logger logger;
-
- private static MineSQLSponge instance;
- private ConfigurationNode root;
- private PluginConfiguration configuration;
- private MineSQLRegistry registry;
- private PluginContainer pluginContainer;
-
- private final Metrics metrics;
-
- @Inject
- public MineSQLSponge(Metrics.Factory factory, PluginContainer pluginContainer) {
- this.metrics = factory.make(14075);
- instance = this;
- HoconConfigurationLoader loader = HoconConfigurationLoader.builder().path(resolveConfig()).build();
- try {
- this.root = loader.load();
- this.configuration = new SpongeConfiguration(root);
- this.registry = new MineSQLRegistry(this);
- this.pluginContainer = pluginContainer;
- enable();
- } catch (ConfigurateException ex) {
- throw new RuntimeException(ex);
- }
- }
-
- @Listener
- public void disable(StoppingEngineEvent e) {
- getLog().info("终止全部数据库连接...");
- for (String dbName : new HashSet<>(getRegistry().list().keySet())) {
- getLog().info(" 正在关闭数据库 " + dbName + "...");
- SQLManager manager = getRegistry().get(dbName);
- getRegistry().shutdown(manager, activeQueries -> {
- getLog().info(" 数据库 " + dbName + " 仍有有 " + activeQueries + " 条活动查询,强制关闭中...");
- if (manager.getDataSource() instanceof BeeDataSource) {
- BeeDataSource dataSource = (BeeDataSource) manager.getDataSource();
- dataSource.close(); //Close bee connection pool
- }
- });
- }
- getRegistry().getManagers().clear(); // release all managers
- }
-
-
- public void enable() {
- /*
- //todo acf-commands not support sponge8
- getLog().info("初始化指令管理器...");
- getLog().info("注册相关指令...");
- */
-
- if (getConfiguration().isMetricsEnabled()) {
- getLog().info("启用统计数据...");
- metrics.addCustomChart(new SimplePie("update_check",
- () -> getConfiguration().isUpdateCheckerEnabled() ? "ENABLED" : "DISABLED")
- );
- metrics.addCustomChart(new SimplePie("properties_configuration",
- () -> getConfiguration().isPropertiesEnabled() ? "ENABLED" : "DISABLED")
- );
- }
-
- if (getConfiguration().isUpdateCheckerEnabled()) {
- getLog().info("开始检查更新...");
- getRegistry().checkUpdate(pluginContainer.metadata().version().getQualifier());
- } else {
- getLog().info("已禁用检查更新,跳过。");
- }
- }
-
- @Override
- public @NotNull Map readConfigurations() {
- return configuration.getDBConfigurations();
- }
-
- @Override
- public @NotNull Map readProperties() {
- if (!getConfiguration().isPropertiesEnabled()) return new HashMap<>();
- String propertiesFolder = getConfiguration().getPropertiesFolder();
- if (propertiesFolder == null || propertiesFolder.length() == 0) return new HashMap<>();
-
- File file = new File(configDirectory.toFile(), propertiesFolder);
- if (!file.exists() || !file.isDirectory()) {
- try {
- JarResourceUtils.copyFolderFromJar(
- "db-properties", file,
- JarResourceUtils.CopyOption.COPY_IF_NOT_EXIST
- );
- } catch (Exception ex) {
- logger.error("初始化properties示例文件失败:" + ex.getMessage());
- }
- }
-
- return DBPropertiesUtil.readFromFolder(file);
- }
-
-
- private Path resolveConfig() {
- Path path = configDirectory.resolve("easysql.conf");
- if (!Files.exists(path)) {
- try {
- //noinspection UnstableApiUsage
- MoreFiles.createParentDirectories(configDirectory);
- try (InputStream is = getClass().getClassLoader().getResourceAsStream("easysql.conf")) {
- Files.copy(is, path);
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- return path;
- }
-
- public ConfigurationNode getRootConfig() {
- return root;
- }
-
- public PluginConfiguration getConfiguration() {
- return configuration;
- }
-
- @Override
- public @NotNull MineSQLRegistry getRegistry() {
- return registry;
- }
-
- public java.util.logging.Logger getLogger() {
- return java.util.logging.Logger.getLogger("easysql-plugin");
- }
-
- public static MineSQLSponge getInstance() {
- return instance;
- }
-
- public Logger getLog() {
- return logger;
- }
-}
diff --git a/platforms/sponge/src/main/java/cc/carm/plugin/minesql/SpongeConfiguration.java b/platforms/sponge/src/main/java/cc/carm/plugin/minesql/SpongeConfiguration.java
deleted file mode 100644
index bfe4eed..0000000
--- a/platforms/sponge/src/main/java/cc/carm/plugin/minesql/SpongeConfiguration.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package cc.carm.plugin.minesql;
-
-import cc.carm.plugin.minesql.api.DBConfiguration;
-import cc.carm.plugin.minesql.api.SQLDriverType;
-import cc.carm.plugin.minesql.configuration.PluginConfiguration;
-import org.jetbrains.annotations.NotNull;
-import org.spongepowered.configurate.ConfigurationNode;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * 2022/6/20
- * MineSQL
- *
- * @author huanmeng_qwq
- */
-public class SpongeConfiguration implements PluginConfiguration {
- private final ConfigurationNode config;
-
- public SpongeConfiguration(ConfigurationNode config) {
- this.config = config;
- }
-
- @Override
- public boolean isDebugEnabled() {
- return config.node("debug").getBoolean(false);
- }
-
- @Override
- public boolean isMetricsEnabled() {
- return config.node("metrics").getBoolean(false);
- }
-
- @Override
- public boolean isUpdateCheckerEnabled() {
- return config.node("check-update").getBoolean(true);
- }
-
- @Override
- public boolean isPropertiesEnabled() {
- return config.node("properties", "enable").getBoolean(true);
- }
-
- @Override
- public String getPropertiesFolder() {
- return config.node("properties", "folder").getString("db-properties/");
- }
-
- @Override
- public @NotNull Map getDBConfigurations() {
- Map dbConfigurations = new LinkedHashMap<>();
- ConfigurationNode dbConfigurationsSection = config.node("databases");
- if (dbConfigurationsSection != null) {
- for (Map.Entry