src/Pure/General/sql.scala
author wenzelm
Wed May 03 16:15:09 2017 +0200 (2017-05-03)
changeset 65701 d788c11176e5
parent 65699 9f74d9aa0bdf
child 65702 7c6a91deb212
permissions -rw-r--r--
simplified: standard toString is SQL.ident;
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@63779
    12
wenzelm@63778
    13
object SQL
wenzelm@63778
    14
{
wenzelm@65006
    15
  /** SQL language **/
wenzelm@65006
    16
wenzelm@63778
    17
  /* concrete syntax */
wenzelm@63778
    18
wenzelm@65321
    19
  def escape_char(c: Char): String =
wenzelm@63778
    20
    c match {
wenzelm@63778
    21
      case '\u0000' => "\\0"
wenzelm@63778
    22
      case '\'' => "\\'"
wenzelm@63778
    23
      case '\"' => "\\\""
wenzelm@63778
    24
      case '\b' => "\\b"
wenzelm@63778
    25
      case '\n' => "\\n"
wenzelm@63778
    26
      case '\r' => "\\r"
wenzelm@63778
    27
      case '\t' => "\\t"
wenzelm@63778
    28
      case '\u001a' => "\\Z"
wenzelm@63778
    29
      case '\\' => "\\\\"
wenzelm@63778
    30
      case _ => c.toString
wenzelm@63778
    31
    }
wenzelm@63778
    32
wenzelm@65648
    33
  def string(s: String): String =
wenzelm@65321
    34
    "'" + s.map(escape_char(_)).mkString + "'"
wenzelm@63778
    35
wenzelm@65695
    36
  def ident(s: String): String =
wenzelm@65677
    37
    Long_Name.implode(Long_Name.explode(s).map(a => quote(a.replace("\"", "\"\""))))
wenzelm@63779
    38
wenzelm@65668
    39
  def enclose(s: String): String = "(" + s + ")"
wenzelm@63791
    40
  def enclosure(ss: Iterable[String]): String = ss.mkString("(", ", ", ")")
wenzelm@63791
    41
wenzelm@65644
    42
  def select(columns: List[Column], distinct: Boolean = false): String =
wenzelm@65695
    43
    "SELECT " + (if (distinct) "DISTINCT " else "") + commas(columns.map(_.ident)) + " FROM "
wenzelm@65644
    44
wenzelm@65668
    45
  def join(table1: Table, table2: Table, sql: String = "", outer: Boolean = false): String =
wenzelm@65695
    46
    table1.ident + (if (outer) " LEFT OUTER JOIN " else " INNER JOIN ") + table2.ident +
wenzelm@65668
    47
      (if (sql == "") "" else " ON " + sql)
wenzelm@65668
    48
wenzelm@65668
    49
  def join_outer(table1: Table, table2: Table, sql: String = ""): String =
wenzelm@65668
    50
    join(table1, table2, sql, outer = true)
wenzelm@65668
    51
wenzelm@63779
    52
wenzelm@65008
    53
  /* types */
wenzelm@65008
    54
wenzelm@65008
    55
  object Type extends Enumeration
wenzelm@65008
    56
  {
wenzelm@65011
    57
    val Boolean = Value("BOOLEAN")
wenzelm@65008
    58
    val Int = Value("INTEGER")
wenzelm@65008
    59
    val Long = Value("BIGINT")
wenzelm@65008
    60
    val Double = Value("DOUBLE PRECISION")
wenzelm@65008
    61
    val String = Value("TEXT")
wenzelm@65008
    62
    val Bytes = Value("BLOB")
wenzelm@65014
    63
    val Date = Value("TIMESTAMP WITH TIME ZONE")
wenzelm@65008
    64
  }
wenzelm@65008
    65
wenzelm@65019
    66
  def sql_type_default(T: Type.Value): String = T.toString
wenzelm@65013
    67
wenzelm@65019
    68
  def sql_type_sqlite(T: Type.Value): String =
wenzelm@65019
    69
    if (T == Type.Boolean) "INTEGER"
wenzelm@65019
    70
    else if (T == Type.Date) "TEXT"
wenzelm@65019
    71
    else sql_type_default(T)
wenzelm@65013
    72
wenzelm@65019
    73
  def sql_type_postgresql(T: Type.Value): String =
wenzelm@65019
    74
    if (T == Type.Bytes) "BYTEA"
wenzelm@65019
    75
    else sql_type_default(T)
wenzelm@65008
    76
wenzelm@65008
    77
wenzelm@63779
    78
  /* columns */
wenzelm@63779
    79
wenzelm@63779
    80
  object Column
wenzelm@63779
    81
  {
wenzelm@65280
    82
    def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    83
      Column(name, Type.Boolean, strict, primary_key)
wenzelm@65280
    84
    def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    85
      Column(name, Type.Int, strict, primary_key)
wenzelm@65280
    86
    def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    87
      Column(name, Type.Long, strict, primary_key)
wenzelm@65280
    88
    def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    89
      Column(name, Type.Double, strict, primary_key)
wenzelm@65280
    90
    def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    91
      Column(name, Type.String, strict, primary_key)
wenzelm@65280
    92
    def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    93
      Column(name, Type.Bytes, strict, primary_key)
wenzelm@65280
    94
    def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
wenzelm@65018
    95
      Column(name, Type.Date, strict, primary_key)
wenzelm@63779
    96
  }
wenzelm@63779
    97
wenzelm@65018
    98
  sealed case class Column(
wenzelm@65280
    99
    name: String, T: Type.Value, strict: Boolean = false, primary_key: Boolean = false)
wenzelm@63779
   100
  {
wenzelm@65691
   101
    def apply(table: Table): Column =
wenzelm@65691
   102
      Column(Long_Name.qualify(table.name, name), T, strict = strict, primary_key = primary_key)
wenzelm@65644
   103
wenzelm@65695
   104
    def ident: String = SQL.ident(name)
wenzelm@65695
   105
wenzelm@65701
   106
    def decl(sql_type: Type.Value => String): String =
wenzelm@65695
   107
      ident + " " + sql_type(T) + (if (strict || primary_key) " NOT NULL" else "")
wenzelm@63781
   108
wenzelm@65699
   109
    def where_equal(s: String): String = "WHERE " + ident + " = " + string(s)
wenzelm@65593
   110
wenzelm@65701
   111
    override def toString: String = ident
wenzelm@63779
   112
  }
wenzelm@63779
   113
wenzelm@63780
   114
wenzelm@63780
   115
  /* tables */
wenzelm@63780
   116
wenzelm@65696
   117
  sealed case class Table(name: String, columns: List[Column], body: String = "")
wenzelm@63780
   118
  {
wenzelm@63790
   119
    private val columns_index: Map[String, Int] =
wenzelm@63790
   120
      columns.iterator.map(_.name).zipWithIndex.toMap
wenzelm@63790
   121
wenzelm@63781
   122
    Library.duplicates(columns.map(_.name)) match {
wenzelm@63781
   123
      case Nil =>
wenzelm@63781
   124
      case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name))
wenzelm@63781
   125
    }
