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