0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ちょっとしたことがGroovy「PostgreSQLのXML型のカラムのデータを修正する」

Last updated at Posted at 2013-08-09

PostgresqlのXML型カラムをSQLだけで安全に編集する方法がいまいち分からなかったので、Groovyで書きました。

修正した内容は嘘だけど、大体こんな感じ。

updateなのにexecuteInsert使っているのは、歴史的経緯からです。。。

xml_data_fix.groovy
@Grab(group='postgresql', module='postgresql', version='9.1-901.jdbc4')
@Grab(group='org.codehaus.gpars', module='gpars', version='1.0.0')

import org.postgresql.ds.PGSimpleDataSource;
import groovy.sql.Sql;

/* meta */
String.metaClass.queryTo = { con ->
  def qry = delegate
  
  new Object(){
      def leftShift = {c -> con.eachRow(qry,c)}
      def forList = new Object(){
        def leftShift = {c -> try{c(con.rows(qry).collect{it[0]})}catch(Exception ex){println ex} }
      }
  }
}

String.metaClass.updateBy = { con,params ->
  def qry = delegate
  con.executeInsert(qry,params)
}

PGSimpleDataSource.metaClass.set = { srv,port,db,usr,pass -> 
  delegate.setServerName(srv) ; delegate.setPortNumber(port)
  delegate.setDatabaseName(db)
  delegate.setUser(usr)       ; delegate.setPassword(pass)
  delegate.getConnection()
}


/* datasource */
def cons = {
  [pg01 : new Sql(new PGSimpleDataSource().set("localhost" , 5432 , "postgres"    , "myUser" , "******"))]
}()

/* query */
"""
select xml_data
from xml_data_store
where
document_number = '20130801'
""".queryTo(cons.pg01) << {
  def xml = it.xml_data.getString().replaceAll('不適切な文言','(不適切な表現につき検閲されました)')
  try{
      def xmlobj = new org.postgresql.jdbc4.Jdbc4SQLXML(cons.publication.connection,xml)
      """
      update xml_data_store
        set xml_data_fixed = ?
      where
        document_number = '20130801'
      """.updateBy(cons.publication,[xmlobj])
  }catch(ex){
      println ex
  }
}

/* close */
cons.each {try{it.value.close()}catch(e){}}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?