Newer
Older
osmCoverage / src / osm / jp / postgis / Postgis.java
@hayashi hayashi on 5 Aug 2018 2 KB new class: Postgis.java
package osm.jp.postgis;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import jp.co.areaweb.tools.database.DatabaseTool;

/**
 * 国土数値情報から読み取ったデータをPostGISへインサートするためのSQLファイルに出力する。
 * 	出力ファイル名:	"t_POSTOFFICE.sql"
 * 	テーブル名:		t_POSTOFFICE
 * 	インデックス:	ix_t_POSTOFFICE_geom
 * 		gid	PostGISの識別ID
 * 		idstr	国土数値情報のノードID
 * 		fixed	OSMのNodeが周辺に存在するかどうか、存在しない場合は0,存在する場合はそのScoreの合計。
 *              area    都道府県コード
 * 		geom	PostGIS形式の位置情報(4612:)
 * @author yuu
 *
 */
public class Postgis implements AutoCloseable
{
    public static void main(String[] args) throws Exception {
        try (Postgis db = new Postgis()) {
            db.initTableAll();
        }
    }
    
    static final String TABLE_FUEL = "t_fuel";
    static final String[] TABLES = {TABLE_FUEL};
    Connection con = null;
    
    public Postgis() throws ClassNotFoundException, SQLException, IOException {
        con = DatabaseTool.openDb("postgis");
    }

    @Override
    public void close() throws Exception {
        if (con != null) {
            DatabaseTool.closeDb(con);
        }
    }
    
    public void initTableAll() throws Exception {
        for (String tableName : TABLES) {
            initTable(tableName);
        }
    }

    public void initTable(String tableName) throws Exception {
        sql("DROP TABLE IF EXISTS "+ tableName +" CASCADE;");
        sql("CREATE TABLE public."+ tableName 
            +" ("
                + "gid SERIAL PRIMARY KEY, "
                + "gmlid varchar(24), "
                + "idref varchar(24), "
                + "fixed integer, "
                + "area integer, "
                + "code integer, "
                + "geom GEOMETRY(POINT, 4612)"
            + ");");
        sql("CREATE INDEX ix_"+ tableName +"_geom ON "+ tableName +" USING GiST (geom);");
    }

    public void sql(String sql) throws SQLException {
        System.out.println(sql);
        try (PreparedStatement ps = this.con.prepareStatement(sql)) {
            ps.executeUpdate();
        }
        catch (SQLSyntaxErrorException e) {
            System.out.println("107:"+ e.toString());
            if (!(e.toString().startsWith("java.sql.SQLSyntaxErrorException: user lacks privilege or object not found:"))) {
                throw e;
            }
        }
    }
}