LoginSignup
3
0

More than 5 years have passed since last update.

GroovyでuroboroSQLをさくっと試してみる

Last updated at Posted at 2017-08-04

概要

Groovyスクリプトにて、オープンソースのuroboroSQLを試してみました。
uroboroSQLのドキュメントはこちら

サンプルのツリー構造

  • sqlはsqlフォルダ配下に配置する
$ tree .                                                                                                                              .
├── logback.xml
├── sql
│   ├── ddl
│   │   └── createTable.sql
│   └── dml
│       ├── delete.sql
│       ├── insert.sql
│       └── select.sql
└── uroborotest.groovy

実行するSQL

sql/ddl/createTable.sql
create table if not exists  address (
    id bigserial,
    name text,
    zip text
)
sql/dml/delete.sql
delete from address
sql/dml/insert.sql
insert into address(name,zip) values (/*name*/'',/*zip*/'')
sql/dml/select.sql
select id,name,zip from address
where name = /*name*/''

ログ設定

uroborosqlのレベルを変更(DEBUG)にすることにより、展開されたSQLやパラメータ等が詳細に表示されます

logback.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!-- logを標準出力に出力 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- ターゲットを標準出力へ -->
        <Target>System.out</Target>
        <!-- パターンレイアウト -->
        <encoder>
            <pattern>[%-5p] %m%n</pattern>
        </encoder>
    </appender>

    <logger name="jp.co.future.uroborosql" level="${LOGLEVEL}" />

    <appender name="CoverageLog" class="ch.qos.logback.core.FileAppender">
        <file>target/coverage.log</file>
        <append>true</append>
        <encoder>
            <pattern>%m%n</pattern>
        </encoder>
    </appender>

    <logger name="jp.co.future.uroborosql.coverage" level="TRACE"
            additivity="false">
        <appender-ref ref="CoverageLog" />
    </logger>


    <!-- ログ出力に関する設定 -->
    <root>
        <!-- 出力するレベルを設定 -->
        <level value="INFO" />

        <!-- アペンダを設定 -->
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Groovyスクリプト

uroborotest.groovy
//@GrabConfig( systemClassLoader=true )
@Grab(group='jp.co.future', module='uroborosql', version='0.2.0') 
@Grab(group='org.postgresql', module='postgresql', version='42.1.3')
@Grab(group='ch.qos.logback', module='logback-classic', version='1.2.3')

import jp.co.future.uroborosql.* 
import jp.co.future.uroborosql.config.* 
import jp.co.future.uroborosql.store.* 

def url = "jdbc:postgresql://127.0.0.1:5432/dbname"
def usr = "user"
def psw = "password"

//Class.forName("org.postgresql.Driver")

// DB接続情報を設定
def config = DefaultSqlConfig.getConfig(url, usr, psw)
def sqlContextFactory = config.getSqlContextFactory()
sqlContextFactory.initialize();

// SqlAgentを作成
def agent = config.createAgent()

// テーブルを作成 (sqlファイルの指定では、拡張子は指定しない)
agent.update("ddl/createTable").count()

// データの削除
def count = agent.update("dml/delete").count()
println("$count rows deleted")

// 挿入するデータ
def params =  [ 
    [ name: 'Mr.Bean'      , zip: 'UK' ]
,   [ name: 'Mr.Nagashima' , zip: 'JP' ]
]

// データの更新(バッチモード)
def updater = agent.update("dml/insert")
params.each { 
    updater.paramMap(it)
    updater.addBatch()
}
def result = updater.batch()
println("${result.size()} rows created")


// データの選択
def selector = agent.query("dml/select")
selector.param("name","Mr.Nagashima").collect().each {
    println(it)
}

// 処理終了
agent.commit()
agent.close()

実行結果

-DLOGLEVELにINFO|DEBUG|TRACEのいずれかを指定することで、uroboroSQLのログレベルを調整できます

$ groovy --version                                                           
Groovy Version: 2.4.10 JVM: 1.8.0_121 Vendor: Oracle Corporation OS: Linux

$ groovy -DLOGLEVEL=DEBUG uroborotest.groovy
[DEBUG] Start loading SQL template.[/mnt/ramdisk/uroborosql/sql]
[DEBUG] Loading SQL template.[]
[DEBUG] Loading SQL template.[dml]
[DEBUG] Loading SQL template.[ddl]
[DEBUG] Executed SQL[
create table if not exists  address (
    id bigserial,
    name text,
    zip text
)
]
[DEBUG] Execute update SQL.
[DEBUG] SQL execution time [ddl/createTable] : [00:00:00.002]
[DEBUG] Executed SQL[
delete from address
]
[DEBUG] Execute update SQL.
[DEBUG] SQL execution time [dml/delete] : [00:00:00.000]
2 rows deleted
[DEBUG] Executed SQL[
insert into address(name,zip) values (?/*name*/,?/*zip*/)
]
[DEBUG] 2 items Added for batch process.
[DEBUG] Execute batch process.
[DEBUG] SQL execution time [dml/insert] : [00:00:00.002]
2 rows created
[DEBUG] Executed SQL[
select id,name,zip from address
where name = ?/*name*/
]
[DEBUG] Set the parameter.[INDEX[1], Parameter name[name], Value[Mr.Nagashima], Class[String]]
[DEBUG] Execute search SQL.
[DEBUG] SQL execution time [dml/select] : [00:00:00.008]
[ID:54, NAME:Mr.Nagashima, ZIP:JP]
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0