Groovyで、テーブル一覧、テーブル定義をHTML出力してみる

2022-10-16Groovy

最近参入したプロジェクトでテーブル定義がない(!?)ため、さっと作ってみました。

出力された内容はまだ見にくいし、Not Null 制約の出力結果がなんだか怪しいけど、ないよりましでしょう。

import groovy.sql.*
import java.sql.ResultSet

def props = [
    user:"てきとうに"
    ,password:"にゅうりょく"
] as Properties
def url = "してね"
def driver = "oracle.jdbc.driver.OracleDriver"

def outputEacchRow = { w, closure ->
    w << """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">n"""
    w << """<?xml version="1.0" encoding="UTF-8"?>n"""
    new groovy.xml.MarkupBuilder(w).html(){
        head(){
            meta('http-equiv':"Content-Type", content:"text/html;charset=UTF8")
            meta('http-equiv':"Content-Style-Type", content:"text/css;charset=UTF8")
            link(rel:"stylesheet", href:"style.css")
        }
        body(){
            table closure
        }
    }
}

def gsql
try{
    gsql = Sql.newInstance(
        url
        ,props
        ,driver)

    def rs = gsql.connection.metaData.getColumns(null, props.user, "%", "%")

    def rows = []
    while(rs.next()){
        rows << rs.toRowResult()
    }
    rs.close()
    def entities = rows.groupBy{ it.TABLE_NAME }.findAll{ !(it.key =~ /.*BIN$.*/) }.sort{ it.key }

    // 出力処理
    def dir = new File("entities")
    if( !dir.exists() || dir.file )
        dir.mkdirs()
    new File("$dir/index.html").withWriter("UTF8"){
        outputEacchRow(it){
            def i = 0

            tr(){
                th "ID"
                th "名称"
            }

            entities.keySet().each{ tableName ->
                tr('class':(i++%2)?"odd":""){
                    td(){

                        a(href:"${tableName}.html", tableName)
                    }
                    td Mapper.tables[tableName]
                }
            }
        }
    }

    entities.each{ entity ->
        def columns = entity.value
        new File("$dir/${entity.key}.html").withWriter("UTF8"){
            outputEacchRow(it){
                tr(){
                    th "ID"
                    th "名称"
                    th "型"
                    th "サイズ"
                    th "NOT NULL"
                }

                def i = 0
                columns.each{ column ->
                    tr('class':(i++%2)?"odd":""){
                        td column.COLUMN_NAME
                        td (Mapper.columns[column.COLUMN_NAME])
                        td column.TYPE_NAME
                        td column.COLUMN_SIZE
                        td (!column.IS_NULLABLE)
                    }
                }
            }
        }
    }
} finally {
    gsql?.close()
}

2022-10-16Groovy