wenzelm@63781
   126
wenzelm@65696
   127
    def ident: String = SQL.ident(name)
wenzelm@65691
   128
wenzelm@65696
   129
    def expr: String =
wenzelm@65696
   130
      if (body == "") error("Missing SQL body for table " + quote(name))
wenzelm@65696
   131
      else SQL.enclose(body)
wenzelm@65649
   132
wenzelm@65701
   133
    def create(strict: Boolean = false, sql_type: Type.Value => String): String =
wenzelm@65325
   134
    {
wenzelm@65325
   135
      val primary_key =
wenzelm@65325
   136
        columns.filter(_.primary_key).map(_.name) match {
wenzelm@65325
   137
          case Nil => Nil
wenzelm@65325
   138
          case keys => List("PRIMARY KEY " + enclosure(keys))
wenzelm@65325
   139
        }
wenzelm@65701
   140
      "CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") +
wenzelm@65701
   141
        ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key)
wenzelm@63781
   142
    }
wenzelm@63781
   143
wenzelm@65698
   144
    def create_index(index_name: String, index_columns: List[Column],
wenzelm@65698
   145
        strict: Boolean = false, unique: Boolean = false): String =
wenzelm@63791
   146
      "CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " +
wenzelm@65695
   147
        (if (strict) "" else "IF NOT EXISTS ") + SQL.ident(index_name) + " ON " +
wenzelm@65695
   148
        ident + " " + enclosure(index_columns.map(_.name))
wenzelm@63791
   149
wenzelm@65698
   150
    def insert(sql: String = ""): String =
wenzelm@65698
   151
      "INSERT INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) +
wenzelm@65698
   152
        (if (sql == "") "" else " " + sql)
