如何在COPY postgresql中的列上使用postgres函数

时间:2016-01-05 17:12:08

标签: postgresql scala apache-spark cartodb

我有一个spark(1.2.1 v)作业,它使用postgresql.Driver for scala将rdd的内容插入postgres。在postgres中,我有一些函数,例如“ CDB_LatLng ”,需要由插入触发(特定函数计算CartoDB表的'the_geom'列)。

我想使用COPY将数据插入postgres:

def copyIn(url: String, username: String, password: String, tableName: String, reader: java.io.Reader, columnStmt: String = "") = {
        //connect to postgres database on the localhost
        val driver = "org.postgresql.Driver"
        var connection:Connection = null
        Class.forName(driver)
        connection = DriverManager.getConnection(url, username, password)

        try {
            connection.unwrap(classOf[PGConnection]).getCopyAPI.copyIn(s"COPY $tableName ($columnStmt) FROM STDIN (FORMAT CSV, DELIMITER ';'))", reader)
        } catch {
            case se: SQLException => println(se.getMessage)
            case t: Throwable => println(t.getMessage)
        } finally {
            connection.close()
        }
}

squares_rdd.foreachPartition(iter => {
        val sb = new StringBuilder()
        var keys : String = ""

        iter.foreach(row => {
            val mapRequest = Utils.getSquaresInsertMap(geoSelectMap, row)
            val mapValues = mapRequest.values.mkString("; ")
            sb.append(mapValues).append("\n")

            if(keys == ""){
                keys = mapRequest.keySet.mkString(", ")
            }

        })

        copyIn(url, username, password, squares_table,  new StringReader(sb.toString), keys)
        sb.clear
  })

当我尝试使用它时,我得到一个错误,即'the_geom'列无法接收字符串数据“CDB_LatLng(x,y)”...... COPY命令应触发{} 3中描述的INSERT命令之类的触发器那么可以在COPY中的列上使用函数吗?

0 个答案:

没有答案