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