src/Pure/General/sql.scala
author wenzelm
Fri Feb 10 09:55:08 2017 +0100 (2017-02-10)
changeset 65018 8b36f225bbee
parent 65014 97a622d01609
child 65019 0ca91e5d52df
permissions -rw-r--r--
clarified signature;
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@63778
     9
wenzelm@65014
    10
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet, Timestamp}
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@63778
    19
  def quote_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@63778
    33
  def quote_string(s: String): String =
wenzelm@63778
    34
    quote(s.map(quote_char(_)).mkString)
wenzelm@63778
    35
wenzelm@63779
    36
  def quote_ident(s: String): String =
wenzelm@65003
    37
    quote(s.replace("\"", "\"\""))
wenzelm@63779
    38
wenzelm@63791
    39
  def enclosure(ss: Iterable[String]): String = ss.mkString("(", ", ", ")")
wenzelm@63791
    40
wenzelm@63779
    41
wenzelm@65008
    42
  /* types */
wenzelm@65008
    43
wenzelm@65008
    44
  object Type extends Enumeration
wenzelm@65008
    45
  {
wenzelm@65011
    46
    val Boolean = Value("BOOLEAN")
wenzelm@65008
    47
    val Int = Value("INTEGER")
wenzelm@65008
    48
    val Long = Value("BIGINT")
wenzelm@65008
    49
    val Double = Value("DOUBLE PRECISION")
wenzelm@65008
    50
    val String = Value("TEXT")
wenzelm@65008
    51
    val Bytes = Value("BLOB")
wenzelm@65014
    52
    val Date = Value("TIMESTAMP WITH TIME ZONE")
wenzelm@65008
    53
  }
wenzelm@65008
    54
wenzelm@65013
    55
  def type_name_default(t: Type.Value): String = t.toString
wenzelm@65013
    56
wenzelm@65013
    57
  def type_name_sqlite(t: Type.Value): String =
wenzelm@65013
    58
    if (t == Type.Boolean) "INTEGER"
wenzelm@65014
    59
    else if (t == Type.Date) "TEXT"
wenzelm@65013
    60
    else type_name_default(t)
wenzelm@65013
    61
wenzelm@65013
    62
  def type_name_postgresql(t: Type.Value): String =
wenzelm@65013
    63
    if (t == Type.Bytes) "BYTEA"
wenzelm@65013
    64
    else type_name_default(t)
wenzelm@65008
    65
wenzelm@65008
    66
wenzelm@63779
    67
  /* columns */
wenzelm@63779
    68
wenzelm@63779
    69
  object Column
