src/Pure/General/sql.scala
author wenzelm
Wed May 24 16:35:18 2017 +0200 (2017-05-24)
changeset 65918 b873cefb3b6a
parent 65890 1b004f5974af
child 66856 6b90c688a6dc
permissions -rw-r--r--
tuned message;
wenzelm@63788
     1
/*  Title:      Pure/General/sql.scala
wenzelm@63778
     2
    Author:     Makarius
wenzelm@63778
     3
wenzelm@65006
     4
Support for SQL databases: SQLite and PostgreSQL.
wenzelm@63778
     5
*/
wenzelm@63778
     6
wenzelm@63778
     7
package isabelle
wenzelm@63778
     8
wenzelm@65021
     9
import java.time.OffsetDateTime
wenzelm@65021
    10
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet}
wenzelm@63779
    11
wenzelm@65740
    12
import scala.collection.mutable
wenzelm@65740
    13
wenzelm@63779
    14
wenzelm@63778
    15
object SQL
wenzelm@63778
    16
{
wenzelm@65006
    17
  /** SQL language **/
wenzelm@65006
    18
wenzelm@65730
    19
  type Source = String
wenzelm@65730
    20
wenzelm@65730
    21
wenzelm@63778
    22
  /* concrete syntax */
wenzelm@63778
    23
wenzelm@65321
    24
  def escape_char(c: Char): String =
wenzelm@63778
    25
    c match {
wenzelm@63778
    26
      case '\u0000' => "\\0"
wenzelm@63778
    27
      case '\'' => "\\'"
wenzelm@63778
    28
      case '\"' => "\\\""
wenzelm@63778
    29
      case '\b' => "\\b"
wenzelm@63778
    30
      case '\n' => "\\n"
wenzelm@63778
    31
      case '\r' => "\\r"
wenzelm@63778
    32
      case '\t' => "\\t"
wenzelm@63778
    33
      case '\u001a' => "\\Z"
wenzelm@63778
    34
      case '\\' => "\\\\"
wenzelm@63778
    35
      case _ => c.toString
wenzelm@63778
    36
    }
wenzelm@63778
    37
wenzelm@65730
    38
  def string(s: String): Source =
wenzelm@65321
    39
    "'" + s.map(escape_char(_)).mkString + "'"
wenzelm@63778
    40
wenzelm@65730
    41
  def ident(s: String): Source =
wenzelm@65677
    42
    Long_Name.implode(Long_Name.explode(s).map(a => quote(a.replace("\"", "\"\""))))
wenzelm@63779
    43
wenzelm@65730
    44
  def enclose(s: Source): Source = "(" + s + ")"
wenzelm@65730
    45
  def enclosure(ss: Iterable[Source]): Source = ss.mkString("(", ", ", ")")
wenzelm@63791
    46
wenzelm@65774
    47
  def select(columns: List[Column] = Nil, distinct: Boolean = false): Source =
wenzelm@65774
    48
    "SELECT " + (if (distinct) "DISTINCT " else "") +
wenzelm@65774
    49
    (if (columns.isEmpty) "*" else commas(columns.map(_.ident))) + " FROM "
wenzelm@65644
    50
wenzelm@65775
    51
  val join_outer: Source = " LEFT OUTER JOIN "
wenzelm@65775
    52
  val join_inner: Source = " INNER JOIN "
wenzelm@65776
    53
  def join(outer: Boolean): Source = if (outer) join_outer else join_inner
wenzelm@65775
    54
wenzelm@65804
    55
  def member(x: Source, set: Iterable[String]): Source =
wenzelm@65804
    56
    set.iterator.map(a => x + " = " + SQL.string(a)).mkString("(", " OR ", ")")
wenzelm@65804
    57
wenzelm@63779
    58
wenzelm@65008
    59
  /* types */
wenzelm@65008
    60
wenzelm@65008
    61
  object Type extends Enumeration
wenzelm@65008
    62
  {
wenzelm@65011
    63
    val Boolean = Value("BOOLEAN")
wenzelm@65008
    64
    val Int = Value("INTEGER")
wenzelm@65008
    65
    val Long = Value("BIGINT")
wenzelm@65008
    66
    val Double = Value("DOUBLE PRECISION")
wenzelm@65008
    67
    val String = Value("TEXT")
wenzelm@65008
    68
    val Bytes = Value("BLOB")
wenzelm@65014
    69
    val Date = Value("TIMESTAMP WITH TIME ZONE")
wenzelm@65008
    70
  }
wenzelm@65008
    71
wenzelm@65730
    72
  def sql_type_default(T: Type.Value): Source = T.toString
wenzelm@65013
    73
wenzelm@65730
    74
  def sql_type_sqlite(T: Type.Value): Source =
wenzelm@65019
    75
    if (T == Type.Boolean) "INTEGER"
wenzelm@65019
    76
    else if (T == Type.Date) "TEXT"
wenzelm@65019
    77
    else sql_type_default(T)
wenzelm@65013
    78
wenzelm@65730
    79
  def sql_type_postgresql(T: Type.Value): Source =
wenzelm@65019
    80
    if (T == Type.Bytes) "BYTEA"
wenzelm@65019
    81
    else sql_type_default(T)
wenzelm@65008
    82
wenzelm@65008
    83
wenzelm@63779
    84
  /* columns */
wenzelm@63779
    85
wenzelm@63779
    86
  object Column
wenzelm@63779
    87
  {
wenzelm@65280
    88
    def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    89
      Column(name, Type.Boolean, strict, primary_key)
wenzelm@65280
    90
    def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    91
      Column(name, Type.Int, strict, primary_key)
wenzelm@65280
    92
    def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    93
      Column(name, Type.Long, strict, primary_key)
wenzelm@65280
    94
    def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    95
      Column(name, Type.Double, strict, primary_key)
wenzelm@65280
    96
    def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    97
      Column(name, Type.String, strict, primary_key)
wenzelm@65280
    98
    def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    99
      Column(name, Type.Bytes, strict, primary_key)
wenzelm@65280
   100
    def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
   101
      Column(name, Type.Date, strict, primary_key)
wenzelm@63779
   102
  }
wenzelm@63779
   103
wenzelm@65018
   104
  sealed case class Column(
wenzelm@65780
   105
    name: String, T: Type.Value, strict: Boolean = false, primary_key: Boolean = false,
wenzelm@65780
   106
    expr: SQL.Source = "")
wenzelm@63779
   107
  {
wenzelm@65691
   108
    def apply(table: Table): Column =
wenzelm@65691
   109
      Column(Long_Name.qualify(table.name, name), T, strict = strict, primary_key = primary_key)
wenzelm@65644
   110
wenzelm@65780
   111
    def ident: Source =
wenzelm@65780
   112
      if (expr == "") SQL.ident(name)
wenzelm@65780
   113
      else enclose(expr) + " AS " + SQL.ident(name)
wenzelm@65695
   114
wenzelm@65730
   115
    def decl(sql_type: Type.Value => Source): Source =
wenzelm@65695
   116
      ident + " " + sql_type(T) + (if (strict || primary_key) " NOT NULL" else "")
wenzelm@63781
   117
wenzelm@65730
   118
    def where_equal(s: String): Source = "WHERE " + ident + " = " + string(s)
wenzelm@65593
   119
wenzelm@65730
   120
    override def toString: Source = ident
wenzelm@63779
   121
  }
wenzelm@63779
   122
wenzelm@63780
   123
wenzelm@63780
   124
  /* tables */
wenzelm@63780
   125
wenzelm@65730
   126
  sealed case class Table(name: String, columns: List[Column], body: Source = "")
wenzelm@63780
   127
  {
wenzelm@63790
   128
    private val columns_index: Map[String, Int] =
wenzelm@63790
   129
      columns.iterator.map(_.name).zipWithIndex.toMap
wenzelm@63790
   130
wenzelm@63781
   131
    Library.duplicates(columns.map(_.name)) match {
wenzelm@63781
   132
      case Nil =>
wenzelm@63781
   133
      case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name))
wenzelm@63781
   134
    }
wenzelm@63781
   135
wenzelm@65730
   136
    def ident: Source = SQL.ident(name)
wenzelm@65691
   137
wenzelm@65730
   138
    def query: Source =
wenzelm@65696
   139
      if (body == "") error("Missing SQL body for table " + quote(name))
wenzelm@65696
   140
      else SQL.enclose(body)
wenzelm@65649
   141
wenzelm@65778
   142
    def query_named: Source = query + " AS " + SQL.ident(name)
wenzelm@65702
   143
wenzelm@65730
   144
    def create(strict: Boolean = false, sql_type: Type.Value => Source): Source =
wenzelm@65325
   145
    {
wenzelm@65325
   146
      val primary_key =
wenzelm@65325
   147
        columns.filter(_.primary_key).map(_.name) match {
wenzelm@65325
   148
          case Nil => Nil
wenzelm@65325
   149
          case keys => List("PRIMARY KEY " + enclosure(keys))
wenzelm@65325
   150
        }
wenzelm@65701
   151
      "CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") +
wenzelm@65701
   152
        ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key)
wenzelm@63781
   153
    }
wenzelm@63781
   154
wenzelm@65698
   155
    def create_index(index_name: String, index_columns: List[Column],
wenzelm@65730
   156
        strict: Boolean = false, unique: Boolean = false): Source =