wenzelm@63791
   153
wenzelm@65698
   154
    def delete(sql: String = ""): String =
wenzelm@65698
   155
      "DELETE FROM " + ident +
wenzelm@65698
   156
        (if (sql == "") "" else " " + sql)
wenzelm@65319
   157
wenzelm@65698
   158
    def select(select_columns: List[Column], sql: String = "", distinct: Boolean = false): String =
wenzelm@65698
   159
      SQL.select(select_columns, distinct = distinct) + ident +
wenzelm@65698
   160
        (if (sql == "") "" else " " + sql)
wenzelm@63790
   161
wenzelm@65701
   162
    override def toString: String = ident
wenzelm@63780
   163
  }
wenzelm@63790
   164
wenzelm@63790
   165
wenzelm@65012
   166
wenzelm@65012
   167
  /** SQL database operations **/
wenzelm@65012
   168
wenzelm@63790
   169
  /* results */
wenzelm@63790
   170
wenzelm@63790
   171
  def iterator[A](rs: ResultSet)(get: ResultSet => A): Iterator[A] = new Iterator[A]
wenzelm@63790
   172
  {
wenzelm@63790
   173
    private var _next: Boolean = rs.next()
wenzelm@63790
   174
    def hasNext: Boolean = _next
wenzelm@63790
   175
    def next: A = { val x = get(rs); _next = rs.next(); x }
wenzelm@63790
   176
  }
wenzelm@65006
   177
wenzelm@65006
   178
  trait Database
