Skip to content

Instantly share code, notes, and snippets.

@ossan-pg
Last active May 23, 2018 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ossan-pg/da7e413966e2c2c945799a1181a6cd4d to your computer and use it in GitHub Desktop.
Save ossan-pg/da7e413966e2c2c945799a1181a6cd4d to your computer and use it in GitHub Desktop.
Spring プロジェクトのテスト時に手軽に SQL を実行したかったがうまくいかなかったのでユーティリティークラスを自前で用意した。
package com.github.ossan_pg
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.env.Environment
import org.springframework.core.io.ResourceLoader
import org.springframework.stereotype.Component
import groovy.sql.Sql
import groovy.transform.TupleConstructor
@Component
@TupleConstructor
public class SqlUtil { // TODO ○○Util は避けたかったがいい名称が思い浮かばなかった。いつか直したい。
@Autowired
final Environment env
@Autowired
final ResourceLoader loader;
/**
* クラスパスからの相対パスで {@code files} に指定された各ファイル内の
* SQL文を順に実行します。<br>
* <br>
* Maven プロジェクト構成で {@code src/test/resources} に
* {@code data1.sql} と {@code data2.sql} が存在した場合、
* このメソッドを {@code executeFile('data1.sql', 'data2.sql')} のように呼び出すと
* {@code data1.sql} の SQL文を実行し、その後 {@code data2.sql} の SQL文を
* 実行します。
* @param files SQL文が記述されているファイルのパスの配列。
*/
public void executeFile(final String... files) {
final String[] sqls = files.collect {
loader.getResource('classpath:' + it).file.text
}.toArray(new String[0])
this.execute(sqls)
}
/**
* {@code sqls} に指定された SQL文を順に実行します。<br>
* <br>
* {@code sqls} の 1つの要素に複数の SQL文が存在する場合、それらを順に実行します。<br>
* {@code sqls} の内容が下記のような場合、{@code DELETE} 文、{@code INSERT} 文、{@code UPDATE} 文の順で実行します。<br>
* <ul>
* <li>{@code sql[0]: "DELETE FROM hoge WHERE id = 123; INSERT INTO hoge(id, name) VALUES(123, 'old_name');"}</li>
* <li>{@code sql[1]: "UPDATE hoge SET name = 'new_name'";}</li>
* </ul>
* @param sqls 実行する SQL文の配列。
*/
public void execute(final String... sqls) {
final Sql conn = Sql.newInstance(
env.getRequiredProperty('spring.datasource.url'),
env.getRequiredProperty('spring.datasource.username'),
env.getRequiredProperty('spring.datasource.password'),
env.getRequiredProperty('spring.datasource.driver-class-name'))
sqls.each { sql -> conn.execute(sql) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment