Version v1.2 of the documentation is no longer actively maintained. The site that you are currently viewing is an archived snapshot. For up-to-date documentation, see the latest version.

クエリのデバッグ

概要

データベースへ接続することなくクエリから生成されるSQLを確認できます。

dryRun

クエリに対してdryRun関数を呼び出すと、クエリによって生成されるSQLやクエリにバインドされた引数を確認できます。

val query: Query<List<Address>> = QueryDsl.from(a).where { a.addressId eq 1 }
val result: DryRunResult = query.dryRun()
println(result)

上記のコードの出力結果は以下の通りです(見やすさのため改行を入れています)。

DryRunResult(
  sql=select t0_.ADDRESS_ID, t0_.STREET, t0_.VERSION from ADDRESS as t0_ where t0_.ADDRESS_ID = ?, 
  sqlWithArgs=select t0_.ADDRESS_ID, t0_.STREET, t0_.VERSION from ADDRESS as t0_ where t0_.ADDRESS_ID = 1, 
  args=[Value(any=1, klass=class kotlin.Int)], 
  throwable=null, 
  description=This data was generated using DryRunDatabaseConfig. To get more correct information, specify the actual DatabaseConfig instance.
)

DryRunResultクラスのプロパティの意味は次の通りです。

sql
クエリから生成されるSQL。バインド変数は?で表現される。例外が発生した場合はSQLではなく例外のメッセージを表す。
sqlWithArgs
クエリから生成される引数付きのSQL。バインド変数は引数の文字列表現で置換されている。例外が発生した場合はSQLではなく例外のメッセージを表す。
args
引数の値と型のペア。
throwable
クエリの生成中にスローされた例外。例外が発生しなかった場合はnull
description
DryRunResultのインスタンスに対する説明。

Dialectの利用

引数なしのdryRun関数は、接続先データベースの ダイアレクト を考慮しない結果を返します。 Dialectを考慮した結果を取得したい場合はDatabaseConfigインスタンスを渡してください。

val database: JdbcDatabase = ...
val query: Query<List<Address>> = QueryDsl.from(a).where { a.addressId eq 1 }
val result: DryRunResult = query.dryRun(database.config)
println(result)

もしくは、DatabaseインスタンスのdryRun関数を呼び出してください。

val database: JdbcDatabase = ...
val query: Query<List<Address>> = QueryDsl.from(a).where { a.addressId eq 1 }
val result: DryRunResult = database.dryRun(query)
println(result)

クエリ構築途中のデバッグ

also関数と組み合わせれば構築途中のクエリ情報を確認できます。

val query: Query<List<Address>> = QueryDsl.from(a)
  .also {
    println("1:" + it.dryRun().sql)
  }.where {
    a.addressId eq 1
  }.also {
    println("2:" + it.dryRun().sql)
  }.orderBy(a.addressId)
  .also {
    println("3:" + it.dryRun().sql)
  }

上記コードの実行結果は以下の通りです。

1:select t0_.ADDRESS_ID, t0_.STREET, t0_.VERSION from ADDRESS as t0_
2:select t0_.ADDRESS_ID, t0_.STREET, t0_.VERSION from ADDRESS as t0_ where t0_.ADDRESS_ID = ?
3:select t0_.ADDRESS_ID, t0_.STREET, t0_.VERSION from ADDRESS as t0_ where t0_.ADDRESS_ID = ? order by t0_.ADDRESS_ID asc
最終更新 March 10, 2022: Update the title and linkTitle (9e170b8)