wenzelm@65006
   179
  {
wenzelm@65008
   180
    /* types */
wenzelm@65008
   181
wenzelm@65019
   182
    def sql_type(T: Type.Value): String
wenzelm@65008
   183
wenzelm@65008
   184
wenzelm@65006
   185
    /* connection */
wenzelm@65006
   186
wenzelm@65006
   187
    def connection: Connection
wenzelm@65006
   188
wenzelm@65006
   189
    def close() { connection.close }
wenzelm@65006
   190
wenzelm@65006
   191
    def transaction[A](body: => A): A =
wenzelm@65006
   192
    {
wenzelm@65006
   193
      val auto_commit = connection.getAutoCommit
wenzelm@65006
   194
      try {
wenzelm@65006
   195
        connection.setAutoCommit(false)
wenzelm@65022
   196
        val savepoint = connection.setSavepoint
wenzelm@65022
   197
        try {
wenzelm@65022
   198
          val result = body
wenzelm@65022
   199
          connection.commit
wenzelm@65022
   200
          result
wenzelm@65022
   201
        }
wenzelm@65022
   202
        catch { case exn: Throwable => connection.rollback(savepoint); throw exn }
wenzelm@65006
   203
      }
wenzelm@65006
   204
      finally { connection.setAutoCommit(auto_commit) }
wenzelm@65006
   205
    }
wenzelm@65006
   206
wenzelm@65006
   207
wenzelm@65006
   208
    /* statements */
wenzelm@65006
   209
wenzelm@65698
   210
    def statement(sql: String): PreparedStatement =
wenzelm@65698
   211
      connection.prepareStatement(sql)
wenzelm@65006
   212
wenzelm@65698
   213
    def using_statement[A](sql: String)(f: PreparedStatement => A): A =
wenzelm@65698
   214
      using(statement(sql))(f)
wenzelm@65006
   215
wenzelm@65006
   216
wenzelm@65020
   217
    /* input */
wenzelm@65020
   218
wenzelm@65020
   219
    def set_bool(stmt: PreparedStatement, i: Int, x: Boolean) { stmt.setBoolean(i, x) }
wenzelm@65612
   220
    def set_bool(stmt: PreparedStatement, i: Int, x: Option[Boolean])
wenzelm@65612
   221
    {
wenzelm@65612
   222
      if (x.isDefined) set_bool(stmt, i, x.get)
wenzelm@65612
   223
      else stmt.setNull(i, java.sql.Types.BOOLEAN)
wenzelm@65612
   224
    }
wenzelm@65615
   225
wenzelm@65020
   226
    def set_int(stmt: PreparedStatement, i: Int, x: Int) { stmt.setInt(i, x) }
wenzelm@65612
   227
    def set_int(stmt: PreparedStatement, i: Int, x: Option[Int])
wenzelm@65612
   228
    {
wenzelm@65612
   229
      if (x.isDefined) set_int(stmt, i, x.get)
wenzelm@65612
   230
      else stmt.setNull(i, java.sql.Types.INTEGER)
wenzelm@65612
   231
    }
wenzelm@65615
   232
wenzelm@65020
   233
    def set_long(stmt: PreparedStatement, i: Int, x: Long) { stmt.setLong(i, x) }
wenzelm@65612
   234
    def set_long(stmt: PreparedStatement, i: Int, x: Option[Long])
wenzelm@65612
   235
    {
wenzelm@65612
   236
      if (x.isDefined) set_long(stmt, i, x.get)
wenzelm@65612
   237
      else stmt.setNull(i, java.sql.Types.BIGINT)
wenzelm@65612
   238
    }
wenzelm@65615
   239
wenzelm@65020
   240
    def set_double(stmt: PreparedStatement, i: Int, x: Double) { stmt.setDouble(i, x) }
wenzelm@65612
   241
    def set_double(stmt: PreparedStatement, i: Int, x: Option[Double])
wenzelm@65612
   242
    {
wenzelm@65612
   243
      if (x.isDefined) set_double(stmt, i, x.get)
wenzelm@65612
   244
      else stmt.setNull(i, java.sql.Types.DOUBLE)
wenzelm@65612
   245
    }
wenzelm@65615
   246
wenzelm@65020
   247
    def set_string(stmt: PreparedStatement, i: Int, x: String) { stmt.setString(i, x) }
wenzelm@65615
   248
    def set_string(stmt: PreparedStatement, i: Int, x: Option[String]): Unit =
wenzelm@65615
   249
      set_string(stmt, i, x.orNull)
wenzelm@65615
   250
wenzelm@65020
   251
    def set_bytes(stmt: PreparedStatement, i: Int, bytes: Bytes)
wenzelm@65610
   252
    {
wenzelm@65610
   253
      if (bytes == null) stmt.setBytes(i, null)
wenzelm@65610
   254
      else stmt.setBinaryStream(i, bytes.stream(), bytes.length)
wenzelm@65610
   255
    }
wenzelm@65615
   256
    def set_bytes(stmt: PreparedStatement, i: Int, bytes: Option[Bytes]): Unit =
wenzelm@65615
   257
      set_bytes(stmt, i, bytes.orNull)
wenzelm@65615
   258
wenzelm@65615
   259
    def set_date(stmt: PreparedStatement, i: Int, date: Date): Unit
wenzelm@65615
   260
    def set_date(stmt: PreparedStatement, i: Int, date: Option[Date]): Unit =
wenzelm@65615
   261
      set_date(stmt, i, date.orNull)
wenzelm@65020
   262
wenzelm@65022
   263
wenzelm@65020
   264
    /* output */
wenzelm@65018
   265
wenzelm@65620
   266
    def bool(rs: ResultSet, column: Column): Boolean = rs.getBoolean(column.name)
wenzelm@65620
   267
    def int(rs: ResultSet, column: Column): Int = rs.getInt(column.name)
wenzelm@65620
   268
    def long(rs: ResultSet, column: Column): Long = rs.getLong(column.name)
wenzelm@65620
   269
    def double(rs: ResultSet, column: Column): Double = rs.getDouble(column.name)
wenzelm@65620
   270
    def string(rs: ResultSet, column: Column): String =
wenzelm@65018
   271
    {
wenzelm@65620
   272
      val s = rs.getString(column.name)
wenzelm@65018
   273
      if (s == null) "" else s
wenzelm@65018
   274
    }
wenzelm@65620
   275
    def bytes(rs: ResultSet, column: Column): Bytes =
wenzelm@65018
   276
    {
wenzelm@65620
   277
      val bs = rs.getBytes(column.name)
wenzelm@65018
   278
      if (bs == null) Bytes.empty else Bytes(bs)
wenzelm@65018
   279
    }
wenzelm@65620
   280
    def date(rs: ResultSet, column: Column): Date
wenzelm@65018
   281
wenzelm@65620
   282
    def get[A](rs: ResultSet, column: Column, f: (ResultSet, Column) => A): Option[A] =
wenzelm@65018
   283
    {
wenzelm@65620
   284
      val x = f(rs, column)
wenzelm@65018
   285
      if (rs.wasNull) None else Some(x)
wenzelm@65018
   286
    }
wenzelm@65697
   287
    def get_bool(rs: ResultSet, column: Column): Option[Boolean] = get(rs, column, bool _)
wenzelm@65697
   288
    def get_int(rs: ResultSet, column: Column): Option[Int] = get(rs, column, int _)
wenzelm@65697
   289
    def get_long(rs: ResultSet, column: Column): Option[Long] = get(rs, column, long _)
wenzelm@65697
   290
    def get_double(rs: ResultSet, column: Column): Option[Double] = get(rs, column, double _)
wenzelm@65697
   291
    def get_string(rs: ResultSet, column: Column): Option[String] = get(rs, column, string _)
wenzelm@65697
   292
    def get_bytes(rs: ResultSet, column: Column): Option[Bytes] = get(rs, column, bytes _)
wenzelm@65697
   293
    def get_date(rs: ResultSet, column: Column): Option[Date] = get(rs, column, date _)
wenzelm@65018
   294
wenzelm@65018
   295
wenzelm@65669
   296
    /* tables and views */
wenzelm@65006
   297
wenzelm@65006
   298
    def tables: List[String] =
wenzelm@65006
   299
      iterator(connection.getMetaData.getTables(null, null, "%", null))(_.getString(3)).toList
wenzelm@65006
   300
wenzelm@65327
   301
    def create_table(table: Table, strict: Boolean = false, sql: String = ""): Unit =
wenzelm@65698
   302
      using_statement(
wenzelm@65698
   303
        table.create(strict, sql_type) + (if (sql == "") "" else " " + sql))(_.execute())
wenzelm@65006
   304
wenzelm@65018
   305
    def create_index(table: Table, name: String, columns: List[Column],
wenzelm@65280
   306
        strict: Boolean = false, unique: Boolean = false): Unit =
wenzelm@65698
   307
      using_statement(table.create_index(name, columns, strict, unique))(_.execute())
wenzelm@65006
   308
wenzelm@65691
   309
    def create_view(table: Table, strict: Boolean = false): Unit =
wenzelm@65691
   310
    {
wenzelm@65691
   311
      if (strict || !tables.contains(table.name)) {
wenzelm@65696
   312
        val sql = "CREATE VIEW " + table.ident + " AS " + table.expr
wenzelm@65698
   313
        using_statement(sql)(_.execute())
wenzelm@65690
   314
      }
wenzelm@65691
   315
    }
wenzelm@65006
   316
  }
