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