wenzelm@63791
   157
      "CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " +
wenzelm@65695
   158
        (if (strict) "" else "IF NOT EXISTS ") + SQL.ident(index_name) + " ON " +
wenzelm@65695
   159
        ident + " " + enclosure(index_columns.map(_.name))
wenzelm@63791
   160
wenzelm@65730
   161
    def insert_cmd(cmd: Source, sql: Source = ""): Source =
wenzelm@65703
   162
      cmd + " INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) +
wenzelm@65698
   163
        (if (sql == "") "" else " " + sql)
wenzelm@63791
   164
wenzelm@65730
   165
    def insert(sql: Source = ""): Source = insert_cmd("INSERT", sql)
wenzelm@65703
   166
wenzelm@65730
   167
    def delete(sql: Source = ""): Source =
wenzelm@65698
   168
      "DELETE FROM " + ident +
wenzelm@65698
   169
        (if (sql == "") "" else " " + sql)
wenzelm@65319
   170
wenzelm@65774
   171
    def select(
wenzelm@65774
   172
        select_columns: List[Column] = Nil, sql: Source = "", distinct: Boolean = false): Source =
wenzelm@65698
   173
      SQL.select(select_columns, distinct = distinct) + ident +
wenzelm@65698
   174
        (if (sql == "") "" else " " + sql)
wenzelm@63790
   175
wenzelm@65730
   176
    override def toString: Source = ident
wenzelm@63780
   177
  }
wenzelm@63790
   178
wenzelm@63790
   179
wenzelm@65012
   180
wenzelm@65012
   181
  /** SQL database operations **/
wenzelm@65012
   182
wenzelm@65740
   183
  /* statements */
wenzelm@65740
   184
wenzelm@65740
   185
  class Statement private[SQL](val db: Database, val rep: PreparedStatement)
