[Editor] Create DatabaseService and add support for fetching database tables

This commit is contained in:
2021-03-24 23:05:31 +01:00
parent 0b5ea55b87
commit 761b878156
5 changed files with 104 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
package com.bartlomiejpluta.base.editor.database.model
class Column(val table: Table, val name: String, val type: ColumnType, val nullable: Boolean, val primary: Boolean)

View File

@@ -0,0 +1,31 @@
package com.bartlomiejpluta.base.editor.database.model
enum class ColumnType {
INT,
BOOLEAN,
TINYINT,
SMALLINT,
BIGINT,
IDENTITY,
DECIMAL,
DOUBLE,
REAL,
TIME,
TIME_WITH_TIME_ZONE,
DATE,
TIMESTAMP,
TIMESTAMP_WITH_TIME_ZONE,
BINARY,
OTHER,
VARCHAR,
VARCHAR_IGNORECASE,
CHAR,
BLOB,
CLOB,
UUID,
ARRAY,
ENUM,
GEOMETRY,
JSON,
INTERVAL
}

View File

@@ -0,0 +1,12 @@
package com.bartlomiejpluta.base.editor.database.model
class Table(val name: String) {
private val mutableColumns = mutableListOf<Column>()
val columns: List<Column>
get() = mutableColumns
fun addColumn(name: String, type: ColumnType, nullable: Boolean, primary: Boolean) {
val column = Column(this, name, type, nullable, primary)
mutableColumns += column
}
}

View File

@@ -0,0 +1,7 @@
package com.bartlomiejpluta.base.editor.database.service
import com.bartlomiejpluta.base.editor.database.model.Table
interface DatabaseService {
val tables: List<Table>
}

View File

@@ -0,0 +1,51 @@
package com.bartlomiejpluta.base.editor.database.service
import com.bartlomiejpluta.base.editor.database.model.ColumnType
import com.bartlomiejpluta.base.editor.database.model.Table
import com.bartlomiejpluta.base.editor.project.context.ProjectContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.sql.Connection
@Service
class H2DatabaseService : DatabaseService {
@Autowired
private lateinit var projectContext: ProjectContext
override val tables: List<Table>
get() {
val tables = connection {
val tables = mutableListOf<Table>()
val results = prepareStatement("SHOW TABLES").executeQuery()
while (results.next()) {
if (results.getString("TABLE_SCHEMA") == "PUBLIC") {
tables.add(Table(results.getString("TABLE_NAME")))
}
}
tables
} ?: emptyList()
tables.forEach { table ->
connection {
val results = prepareStatement("SHOW COLUMNS FROM ${table.name}").executeQuery()
while (results.next()) {
table.addColumn(
results.getString("FIELD"),
parseType(results.getString("TYPE")),
results.getBoolean("NULL"),
results.getString("KEY") == "PRI"
)
}
}
}
return tables
}
private inline fun <reified T> connection(op: Connection.() -> T) =
projectContext.project?.database?.connection?.use(op)
private fun parseType(type: String) = ColumnType.valueOf(type.replace(" ", "_").substringBefore("("))
}