티스토리 뷰

오늘 일을 하다, 몇몇 테이블에서 url 컬럼에 시작값이 http://www.daum.net 또는 http://www.naver.com 또는 http://www.nate.com 인 녀석들의 통계를 구하는 작업을 했습니다.(여기서 컬럼명 url, 값 네이버, 다음, 네이트 등등은 실제 데이터는 아닙니다.)

이 작업은 꽤 많은 테이블에 반복적인 쿼리를 날려야 하는 일로, 쉽지않은 방법으로 아래와 같은 그루비(=Groovy) 코드를 만들었습니다.

@GrabConfig(systemClassLoader=true)
@Grab(group='mysql', module='mysql-connector-java', version='5.1.21')

import groovy.sql.Sql

def db1 = Sql.newInstance('jdbc:mysql://DB_SERVER1:3306/db1','ID', 'Password', 'com.mysql.jdbc.Driver')
def db2 = Sql.newInstance('jdbc:mysql://DB_SERVER2:3306/db2','ID', 'Password', 'com.mysql.jdbc.Driver')
def db1_tables = [ 'T001', 'T002']
def db2_tables = [ 'T003', 'T004']

countEmbedTypes = { bbs, tables ->
    tables.each{ table ->
        bbs.eachRow(
            """
            SELECT 
                SUM(1) AS 'Total',
                SUM(IF (url LIKE "http://www.daum.net%", 1, 0)) AS 'daum',
                SUM(IF (url LIKE "http://www.naver.com%", 1, 0)) AS 'naver',
                SUM(IF (url LIKE "http://www.nate.com/%", 1, 0)) AS 'nate'
                FROM """ + table
        ){
            def total = toInt(it.Total)
            def daum = toInt(it.daum)
            def naver = toInt(it.naver)
            def nate = toInt(it.nate)
            printf ( "| %6s | %6s | %6s | %6s | %6s | \n", [table, total, daum, naver, nate])
        }
    }
}

def toInt(i) {
    return (i == null) ? 0 : i.toInteger()
}

countUrlTypes(db1, db1_tables)
countUrlTypes(db2, db2_tables)

첫 번째 난관은 SQL 쿼리를 만드는 일, 이건 StackOverflow 에서 해답을 구했습니다. 아래와 같은 형태로. 몇번 실행해보니 원하던 값이 나오더군요.

SELECT
    SUM(1) AS 'Total',
    SUM(IF (url LIKE "http://www.daum.net%", 1, 0)) AS 'daum',
    SUM(IF (url LIKE "http://www.naver.com%", 1, 0)) AS 'naver',
    SUM(IF (url LIKE "http://www.nate.com/%", 1, 0)) AS 'nate'
FROM YOUR_TABLE

두번째 난관은 그루비에서 MySQL 서버에 연결하는 방법.

import groovy.sql.Sql
def db1 = Sql.newInstance('jdbc:mysql://DB_SERVER1:3306/db1','ID', 'Password', 'com.mysql.jdbc.Driver')

그루비 홈페이지에서 위와 같은 코드는 쉽게 발견할 수 있었는데, 문제는 예제 코드를 실행하면, com.mysql.jdbc.Driver 관련 클래스를 찾을 수 없다는 오류 메시지.

혹시나해서 Maven Classpath를 Groovy에서 쓸수 있는 방법을 찾다가. @Grab 이란 표현으로 메이븐 저장소의 라이브러리를 읽어 올 수 있다는 방법을 알게 되었습니다.

@Grab(group='mysql', module='mysql-connector-java', version='5.1.21')

그리고, 데이터베이스 드라이버의 경우, @GrabConfig 에서 systemClassLoadertrue로 설정해야 한다고 합니다.

@GrabConfig(systemClassLoader=true)

systemClassLoader 설정은 그루비 API 페이지에, 아래와 같은 설명으로 되어 있는데, 내용은 잘 이해가 안되네여.. '포도'를 로딩하다니,...

Set to true if you want to use the system classloader when loading the grape. This is normally only required when a core Java class needs to reference the grabbed classes, e.g. for a database driver accessed using DriverManager.

그 외에도 그루비 클로져도 찾아 쓰고, 함수도 찾아 써봐서, 생각보다 어렵게 하지만 재미있는 스크립트를 만들 수 있었습니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함