wenzelm@63778
   317
}
wenzelm@65006
   318
wenzelm@65006
   319
wenzelm@65006
   320
wenzelm@65006
   321
/** SQLite **/
wenzelm@65006
   322
wenzelm@65006
   323
object SQLite
wenzelm@65006
   324
{
wenzelm@65021
   325
  // see https://www.sqlite.org/lang_datefunc.html
wenzelm@65021
   326
  val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x")
wenzelm@65021
   327
wenzelm@65292
   328
  lazy val init_jdbc: Unit = Class.forName("org.sqlite.JDBC")
wenzelm@65292
   329
wenzelm@65006
   330
  def open_database(path: Path): Database =
wenzelm@65006
   331
  {
wenzelm@65292
   332
    init_jdbc
wenzelm@65006
   333
    val path0 = path.expand
wenzelm@65006
   334
    val s0 = File.platform_path(path0)
wenzelm@65006
   335
    val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
wenzelm@65006
   336
    val connection = DriverManager.getConnection("jdbc:sqlite:" + s1)
wenzelm@65007
   337
    new Database(path0.toString, connection)
wenzelm@65006
   338
  }
wenzelm@65006
   339
wenzelm@65007
   340
  class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database
wenzelm@65006
   341
  {
wenzelm@65007
   342
    override def toString: String = name
wenzelm@65006
   343
wenzelm@65019
   344
    def sql_type(T: SQL.Type.Value): String = SQL.sql_type_sqlite(T)
wenzelm@65011
   345
wenzelm@65021
   346
    def set_date(stmt: PreparedStatement, i: Int, date: Date): Unit =
wenzelm@65615
   347
      if (date == null) set_string(stmt, i, null: String)
wenzelm@65598
   348
      else set_string(stmt, i, date_format(date))
wenzelm@65598
   349
wenzelm@65620
   350
    def date(rs: ResultSet, column: SQL.Column): Date =
wenzelm@65620
   351
      date_format.parse(string(rs, column))
wenzelm@65021
   352
wenzelm@65698
   353
    def rebuild { using_statement("VACUUM")(_.execute()) }
wenzelm@65006
   354
  }
wenzelm@65006
   355
}
wenzelm@65006
   356
