Advertisement
Guest User

Untitled

a guest
Jan 30th, 2017
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. import fs2.Task
  2. import cats.implicits._
  3. import doobie.imports._
  4. import doobie.free.{databasemetadata => DMD}
  5.  
  6. package object migrations {
  7. case class TableDesc(
  8. catalog: Option[String],
  9. schema: Option[String],
  10. name: String
  11. )
  12.  
  13. val getTables: ConnectionIO[List[TableDesc]] =
  14. HC.getMetaData(DMD.getTables(null, null, null, null))
  15. .flatMap(HRS.list[TableDesc].transK[ConnectionIO].run)
  16.  
  17. def versionTableExists(t: List[TableDesc]) =
  18. t.exists(_.name == "schema_version")
  19.  
  20. val createSchemaVersionTableQ =
  21. sql"CREATE TABLE schema_version (version int NOT NULL)".update
  22.  
  23. def setInitialVersionQ(v: Int) =
  24. sql"INSERT INTO schema_version (version) VALUES ($v)".update
  25.  
  26. def setVersionQ(v: Int) =
  27. sql"UPDATE schema_version SET version = $v".update
  28.  
  29. val currentVersionQ =
  30. sql"SELECT version FROM schema_version".query[Int]
  31.  
  32. def migrate(migrations: List[ConnectionIO[Unit]]) =
  33. getTables.flatMap { tds =>
  34. val version = migrations.length
  35. if (versionTableExists(tds)) {
  36. currentVersionQ.unique.flatMap { currentVersion =>
  37. if (currentVersion < version) {
  38. val migrationsToPerform = migrations.drop(currentVersion)
  39. migrationsToPerform.sequence_ *>
  40. setVersionQ(newVersion).run.void
  41. } else ().pure[ConnectionIO]
  42. }
  43. } else {
  44. createSchemaVersionTableQ.run *>
  45. migrations.sequence_ *>
  46. setInitialVersionQ(version).run.void
  47. }
  48. }
  49. }
  50.  
  51. object example extends App {
  52. val xa = DriverManagerTransactor[Task](
  53. "org.postgresql.Driver",
  54. "jdbc:postgresql:test",
  55. "postgres",
  56. ""
  57. )
  58.  
  59. val migrations = List(
  60. sql"create table test (id int not null, name text not null)".update.run.void,
  61. sql"insert into test values (1, 'test1')".update.run.void
  62. )
  63.  
  64. val p = migrations.migrate(migrations).transact(xa)
  65.  
  66. p.unsafeValue
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement