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