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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
|
import java.net.URI
import java.nio.file.Paths
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global
import slick.backend.DatabaseConfig
import slick.codegen.{
OutputHelpers,
SourceCodeGenerator,
StringGeneratorHelpers
}
import slick.dbio.DBIO
import slick.driver.JdbcProfile
import slick.jdbc.meta.MTable
import slick.{model => sModel}
import slick.model.{Column, Model, Table, QualifiedName}
object Generator {
def run(uri: URI,
pkg: String,
schemaNames: Option[List[String]],
outputPath: String,
manualForeignKeys: Map[(String, String), (String, String)],
schemaBaseClass: String,
idType: Option[String],
schemaImports: List[String]) = {
val dc: DatabaseConfig[JdbcProfile] =
DatabaseConfig.forURI[JdbcProfile](uri)
val parsedSchemasOpt: Option[Map[String, List[String]]] =
schemaNames.map(SchemaParser.parse)
val dbModel: Model = Await.result(
dc.db.run(SchemaParser.createModel(dc.driver, parsedSchemasOpt)),
Duration.Inf)
val generator = new Generator(uri,
pkg,
dbModel,
outputPath,
manualForeignKeys,
schemaBaseClass,
idType,
schemaImports)
generator.code // Yes... Files are written as a side effect
parsedSchemasOpt
.getOrElse(Map())
.keys
.map(schemaName => FileHelpers.schemaOutputPath(outputPath, schemaName))
}
}
class PackageNameGenerator(pkg: String, dbModel: Model)
extends SourceCodeGenerator(dbModel) {
override def code: String =
s"""
|// format: OFF
|// scalastyle:off
|package ${pkg}
|
|""".stripMargin
}
class ImportGenerator(dbModel: Model, schemaImports: List[String])
extends SourceCodeGenerator(dbModel) {
val baseImports: String = schemaImports.map("import " + _).mkString("\n")
val hlistImports: String =
if (tables.exists(_.hlistEnabled))
"""
|import slick.collection.heterogeneous._
|import slick.collection.heterogeneous.syntax._
|
|""".stripMargin
else ""
val plainSqlMapperImports: String =
if (tables.exists(_.PlainSqlMapper.enabled))
"""
|import slick.jdbc.{GetResult => GR}
|//NOTE: GetResult mappers for plain SQL are only generated for tables where Slick knows how to map the types of all columns.\n
|
|""".stripMargin
else ""
override def code: String =
baseImports + hlistImports + plainSqlMapperImports
}
class Generator(uri: URI,
pkg: String,
dbModel: Model,
outputPath: String,
manualForeignKeys: Map[(String, String), (String, String)],
schemaBaseClass: String,
idType: Option[String],
schemaImports: List[String])
extends SourceCodeGenerator(dbModel)
with OutputHelpers {
val packageName = new PackageNameGenerator(pkg, dbModel).code
val allImports: String = new ImportGenerator(dbModel, schemaImports).code
val defaultIdImplementation =
"""|final case class Id[T](v: Int)
|trait DefaultIdTypeMapper {
| val profile: slick.driver.JdbcProfile
| import profile.api._
| implicit def idTypeMapper[A]: BaseColumnType[Id[A]] = MappedColumnType.base[Id[A], Int](_.v, Id(_))
|}
|""".stripMargin
override def code: String = {
val sortedSchemaTables: List[(String, Seq[TableDef])] = tables
.groupBy(t => t.model.name.schema.getOrElse("`public`"))
.toList
.sortBy(_._1)
val schemata: String = sortedSchemaTables.map {
case (schemaName, tableDefs) =>
val tableCode = tableDefs
.sortBy(_.model.name.table)
.map(_.code.mkString("\n"))
.mkString("\n\n")
val generatedSchema = s"""
|object ${schemaName} extends {
| val profile = slick.backend.DatabaseConfig.forConfig("${uri.getFragment()}").driver
|} with $schemaBaseClass {
| import profile.api._
| ${tableCode}
|
|}
|// scalastyle:on""".stripMargin
writeStringToFile(
packageName + allImports + generatedSchema,
outputPath,
pkg,
s"${schemaName}.scala"
)
if (idType.isEmpty) {
writeStringToFile(packageName + defaultIdImplementation,
outputPath,
pkg,
"Id.scala")
}
generatedSchema
}.mkString("\n\n")
allImports + schemata
}
override def Table = new Table(_) { table =>
// need this in order to use our own TableClass generator
override def definitions =
Seq[Def](EntityTypeRef, PlainSqlMapper, TableClassRef, TableValue)
def TableClassRef = new TableClass() {
// We disable the option mapping, as it is a bit more complex to support and we don't appear to need it
override def option = "" // if(hlistEnabled) "" else super.option
}
// use hlists all the time
override def hlistEnabled: Boolean = true
// if false rows are type aliases to hlists, if true rows are case classes
override def mappingEnabled: Boolean = true
// create case class from colums
override def factory: String =
if (!hlistEnabled) super.factory
else {
val args = columns.zipWithIndex.map("a" + _._2)
val hlist = args.mkString("::") + ":: HNil"
val hlistType = columns
.map(_.actualType)
.mkString("::") + ":: HNil.type"
s"((h : $hlistType) => h match {case $hlist => ${TableClass.elementType}(${args.mkString(",")})})"
}
// from case class create columns
override def extractor: String =
if (!hlistEnabled) super.extractor
else
s"(a : ${TableClass.elementType}) => Some(" + columns
.map("a." + _.name)
.mkString("::") + ":: HNil)"
def EntityTypeRef = new EntityTypeDef {
override def code: String =
(if (classEnabled) "final " else "") + super.code
}
override def Column = new Column(_) { column =>
val manualReferences =
SchemaParser.references(dbModel, manualForeignKeys)
// work out the destination of the foreign key
def derefColumn(table: sModel.Table,
column: sModel.Column): (sModel.Table, sModel.Column) = {
val referencedColumn: Seq[(sModel.Table, sModel.Column)] =
table.foreignKeys
.filter(tableFk => tableFk.referencingColumns.forall(_ == column))
.filter(columnFk => columnFk.referencedColumns.length == 1)
.flatMap(_.referencedColumns.map(c =>
(dbModel.tablesByName(c.table), c)))
assert(referencedColumn.distinct.length <= 1, referencedColumn)
referencedColumn.headOption
.orElse(manualReferences.get((table.name.asString, column.name)))
.map((derefColumn _).tupled)
.getOrElse((table, column))
}
def tableReferenceName(tableName: QualifiedName) = {
val schemaObjectName = tableName.schema.getOrElse("`public`")
val rowTypeName = entityName(tableName.table)
val idTypeName = idType.getOrElse("Id")
s"$idTypeName[$schemaObjectName.$rowTypeName]"
}
// re-write ids, and time types
override def rawType: String = {
val (referencedTable, referencedColumn) =
derefColumn(table.model, column.model)
if (referencedColumn.options.contains(
slick.ast.ColumnOption.PrimaryKey))
tableReferenceName(referencedTable.name)
else
model.tpe match {
// TODO: There should be a way to add adhoc custom time mappings
case "java.sql.Time" => "xyz.driver.core.time.Time"
case "java.sql.Timestamp" => "xyz.driver.core.time.Time"
case _ => super.rawType
}
}
}
override def ForeignKey = new ForeignKey(_) {
override def code = {
val fkColumns = compoundValue(referencingColumns.map(_.name))
val qualifier =
if (referencedTable.model.name.schema == referencingTable.model.name.schema)
""
else
referencedTable.model.name.schema.fold("")(sname =>
s"$pkg.$sname.")
val qualifiedName = qualifier + referencedTable.TableValue.name
val pkColumns = compoundValue(referencedColumns.map(c =>
s"r.${c.name}${if (!c.model.nullable && referencingColumns.forall(_.model.nullable)) ".?"
else ""}"))
val fkName = referencingColumns
.map(_.name)
.flatMap(_.split("_"))
.map(_.capitalize)
.mkString
.uncapitalize + "Fk"
s"""lazy val $fkName = foreignKey("$dbName", $fkColumns, $qualifiedName)(r => $pkColumns, onUpdate=$onUpdate, onDelete=$onDelete)"""
}
}
}
}
object SchemaParser {
def references(dbModel: Model,
tcMappings: Map[(String, String), (String, String)])
: Map[(String, String), (Table, Column)] = {
def getTableColumn(tc: (String, String)): (Table, Column) = {
val (tableName, columnName) = tc
val table = dbModel.tables
.find(_.name.asString == tableName)
.getOrElse(throw new RuntimeException("No table " + tableName))
val column = table.columns
.find(_.name == columnName)
.getOrElse(throw new RuntimeException(
"No column " + columnName + " in table " + tableName))
(table, column)
}
tcMappings.map {
case (from, to) => ({ getTableColumn(from); from }, getTableColumn(to))
}
}
def parse(schemaTableNames: List[String]): Map[String, List[String]] =
schemaTableNames
.map(_.split('.'))
.groupBy(_.head)
.mapValues(_.flatMap(_.tail))
def createModel(
jdbcProfile: JdbcProfile,
mappedSchemasOpt: Option[Map[String, List[String]]]): DBIO[Model] = {
val allTables: DBIO[Vector[MTable]] = MTable.getTables
val filteredTables = mappedSchemasOpt.map(
mappedSchemas =>
allTables.map(
(tables: Vector[MTable]) =>
tables.filter(
table =>
table.name.schema
.flatMap(mappedSchemas.get)
.exists(ts => ts.isEmpty || ts.contains(table.name.name)))))
jdbcProfile.createModel(filteredTables orElse Some(allTables))
}
}
object FileHelpers {
def schemaOutputPath(path: String, schemaName: String): String =
Paths.get(path, s"${schemaName}.scala").toAbsolutePath().toString()
}
|