src/Pure/General/sql.scala
author wenzelm
Thu Feb 09 16:58:27 2017 +0100 (2017-02-09)
changeset 65012 14641ca387f8
parent 65011 42bffd1637f0
child 65013 86308845aa43
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@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@65012
   198
wenzelm@65012
   199
  /** SQL database operations **/
wenzelm@65012
   200
wenzelm@63790
   201
  /* results */
wenzelm@63790
   202
wenzelm@63790
   203
  def iterator[A](rs: ResultSet)(get: ResultSet => A): Iterator[A] = new Iterator[A]
wenzelm@63790
   204
  {
wenzelm@63790
   205
    private var _next: Boolean = rs.next()
wenzelm@63790
   206
    def hasNext: Boolean = _next
wenzelm@63790
   207
    def next: A = { val x = get(rs); _next = rs.next(); x }
wenzelm@63790
   208
  }
wenzelm@65006
   209
wenzelm@65006
   210
  trait Database
wenzelm@65006
   211
  {
wenzelm@65008
   212
    /* types */
wenzelm@65008
   213
wenzelm@65011
   214
    def type_name(t: Type.Value): String
wenzelm@65008
   215
wenzelm@65008
   216
wenzelm@65006
   217
    /* connection */
wenzelm@65006
   218
wenzelm@65006
   219
    def connection: Connection
wenzelm@65006
   220
wenzelm@65006
   221
    def close() { connection.close }
wenzelm@65006
   222
wenzelm@65006
   223
    def transaction[A](body: => A): A =
wenzelm@65006
   224
    {
wenzelm@65006
   225
      val auto_commit = connection.getAutoCommit
wenzelm@65006
   226
      val savepoint = connection.setSavepoint
wenzelm@65006
   227
wenzelm@65006
   228
      try {
wenzelm@65006
   229
        connection.setAutoCommit(false)
wenzelm@65006
   230
        val result = body
wenzelm@65006
   231
        connection.commit
wenzelm@65006
   232
        result
wenzelm@65006
   233
      }
wenzelm@65006
   234
      catch { case exn: Throwable => connection.rollback(savepoint); throw exn }
wenzelm@65006
   235
      finally { connection.setAutoCommit(auto_commit) }
wenzelm@65006
   236
    }
wenzelm@65006
   237
wenzelm@65006
   238
wenzelm@65006
   239
    /* statements */
wenzelm@65006
   240
wenzelm@65006
   241
    def statement(sql: String): PreparedStatement = connection.prepareStatement(sql)
wenzelm@65006
   242
wenzelm@65006
   243
    def insert_statement(table: Table): PreparedStatement = statement(table.sql_insert)
wenzelm@65006
   244
wenzelm@65006
   245
    def select_statement(table: Table, columns: List[Column[Any]],
wenzelm@65006
   246
        sql: String = "", distinct: Boolean = false): PreparedStatement =
wenzelm@65006
   247
      statement(table.sql_select(columns, distinct) + (if (sql == "") "" else " " + sql))
wenzelm@65006
   248
wenzelm@65006
   249
wenzelm@65006
   250
    /* tables */
wenzelm@65006
   251
wenzelm@65006
   252
    def tables: List[String] =
wenzelm@65006
   253
      iterator(connection.getMetaData.getTables(null, null, "%", null))(_.getString(3)).toList
wenzelm@65006
   254
wenzelm@65006
   255
    def create_table(table: Table, strict: Boolean = true, rowid: Boolean = true): Unit =
wenzelm@65008
   256
      using(statement(table.sql_create(strict, rowid, type_name)))(_.execute())
wenzelm@65006
   257
wenzelm@65006
   258
    def drop_table(table: Table, strict: Boolean = true): Unit =
wenzelm@65006
   259
      using(statement(table.sql_drop(strict)))(_.execute())
wenzelm@65006
   260
wenzelm@65006
   261
    def create_index(table: Table, name: String, columns: List[Column[Any]],
wenzelm@65006
   262
        strict: Boolean = true, unique: Boolean = false): Unit =
wenzelm@65006
   263
      using(statement(table.sql_create_index(name, columns, strict, unique)))(_.execute())
wenzelm@65006
   264
wenzelm@65006
   265
    def drop_index(table: Table, name: String, strict: Boolean = true): Unit =
wenzelm@65006
   266
      using(statement(table.sql_drop_index(name, strict)))(_.execute())
wenzelm@65006
   267
  }
wenzelm@63778
   268
}
wenzelm@65006
   269
wenzelm@65006
   270
wenzelm@65006
   271
wenzelm@65006
   272
