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