wenzelm@65006
   357
wenzelm@65006
   358
wenzelm@65006
   359
/** PostgreSQL **/
wenzelm@65006
   360
wenzelm@65006
   361
object PostgreSQL
wenzelm@65006
   362
{
wenzelm@65006
   363
  val default_port = 5432
wenzelm@65006
   364
wenzelm@65292
   365
  lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver")
wenzelm@65292
   366
wenzelm@65006
   367
  def open_database(
wenzelm@65006
   368
    user: String,
wenzelm@65006
   369
    password: String,
wenzelm@65006
   370
    database: String = "",
wenzelm@65006
   371
    host: String = "",
wenzelm@65594
   372
    port: Int = 0,
wenzelm@65636
   373
    ssh: Option[SSH.Session] = None,
wenzelm@65636
   374
    ssh_close: Boolean = false): Database =
wenzelm@65006
   375
  {
wenzelm@65292
   376
    init_jdbc
wenzelm@65292
   377
wenzelm@65641
   378
    if (user == "") error("Undefined database user")
wenzelm@65009
   379
wenzelm@65009
   380
    val db_host = if (host != "") host else "localhost"
wenzelm@65594
   381
    val db_port = if (port > 0 && port != default_port) ":" + port else ""
wenzelm@65009
   382
    val db_name = "/" + (if (database != "") database else user)
wenzelm@65009
   383
wenzelm@65010
   384
    val (url, name, port_forwarding) =
wenzelm@65009
   385
      ssh match {
wenzelm@65010
   386
        case None =>
wenzelm@65010
   387
          val spec = db_host + db_port + db_name
wenzelm@65010
   388
          val url = "jdbc:postgresql://" + spec
wenzelm@65010
   389
          val name = user + "@" + spec
wenzelm@65010
   390
          (url, name, None)
wenzelm@65009
   391
        case Some(ssh) =>
wenzelm@65594
   392
          val fw =
wenzelm@65594
   393
            ssh.port_forwarding(remote_host = db_host,
wenzelm@65636
   394
              remote_port = if (port > 0) port else default_port,
wenzelm@65636
   395
              ssh_close = ssh_close)
wenzelm@65010
   396
          val url = "jdbc:postgresql://localhost:" + fw.local_port + db_name
wenzelm@65010
   397
          val name = user + "@" + fw + db_name + " via ssh " + ssh
wenzelm@65010
   398
          (url, name, Some(fw))
wenzelm@65009
   399
      }
wenzelm@65009
   400
    try {
wenzelm@65010
   401
      val connection = DriverManager.getConnection(url, user, password)
wenzelm@65010
   402
      new Database(name, connection, port_forwarding)
wenzelm@65009
   403
    }
wenzelm@65009
   404
    catch { case exn: Throwable => port_forwarding.foreach(_.close); throw exn }
wenzelm@65006
   405
  }
wenzelm@65006
   406
wenzelm@65009
   407
  class Database private[PostgreSQL](
wenzelm@65009
   408
      name: String, val connection: Connection, port_forwarding: Option[SSH.Port_Forwarding])
wenzelm@65009
   409
    extends SQL.Database
wenzelm@65006
   410
  {
wenzelm@65010
   411
    override def toString: String = name
wenzelm@65008
   412
wenzelm@65019
   413
    def sql_type(T: SQL.Type.Value): String = SQL.sql_type_postgresql(T)
wenzelm@65009
   414
wenzelm@65021
   415
    // see https://jdbc.postgresql.org/documentation/head/8-date-time.html
wenzelm@65021
   416
    def set_date(stmt: PreparedStatement, i: Int, date: Date): Unit =
wenzelm@65598
   417
      if (date == null) stmt.setObject(i, null)
wenzelm@65598
   418
      else stmt.setObject(i, OffsetDateTime.from(date.to_utc.rep))
wenzelm@65598
   419
wenzelm@65620
   420
    def date(rs: ResultSet, column: SQL.Column): Date =
wenzelm@65620
   421
      Date.instant(rs.getObject(column.name, classOf[OffsetDateTime]).toInstant)
wenzelm@65021
   422
wenzelm@65009
   423
    override def close() { super.close; port_forwarding.foreach(_.close) }
wenzelm@65006
   424
  }
wenzelm@65006
   425
}