wenzelm@63779
    70
  {
wenzelm@65018
    71
    def bool(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    72
      Column(name, Type.Boolean, strict, primary_key)
wenzelm@65018
    73
    def int(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    74
      Column(name, Type.Int, strict, primary_key)
wenzelm@65018
    75
    def long(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    76
      Column(name, Type.Long, strict, primary_key)
wenzelm@65018
    77
    def double(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    78
      Column(name, Type.Double, strict, primary_key)
wenzelm@65018
    79
    def string(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    80
      Column(name, Type.String, strict, primary_key)
wenzelm@65018
    81
    def bytes(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    82
      Column(name, Type.Bytes, strict, primary_key)
wenzelm@65018
    83
    def date(name: String, strict: Boolean = true, primary_key: Boolean = false): Column =
wenzelm@65018
    84
      Column(name, Type.Date, strict, primary_key)
wenzelm@63779
    85
  }
wenzelm@63779
    86
wenzelm@65018
    87
  sealed case class Column(
wenzelm@65018
    88
    name: String, t: Type.Value, strict: Boolean = true, primary_key: Boolean = false)
wenzelm@63779
    89
  {
wenzelm@63779
    90
    def sql_name: String = quote_ident(name)
wenzelm@65018
    91
    def sql_decl(type_name: Type.Value => String): String =
wenzelm@65018
    92
      sql_name + " " + type_name(t) +
wenzelm@63781
    93
      (if (strict) " NOT NULL" else "") +
wenzelm@63781
    94
      (if (primary_key) " PRIMARY KEY" else "")
wenzelm@63781
    95
wenzelm@65013
    96
    override def toString: String = sql_decl(type_name_default)
wenzelm@63779
    97
  }
wenzelm@63779
    98
wenzelm@63780
    99
wenzelm@63780
   100
  /* tables */
wenzelm@63780
   101
wenzelm@65018
   102
  sealed case class Table(name: String, columns: List[Column])
wenzelm@63780
   103
  {
wenzelm@63790
   104
    private val columns_index: Map[String, Int] =
wenzelm@63790
   105
      columns.iterator.map(_.name).zipWithIndex.toMap
wenzelm@63790
   106
wenzelm@63781
   107
    Library.duplicates(columns.map(_.name)) match {
wenzelm@63781
   108
      case Nil =>
wenzelm@63781
   109
      case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name))
wenzelm@63781
   110
    }
wenzelm@63781
   111
wenzelm@63781
   112
    columns.filter(_.primary_key) match {
wenzelm@63781
   113
      case bad if bad.length > 1 =>
wenzelm@63781
   114
        error("Multiple primary keys " + commas_quote(bad.map(_.name)) + " for table " + quote(name))
wenzelm@63781
   115
      case _ =>
wenzelm@63781
   116
    }
wenzelm@63781
   117
wenzelm@65018
   118
    def sql_create(strict: Boolean, rowid: Boolean, type_name: Type.Value => String): String =
wenzelm@63784
   119
      "CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") +
wenzelm@65008
   120
        quote_ident(name) + " " + enclosure(columns.map(_.sql_decl(type_name))) +
wenzelm@63780
   121
        (if (rowid) "" else " WITHOUT ROWID")
wenzelm@63780
   122
wenzelm@63780
   123
    def sql_drop(strict: Boolean): String =
wenzelm@63784
   124
      "DROP TABLE " + (if (strict) "" else "IF EXISTS ") + quote_ident(name)
wenzelm@63783
   125
wenzelm@63791
   126
    def sql_create_index(
wenzelm@65018
   127
        index_name: String, index_columns: List[Column],
wenzelm@63791
   128
        strict: Boolean, unique: Boolean): String =
wenzelm@63791
   129
      "CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " +
wenzelm@63791
   130
        (if (strict) "" else "IF NOT EXISTS ") + quote_ident(index_name) + " ON " +
wenzelm@63791
   131
        quote_ident(name) + " " + enclosure(index_columns.map(_.name))
wenzelm@63791
   132
wenzelm@63791
   133
    def sql_drop_index(index_name: String, strict: Boolean): String =
wenzelm@63791
   134
      "DROP INDEX " + (if (strict) "" else "IF EXISTS ") + quote_ident(index_name)
wenzelm@63791
   135
wenzelm@63790
   136
    def sql_insert: String =
wenzelm@63791
   137
      "INSERT INTO " + quote_ident(name) + " VALUES " + enclosure(columns.map(_ => "?"))
wenzelm@63791
   138
wenzelm@65018
   139
    def sql_select(select_columns: List[Column], distinct: Boolean): String =
wenzelm@63791
   140
      "SELECT " + (if (distinct) "DISTINCT " else "") +
wenzelm@63791
   141
      commas(select_columns.map(_.sql_name)) + " FROM " + quote_ident(name)
wenzelm@63790
   142
wenzelm@63783
   143
    override def toString: String =
wenzelm@63791
   144
      "TABLE " + quote_ident(name) + " " + enclosure(columns.map(_.toString))
wenzelm@63780
   145
  }
wenzelm@63790
   146
wenzelm@63790
   147
wenzelm@65012
   148
wenzelm@65012
   149
  /** SQL database operations **/
wenzelm@65012
   150
wenzelm@63790
   151
  /* results */
wenzelm@63790
   152
wenzelm@63790
   153
  def iterator[A](rs: ResultSet)(get: ResultSet => A): Iterator[A] = new Iterator[A]
wenzelm@63790
   154
  {
wenzelm@63790
   155
    private var _next: Boolean = rs.next()
wenzelm@63790
   156
    def hasNext: Boolean = _next
wenzelm@63790
   157
    def next: A = { val x = get(rs); _next = rs.next(); x }
wenzelm@63790
   158
  }
wenzelm@65006
   159
wenzelm@65006
   160
  trait Database
wenzelm@65006
   161
  {
wenzelm@65008
   162
    /* types */
wenzelm@65008
   163
wenzelm@65011
   164
    def type_name(t: Type.Value): String
wenzelm@65008
   165
wenzelm@65008
   166
wenzelm@65006
   167
    /* connection */
wenzelm@65006
   168
wenzelm@65006
   169
    def connection: Connection
wenzelm@65006
   170
wenzelm@65006
   171
    def close() { connection.close }
wenzelm@65006
   172
wenzelm@65006
   173
    def transaction[A](body: => A): A =
wenzelm@65006
   174
    {
wenzelm@65006
   175
      val auto_commit = connection.getAutoCommit
wenzelm@65006
   176
      val savepoint = connection.setSavepoint
wenzelm@65006
   177
wenzelm@65006
   178
      try {
wenzelm@65006
   179
        connection.setAutoCommit(false)
wenzelm@65006
   180
        val result = body
wenzelm@65006
   181
        connection.commit
wenzelm@65006
   182
        result
wenzelm@65006
   183
      }
wenzelm@65006
   184
      catch { case exn: Throwable => connection.rollback(savepoint); throw exn }
wenzelm@65006
   185
      finally { connection.setAutoCommit(auto_commit) }
wenzelm@65006
   186
    }
wenzelm@65006
   187
wenzelm@65006
   188
wenzelm@65006
   189
    /* statements */
wenzelm@65006
   190
wenzelm@65006
   191
    def statement(sql: String): PreparedStatement = connection.prepareStatement(sql)
wenzelm@65006
   192
wenzelm@65006
   193
    def insert_statement(table: Table): PreparedStatement = statement(table.sql_insert)
wenzelm@65006
   194
wenzelm@65018
   195
    def select_statement(table: Table, columns: List[Column],
wenzelm@65006
   196
        sql: String = "", distinct: Boolean = false): PreparedStatement =
wenzelm@65006
   197
      statement(table.sql_select(columns, distinct) + (if (sql == "") "" else " " + sql))
wenzelm@65006
   198
wenzelm@65006
   199
wenzelm@65018
   200
    /* results */
wenzelm@65018
   201
wenzelm@65018
   202
    def bool(rs: ResultSet, name: String): Boolean = rs.getBoolean(name)
wenzelm@65018
   203
    def int(rs: ResultSet, name: String): Int = rs.getInt(name)
wenzelm@65018
   204
    def long(rs: ResultSet, name: String): Long = rs.getLong(name)
wenzelm@65018
   205
    def double(rs: ResultSet, name: String): Double = rs.getDouble(name)
wenzelm@65018
   206
    def string(rs: ResultSet, name: String): String =
wenzelm@65018
   207
    {
wenzelm@65018
   208
      val s = rs.getString(name)
wenzelm@65018
   209
      if (s == null) "" else s
wenzelm@65018
   210
    }
wenzelm@65018
   211
    def bytes(rs: ResultSet, name: String): Bytes =
wenzelm@65018
   212
    {
wenzelm@65018
   213
      val bs = rs.getBytes(name)
wenzelm@65018
   214
      if (bs == null) Bytes.empty else Bytes(bs)
wenzelm@65018
   215
    }
wenzelm@65018
   216
    def date(rs: ResultSet, name: String): Date =
wenzelm@65018
   217
      Date.instant(rs.getTimestamp(name).toInstant)
wenzelm@65018
   218
wenzelm@65018
   219
    def get[A](rs: ResultSet, name: String, f: (ResultSet, String) => A): Option[A] =
wenzelm@65018
   220
    {
wenzelm@65018
   221
      val x = f(rs, name)
wenzelm@65018
   222
      if (rs.wasNull) None else Some(x)
wenzelm@65018
   223
    }
wenzelm@65018
   224
wenzelm@65018
   225
wenzelm@65006
   226
    /* tables */
wenzelm@65006
   227
wenzelm@65006
   228
    def tables: List[String] =
wenzelm@65006
   229
      iterator(connection.getMetaData.getTables(null, null, "%", null))(_.getString(3)).toList
wenzelm@65006
   230
wenzelm@65006
   231
    def create_table(table: Table, strict: Boolean = true, rowid: Boolean = true): Unit =
wenzelm@65008
   232
      using(statement(table.sql_create(strict, rowid, type_name)))(_.execute())
wenzelm@65006
   233
wenzelm@65006
   234
    def drop_table(table: Table, strict: Boolean = true): Unit =
wenzelm@65006
   235
      using(statement(table.sql_drop(strict)))(_.execute())
wenzelm@65006
   236
wenzelm@65018
   237
    def create_index(table: Table, name: String, columns: List[Column],
wenzelm@65006
   238
        strict: Boolean = true, unique: Boolean = false): Unit =
wenzelm@65006
   239
      using(statement(table.sql_create_index(name, columns, strict, unique)))(_.execute())
wenzelm@65006
   240
wenzelm@65006
   241
    def drop_index(table: Table, name: String, strict: Boolean = true): Unit =
wenzelm@65006
   242
      using(statement(table.sql_drop_index(name, strict)))(_.execute())
wenzelm@65006
   243
  }
wenzelm@63778
   244
}
wenzelm@65006
   245
wenzelm@65006
   246
wenzelm@65006
   247
wenzelm@65006
   248
/** SQLite **/
wenzelm@65006
   249
wenzelm@65006
   250
object SQLite
wenzelm@65006
   251
{
wenzelm@65006
   252
  def open_database(path: Path): Database =
wenzelm@65006
   253
  {
wenzelm@65006
   254
    val path0 = path.expand
wenzelm@65006
   255
    val s0 = File.platform_path(path0)
wenzelm@65006
   256
    val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
wenzelm@65006
   257
    val connection = DriverManager.getConnection("jdbc:sqlite:" + s1)
wenzelm@65007
   258
    new Database(path0.toString, connection)
wenzelm@65006
   259
  }
wenzelm@65006
   260
wenzelm@65007
   261
  class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database
wenzelm@65006
   262
  {
wenzelm@65007
   263
    override def toString: String = name
wenzelm@65006
   264
wenzelm@65013
   265
    def type_name(t: SQL.Type.Value): String = SQL.type_name_sqlite(t)
wenzelm@65011
   266
wenzelm@65006
   267
    def rebuild { using(statement("VACUUM"))(_.execute()) }
wenzelm@65006
   268
  }
wenzelm@65006
   269
}
wenzelm@65006
   270
wenzelm@65006
   271
wenzelm@65006
   272
wenzelm@65006
   273
/** PostgreSQL **/
wenzelm@65006
   274
wenzelm@65006
   275
object PostgreSQL
wenzelm@65006
   276
{
wenzelm@65006
   277
  val default_port = 5432
wenzelm@65006
   278
wenzelm@65006
   279
  def open_database(
wenzelm@65006
   280
    user: String,
wenzelm@65006
   281
    password: String,
wenzelm@65006
   282
    database: String = "",
wenzelm@65006
   283
    host: String = "",
wenzelm@65009
   284
    port: Int = default_port,
wenzelm@65009
   285
    ssh: Option[SSH.Session] = None): Database =
wenzelm@65006
   286
  {
wenzelm@65006
   287
    require(user != "")
wenzelm@65009
   288
wenzelm@65009
   289
    val db_host = if (host != "") host else "localhost"
wenzelm@65009
   290
    val db_port = if (port != default_port) ":" + port else ""
wenzelm@65009
   291
    val db_name = "/" + (if (database != "") database else user)
wenzelm@65009
   292
wenzelm@65010
   293
    val (url, name, port_forwarding) =
wenzelm@65009
   294
      ssh match {
wenzelm@65010
   295
        case None =>
wenzelm@65010
   296
          val spec = db_host + db_port + db_name
wenzelm@65010
   297
          val url = "jdbc:postgresql://" + spec
wenzelm@65010
   298
          val name = user + "@" + spec
wenzelm@65010
   299
          (url, name, None)
wenzelm@65009
   300
        case Some(ssh) =>
wenzelm@65009
   301
          val fw = ssh.port_forwarding(remote_host = db_host, remote_port = port)
wenzelm@65010
   302
          val url = "jdbc:postgresql://localhost:" + fw.local_port + db_name
wenzelm@65010
   303
          val name = user + "@" + fw + db_name + " via ssh " + ssh
wenzelm@65010
   304
          (url, name, Some(fw))
wenzelm@65009
   305
      }
wenzelm@65009
   306
    try {
wenzelm@65010
   307
      val connection = DriverManager.getConnection(url, user, password)
wenzelm@65010
   308
      new Database(name, connection, port_forwarding)
wenzelm@65009
   309
    }
wenzelm@65009
   310
    catch { case exn: Throwable => port_forwarding.foreach(_.close); throw exn }
wenzelm@65006
   311
  }
wenzelm@65006
   312
wenzelm@65009
   313
  class Database private[PostgreSQL](
wenzelm@65009
   314
      name: String, val connection: Connection, port_forwarding: Option[SSH.Port_Forwarding])
wenzelm@65009
   315
    extends SQL.Database
wenzelm@65006
   316
  {
wenzelm@65010
   317
    override def toString: String = name
wenzelm@65008
   318
wenzelm@65013
   319
    def type_name(t: SQL.Type.Value): String = SQL.type_name_postgresql(t)
wenzelm@65009
   320
wenzelm@65009
   321
    override def close() { super.close; port_forwarding.foreach(_.close) }
wenzelm@65006
   322
  }
wenzelm@65006
   323
}