<commit_before>//===========================================================================
//    Copyright 2015 Delving B.V.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//===========================================================================

package triplestore

import dataset.DsInfo
import dataset.DsInfo._
import mapping.VocabInfo.CATEGORIES_SPEC
import org.ActorStore.{NXActor, NXProfile}
import org.joda.time.DateTime
import play.api.libs.json.JsValue
import services.StringHandling._
import services.Temporal
import triplestore.GraphProperties._
import triplestore.TripleStore.QueryValue

object Sparql {
  // === actor store ===
  private val SPARQL_ESCAPE: Map[Char, String] = Map(
    '\t' -> "\\t",
    '\n' -> "\\n",
    '\r' -> "\\r",
    '\b' -> "\\b",
    '\f' -> "\\f",
    '"' -> "\\\"",
    '\'' -> "\\'",
    '\\' -> "\\\\"
  )

  private def escape(value: String): String = value.map(c => SPARQL_ESCAPE.getOrElse(c, c.toString)).mkString

  private def literalExpression(value: String, languageOpt: Option[String]) = languageOpt.map { language =>
    s"'${escape(value)}'@$language"
  } getOrElse {
    s"'${escape(value)}'"
  }

  def graphExistsQ(graphName: String) =
    s"""
      |ASK {
      |   GRAPH <$graphName> { ?s ?p ?o }
      |}
     """.stripMargin


  def insertActorQ(actor: NXActor, passwordHashString: String, adminActor: NXActor) =
    s"""
      |WITH <$actorsGraph>
      |DELETE {
      |   <$actor>
      |      a <$actorEntity>;
      |      <$username> ?userName ;
      |      <$actorOwner> ?userMaker ;
      |      <$passwordHash> ?passwordHash .
      |}
      |INSERT {
      |   <$actor>
      |      a <$actorEntity>;
      |      <$username> ${literalExpression(actor.actorName, None)} ;
      |      <$actorOwner> <$adminActor> ;
      |      <$passwordHash> '$password<PASSWORD>' .
      |}
      |WHERE {
      |   OPTIONAL {
      |      <$actor>
      |         a <$actorEntity>;
      |         <$username> ?username ;
      |         <$actorOwner> ?userMaker ;
      |         <$passwordHash> ?passwordHash .
      |   }
      |}
     """.stripMargin

  def setActorProfileQ(actor: NXActor, profile: NXProfile) =
    s"""
      |WITH <$actorsGraph>
      |DELETE {
      |   <$actor>
      |      <$userFirstName> ?firstName ;
      |      <$userLastName> ?lastName ;
      |      <$userEMail> ?email .
      |}
      |INSERT {
      |   <$actor>
      |      <$userFirstName> ${literalExpression(profile.firstName, None)} ;
      |      <$userLastName> ${literalExpression(profile.lastName, None)} ;
      |      <$userEMail> ${literalExpression(profile.email, None)} .
      |}
      |WHERE {
      |   <$actor>
      |      a <$actorEntity> ;
      |      <$userFirstName> ?firstName ;
      |      <$userLastName> ?lastName ;
      |      <$userEMail> ?email .
      |}
     """.stripMargin

  def setActorPasswordQ(actor: NXActor, passwordHashString: String) =
    s"""
      |WITH <$actorsGraph>
      |DELETE { <$actor> <$passwordHash> ?oldPassword }
      |INSERT { <$actor> <$passwordHash> '$passwordHashString' }
      |WHERE { <$actor> <$passwordHash> ?oldPassword }
     """.stripMargin

  // === dataset info ===

