package com.zy.system.config;
|
|
import org.springframework.stereotype.Component;
|
|
import javax.annotation.PostConstruct;
|
import javax.sql.DataSource;
|
import java.sql.Connection;
|
import java.sql.DatabaseMetaData;
|
import java.sql.ResultSet;
|
import java.sql.Statement;
|
|
@Component
|
public class LicenseSchemaInitializer {
|
|
private final DataSource dataSource;
|
|
public LicenseSchemaInitializer(DataSource dataSource) {
|
this.dataSource = dataSource;
|
}
|
|
@PostConstruct
|
public void init() {
|
ensureTable();
|
ensureColumn("sys_license_infos", "request_code", "NVARCHAR(2048) NULL");
|
}
|
|
private void ensureTable() {
|
try (Connection connection = dataSource.getConnection()) {
|
if (hasTable(connection, "sys_license_infos")) {
|
return;
|
}
|
try (Statement statement = connection.createStatement()) {
|
statement.executeUpdate("CREATE TABLE sys_license_infos ("
|
+ "id INT IDENTITY(1,1) NOT NULL PRIMARY KEY, "
|
+ "[license] NVARCHAR(MAX) NULL, "
|
+ "license_time NVARCHAR(255) NULL, "
|
+ "request_code NVARCHAR(2048) NULL, "
|
+ "create_time DATETIME NULL)");
|
}
|
} catch (Exception ignored) {
|
}
|
}
|
|
private void ensureColumn(String tableName, String columnName, String columnDefinition) {
|
try (Connection connection = dataSource.getConnection()) {
|
if (!hasTable(connection, tableName) || hasColumn(connection, tableName, columnName)) {
|
return;
|
}
|
try (Statement statement = connection.createStatement()) {
|
statement.executeUpdate("ALTER TABLE " + tableName + " ADD " + columnName + " " + columnDefinition);
|
}
|
} catch (Exception ignored) {
|
}
|
}
|
|
private boolean hasTable(Connection connection, String tableName) throws Exception {
|
DatabaseMetaData metaData = connection.getMetaData();
|
try (ResultSet resultSet = metaData.getTables(connection.getCatalog(), null, tableName, new String[]{"TABLE"})) {
|
while (resultSet.next()) {
|
if (tableName.equalsIgnoreCase(resultSet.getString("TABLE_NAME"))) {
|
return true;
|
}
|
}
|
}
|
return false;
|
}
|
|
private boolean hasColumn(Connection connection, String tableName, String columnName) throws Exception {
|
DatabaseMetaData metaData = connection.getMetaData();
|
try (ResultSet resultSet = metaData.getColumns(connection.getCatalog(), null, tableName, columnName)) {
|
while (resultSet.next()) {
|
if (columnName.equalsIgnoreCase(resultSet.getString("COLUMN_NAME"))) {
|
return true;
|
}
|
}
|
}
|
return false;
|
}
|
}
|