<commit_before>/**
 * Copyright (C) 2016 Orbeon, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */
package org.orbeon.oxf.fr.persistence.relational

import java.sql.{Connection, ResultSet}
import javax.xml.transform.stream.StreamSource

import org.orbeon.oxf.util.IOUtils._
import org.orbeon.oxf.util.StringUtils._
import org.orbeon.oxf.util.XPath
import org.orbeon.oxf.xml.TransformerUtils
import org.orbeon.saxon.om.DocumentInfo

sealed trait Provider    extends Product with Serializable {
  val name: String
  def uri : String = "/fr/service/" + name
}

object Provider {

  case object  MySQL       extends Provider { val name = "mysql"      }
  case object  PostgreSQL  extends Provider { val name = "postgresql" }

  def providerFromToken(token: String): Provider = {
    val AllProviders = List(MySQL, PostgreSQL)
    val providerOpt = AllProviders.find(_.name == token)
    providerOpt.getOrElse(throw new IllegalStateException)
  }

  def xmlCol(provider: Provider, tableName: String) =
    provider match {
      case PostgreSQL ⇒ s"$tableName.xml as xml"
      case _          ⇒ s"$tableName.xml xml"
    }

  def xmlContains(provider: Provider): String =
    provider match {
      case MySQL      ⇒ "xml like ?"
      case PostgreSQL ⇒ "xml::text ilike ?"
    }

  def xmlContainsParam(provider: Provider, param: String): String =
    provider match {
      case MySQL | PostgreSQL ⇒ s"%$param%"
      case _                  ⇒ param
    }

  def textContains(provider: Provider, colName: String): String =
    provider match {
      case MySQL ⇒
        // LIKE is case insensitive on MySQL and SQL Server
        s"$colName LIKE ?"
      case PostgreSQL ⇒
        // PostgreSQL has ILIKE as a case insensitive version of LIKE
        s"$colName ILIKE ?"
    }

  def readXmlColumn(provider: Provider, resultSet: ResultSet): DocumentInfo = {
    provider match {
      case PostgreSQL ⇒
        val xmlString = resultSet.getString("xml")
        TransformerUtils.stringToTinyTree(XPath.GlobalConfiguration, xmlString, false, false)
      case _ ⇒
        val dataClob = resultSet.getClob("xml")
        val source = new StreamSource(dataClob.getCharacterStream)
        TransformerUtils.readTinyTree(XPath.GlobalConfiguration, source, false)
    }
  }

  def seqNextVal(connection: Connection, provider: Provider): Int = {
    val nextValSql = provider match {
      case _ ⇒
        val insertSql = provider match {
          case MySQL ⇒ "INSERT INTO orbeon_seq VALUES ()"
          case _     ⇒ "INSERT INTO orbeon_seq DEFAULT VALUES"
        }
        useAndClose(connection.prepareStatement(insertSql))(_.executeUpdate())
        "SELECT max(val) FROM orbeon_seq"
    }
    useAndClose(connection.prepareStatement(nextValSql)){ statement ⇒
      useAndClose(statement.executeQuery()) { resultSet ⇒
        resultSet.next()
        resultSet.getInt(1)
      }
    }
  }

  def lockTable(connection: Connection, provider: Provider, tableName: String): Unit = {
    val sql =
      provider match {
        case MySQL      ⇒ s"LOCK TABLES $tableName WRITE"
        case PostgreSQL ⇒ s"LOCK TABLE $tableName IN EXCLUSIVE MODE"
        case _          ⇒ throw new UnsupportedOperationException
      }
    useAndClose(connection.prepareStatement(sql))(_.executeUpdate())<commit_msg>For #1067: fix for cases when we have a query (SQL Server)<commit_after>/**
 * Copyright (C) 2016 Orbeon, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */
package org.orbeon.oxf.fr.persistence.relational

import java.sql.{Connection, ResultSet}
import javax.xml.transform.stream.StreamSource

import org.orbeon.oxf.util.IOUtils._
import org.orbeon.oxf.util.StringUtils._
import org.orbeon.oxf.util.XPath
import org.orbeon.oxf.xml.TransformerUtils
import org.orbeon.saxon.om.DocumentInfo

sealed trait Provider    extends Product with Serializable {
  val name: String
  def uri : String = "/fr/service/" + name
}

object Provider {

  case object  MySQL       extends Provider { val name = "mysql"      }
  case object  PostgreSQL  extends Provider { val name = "postgresql" }

  def providerFromToken(token: String): Provider = {
    val AllProviders = List(MySQL, PostgreSQL)
    val providerOpt = AllProviders.find(_.name == token)
    providerOpt.getOrElse(throw new IllegalStateException)
  }

  def xmlCol(provider: Provider, tableName: String) =
    provider match {
      case PostgreSQL ⇒ s"$tableName.xml as xml"
      case _          ⇒ s"$tableName.xml xml"
    }

  def xmlContains(provider: Provider): String =
    provider match {
      case MySQL      ⇒ "xml like ?"
      case PostgreSQL ⇒ "xml::text ilike ?"
    }

  def xmlContainsParam(provider: Provider, param: String): String =
    provider match {
      case MySQL | PostgreSQL ⇒ s"%$param%"
      case _                  ⇒ param
    }

  def textContains(provider: Provider, colName: String): String =
    provider match {
      case MySQL ⇒
        // LIKE is case insensitive on MySQL and SQL Server
        s"$colName LIKE ?"
      case PostgreSQL ⇒
        // PostgreSQL has ILIKE as a case insensitive version of LIKE
        s"$colName ILIKE ?"
    }

  def readXmlColumn(provider: Provider, resultSet: ResultSet): DocumentInfo = {
    provider match {
      case PostgreSQL ⇒
        val xmlString = resultSet.getString("xml")
        TransformerUtils.stringToTinyTree(XPath.GlobalConfiguration, xmlString, false, false)
      case _ ⇒
        val dataClob = resultSet.getClob("xml")
        val source = new StreamSource(dataClob.getCharacterStream)
        TransformerUtils.readTinyTree(XPath.GlobalConfiguration, source, false)
    }
  }

  def seqNextVal(connection: Connection, provider: Provider): Int = {
    val nextValSql = provider match {
      case _ ⇒
        val insertSql = provider match {
          case MySQL ⇒ "INSERT INTO orbeon_seq VALUES ()"
          case _     ⇒ "INSERT INTO orbeon_seq DEFAULT VALUES"
        }
        useAndClose(connection.prepareStatement(insertSql))(_.executeUpdate())
        "SELECT max(val) FROM orbeon_seq"
    }
    useAndClose(connection.prepareStatement(nextValSql)){ statement ⇒
      useAndClose(statement.executeQuery()) { resultSet ⇒
        resultSet.next()
        resultSet.getInt(1)
      }
    }
  }

  def lockTable(connection: Connection, provider: Provider, tableName: String): Unit = {
    val sql =
      provider match {
        case MySQL      ⇒ s"LOCK TABLES $tableName WRITE"
        case PostgreSQL ⇒ s"LOCK TABLE $tableName IN EXCLUSIVE MODE"
        case _          ⇒ throw new UnsupportedOperationException
      }
    useAndClose(connection.prepareStatement(sql))(_.execute())
{'fraction_non_alphanumeric': 0.08583580358293595, 'fraction_numerical': 0.002319886583322593, 'mean_word_length': 3.0124095139607032, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 30}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4158166', 'n_tokens_mistral': 2288, 'n_tokens_neox': 2246, 'n_words': 720}