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