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