wenzelm@65740
   186
  {
wenzelm@65740
   187
    stmt =>
wenzelm@65740
   188
wenzelm@65748
   189
    object bool
wenzelm@65740
   190
    {
wenzelm@65748
   191
      def update(i: Int, x: Boolean) { rep.setBoolean(i, x) }
wenzelm@65748
   192
      def update(i: Int, x: Option[Boolean])
wenzelm@65748
   193
      {
wenzelm@65748
   194
        if (x.isDefined) update(i, x.get)
wenzelm@65748
   195
        else rep.setNull(i, java.sql.Types.BOOLEAN)
wenzelm@65748
   196
      }
wenzelm@65740
   197
    }
wenzelm@65748
   198
    object int
wenzelm@65740
   199
    {
wenzelm@65748
   200
      def update(i: Int, x: Int) { rep.setInt(i, x) }
wenzelm@65748
   201
      def update(i: Int, x: Option[Int])
wenzelm@65748
   202
      {
wenzelm@65748
   203
        if (x.isDefined) update(i, x.get)
wenzelm@65748
   204
        else rep.setNull(i, java.sql.Types.INTEGER)
wenzelm@65748
   205
      }
wenzelm@65740
   206
    }
wenzelm@65748
   207
    object long
wenzelm@65740
   208
    {
wenzelm@65748
   209
      def update(i: Int, x: Long) { rep.setLong(i, x) }
wenzelm@65748
   210
      def update(i: Int, x: Option[Long])
wenzelm@65748
   211
      {
wenzelm@65748
   212
        if (x.isDefined) update(i, x.get)
wenzelm@65748
   213
        else rep.setNull(i, java.sql.Types.BIGINT)
wenzelm@65748
   214
      }
wenzelm@65740
   215
    }
wenzelm@65748
   216
    object double
wenzelm@65740
   217
    {
wenzelm@65748
   218
      def update(i: Int, x: Double) { rep.setDouble(i, x) }
wenzelm@65748
   219
      def update(i: Int, x: Option[Double])
wenzelm@65748
   220
      {
wenzelm@65748
   221
        if (x.isDefined) update(i, x.get)
wenzelm@65748
   222
        else rep.setNull(i, java.sql.Types.DOUBLE)
wenzelm@65748
   223
      }
wenzelm@65748
   224
    }
wenzelm@65748
   225
    object string
wenzelm@65748
   226
    {
wenzelm@65748
   227
      def update(i: Int, x: String) { rep.setString(i, x) }
wenzelm@65748
   228
      def update(i: Int, x: Option[String]): Unit = update(i, x.orNull)
wenzelm@65740
   229
    }
wenzelm@65748
   230
    object bytes
wenzelm@65740
   231
    {
wenzelm@65748
   232
      def update(i: Int, bytes: Bytes)
wenzelm@65748
   233
      {
wenzelm@65748
   234
        if (bytes == null) rep.setBytes(i, null)
wenzelm@65748
   235
        else rep.setBinaryStream(i, bytes.stream(), bytes.length)
wenzelm@65748
   236
      }
wenzelm@65748
   237
      def update(i: Int, bytes: Option[Bytes]): Unit = update(i, bytes.orNull)
wenzelm@65740
   238
    }
wenzelm@65748
   239
    object date
wenzelm@65748
   240
    {
wenzelm@65748
   241
      def update(i: Int, date: Date): Unit = db.update_date(stmt, i, date)
wenzelm@65748
   242
      def update(i: Int, date: Option[Date]): Unit = update(i, date.orNull)
wenzelm@65748
   243
    }
wenzelm@65740
   244
wenzelm@65740
   245
    def execute(): Boolean = rep.execute()
wenzelm@65740
   246
    def execute_query(): Result = new Result(this, rep.executeQuery())
wenzelm@65740
   247
wenzelm@65740
   248
    def close(): Unit = rep.close
wenzelm@65740
   249
  }
wenzelm@65740
   250
wenzelm@65740
   251
wenzelm@63790
   252
  /* results */
wenzelm@63790
   253
wenzelm@65740
   254
  class Result private[SQL](val stmt: Statement, val rep: ResultSet)
wenzelm@63790
   255
  {
wenzelm@65740
   256
    res =>
wenzelm@65740
   257
wenzelm@65740
   258
    def next(): Boolean = rep.next()
wenzelm@65740
   259
wenzelm@65740
   260
    def iterator[A](get: Result => A): Iterator[A] = new Iterator[A]
wenzelm@65740
   261
    {
wenzelm@65740
   262
      private var _next: Boolean = res.next()
wenzelm@65740
   263
      def hasNext: Boolean = _next
wenzelm@65740
   264
      def next: A = { val x = get(res); _next = res.next(); x }
wenzelm@65740
   265
    }
wenzelm@65740
   266
wenzelm@65740
   267
    def bool(column: Column): Boolean = rep.getBoolean(column.name)
wenzelm@65740
   268
    def int(column: Column): Int = rep.getInt(column.name)
wenzelm@65740
   269
    def long(column: Column): Long = rep.getLong(column.name)
wenzelm@65740
   270
    def double(column: Column): Double = rep.getDouble(column.name)
wenzelm@65740
   271
    def string(column: Column): String =
wenzelm@65740
   272
    {
wenzelm@65740
   273
      val s = rep.getString(column.name)
wenzelm@65740
   274
      if (s == null) "" else s
wenzelm@65740
   275
    }
wenzelm@65740
   276
    def bytes(column: Column): Bytes =
wenzelm@65740
   277
    {
wenzelm@65740
   278
      val bs = rep.getBytes(column.name)
wenzelm@65740
   279
      if (bs == null) Bytes.empty else Bytes(bs)
wenzelm@65740
   280
    }
wenzelm@65740
   281
    def date(column: Column): Date = stmt.db.date(res, column)
wenzelm@65740
   282
wenzelm@65741
   283
    def timing(c1: Column, c2: Column, c3: Column) =
wenzelm@65741
   284
      Timing(Time.ms(long(c1)), Time.ms(long(c2)), Time.ms(long(c3)))
wenzelm@65741
   285
wenzelm@65740
   286
    def get[A](column: Column, f: Column => A): Option[A] =
wenzelm@65740
   287
    {
wenzelm@65740
   288
      val x = f(column)
wenzelm@65740
   289
      if (rep.wasNull) None else Some(x)
wenzelm@65740
   290
    }
wenzelm@65740
   291
    def get_bool(column: Column): Option[Boolean] = get(column, bool _)
wenzelm@65740
   292
    def get_int(column: Column): Option[Int] = get(column, int _)
wenzelm@65740
   293
    def get_long(column: Column): Option[Long] = get(column, long _)
wenzelm@65740
   294
    def get_double(column: Column): Option[Double] = get(column, double _)
wenzelm@65740
   295
    def get_string(column: Column): Option[String] = get(column, string _)
wenzelm@65740
   296
    def get_bytes(column: Column): Option[Bytes] = get(column, bytes _)
wenzelm@65740
   297
    def get_date(column: Column): Option[Date] = get(column, date _)
wenzelm@63790
   298
  }
