-
Notifications
You must be signed in to change notification settings - Fork 30
/
R2rmlUtils.scala
176 lines (141 loc) · 6.69 KB
/
R2rmlUtils.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package net.sansa_stack.rdf.common.partition.r2rml
import net.sansa_stack.rdf.common.partition.core.{RdfPartitionStateDefault, RdfPartitioner}
import org.aksw.r2rml.jena.domain.api._
import org.aksw.r2rml.jena.vocab.RR
import org.aksw.r2rmlx.domain.api.TermMapX
import org.aksw.sparqlify.core.sql.common.serialization.{SqlEscaper, SqlEscaperBacktick}
import org.apache.jena.graph.NodeFactory
import org.apache.jena.rdf.model.{Model, ModelFactory, ResourceFactory}
import org.apache.jena.sparql.core.Var
import org.apache.jena.sparql.expr.ExprVar
import scala.reflect.runtime.universe.MethodSymbol
object R2rmlUtils {
implicit def newExprVar(varName: String): ExprVar = new ExprVar(Var.alloc(varName))
implicit def newExprVar(varId: Int): ExprVar = "_" + varId
def newExprVar(i: Int, attrNames: List[String]): ExprVar = {
val attrName = attrNames(i)
attrName
}
def createR2rmlMappings(partitioner: RdfPartitioner[RdfPartitionStateDefault],
partition: RdfPartitionStateDefault,
model: Model,
explodeLanguageTags: Boolean): Seq[TriplesMap] = {
createR2rmlMappings(
partitioner,
partition,
x => createDefaultTableName(x), // Map the partition to a name
new SqlEscaperBacktick,
model,
explodeLanguageTags)
}
def createR2rmlMappings(partitioner: RdfPartitioner[RdfPartitionStateDefault],
partitions: Seq[RdfPartitionStateDefault],
model: Model,
explodeLanguageTags: Boolean): Seq[TriplesMap] = {
partitions
.flatMap(p => createR2rmlMappings(
partitioner,
p,
model,
explodeLanguageTags))
}
/**
* Transform a RdfPartitionStateDefault into a sequence of R2RML mappings.
* If the language handling strategy demands a dedicated column for language tags then the
* resulting R2RML contains the non-standard 'rr:langColumn' property.
*
* FIXME Creating mappings per language tag needs yet to be implemented
*
* @param partitioner The partitioner
* @param partitionState The partition state generated by the partitioner
* @param extractTableName A function to obtain a table name from the partition state
* @param sqlEscaper SQL escaping policies for table names, column names, string literals and aliases
* @param outModel The output model
* @param explodeLanguageTags If true then a mapping is generated for each language tag listed in the partition state.
* Otherwise a generic language column is introduces
* @return The set of {@link TriplesMap}s added to the output model
*/
def createR2rmlMappings(partitioner: RdfPartitioner[RdfPartitionStateDefault],
partitionState: RdfPartitionStateDefault,
extractTableName: RdfPartitionStateDefault => String,
sqlEscaper: SqlEscaper,
outModel: Model,
explodeLanguageTags: Boolean): Seq[TriplesMap] = {
val p = partitionState // Shorthand
val t = partitioner.determineLayout(partitionState).schema
val attrNames = t.members.sorted.collect({ case m: MethodSymbol if m.isCaseAccessor => m.name.toString })
val predicateIri: String = partitionState.predicate
val tableName = extractTableName(partitionState)
if (explodeLanguageTags && attrNames.length == 3) {
val langColSql = sqlEscaper.escapeColumnName(attrNames(2))
val columnsSql = attrNames.slice(0, 2).map(sqlEscaper.escapeColumnName(_)).mkString(", ")
p.languages.map(lang => {
val tableNameSql = sqlEscaper.escapeTableName(tableName)
val langSql = sqlEscaper.escapeStringLiteral(lang)
val tm: TriplesMap = outModel.createResource.as(classOf[TriplesMap])
// create subject map
val sm: SubjectMap = tm.getOrSetSubjectMap()
setTermMapForNode(sm, 0, attrNames, p.subjectType, "", false)
val pom: PredicateObjectMap = tm.addNewPredicateObjectMap()
pom.addPredicate(predicateIri)
val om: ObjectMap = pom.addNewObjectMap()
om.setColumn(attrNames(1))
om.setLanguage(lang)
tm.getOrSetLogicalTable().setSqlQuery(s"SELECT $columnsSql FROM $tableNameSql WHERE $langColSql = $langSql")
tm
}).toSeq
} else {
val tm: TriplesMap = ModelFactory.createDefaultModel.createResource.as(classOf[TriplesMap])
val pom: PredicateObjectMap = tm.addNewPredicateObjectMap()
pom.addPredicate(predicateIri)
val sm: SubjectMap = tm.getOrSetSubjectMap()
val om: ObjectMap = pom.addNewObjectMap()
// create subject map
setTermMapForNode(sm, 0, attrNames, p.subjectType, "", false)
setTermMapForNode(om, 1, attrNames, p.objectType, p.datatype, p.langTagPresent)
tm.getOrSetLogicalTable().setTableName(tableName)
Seq(tm)
}
}
def setTermMapForNode(target: TermMap, offset: Int, attrNames: List[String], termType: Byte, datatype: String, langTagPresent: Boolean): TermMap = {
// val o = offset + 1
val o = offset
val on = newExprVar(o, attrNames)
termType match {
// TODO The RR.IRI.inModel(...) is a workaround right now
case 0 => target.setColumn(attrNames(o)).setDatatype(RR.BlankNode.inModel(target.getModel))
case 1 => target.setColumn(attrNames(o)).setDatatype(RR.IRI.inModel(target.getModel))
case 2 =>
target.setColumn(attrNames(o))
if (langTagPresent) {
target.as(classOf[TermMapX]).setLangColumn(attrNames(o + 1))
} else {
target.setDatatype(ResourceFactory.createProperty(datatype))
}
// case 2 if(!Option(datatype).getOrElse("").isEmpty) => E_RdfTerm.createTypedLiteral(o, o + 1)
case _ => throw new RuntimeException("Unhandled case")
}
target
}
/**
* Creates a SQL table name for a partition.
*
* FIXME Consolidate with SQLUtils in the spark module?
*
* @param p the RDF partition
* @return
*/
def createDefaultTableName(p: RdfPartitionStateDefault): String = {
// For now let's just use the full predicate as the uri
// val predPart = pred.substring(pred.lastIndexOf("/") + 1)
val predPart = p.predicate
val pn = NodeFactory.createURI(p.predicate)
val dt = p.datatype
val dtPart = if (dt != null && dt.nonEmpty) "_" + dt.substring(dt.lastIndexOf("/") + 1) else ""
val langPart = if (p.langTagPresent) "_lang" else ""
val sTermTypePart = if (p.subjectType == 0) "sbn" else ""
val oTermTypePart = if (p.objectType == 0) "obn" else ""
val tableName = predPart + dtPart + langPart + sTermTypePart + oTermTypePart
tableName
}
}