/** SQLite **/
wenzelm@65006
   273
wenzelm@65006
   274
object SQLite
wenzelm@65006
   275
{
wenzelm@65006
   276
  def open_database(path: Path): Database =
wenzelm@65006
   277
  {
wenzelm@65006
   278
    val path0 = path.expand
wenzelm@65006
   279
    val s0 = File.platform_path(path0)
wenzelm@65006
   280
    val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
wenzelm@65006
   281
    val connection = DriverManager.getConnection("jdbc:sqlite:" + s1)
wenzelm@65007
   282
    new Database(path0.toString, connection)
wenzelm@65006
   283
  }
wenzelm@65006
   284
wenzelm@65007
   285
  class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database
wenzelm@65006
   286
  {
wenzelm@65007
   287
    override def toString: String = name
wenzelm@65006
   288
wenzelm@65011
   289
    def type_name(t: SQL.Type.Value): String =
wenzelm@65011
   290
      if (t == SQL.Type.Boolean) "INTEGER"
wenzelm@65011
   291
      else SQL.default_type_name(t)
wenzelm@65011
   292
wenzelm@65006
   293
    def rebuild { using(statement("VACUUM"))(_.execute()) }
wenzelm@65006
   294
  }
wenzelm@65006
   295
}
wenzelm@65006
   296
wenzelm@65006
   297
wenzelm@65006
   298
wenzelm@65006
   299
/** PostgreSQL **/
wenzelm@65006
   300
wenzelm@65006
   301
object PostgreSQL
wenzelm@65006
   302
{
wenzelm@65006
   303
  val default_port = 5432
wenzelm@65006
   304
wenzelm@65006
   305
  def open_database(
wenzelm@65006
   306
    user: String,
wenzelm@65006
   307
    password: String,
wenzelm@65006
   308
    database: String = "",
wenzelm@65006
   309
    host: String = "",
wenzelm@65009
   310
    port: Int = default_port,
wenzelm@65009
   311
    ssh: Option[SSH.Session] = None): Database =
wenzelm@65006
   312
  {
wenzelm@65006
   313
    require(user != "")
wenzelm@65009
   314
wenzelm@65009
   315
    val db_host = if (host != "") host else "localhost"
wenzelm@65009
   316
    val db_port = if (port != default_port) ":" + port else ""
wenzelm@65009
   317
    val db_name = "/" + (if (database != "") database else user)
wenzelm@65009
   318
wenzelm@65010
   319
    val (url, name, port_forwarding) =
wenzelm@65009
   320
      ssh match {
wenzelm@65010
   321
        case None =>
wenzelm@65010
   322
          val spec = db_host + db_port + db_name
wenzelm@65010
   323
          val url = "jdbc:postgresql://" + spec
wenzelm@65010
   324
          val name = user + "@" + spec
wenzelm@65010
   325
          (url, name, None)
wenzelm@65009
   326
        case Some(ssh) =>
wenzelm@65009
   327
          val fw = ssh.port_forwarding(remote_host = db_host, remote_port = port)
wenzelm@65010
   328
          val url = "jdbc:postgresql://localhost:" + fw.local_port + db_name
wenzelm@65010
   329
          val name = user + "@" + fw + db_name + " via ssh " + ssh
wenzelm@65010
   330
          (url, name, Some(fw))
wenzelm@65009
   331
      }
wenzelm@65009
   332
    try {
wenzelm@65010
   333
      val connection = DriverManager.getConnection(url, user, password)
wenzelm@65010
   334
      new Database(name, connection, port_forwarding)
wenzelm@65009
   335
    }
wenzelm@65009
   336
    catch { case exn: Throwable => port_forwarding.foreach(_.close); throw exn }
wenzelm@65006
   337
  }
wenzelm@65006
   338
wenzelm@65009
   339
  class Database private[PostgreSQL](
wenzelm@65009
   340
      name: String, val connection: Connection, port_forwarding: Option[SSH.Port_Forwarding])
wenzelm@65009
   341
    extends SQL.Database
wenzelm@65006
   342
  {
wenzelm@65010
   343
    override def toString: String = name
wenzelm@65008
   344
wenzelm@65011
   345
    def type_name(t: SQL.Type.Value): String =
wenzelm@65008
   346
      if (t == SQL.Type.Bytes) "BYTEA"
wenzelm@65008
   347
      else SQL.default_type_name(t)
wenzelm@65009
   348
wenzelm@65009
   349
    override def close() { super.close; port_forwarding.foreach(_.close) }
wenzelm@65006
   350
  }
wenzelm@65006
   351
}