wenzelm@65006
   299
wenzelm@65740
   300
wenzelm@65740
   301
  /* database */
wenzelm@65740
   302
wenzelm@65006
   303
  trait Database
wenzelm@65006
   304
  {
wenzelm@65740
   305
    db =>
wenzelm@65740
   306
wenzelm@65740
   307
wenzelm@65008
   308
    /* types */
wenzelm@65008
   309
wenzelm@65730
   310
    def sql_type(T: Type.Value): Source
wenzelm@65008
   311
wenzelm@65008
   312
wenzelm@65006
   313
    /* connection */
wenzelm@65006
   314
wenzelm@65006
   315
    def connection: Connection
wenzelm@65006
   316
wenzelm@65006
   317
    def close() { connection.close }
wenzelm@65006
   318
wenzelm@65006
   319
    def transaction[A](body: => A): A =
wenzelm@65006
   320
    {
wenzelm@65006
   321
      val auto_commit = connection.getAutoCommit
wenzelm@65006
   322
      try {
wenzelm@65006
   323
        connection.setAutoCommit(false)
wenzelm@65022
   324
        val savepoint = connection.setSavepoint
wenzelm@65022
   325
        try {
wenzelm@65022
   326
          val result = body
wenzelm@65022
   327
          connection.commit
wenzelm@65022
   328
          result
wenzelm@65022
   329
        }
wenzelm@65022
   330
        catch { case exn: Throwable => connection.rollback(savepoint); throw exn }
wenzelm@65006
   331
      }
wenzelm@65006
   332
      finally { connection.setAutoCommit(auto_commit) }
wenzelm@65006
   333
    }
wenzelm@65006
   334
wenzelm@65006
   335
wenzelm@65740
   336
    /* statements and results */
wenzelm@65740
   337
wenzelm@65740
   338
    def statement(sql: Source): Statement =
wenzelm@65740
   339
      new Statement(db, connection.prepareStatement(sql))
wenzelm@65006
   340
wenzelm@65740
   341
    def using_statement[A](sql: Source)(f: Statement => A): A =
wenzelm@65740
   342
      using(statement(sql))(f)
wenzelm@65006
   343
wenzelm@65748
   344
    def update_date(stmt: Statement, i: Int, date: Date): Unit
wenzelm@65740
   345
    def date(res: Result, column: Column): Date
wenzelm@65006
   346
wenzelm@65730
   347
    def insert_permissive(table: Table, sql: Source = ""): Source
wenzelm@65703
   348
wenzelm@65006
   349
wenzelm@65669
   350
    /* tables and views */
wenzelm@65006
   351
wenzelm@65006
   352
    def tables: List[String] =
wenzelm@65740
   353
    {
wenzelm@65740
   354
      val result = new mutable.ListBuffer[String]
wenzelm@65740
   355
      val rs = connection.getMetaData.getTables(null, null, "%", null)
wenzelm@65740
   356
      while (rs.next) { result += rs.getString(3) }
wenzelm@65740
   357
      result.toList
wenzelm@65740
   358
    }
wenzelm@65006
   359
wenzelm@65730
   360
    def create_table(table: Table, strict: Boolean = false, sql: Source = ""): Unit =
wenzelm@65698
   361
      using_statement(
wenzelm@65698
   362
        table.create(strict, sql_type) + (if (sql == "") "" else " " + sql))(_.execute())
wenzelm@65006
   363
wenzelm@65018
   364
    def create_index(table: Table, name: String, columns: List[Column],
wenzelm@65280
   365
        strict: Boolean = false, unique: Boolean = false): Unit =
wenzelm@65698
   366
      using_statement(table.create_index(name, columns, strict, unique))(_.execute())
wenzelm@65006
   367
wenzelm@65691
   368
    def create_view(table: Table, strict: Boolean = false): Unit =
wenzelm@65691
   369
    {
wenzelm@65691
   370
      if (strict || !tables.contains(table.name)) {
wenzelm@65731
   371
        val sql = "CREATE VIEW " + table + " AS " + { table.query; table.body }
wenzelm@65698
   372
        using_statement(sql)(_.execute())
wenzelm@65690
   373
      }
wenzelm@65691
   374
    }
wenzelm@65006
   375
  }