  val selectDatasetSpecsQ =
    s"""
      |SELECT ?spec
      |WHERE {
      |  GRAPH ?g {
      |    ?s <$datasetSpec> ?spec .
      |    FILTER NOT EXISTS { ?s <$deleted> true }
      |  }<commit_msg>Selecting distinct dataset specs.<commit_after>//===========================================================================
//    Copyright 2015 Delving B.V.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//===========================================================================

package triplestore

import dataset.DsInfo
import dataset.DsInfo._
import mapping.VocabInfo.CATEGORIES_SPEC
import org.ActorStore.{NXActor, NXProfile}
import org.joda.time.DateTime
import play.api.libs.json.JsValue
import services.StringHandling._
import services.Temporal
import triplestore.GraphProperties._
import triplestore.TripleStore.QueryValue

object Sparql {
  // === actor store ===
  private val SPARQL_ESCAPE: Map[Char, String] = Map(
    '\t' -> "\\t",
    '\n' -> "\\n",
    '\r' -> "\\r",
    '\b' -> "\\b",
    '\f' -> "\\f",
    '"' -> "\\\"",
    '\'' -> "\\'",
    '\\' -> "\\\\"
  )

  private def escape(value: String): String = value.map(c => SPARQL_ESCAPE.getOrElse(c, c.toString)).mkString

  private def literalExpression(value: String, languageOpt: Option[String]) = languageOpt.map { language =>
    s"'${escape(value)}'@$language"
  } getOrElse {
    s"'${escape(value)}'"
  }

  def graphExistsQ(graphName: String) =
    s"""
      |ASK {
      |   GRAPH <$graphName> { ?s ?p ?o }
      |}
     """.stripMargin


  def insertActorQ(actor: NXActor, passwordHashString: String, adminActor: NXActor) =
    s"""
      |WITH <$actorsGraph>
      |DELETE {
      |   <$actor>
      |      a <$actorEntity>;
      |      <$username> ?userName ;
      |      <$actorOwner> ?userMaker ;
      |      <$passwordHash> ?passwordHash .
      |}
      |INSERT {
      |   <$actor>
      |      a <$actorEntity>;
      |      <$username> ${literalExpression(actor.actorName, None)} ;
      |      <$actorOwner> <$adminActor> ;
      |      <$passwordHash> '$passwordHashString' .
      |}
      |WHERE {
      |   OPTIONAL {
      |      <$actor>
      |         a <$actorEntity>;
      |         <$username> ?username ;
      |         <$actorOwner> ?userMaker ;
      |         <$passwordHash> ?passwordHash .
      |   }
      |}
     """.stripMargin

  def setActorProfileQ(actor: NXActor, profile: NXProfile) =
    s"""
      |WITH <$actorsGraph>
      |DELETE {
      |   <$actor>
      |      <$userFirstName> ?firstName ;
      |      <$userLastName> ?lastName ;
      |      <$userEMail> ?email .
      |}
      |INSERT {
      |   <$actor>
      |      <$userFirstName> ${literalExpression(profile.firstName, None)} ;
      |      <$userLastName> ${literalExpression(profile.lastName, None)} ;
      |      <$userEMail> ${literalExpression(profile.email, None)} .
      |}
      |WHERE {
      |   <$actor>
      |      a <$actorEntity> ;
      |      <$userFirstName> ?firstName ;
      |      <$userLastName> ?lastName ;
      |      <$userEMail> ?email .
      |}
     """.stripMargin

  def setActorPasswordQ(actor: NXActor, passwordHashString: String) =
    s"""
      |WITH <$actorsGraph>
      |DELETE { <$actor> <$passwordHash> ?oldPassword }
      |INSERT { <$actor> <$passwordHash> '$passwordHashString' }
      |WHERE { <$actor> <$passwordHash> ?oldPassword }
     """.stripMargin

  // === dataset info ===

  val selectDatasetSpecsQ =
    s"""
      |SELECT DISTINCT ?spec
      |WHERE {
      |  GRAPH ?g {
      |    ?s <$datasetSpec> ?spec .
      |    FILTER NOT EXISTS { ?s <$deleted> true }
      |  }
{'fraction_non_alphanumeric': 0.18723889099886062, 'fraction_numerical': 0.002025572857323712, 'mean_word_length': 2.353140916808149, 'pattern_counts': {'":': 0, '<': 86, '<?xml version=': 0, '>': 106, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, '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': '6246526', 'n_tokens_mistral': 2555, 'n_tokens_neox': 2455, 'n_words': 558}