author | wenzelm |
Thu, 27 Apr 2017 23:36:59 +0200 | |
changeset 65598 | 5deef985e38e |
parent 65594 | 659305708959 |
child 65602 | d9533e9615ad |
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 |
||
65021 | 9 |
import java.time.OffsetDateTime |
10 |
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet} |
|
63779 | 11 |
|
12 |
||
63778 | 13 |
object SQL |
14 |
{ |
|
65006 | 15 |
/** SQL language **/ |
16 |
||
63778 | 17 |
/* concrete syntax */ |
18 |
||
65321 | 19 |
def escape_char(c: Char): String = |
63778 | 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 = |
|
65321 | 34 |
"'" + s.map(escape_char(_)).mkString + "'" |
63778 | 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 |
||
65019 | 55 |
def sql_type_default(T: Type.Value): String = T.toString |
65013 | 56 |
|
65019 | 57 |
def sql_type_sqlite(T: Type.Value): String = |
58 |
if (T == Type.Boolean) "INTEGER" |
|
59 |
else if (T == Type.Date) "TEXT" |
|
60 |
else sql_type_default(T) |
|
65013 | 61 |
|
65019 | 62 |
def sql_type_postgresql(T: Type.Value): String = |
63 |
if (T == Type.Bytes) "BYTEA" |
|
64 |
else sql_type_default(T) |
|
65008 | 65 |
|
66 |
||
63779 | 67 |
/* columns */ |
68 |
||
69 |
object Column |
|
70 |
{ |
|
65280 | 71 |
def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 72 |
Column(name, Type.Boolean, strict, primary_key) |
65280 | 73 |
def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 74 |
Column(name, Type.Int, strict, primary_key) |
65280 | 75 |
def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 76 |
Column(name, Type.Long, strict, primary_key) |
65280 | 77 |
def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 78 |
Column(name, Type.Double, strict, primary_key) |
65280 | 79 |
def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 80 |
Column(name, Type.String, strict, primary_key) |
65280 | 81 |
def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 82 |
Column(name, Type.Bytes, strict, primary_key) |
65280 | 83 |
def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 84 |
Column(name, Type.Date, strict, primary_key) |
63779 | 85 |
} |
86 |
||
65018 | 87 |
sealed case class Column( |
65280 | 88 |
name: String, T: Type.Value, strict: Boolean = false, primary_key: Boolean = false) |
63779 | 89 |
{ |
90 |
def sql_name: String = quote_ident(name) |
|
65019 | 91 |
def sql_decl(sql_type: Type.Value => String): String = |
65325 | 92 |
sql_name + " " + sql_type(T) + (if (strict || primary_key) " NOT NULL" else "") |
63781 | 93 |
|
65593 | 94 |
def sql_where_eq: String = "WHERE " + sql_name + " = " |
95 |
def sql_where_eq_string(s: String): String = sql_where_eq + quote_string(s) |
|
96 |
||
65019 | 97 |
override def toString: String = sql_decl(sql_type_default) |
63779 | 98 |
} |
99 |
||
63780 | 100 |
|
101 |
/* tables */ |
|
102 |
||
65018 | 103 |
sealed case class Table(name: String, columns: List[Column]) |
63780 | 104 |
{ |
63790 | 105 |
private val columns_index: Map[String, Int] = |
106 |
columns.iterator.map(_.name).zipWithIndex.toMap |
|
107 |
||
63781 | 108 |
Library.duplicates(columns.map(_.name)) match { |
109 |
case Nil => |
|
110 |
case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name)) |
|
111 |
} |
|
112 |
||
65325 | 113 |
def sql_columns(sql_type: Type.Value => String): String = |
114 |
{ |
|
115 |
val primary_key = |
|
116 |
columns.filter(_.primary_key).map(_.name) match { |
|
117 |
case Nil => Nil |
|
118 |
case keys => List("PRIMARY KEY " + enclosure(keys)) |
|
119 |
} |
|
120 |
enclosure(columns.map(_.sql_decl(sql_type)) ::: primary_key) |
|
63781 | 121 |
} |
122 |
||
65327
e886aed88b2c
clarified signature: rowid is specific to SQLite;
wenzelm
parents:
65325
diff
changeset
|
123 |
def sql_create(strict: Boolean, sql_type: Type.Value => String): String = |
63784 | 124 |
"CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") + |
65327
e886aed88b2c
clarified signature: rowid is specific to SQLite;
wenzelm
parents:
65325
diff
changeset
|
125 |
quote_ident(name) + " " + sql_columns(sql_type) |
63780 | 126 |
|
127 |
def sql_drop(strict: Boolean): String = |
|
63784 | 128 |
"DROP TABLE " + (if (strict) "" else "IF EXISTS ") + quote_ident(name) |
63783 | 129 |
|
63791 | 130 |
def sql_create_index( |
65018 | 131 |
index_name: String, index_columns: List[Column], |
63791 | 132 |
strict: Boolean, unique: Boolean): String = |
133 |
"CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " + |
|
134 |
(if (strict) "" else "IF NOT EXISTS ") + quote_ident(index_name) + " ON " + |
|
135 |
quote_ident(name) + " " + enclosure(index_columns.map(_.name)) |
|
136 |
||
137 |
def sql_drop_index(index_name: String, strict: Boolean): String = |
|
138 |
"DROP INDEX " + (if (strict) "" else "IF EXISTS ") + quote_ident(index_name) |
|
139 |
||
63790 | 140 |
def sql_insert: String = |
63791 | 141 |
"INSERT INTO " + quote_ident(name) + " VALUES " + enclosure(columns.map(_ => "?")) |
142 |
||
65319 | 143 |
def sql_delete: String = |
144 |
"DELETE FROM " + quote_ident(name) |
|
145 |
||
65018 | 146 |
def sql_select(select_columns: List[Column], distinct: Boolean): String = |
63791 | 147 |
"SELECT " + (if (distinct) "DISTINCT " else "") + |
148 |
commas(select_columns.map(_.sql_name)) + " FROM " + quote_ident(name) |
|
63790 | 149 |
|
63783 | 150 |
override def toString: String = |
65325 | 151 |
"TABLE " + quote_ident(name) + " " + sql_columns(sql_type_default) |
63780 | 152 |
} |
63790 | 153 |
|
154 |
||
65012 | 155 |
|
156 |
/** SQL database operations **/ |
|
157 |
||
63790 | 158 |
/* results */ |
159 |
||
160 |
def iterator[A](rs: ResultSet)(get: ResultSet => A): Iterator[A] = new Iterator[A] |
|
161 |
{ |
|
162 |
private var _next: Boolean = rs.next() |
|
163 |
def hasNext: Boolean = _next |
|
164 |
def next: A = { val x = get(rs); _next = rs.next(); x } |
|
165 |
} |
|
65006 | 166 |
|
167 |
trait Database |
|
168 |
{ |
|
65008 | 169 |
/* types */ |
170 |
||
65019 | 171 |
def sql_type(T: Type.Value): String |
65008 | 172 |
|
173 |
||
65006 | 174 |
/* connection */ |
175 |
||
176 |
def connection: Connection |
|
177 |
||
178 |
def close() { connection.close } |
|
179 |
||
180 |
def transaction[A](body: => A): A = |
|
181 |
{ |
|
182 |
val auto_commit = connection.getAutoCommit |
|
183 |
try { |
|
184 |
connection.setAutoCommit(false) |
|
65022 | 185 |
val savepoint = connection.setSavepoint |
186 |
try { |
|
187 |
val result = body |
|
188 |
connection.commit |
|
189 |
result |
|
190 |
} |
|
191 |
catch { case exn: Throwable => connection.rollback(savepoint); throw exn } |
|
65006 | 192 |
} |
193 |
finally { connection.setAutoCommit(auto_commit) } |
|
194 |
} |
|
195 |
||
196 |
||
197 |
/* statements */ |
|
198 |
||
199 |
def statement(sql: String): PreparedStatement = connection.prepareStatement(sql) |
|
200 |
||
201 |
def insert_statement(table: Table): PreparedStatement = statement(table.sql_insert) |
|
202 |
||
65319 | 203 |
def delete_statement(table: Table, sql: String = ""): PreparedStatement = |
204 |
statement(table.sql_delete + (if (sql == "") "" else " " + sql)) |
|
205 |
||
65018 | 206 |
def select_statement(table: Table, columns: List[Column], |
65006 | 207 |
sql: String = "", distinct: Boolean = false): PreparedStatement = |
208 |
statement(table.sql_select(columns, distinct) + (if (sql == "") "" else " " + sql)) |
|
209 |
||
210 |
||
65020 | 211 |
/* input */ |
212 |
||
213 |
def set_bool(stmt: PreparedStatement, i: Int, x: Boolean) { stmt.setBoolean(i, x) } |
|
214 |
def set_int(stmt: PreparedStatement, i: Int, x: Int) { stmt.setInt(i, x) } |
|
215 |
def set_long(stmt: PreparedStatement, i: Int, x: Long) { stmt.setLong(i, x) } |
|
216 |
def set_double(stmt: PreparedStatement, i: Int, x: Double) { stmt.setDouble(i, x) } |
|
217 |
def set_string(stmt: PreparedStatement, i: Int, x: String) { stmt.setString(i, x) } |
|
218 |
def set_bytes(stmt: PreparedStatement, i: Int, bytes: Bytes) |
|
219 |
{ stmt.setBinaryStream(i, bytes.stream(), bytes.length) } |
|
220 |
def set_date(stmt: PreparedStatement, i: Int, date: Date) |
|
221 |
||
65022 | 222 |
|
65020 | 223 |
/* output */ |
65018 | 224 |
|
225 |
def bool(rs: ResultSet, name: String): Boolean = rs.getBoolean(name) |
|
226 |
def int(rs: ResultSet, name: String): Int = rs.getInt(name) |
|
227 |
def long(rs: ResultSet, name: String): Long = rs.getLong(name) |
|
228 |
def double(rs: ResultSet, name: String): Double = rs.getDouble(name) |
|
229 |
def string(rs: ResultSet, name: String): String = |
|
230 |
{ |
|
231 |
val s = rs.getString(name) |
|
232 |
if (s == null) "" else s |
|
233 |
} |
|
234 |
def bytes(rs: ResultSet, name: String): Bytes = |
|
235 |
{ |
|
236 |
val bs = rs.getBytes(name) |
|
237 |
if (bs == null) Bytes.empty else Bytes(bs) |
|
238 |
} |
|
65021 | 239 |
def date(rs: ResultSet, name: String): Date |
65018 | 240 |
|
65323 | 241 |
def bool(rs: ResultSet, column: Column): Boolean = bool(rs, column.name) |
242 |
def int(rs: ResultSet, column: Column): Int = int(rs, column.name) |
|
243 |
def long(rs: ResultSet, column: Column): Long = long(rs, column.name) |
|
244 |
def double(rs: ResultSet, column: Column): Double = double(rs, column.name) |
|
245 |
def string(rs: ResultSet, column: Column): String = string(rs, column.name) |
|
246 |
def bytes(rs: ResultSet, column: Column): Bytes = bytes(rs, column.name) |
|
247 |
def date(rs: ResultSet, column: Column): Date = date(rs, column.name) |
|
248 |
||
249 |
def get[A, B](rs: ResultSet, a: A, f: (ResultSet, A) => B): Option[B] = |
|
65018 | 250 |
{ |
65323 | 251 |
val x = f(rs, a) |
65018 | 252 |
if (rs.wasNull) None else Some(x) |
253 |
} |
|
254 |
||
255 |
||
65006 | 256 |
/* tables */ |
257 |
||
258 |
def tables: List[String] = |
|
259 |
iterator(connection.getMetaData.getTables(null, null, "%", null))(_.getString(3)).toList |
|
260 |
||
65327
e886aed88b2c
clarified signature: rowid is specific to SQLite;
wenzelm
parents:
65325
diff
changeset
|
261 |
def create_table(table: Table, strict: Boolean = false, sql: String = ""): Unit = |
e886aed88b2c
clarified signature: rowid is specific to SQLite;
wenzelm
parents:
65325
diff
changeset
|
262 |
using(statement(table.sql_create(strict, sql_type) + (if (sql == "") "" else " " + sql)))( |
e886aed88b2c
clarified signature: rowid is specific to SQLite;
wenzelm
parents:
65325
diff
changeset
|
263 |
_.execute()) |
65006 | 264 |
|
65280 | 265 |
def drop_table(table: Table, strict: Boolean = false): Unit = |
65006 | 266 |
using(statement(table.sql_drop(strict)))(_.execute()) |
267 |
||
65018 | 268 |
def create_index(table: Table, name: String, columns: List[Column], |
65280 | 269 |
strict: Boolean = false, unique: Boolean = false): Unit = |
65006 | 270 |
using(statement(table.sql_create_index(name, columns, strict, unique)))(_.execute()) |
271 |
||
65280 | 272 |
def drop_index(table: Table, name: String, strict: Boolean = false): Unit = |
65006 | 273 |
using(statement(table.sql_drop_index(name, strict)))(_.execute()) |
274 |
} |
|
63778 | 275 |
} |
65006 | 276 |
|
277 |
||
278 |
||
279 |
/** SQLite **/ |
|
280 |
||
281 |
object SQLite |
|
282 |
{ |
|
65021 | 283 |
// see https://www.sqlite.org/lang_datefunc.html |
284 |
val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x") |
|
285 |
||
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
286 |
lazy val init_jdbc: Unit = Class.forName("org.sqlite.JDBC") |
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
287 |
|
65006 | 288 |
def open_database(path: Path): Database = |
289 |
{ |
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
290 |
init_jdbc |
65006 | 291 |
val path0 = path.expand |
292 |
val s0 = File.platform_path(path0) |
|
293 |
val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0 |
|
294 |
val connection = DriverManager.getConnection("jdbc:sqlite:" + s1) |
|
65007 | 295 |
new Database(path0.toString, connection) |
65006 | 296 |
} |
297 |
||
65007 | 298 |
class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database |
65006 | 299 |
{ |
65007 | 300 |
override def toString: String = name |
65006 | 301 |
|
65019 | 302 |
def sql_type(T: SQL.Type.Value): String = SQL.sql_type_sqlite(T) |
65011 | 303 |
|
65021 | 304 |
def set_date(stmt: PreparedStatement, i: Int, date: Date): Unit = |
65598 | 305 |
if (date == null) set_string(stmt, i, null) |
306 |
else set_string(stmt, i, date_format(date)) |
|
307 |
||
65021 | 308 |
def date(rs: ResultSet, name: String): Date = |
309 |
date_format.parse(string(rs, name)) |
|
310 |
||
65006 | 311 |
def rebuild { using(statement("VACUUM"))(_.execute()) } |
312 |
} |
|
313 |
} |
|
314 |
||
315 |
||
316 |
||
317 |
/** PostgreSQL **/ |
|
318 |
||
319 |
object PostgreSQL |
|
320 |
{ |
|
321 |
val default_port = 5432 |
|
322 |
||
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
323 |
lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver") |
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
324 |
|
65006 | 325 |
def open_database( |
326 |
user: String, |
|
327 |
password: String, |
|
328 |
database: String = "", |
|
329 |
host: String = "", |
|
65594 | 330 |
port: Int = 0, |
65009 | 331 |
ssh: Option[SSH.Session] = None): Database = |
65006 | 332 |
{ |
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
333 |
init_jdbc |
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
334 |
|
65006 | 335 |
require(user != "") |
65009 | 336 |
|
337 |
val db_host = if (host != "") host else "localhost" |
|
65594 | 338 |
val db_port = if (port > 0 && port != default_port) ":" + port else "" |
65009 | 339 |
val db_name = "/" + (if (database != "") database else user) |
340 |
||
65010 | 341 |
val (url, name, port_forwarding) = |
65009 | 342 |
ssh match { |
65010 | 343 |
case None => |
344 |
val spec = db_host + db_port + db_name |
|
345 |
val url = "jdbc:postgresql://" + spec |
|
346 |
val name = user + "@" + spec |
|
347 |
(url, name, None) |
|
65009 | 348 |
case Some(ssh) => |
65594 | 349 |
val fw = |
350 |
ssh.port_forwarding(remote_host = db_host, |
|
351 |
remote_port = if (port > 0) port else default_port) |
|
65010 | 352 |
val url = "jdbc:postgresql://localhost:" + fw.local_port + db_name |
353 |
val name = user + "@" + fw + db_name + " via ssh " + ssh |
|
354 |
(url, name, Some(fw)) |
|
65009 | 355 |
} |
356 |
try { |
|
65010 | 357 |
val connection = DriverManager.getConnection(url, user, password) |
358 |
new Database(name, connection, port_forwarding) |
|
65009 | 359 |
} |
360 |
catch { case exn: Throwable => port_forwarding.foreach(_.close); throw exn } |
|
65006 | 361 |
} |
362 |
||
65009 | 363 |
class Database private[PostgreSQL]( |
364 |
name: String, val connection: Connection, port_forwarding: Option[SSH.Port_Forwarding]) |
|
365 |
extends SQL.Database |
|
65006 | 366 |
{ |
65010 | 367 |
override def toString: String = name |
65008 | 368 |
|
65019 | 369 |
def sql_type(T: SQL.Type.Value): String = SQL.sql_type_postgresql(T) |
65009 | 370 |
|
65021 | 371 |
// see https://jdbc.postgresql.org/documentation/head/8-date-time.html |
372 |
def set_date(stmt: PreparedStatement, i: Int, date: Date): Unit = |
|
65598 | 373 |
if (date == null) stmt.setObject(i, null) |
374 |
else stmt.setObject(i, OffsetDateTime.from(date.to_utc.rep)) |
|
375 |
||
65021 | 376 |
def date(rs: ResultSet, name: String): Date = |
377 |
Date.instant(rs.getObject(name, classOf[OffsetDateTime]).toInstant) |
|
378 |
||
65009 | 379 |
override def close() { super.close; port_forwarding.foreach(_.close) } |
65006 | 380 |
} |
381 |
} |