wenzelm@63778
   376
}
wenzelm@65006
   377
wenzelm@65006
   378
wenzelm@65006
   379
wenzelm@65006
   380
/** SQLite **/
wenzelm@65006
   381
wenzelm@65006
   382
object SQLite
wenzelm@65006
   383
{
wenzelm@65021
   384
  // see https://www.sqlite.org/lang_datefunc.html
wenzelm@65021
   385
  val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x")
wenzelm@65021
   386
wenzelm@65890
   387
  lazy val init_jdbc: Unit =
wenzelm@65890
   388
  {
wenzelm@65890
   389
    val lib_path = Path.explode("$ISABELLE_SQLITE_HOME/" + Platform.jvm_platform)
wenzelm@65890
   390
    val lib_name =
wenzelm@65890
   391
      File.find_files(lib_path.file) match {
wenzelm@65890
   392
        case List(file) => file.getName
wenzelm@65918
   393
        case _ => error("Exactly one file expected in directory " + lib_path.expand)
wenzelm@65890
   394
      }
wenzelm@65890
   395
    System.setProperty("org.sqlite.lib.path", File.platform_path(lib_path))
wenzelm@65890
   396
    System.setProperty("org.sqlite.lib.name", lib_name)
wenzelm@65890
   397
wenzelm@65890
   398
    Class.forName("org.sqlite.JDBC")
wenzelm@65890
   399
  }
wenzelm@65292
   400
wenzelm@65006
   401
  def open_database(path: Path): Database =
wenzelm@65006
   402
  {
wenzelm@65292
   403
    init_jdbc
wenzelm@65006
   404
    val path0 = path.expand
wenzelm@65006
   405
    val s0 = File.platform_path(path0)
wenzelm@65006
   406
    val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
wenzelm@65006
   407
    val connection = DriverManager.getConnection("jdbc:sqlite:" + s1)
wenzelm@65007
   408
    new Database(path0.toString, connection)
wenzelm@65006
   409
  }
wenzelm@65006
   410
wenzelm@65007
   411
  class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database
wenzelm@65006
   412
  {
wenzelm@65007
   413
    override def toString: String = name
wenzelm@65006
   414
wenzelm@65730
   415
    def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_sqlite(T)
wenzelm@65011
   416
wenzelm@65748
   417
    def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit =
wenzelm@65748
   418
      if (date == null) stmt.string(i) = (null: String)
wenzelm@65748
   419
      else stmt.string(i) = date_format(date)
wenzelm@65598
   420
wenzelm@65740
   421
    def date(res: SQL.Result, column: SQL.Column): Date =
wenzelm@65740
   422
      date_format.parse(res.string(column))
wenzelm@65021
   423
wenzelm@65730
   424
    def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source =
wenzelm@65703
   425
      table.insert_cmd("INSERT OR IGNORE", sql = sql)
wenzelm@65703
   426
wenzelm@65698
   427
    def rebuild { using_statement("VACUUM")(_.execute()) }
wenzelm@65006
   428
  }
wenzelm@65006
   429
}
wenzelm@65006
   430
wenzelm@65006
   431
wenzelm@65006
   432
wenzelm@65006
   433
/** PostgreSQL **/
wenzelm@65006
   434
wenzelm@65006
   435
