0

Trying out Kotlin Exposed for the first time. I have been able to learn Kotlin to a reasonable extent now and now I'm trying to learn Kotlin Exposed API for database access. But I'm unable to find an equivalent for SHOW tables; of MySQL.

It would be nice to be able to list out tables without previously hard coding them into the program.

Is there an equivalent to that query in Exposed? if so how? Thanks in advance

Deepan
  • 124
  • 1
  • 10
  • if I may ask, why do you want to list the db tables from within the code? – euniceadu Mar 24 '19 at 09:14
  • I want to write extensible code that would automatically create pages for each individual table, and a navbar with the list of tables. so when the application loads I want to populate the list of tables dynamically from the database. the database will change anytime and tables may get added in the future – Deepan Mar 24 '19 at 10:52

2 Answers2

3

There is VendorDialect.allTableNames() function in Exposed which uses jdbc DatabaseMetadata to fetch tables.

Database.connect(/* your connection string */)

transaction { 
    val tableNames = TransactionManager.current().db.dialect.allTablesNames()
}
Dark Knight
  • 6,116
  • 1
  • 15
  • 37
Tapac
  • 1,889
  • 1
  • 14
  • 18
1

From what I've seen in the documentation and the source code so far, the fetchAllTables method in the SchemaUtils class is private so your best option will be to execute a MySQL query. The code below does what you want:

val connect = Database.Companion.connect(dataSource())

    val tableNames = mutableListOf<String>()

    transaction {
        val conn = TransactionManager.current().connection
        val statement = conn.createStatement()
        val query = "show tables"
        statement.execute(query)
        val results = statement.resultSet
        while (results.next()) {
            tableNames.add(results.getString(1))
        }
    }

    tableNames.forEach {
        println(it)
    }
euniceadu
  • 868
  • 16
  • 34
  • I understand. I just have to use the normal piece of code instead of Exposed. I hope there's a way to do this in exposed. because I might want to construct the DAO dynamically too using `describe;` – Deepan Mar 24 '19 at 12:04