| author | wenzelm |
| Tue, 11 Apr 2023 10:45:04 +0200 | |
| changeset 77817 | a1bf8f706bc1 |
| parent 77681 | 1db732e6c3d2 |
| child 78151 | 2fdf3d8a94e6 |
| 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 |
||
|
69393
ed0824ef337e
static type for Library.using: avoid Java 11 warnings on "Illegal reflective access";
wenzelm
parents:
69327
diff
changeset
|
9 |
|
| 65021 | 10 |
import java.time.OffsetDateTime |
11 |
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet}
|
|
| 63779 | 12 |
|
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
13 |
import org.sqlite.jdbc4.JDBC4Connection |
| 77039 | 14 |
import org.postgresql.{PGConnection, PGNotification}
|
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
15 |
|
| 65740 | 16 |
import scala.collection.mutable |
17 |
||
| 63779 | 18 |
|
| 75393 | 19 |
object SQL {
|
| 65006 | 20 |
/** SQL language **/ |
21 |
||
| 65730 | 22 |
type Source = String |
23 |
||
24 |
||
| 63778 | 25 |
/* concrete syntax */ |
26 |
||
| 65321 | 27 |
def escape_char(c: Char): String = |
| 63778 | 28 |
c match {
|
29 |
case '\u0000' => "\\0" |
|
30 |
case '\'' => "\\'" |
|
31 |
case '\"' => "\\\"" |
|
32 |
case '\b' => "\\b" |
|
33 |
case '\n' => "\\n" |
|
34 |
case '\r' => "\\r" |
|
35 |
case '\t' => "\\t" |
|
36 |
case '\u001a' => "\\Z" |
|
37 |
case '\\' => "\\\\" |
|
38 |
case _ => c.toString |
|
39 |
} |
|
40 |
||
| 65730 | 41 |
def string(s: String): Source = |
| 71601 | 42 |
s.iterator.map(escape_char).mkString("'", "", "'")
|
| 63778 | 43 |
|
| 65730 | 44 |
def ident(s: String): Source = |
|
65677
7d25b8dbdbfa
proper quote (amending 546020a98a91): e.g. relevant for "ISABELLE_BUILD_OPTIONS";
wenzelm
parents:
65673
diff
changeset
|
45 |
Long_Name.implode(Long_Name.explode(s).map(a => quote(a.replace("\"", "\"\""))))
|
| 63779 | 46 |
|
| 65730 | 47 |
def enclose(s: Source): Source = "(" + s + ")"
|
48 |
def enclosure(ss: Iterable[Source]): Source = ss.mkString("(", ", ", ")")
|
|
| 63791 | 49 |
|
|
77381
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
50 |
def separate(sql: Source): Source = |
|
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
51 |
(if (sql.isEmpty || sql.startsWith(" ")) "" else " ") + sql
|
|
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
52 |
|
|
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
53 |
def select(columns: List[Column] = Nil, distinct: Boolean = false, sql: Source = ""): Source = |
| 65774 | 54 |
"SELECT " + (if (distinct) "DISTINCT " else "") + |
|
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
55 |
(if (columns.isEmpty) "*" else commas(columns.map(_.ident))) + " FROM " + sql |
|
65644
7ef438495a02
support for qualified names, which are not quoted (e.g. for SQLite);
wenzelm
parents:
65641
diff
changeset
|
56 |
|
| 65775 | 57 |
val join_outer: Source = " LEFT OUTER JOIN " |
58 |
val join_inner: Source = " INNER JOIN " |
|
| 65776 | 59 |
def join(outer: Boolean): Source = if (outer) join_outer else join_inner |
| 65775 | 60 |
|
| 77370 | 61 |
def infix(op: Source, args: Iterable[Source]): Source = {
|
62 |
val body = args.iterator.filter(_.nonEmpty).mkString(" " + op + " ")
|
|
63 |
if_proper(body, enclose(body)) |
|
64 |
} |
|
65 |
||
66 |
def AND(args: Iterable[Source]): Source = infix("AND", args)
|
|
67 |
def OR(args: Iterable[Source]): Source = infix("OR", args)
|
|
68 |
||
69 |
def and(args: Source*): Source = AND(args) |
|
70 |
def or(args: Source*): Source = OR(args) |
|
71 |
||
72 |
val TRUE: Source = "TRUE" |
|
73 |
val FALSE: Source = "FALSE" |
|
74 |
||
| 77375 | 75 |
def equal(sql: Source, s: String): Source = sql + " = " + string(s) |
76 |
||
77 |
def member(sql: Source, set: Iterable[String]): Source = |
|
| 77370 | 78 |
if (set.isEmpty) FALSE |
| 77375 | 79 |
else OR(set.iterator.map(equal(sql, _)).toList) |
| 65804 | 80 |
|
| 77370 | 81 |
def where(sql: Source): Source = if_proper(sql, " WHERE " + sql) |
82 |
||
83 |
||
| 65008 | 84 |
/* types */ |
85 |
||
| 75393 | 86 |
object Type extends Enumeration {
|
| 65011 | 87 |
val Boolean = Value("BOOLEAN")
|
| 65008 | 88 |
val Int = Value("INTEGER")
|
89 |
val Long = Value("BIGINT")
|
|
90 |
val Double = Value("DOUBLE PRECISION")
|
|
91 |
val String = Value("TEXT")
|
|
92 |
val Bytes = Value("BLOB")
|
|
| 65014 | 93 |
val Date = Value("TIMESTAMP WITH TIME ZONE")
|
| 65008 | 94 |
} |
95 |
||
| 65730 | 96 |
def sql_type_default(T: Type.Value): Source = T.toString |
| 65013 | 97 |
|
| 65730 | 98 |
def sql_type_sqlite(T: Type.Value): Source = |
| 65019 | 99 |
if (T == Type.Boolean) "INTEGER" |
100 |
else if (T == Type.Date) "TEXT" |
|
101 |
else sql_type_default(T) |
|
| 65013 | 102 |
|
| 65730 | 103 |
def sql_type_postgresql(T: Type.Value): Source = |
| 65019 | 104 |
if (T == Type.Bytes) "BYTEA" |
105 |
else sql_type_default(T) |
|
| 65008 | 106 |
|
107 |
||
| 63779 | 108 |
/* columns */ |
109 |
||
| 75393 | 110 |
object Column {
|
| 65280 | 111 |
def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 112 |
Column(name, Type.Boolean, strict, primary_key) |
| 65280 | 113 |
def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 114 |
Column(name, Type.Int, strict, primary_key) |
| 65280 | 115 |
def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 116 |
Column(name, Type.Long, strict, primary_key) |
| 65280 | 117 |
def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 118 |
Column(name, Type.Double, strict, primary_key) |
| 65280 | 119 |
def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 120 |
Column(name, Type.String, strict, primary_key) |
| 65280 | 121 |
def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 122 |
Column(name, Type.Bytes, strict, primary_key) |
| 65280 | 123 |
def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 124 |
Column(name, Type.Date, strict, primary_key) |
| 63779 | 125 |
} |
126 |
||
| 65018 | 127 |
sealed case class Column( |
| 75393 | 128 |
name: String, |
129 |
T: Type.Value, |
|
130 |
strict: Boolean = false, |
|
131 |
primary_key: Boolean = false, |
|
132 |
expr: SQL.Source = "" |
|
133 |
) {
|
|
| 66857 | 134 |
def make_primary_key: Column = copy(primary_key = true) |
135 |
||
| 65691 | 136 |
def apply(table: Table): Column = |
137 |
Column(Long_Name.qualify(table.name, name), T, strict = strict, primary_key = primary_key) |
|
|
65644
7ef438495a02
support for qualified names, which are not quoted (e.g. for SQLite);
wenzelm
parents:
65641
diff
changeset
|
138 |
|
| 65780 | 139 |
def ident: Source = |
140 |
if (expr == "") SQL.ident(name) |
|
141 |
else enclose(expr) + " AS " + SQL.ident(name) |
|
| 65695 | 142 |
|
| 65730 | 143 |
def decl(sql_type: Type.Value => Source): Source = |
| 65695 | 144 |
ident + " " + sql_type(T) + (if (strict || primary_key) " NOT NULL" else "") |
| 63781 | 145 |
|
| 66856 | 146 |
def defined: String = ident + " IS NOT NULL" |
147 |
def undefined: String = ident + " IS NULL" |
|
148 |
||
| 77375 | 149 |
def equal(s: String): Source = SQL.equal(ident, s) |
150 |
def member(set: Iterable[String]): Source = SQL.member(ident, set) |
|
151 |
||
152 |
def where_equal(s: String): Source = SQL.where(equal(s)) |
|
153 |
def where_member(set: Iterable[String]): Source = SQL.where(member(set)) |
|
| 65593 | 154 |
|
| 65730 | 155 |
override def toString: Source = ident |
| 63779 | 156 |
} |
157 |
||
| 76870 | 158 |
def order_by(columns: List[Column], descending: Boolean = false): Source = |
159 |
" ORDER BY " + columns.mkString(", ") + (if (descending) " DESC" else "")
|
|
160 |
||
| 63780 | 161 |
|
162 |
/* tables */ |
|
163 |
||
| 75393 | 164 |
sealed case class Table(name: String, columns: List[Column], body: Source = "") {
|
| 63781 | 165 |
Library.duplicates(columns.map(_.name)) match {
|
166 |
case Nil => |
|
167 |
case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name))
|
|
168 |
} |
|
169 |
||
| 65730 | 170 |
def ident: Source = SQL.ident(name) |
| 65691 | 171 |
|
| 65730 | 172 |
def query: Source = |
| 65696 | 173 |
if (body == "") error("Missing SQL body for table " + quote(name))
|
174 |
else SQL.enclose(body) |
|
| 65649 | 175 |
|
| 65778 | 176 |
def query_named: Source = query + " AS " + SQL.ident(name) |
| 65702 | 177 |
|
| 75966 | 178 |
def create(strict: Boolean, sql_type: Type.Value => Source): Source = {
|
| 65325 | 179 |
val primary_key = |
180 |
columns.filter(_.primary_key).map(_.name) match {
|
|
181 |
case Nil => Nil |
|
182 |
case keys => List("PRIMARY KEY " + enclosure(keys))
|
|
183 |
} |
|
| 65701 | 184 |
"CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") + |
185 |
ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key) |
|
| 63781 | 186 |
} |
187 |
||
| 65698 | 188 |
def create_index(index_name: String, index_columns: List[Column], |
| 65730 | 189 |
strict: Boolean = false, unique: Boolean = false): Source = |
| 63791 | 190 |
"CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " + |
| 65695 | 191 |
(if (strict) "" else "IF NOT EXISTS ") + SQL.ident(index_name) + " ON " + |
192 |
ident + " " + enclosure(index_columns.map(_.name)) |
|
| 63791 | 193 |
|
| 77365 | 194 |
def insert_cmd(cmd: Source = "INSERT", sql: Source = ""): Source = |
| 77377 | 195 |
cmd + " INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) + SQL.separate(sql) |
| 63791 | 196 |
|
| 77365 | 197 |
def insert(sql: Source = ""): Source = insert_cmd(sql = sql) |
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
198 |
|
| 65730 | 199 |
def delete(sql: Source = ""): Source = |
| 77377 | 200 |
"DELETE FROM " + ident + SQL.separate(sql) |
| 65319 | 201 |
|
| 77537 | 202 |
def update(update_columns: List[Column] = Nil, sql: Source = ""): Source = |
203 |
"UPDATE " + ident + " SET " + commas(update_columns.map(c => c.ident + " = ?")) + |
|
204 |
SQL.separate(sql) |
|
205 |
||
| 65774 | 206 |
def select( |
|
77381
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
207 |
select_columns: List[Column] = Nil, |
|
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
208 |
distinct: Boolean = false, |
|
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
209 |
sql: Source = "" |
|
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
210 |
): Source = SQL.select(select_columns, distinct = distinct, sql = ident + SQL.separate(sql)) |
| 63790 | 211 |
|
| 65730 | 212 |
override def toString: Source = ident |
| 63780 | 213 |
} |
| 63790 | 214 |
|
215 |
||
| 77596 | 216 |
/* table groups */ |
217 |
||
218 |
object Tables {
|
|
219 |
def list(list: List[Table]): Tables = new Tables(list) |
|
|
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
220 |
val empty: Tables = list(Nil) |
| 77596 | 221 |
def apply(args: Table*): Tables = list(args.toList) |
222 |
} |
|
223 |
||
224 |
final class Tables private(val list: List[Table]) extends Iterable[Table] {
|
|
225 |
override def toString: String = list.mkString("SQL.Tables(", ", ", ")")
|
|
226 |
||
| 77665 | 227 |
def ::: (other: Tables): Tables = new Tables(other.list ::: list) |
228 |
||
| 77596 | 229 |
def iterator: Iterator[Table] = list.iterator |
230 |
||
231 |
// requires transaction |
|
232 |
def create_lock(db: Database): Unit = {
|
|
233 |
foreach(db.create_table(_)) |
|
234 |
lock(db) |
|
235 |
} |
|
236 |
||
237 |
// requires transaction |
|
238 |
def lock(db: Database): Unit = {
|
|
239 |
val sql = db.lock_tables(list) |
|
240 |
if (sql.nonEmpty) db.execute_statement(sql) |
|
241 |
} |
|
242 |
} |
|
243 |
||
244 |
||
| 65012 | 245 |
|
246 |
/** SQL database operations **/ |
|
247 |
||
| 65740 | 248 |
/* statements */ |
249 |
||
| 75393 | 250 |
class Statement private[SQL](val db: Database, val rep: PreparedStatement) extends AutoCloseable {
|
| 65740 | 251 |
stmt => |
252 |
||
| 75393 | 253 |
object bool {
|
| 73340 | 254 |
def update(i: Int, x: Boolean): Unit = rep.setBoolean(i, x) |
| 75393 | 255 |
def update(i: Int, x: Option[Boolean]): Unit = {
|
| 65748 | 256 |
if (x.isDefined) update(i, x.get) |
257 |
else rep.setNull(i, java.sql.Types.BOOLEAN) |
|
258 |
} |
|
| 65740 | 259 |
} |
| 75393 | 260 |
object int {
|
| 73340 | 261 |
def update(i: Int, x: Int): Unit = rep.setInt(i, x) |
| 75393 | 262 |
def update(i: Int, x: Option[Int]): Unit = {
|
| 65748 | 263 |
if (x.isDefined) update(i, x.get) |
264 |
else rep.setNull(i, java.sql.Types.INTEGER) |
|
265 |
} |
|
| 65740 | 266 |
} |
| 75393 | 267 |
object long {
|
| 73340 | 268 |
def update(i: Int, x: Long): Unit = rep.setLong(i, x) |
| 75393 | 269 |
def update(i: Int, x: Option[Long]): Unit = {
|
| 65748 | 270 |
if (x.isDefined) update(i, x.get) |
271 |
else rep.setNull(i, java.sql.Types.BIGINT) |
|
272 |
} |
|
| 65740 | 273 |
} |
| 75393 | 274 |
object double {
|
| 73340 | 275 |
def update(i: Int, x: Double): Unit = rep.setDouble(i, x) |
| 75393 | 276 |
def update(i: Int, x: Option[Double]): Unit = {
|
| 65748 | 277 |
if (x.isDefined) update(i, x.get) |
278 |
else rep.setNull(i, java.sql.Types.DOUBLE) |
|
279 |
} |
|
280 |
} |
|
| 75393 | 281 |
object string {
|
| 73340 | 282 |
def update(i: Int, x: String): Unit = rep.setString(i, x) |
| 65748 | 283 |
def update(i: Int, x: Option[String]): Unit = update(i, x.orNull) |
| 65740 | 284 |
} |
| 75393 | 285 |
object bytes {
|
286 |
def update(i: Int, bytes: Bytes): Unit = {
|
|
| 65748 | 287 |
if (bytes == null) rep.setBytes(i, null) |
288 |
else rep.setBinaryStream(i, bytes.stream(), bytes.length) |
|
289 |
} |
|
290 |
def update(i: Int, bytes: Option[Bytes]): Unit = update(i, bytes.orNull) |
|
| 65740 | 291 |
} |
| 75393 | 292 |
object date {
|
| 65748 | 293 |
def update(i: Int, date: Date): Unit = db.update_date(stmt, i, date) |
294 |
def update(i: Int, date: Option[Date]): Unit = update(i, date.orNull) |
|
295 |
} |
|
| 65740 | 296 |
|
297 |
def execute(): Boolean = rep.execute() |
|
298 |
def execute_query(): Result = new Result(this, rep.executeQuery()) |
|
299 |
||
| 73367 | 300 |
def close(): Unit = rep.close() |
| 65740 | 301 |
} |
302 |
||
303 |
||
| 63790 | 304 |
/* results */ |
305 |
||
| 75393 | 306 |
class Result private[SQL](val stmt: Statement, val rep: ResultSet) {
|
| 65740 | 307 |
res => |
308 |
||
309 |
def next(): Boolean = rep.next() |
|
310 |
||
| 75393 | 311 |
def iterator[A](get: Result => A): Iterator[A] = new Iterator[A] {
|
| 65740 | 312 |
private var _next: Boolean = res.next() |
313 |
def hasNext: Boolean = _next |
|
| 73337 | 314 |
def next(): A = { val x = get(res); _next = res.next(); x }
|
| 65740 | 315 |
} |
316 |
||
317 |
def bool(column: Column): Boolean = rep.getBoolean(column.name) |
|
318 |
def int(column: Column): Int = rep.getInt(column.name) |
|
319 |
def long(column: Column): Long = rep.getLong(column.name) |
|
320 |
def double(column: Column): Double = rep.getDouble(column.name) |
|
| 75393 | 321 |
def string(column: Column): String = {
|
| 65740 | 322 |
val s = rep.getString(column.name) |
323 |
if (s == null) "" else s |
|
324 |
} |
|
| 75393 | 325 |
def bytes(column: Column): Bytes = {
|
| 65740 | 326 |
val bs = rep.getBytes(column.name) |
327 |
if (bs == null) Bytes.empty else Bytes(bs) |
|
328 |
} |
|
329 |
def date(column: Column): Date = stmt.db.date(res, column) |
|
330 |
||
| 71601 | 331 |
def timing(c1: Column, c2: Column, c3: Column): Timing = |
| 65741 | 332 |
Timing(Time.ms(long(c1)), Time.ms(long(c2)), Time.ms(long(c3))) |
333 |
||
| 75393 | 334 |
def get[A](column: Column, f: Column => A): Option[A] = {
|
| 65740 | 335 |
val x = f(column) |
| 77598 | 336 |
if (rep.wasNull || x == null) None else Some(x) |
| 65740 | 337 |
} |
| 71601 | 338 |
def get_bool(column: Column): Option[Boolean] = get(column, bool) |
339 |
def get_int(column: Column): Option[Int] = get(column, int) |
|
340 |
def get_long(column: Column): Option[Long] = get(column, long) |
|
341 |
def get_double(column: Column): Option[Double] = get(column, double) |
|
342 |
def get_string(column: Column): Option[String] = get(column, string) |
|
343 |
def get_bytes(column: Column): Option[Bytes] = get(column, bytes) |
|
344 |
def get_date(column: Column): Option[Date] = get(column, date) |
|
| 63790 | 345 |
} |
| 65006 | 346 |
|
| 65740 | 347 |
|
348 |
/* database */ |
|
349 |
||
| 75393 | 350 |
trait Database extends AutoCloseable {
|
| 65740 | 351 |
db => |
352 |
||
| 77542 | 353 |
def is_sqlite: Boolean = isInstanceOf[SQLite.Database] |
354 |
def is_postgresql: Boolean = isInstanceOf[PostgreSQL.Database] |
|
|
76363
f7174238b5e3
no compression for database server: let PostgreSQL/TOAST do the job;
wenzelm
parents:
76122
diff
changeset
|
355 |
|
|
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
356 |
def vacuum(tables: SQL.Tables = SQL.Tables.empty): Unit |
| 77348 | 357 |
|
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
358 |
def now(): Date |
|
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
359 |
|
| 65740 | 360 |
|
| 65008 | 361 |
/* types */ |
362 |
||
| 65730 | 363 |
def sql_type(T: Type.Value): Source |
| 65008 | 364 |
|
365 |
||
| 65006 | 366 |
/* connection */ |
367 |
||
368 |
def connection: Connection |
|
369 |
||
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
370 |
def sqlite_connection: Option[JDBC4Connection] = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
371 |
connection match { case conn: JDBC4Connection => Some(conn) case _ => None }
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
372 |
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
373 |
def postgresql_connection: Option[PGConnection] = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
374 |
connection match { case conn: PGConnection => Some(conn) case _ => None }
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
375 |
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
376 |
def the_sqlite_connection: JDBC4Connection = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
377 |
sqlite_connection getOrElse |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
378 |
error("SQLite connection expected, but found " + connection.getClass.getName)
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
379 |
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
380 |
def the_postgresql_connection: PGConnection = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
381 |
postgresql_connection getOrElse |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
382 |
error("PostgreSQL connection expected, but found " + connection.getClass.getName)
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
383 |
|
| 73367 | 384 |
def close(): Unit = connection.close() |
| 65006 | 385 |
|
| 75393 | 386 |
def transaction[A](body: => A): A = {
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
387 |
val auto_commit = connection.getAutoCommit() |
| 65006 | 388 |
try {
|
389 |
connection.setAutoCommit(false) |
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
390 |
val savepoint = connection.setSavepoint() |
| 65022 | 391 |
try {
|
392 |
val result = body |
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
393 |
connection.commit() |
| 65022 | 394 |
result |
395 |
} |
|
396 |
catch { case exn: Throwable => connection.rollback(savepoint); throw exn }
|
|
| 65006 | 397 |
} |
398 |
finally { connection.setAutoCommit(auto_commit) }
|
|
399 |
} |
|
400 |
||
| 77596 | 401 |
def transaction_lock[A](tables: Tables)(body: => A): A = |
402 |
transaction { tables.lock(db); body }
|
|
403 |
||
404 |
def lock_tables(tables: List[Table]): Source = "" // PostgreSQL only |
|
|
77590
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
405 |
|
| 65006 | 406 |
|
| 65740 | 407 |
/* statements and results */ |
408 |
||
409 |
def statement(sql: Source): Statement = |
|
410 |
new Statement(db, connection.prepareStatement(sql)) |
|
| 65006 | 411 |
|
| 65740 | 412 |
def using_statement[A](sql: Source)(f: Statement => A): A = |
413 |
using(statement(sql))(f) |
|
| 65006 | 414 |
|
| 77541 | 415 |
def execute_statement(sql: Source, body: Statement => Unit = _ => ()): Unit = |
416 |
using_statement(sql) { stmt => body(stmt); stmt.execute() }
|
|
| 77540 | 417 |
|
| 77552 | 418 |
def execute_query_statement[A, B]( |
419 |
sql: Source, |
|
420 |
make_result: Iterator[A] => B, |
|
421 |
get: Result => A |
|
422 |
): B = using_statement(sql)(stmt => make_result(stmt.execute_query().iterator(get))) |
|
423 |
||
424 |
def execute_query_statementO[A](sql: Source, get: Result => A): Option[A] = |
|
425 |
execute_query_statement[A, Option[A]](sql, _.nextOption, get) |
|
426 |
||
427 |
def execute_query_statementB(sql: Source): Boolean = |
|
428 |
using_statement(sql)(stmt => stmt.execute_query().next()) |
|
429 |
||
| 65748 | 430 |
def update_date(stmt: Statement, i: Int, date: Date): Unit |
| 65740 | 431 |
def date(res: Result, column: Column): Date |
| 65006 | 432 |
|
| 65730 | 433 |
def insert_permissive(table: Table, sql: Source = ""): Source |
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
434 |
|
| 65006 | 435 |
|
| 65669 | 436 |
/* tables and views */ |
| 65006 | 437 |
|
| 75393 | 438 |
def tables: List[String] = {
|
| 65740 | 439 |
val result = new mutable.ListBuffer[String] |
440 |
val rs = connection.getMetaData.getTables(null, null, "%", null) |
|
441 |
while (rs.next) { result += rs.getString(3) }
|
|
442 |
result.toList |
|
443 |
} |
|
| 65006 | 444 |
|
|
77681
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
445 |
def create_table(table: Table, strict: Boolean = false, sql: Source = ""): Unit = {
|
| 77540 | 446 |
execute_statement(table.create(strict, sql_type) + SQL.separate(sql)) |
|
77681
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
447 |
if (is_postgresql) {
|
|
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
448 |
for (column <- table.columns if column.T == SQL.Type.Bytes) {
|
|
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
449 |
execute_statement( |
|
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
450 |
"ALTER TABLE " + table + " ALTER COLUMN " + column + " SET STORAGE EXTERNAL") |
|
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
451 |
} |
|
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
452 |
} |
|
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
453 |
} |
| 65006 | 454 |
|
| 65018 | 455 |
def create_index(table: Table, name: String, columns: List[Column], |
| 65280 | 456 |
strict: Boolean = false, unique: Boolean = false): Unit = |
| 77540 | 457 |
execute_statement(table.create_index(name, columns, strict, unique)) |
| 65006 | 458 |
|
| 75393 | 459 |
def create_view(table: Table, strict: Boolean = false): Unit = {
|
| 65691 | 460 |
if (strict || !tables.contains(table.name)) {
|
| 77540 | 461 |
execute_statement("CREATE VIEW " + table + " AS " + { table.query; table.body })
|
| 65690 | 462 |
} |
| 65691 | 463 |
} |
| 65006 | 464 |
} |
| 63778 | 465 |
} |
| 65006 | 466 |
|
467 |
||
468 |
||
469 |
/** SQLite **/ |
|
470 |
||
| 75393 | 471 |
object SQLite {
|
| 65021 | 472 |
// see https://www.sqlite.org/lang_datefunc.html |
473 |
val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x")
|
|
474 |
||
| 75393 | 475 |
lazy val init_jdbc: Unit = {
|
|
65890
1b004f5974af
refer to already extracted library files, to avoid tmp files produced by SQLiteJDBCLoader, which tend to remain after JVM crash;
wenzelm
parents:
65804
diff
changeset
|
476 |
val lib_path = Path.explode("$ISABELLE_SQLITE_HOME/" + Platform.jvm_platform)
|
| 76529 | 477 |
val lib_name = File.get_file(lib_path).file_name |
478 |
||
|
65890
1b004f5974af
refer to already extracted library files, to avoid tmp files produced by SQLiteJDBCLoader, which tend to remain after JVM crash;
wenzelm
parents:
65804
diff
changeset
|
479 |
System.setProperty("org.sqlite.lib.path", File.platform_path(lib_path))
|
|
1b004f5974af
refer to already extracted library files, to avoid tmp files produced by SQLiteJDBCLoader, which tend to remain after JVM crash;
wenzelm
parents:
65804
diff
changeset
|
480 |
System.setProperty("org.sqlite.lib.name", lib_name)
|
|
1b004f5974af
refer to already extracted library files, to avoid tmp files produced by SQLiteJDBCLoader, which tend to remain after JVM crash;
wenzelm
parents:
65804
diff
changeset
|
481 |
|
|
1b004f5974af
refer to already extracted library files, to avoid tmp files produced by SQLiteJDBCLoader, which tend to remain after JVM crash;
wenzelm
parents:
65804
diff
changeset
|
482 |
Class.forName("org.sqlite.JDBC")
|
|
1b004f5974af
refer to already extracted library files, to avoid tmp files produced by SQLiteJDBCLoader, which tend to remain after JVM crash;
wenzelm
parents:
65804
diff
changeset
|
483 |
} |
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
484 |
|
| 75393 | 485 |
def open_database(path: Path): Database = {
|
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
486 |
init_jdbc |
| 65006 | 487 |
val path0 = path.expand |
488 |
val s0 = File.platform_path(path0) |
|
489 |
val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
|
|
490 |
val connection = DriverManager.getConnection("jdbc:sqlite:" + s1)
|
|
| 65007 | 491 |
new Database(path0.toString, connection) |
| 65006 | 492 |
} |
493 |
||
| 75393 | 494 |
class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database {
|
| 65007 | 495 |
override def toString: String = name |
|
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
496 |
|
|
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
497 |
override def vacuum(tables: SQL.Tables = SQL.Tables.empty): Unit = |
|
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
498 |
execute_statement("VACUUM") // always FULL
|
| 65006 | 499 |
|
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
500 |
override def now(): Date = Date.now() |
|
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
501 |
|
| 65730 | 502 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_sqlite(T) |
| 65011 | 503 |
|
| 65748 | 504 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
505 |
if (date == null) stmt.string(i) = (null: String) |
|
506 |
else stmt.string(i) = date_format(date) |
|
| 65598 | 507 |
|
| 65740 | 508 |
def date(res: SQL.Result, column: SQL.Column): Date = |
| 77598 | 509 |
proper_string(res.string(column)) match {
|
510 |
case None => null |
|
511 |
case Some(s) => date_format.parse(s) |
|
512 |
} |
|
| 65021 | 513 |
|
| 65730 | 514 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
| 77365 | 515 |
table.insert_cmd(cmd = "INSERT OR IGNORE", sql = sql) |
| 65006 | 516 |
} |
517 |
} |
|
518 |
||
519 |
||
520 |
||
521 |
/** PostgreSQL **/ |
|
522 |
||
| 75393 | 523 |
object PostgreSQL {
|
|
75967
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
524 |
type Source = SQL.Source |
|
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
525 |
|
| 65006 | 526 |
val default_port = 5432 |
527 |
||
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
528 |
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
|
529 |
|
| 65006 | 530 |
def open_database( |
531 |
user: String, |
|
532 |
password: String, |
|
533 |
database: String = "", |
|
534 |
host: String = "", |
|
| 65594 | 535 |
port: Int = 0, |
|
65636
df804cdba5f9
ssh_close for proper termination after use of database;
wenzelm
parents:
65620
diff
changeset
|
536 |
ssh: Option[SSH.Session] = None, |
| 77591 | 537 |
ssh_close: Boolean = false, |
538 |
// see https://www.postgresql.org/docs/current/transaction-iso.html |
|
539 |
transaction_isolation: Int = Connection.TRANSACTION_SERIALIZABLE |
|
| 75393 | 540 |
): Database = {
|
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
541 |
init_jdbc |
|
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
542 |
|
| 65641 | 543 |
if (user == "") error("Undefined database user")
|
| 65009 | 544 |
|
| 65717 | 545 |
val db_host = proper_string(host) getOrElse "localhost" |
| 65594 | 546 |
val db_port = if (port > 0 && port != default_port) ":" + port else "" |
| 65717 | 547 |
val db_name = "/" + (proper_string(database) getOrElse user) |
| 65009 | 548 |
|
| 65010 | 549 |
val (url, name, port_forwarding) = |
| 65009 | 550 |
ssh match {
|
| 65010 | 551 |
case None => |
552 |
val spec = db_host + db_port + db_name |
|
553 |
val url = "jdbc:postgresql://" + spec |
|
554 |
val name = user + "@" + spec |
|
555 |
(url, name, None) |
|
| 65009 | 556 |
case Some(ssh) => |
| 65594 | 557 |
val fw = |
558 |
ssh.port_forwarding(remote_host = db_host, |
|
|
65636
df804cdba5f9
ssh_close for proper termination after use of database;
wenzelm
parents:
65620
diff
changeset
|
559 |
remote_port = if (port > 0) port else default_port, |
|
df804cdba5f9
ssh_close for proper termination after use of database;
wenzelm
parents:
65620
diff
changeset
|
560 |
ssh_close = ssh_close) |
|
76122
b8f26c20d3b1
ssh client via regular OpenSSH tools, with authentic use of .ssh/config (notably proxy configuration);
wenzelm
parents:
75967
diff
changeset
|
561 |
val url = "jdbc:postgresql://localhost:" + fw.port + db_name |
| 65010 | 562 |
val name = user + "@" + fw + db_name + " via ssh " + ssh |
563 |
(url, name, Some(fw)) |
|
| 65009 | 564 |
} |
565 |
try {
|
|
| 65010 | 566 |
val connection = DriverManager.getConnection(url, user, password) |
| 77591 | 567 |
connection.setTransactionIsolation(transaction_isolation) |
| 65010 | 568 |
new Database(name, connection, port_forwarding) |
| 65009 | 569 |
} |
| 73367 | 570 |
catch { case exn: Throwable => port_forwarding.foreach(_.close()); throw exn }
|
| 65006 | 571 |
} |
572 |
||
| 65009 | 573 |
class Database private[PostgreSQL]( |
| 75393 | 574 |
name: String, |
575 |
val connection: Connection, |
|
576 |
port_forwarding: Option[SSH.Port_Forwarding] |
|
577 |
) extends SQL.Database {
|
|
| 65010 | 578 |
override def toString: String = name |
| 65008 | 579 |
|
|
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
580 |
override def vacuum(tables: SQL.Tables = SQL.Tables.empty): Unit = |
|
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
581 |
execute_statement("VACUUM" + if_proper(tables.list, " " + commas(tables.list.map(_.ident))))
|
|
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
582 |
|
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
583 |
override def now(): Date = {
|
|
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
584 |
val now = SQL.Column.date("now")
|
| 77552 | 585 |
execute_query_statementO[Date]("SELECT NOW() as " + now.ident, res => res.date(now))
|
586 |
.getOrElse(error("Failed to get current date/time from database server " + toString))
|
|
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
587 |
} |
|
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
588 |
|
| 65730 | 589 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_postgresql(T) |
| 65009 | 590 |
|
| 65021 | 591 |
// see https://jdbc.postgresql.org/documentation/head/8-date-time.html |
| 65748 | 592 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
| 65740 | 593 |
if (date == null) stmt.rep.setObject(i, null) |
| 69980 | 594 |
else stmt.rep.setObject(i, OffsetDateTime.from(date.to(Date.timezone_utc).rep)) |
| 65598 | 595 |
|
| 75393 | 596 |
def date(res: SQL.Result, column: SQL.Column): Date = {
|
| 65740 | 597 |
val obj = res.rep.getObject(column.name, classOf[OffsetDateTime]) |
| 65704 | 598 |
if (obj == null) null else Date.instant(obj.toInstant) |
599 |
} |
|
| 65021 | 600 |
|
| 65730 | 601 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
| 77377 | 602 |
table.insert_cmd(sql = if_proper(sql, sql + " ") + "ON CONFLICT DO NOTHING") |
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
603 |
|
| 77039 | 604 |
|
|
77590
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
605 |
/* explicit locking: only applicable to PostgreSQL within transaction context */ |
|
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
606 |
// see https://www.postgresql.org/docs/current/sql-lock.html |
|
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
607 |
// see https://www.postgresql.org/docs/current/explicit-locking.html |
|
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
608 |
|
| 77596 | 609 |
override def lock_tables(tables: List[SQL.Table]): PostgreSQL.Source = |
610 |
"LOCK TABLE " + tables.mkString(", ") + " IN ACCESS EXCLUSIVE MODE"
|
|
|
77590
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
611 |
|
|
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
612 |
|
| 77039 | 613 |
/* notifications: IPC via database server */ |
614 |
// see https://www.postgresql.org/docs/current/sql-notify.html |
|
615 |
||
616 |
def listen(name: String): Unit = |
|
| 77541 | 617 |
execute_statement("LISTEN " + SQL.ident(name))
|
| 77039 | 618 |
|
619 |
def unlisten(name: String = "*"): Unit = |
|
| 77541 | 620 |
execute_statement("UNLISTEN " + (if (name == "*") name else SQL.ident(name)))
|
| 77039 | 621 |
|
622 |
def notify(name: String, payload: String = ""): Unit = |
|
| 77543 | 623 |
execute_statement("NOTIFY " + SQL.ident(name) + if_proper(payload, ", " + SQL.string(payload)))
|
| 77039 | 624 |
|
625 |
def get_notifications(): List[PGNotification] = |
|
626 |
the_postgresql_connection.getNotifications() match {
|
|
627 |
case null => Nil |
|
628 |
case array => array.toList |
|
629 |
} |
|
630 |
||
631 |
||
| 73367 | 632 |
override def close(): Unit = { super.close(); port_forwarding.foreach(_.close()) }
|
| 65006 | 633 |
} |
634 |
} |