object PostgreSQL
wenzelm@65006
   436
{
wenzelm@65006
   437
  val default_port = 5432
wenzelm@65006
   438
wenzelm@65292
   439
  lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver")
wenzelm@65292
   440
wenzelm@65006
   441
  def open_database(
wenzelm@65006
   442
    user: String,
wenzelm@65006
   443
    password: String,
wenzelm@65006
   444
    database: String = "",
wenzelm@65006
   445
    host: String = "",
wenzelm@65594
   446
    port: Int = 0,
wenzelm@65636
   447
    ssh: Option[SSH.Session] = None,
wenzelm@65636
   448
    ssh_close: Boolean = false): Database =
wenzelm@65006
   449
  {
wenzelm@65292
   450
    init_jdbc
wenzelm@65292
   451
wenzelm@65641
   452
    if (user == "") error("Undefined database user")
wenzelm@65009
   453
wenzelm@65717
   454
    val db_host = proper_string(host) getOrElse "localhost"
wenzelm@65594
   455
    val db_port = if (port > 0 && port != default_port) ":" + port else ""
wenzelm@65717
   456
    val db_name = "/" + (proper_string(database) getOrElse user)
wenzelm@65009
   457
wenzelm@65010
   458
    val (url, name, port_forwarding) =
wenzelm@65009
   459
      ssh match {
wenzelm@65010
   460
        case None =>
wenzelm@65010
   461
          val spec = db_host + db_port + db_name
wenzelm@65010
   462
          val url = "jdbc:postgresql://" + spec
wenzelm@65010
   463
          val name = user + "@" + spec
wenzelm@65010
   464
          (url, name, None)
wenzelm@65009
   465
        case Some(ssh) =>
wenzelm@65594
   466
          val fw =
wenzelm@65594
   467
            ssh.port_forwarding(remote_host = db_host,
wenzelm@65636
   468
              remote_port = if (port > 0) port else default_port,
wenzelm@65636
   469
              ssh_close = ssh_close)
wenzelm@65010
   470
          val url = "jdbc:postgresql://localhost:" + fw.local_port + db_name
wenzelm@65010
   471
          val name = user + "@" + fw + db_name + " via ssh " + ssh
wenzelm@65010
   472
          (url, name, Some(fw))
wenzelm@65009
   473
      }
wenzelm@65009
   474
    try {
wenzelm@65010
   475
      val connection = DriverManager.getConnection(url, user, password)
wenzelm@65010
   476
      new Database(name, connection, port_forwarding)
wenzelm@65009
   477
    }
wenzelm@65009
   478
    catch { case exn: Throwable => port_forwarding.foreach(_.close); throw exn }
wenzelm@65006
   479
  }
wenzelm@65006
   480
wenzelm@65009
   481
  class Database private[PostgreSQL](
wenzelm@65009
   482
      name: String, val connection: Connection, port_forwarding: Option[SSH.Port_Forwarding])
wenzelm@65009
   483
    extends SQL.Database
wenzelm@65006
   484
  {
wenzelm@65010
   485
    override def toString: String = name
wenzelm@65008
   486
wenzelm@65730
   487
    def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_postgresql(T)
wenzelm@65009
   488
wenzelm@65021
   489
    // see https://jdbc.postgresql.org/documentation/head/8-date-time.html
wenzelm@65748
   490
    def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit =
wenzelm@65740
   491
      if (date == null) stmt.rep.setObject(i, null)
wenzelm@65740
   492
      else stmt.rep.setObject(i, OffsetDateTime.from(date.to_utc.rep))
wenzelm@65598
   493
wenzelm@65740
   494
    def date(res: SQL.Result, column: SQL.Column): Date =
wenzelm@65704
   495
    {
wenzelm@65740
   496
      val obj = res.rep.getObject(column.name, classOf[OffsetDateTime])
wenzelm@65704
   497
      if (obj == null) null else Date.instant(obj.toInstant)
wenzelm@65704
   498
    }
wenzelm@65021
   499
wenzelm@65730
   500
    def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source =
wenzelm@65703
   501
      table.insert_cmd("INSERT",
wenzelm@65703
   502
        sql = sql + (if (sql == "") "" else " ") + "ON CONFLICT DO NOTHING")
wenzelm@65703
   503
wenzelm@65009
   504
    override def close() { super.close; port_forwarding.foreach(_.close) }
wenzelm@65006
   505
  }
wenzelm@65006
   506
}