author | wenzelm |
Sat, 19 Aug 2023 22:57:06 +0200 | |
changeset 78540 | a6d079e0575d |
parent 78538 | 56e8458ba262 |
child 78544 | 3be0437759cf |
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. |
78351 | 5 |
|
6 |
See https://docs.oracle.com/en/java/javase/17/docs/api/java.sql/java/sql/Connection.html |
|
63778 | 7 |
*/ |
8 |
||
9 |
package isabelle |
|
10 |
||
69393
ed0824ef337e
static type for Library.using: avoid Java 11 warnings on "Illegal reflective access";
wenzelm
parents:
69327
diff
changeset
|
11 |
|
65021 | 12 |
import java.time.OffsetDateTime |
78538
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
13 |
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet, SQLException} |
63779 | 14 |
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
15 |
import org.sqlite.jdbc4.JDBC4Connection |
77039 | 16 |
import org.postgresql.{PGConnection, PGNotification} |
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
17 |
|
65740 | 18 |
import scala.collection.mutable |
19 |
||
63779 | 20 |
|
75393 | 21 |
object SQL { |
65006 | 22 |
/** SQL language **/ |
23 |
||
65730 | 24 |
type Source = String |
25 |
||
26 |
||
63778 | 27 |
/* concrete syntax */ |
28 |
||
65321 | 29 |
def escape_char(c: Char): String = |
63778 | 30 |
c match { |
31 |
case '\u0000' => "\\0" |
|
32 |
case '\'' => "\\'" |
|
33 |
case '\"' => "\\\"" |
|
34 |
case '\b' => "\\b" |
|
35 |
case '\n' => "\\n" |
|
36 |
case '\r' => "\\r" |
|
37 |
case '\t' => "\\t" |
|
38 |
case '\u001a' => "\\Z" |
|
39 |
case '\\' => "\\\\" |
|
40 |
case _ => c.toString |
|
41 |
} |
|
42 |
||
65730 | 43 |
def string(s: String): Source = |
71601 | 44 |
s.iterator.map(escape_char).mkString("'", "", "'") |
63778 | 45 |
|
65730 | 46 |
def ident(s: String): Source = |
65677
7d25b8dbdbfa
proper quote (amending 546020a98a91): e.g. relevant for "ISABELLE_BUILD_OPTIONS";
wenzelm
parents:
65673
diff
changeset
|
47 |
Long_Name.implode(Long_Name.explode(s).map(a => quote(a.replace("\"", "\"\"")))) |
63779 | 48 |
|
65730 | 49 |
def enclose(s: Source): Source = "(" + s + ")" |
50 |
def enclosure(ss: Iterable[Source]): Source = ss.mkString("(", ", ", ")") |
|
63791 | 51 |
|
77381
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
52 |
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
|
53 |
(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
|
54 |
|
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
55 |
def select(columns: List[Column] = Nil, distinct: Boolean = false, sql: Source = ""): Source = |
65774 | 56 |
"SELECT " + (if (distinct) "DISTINCT " else "") + |
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
57 |
(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
|
58 |
|
65775 | 59 |
val join_outer: Source = " LEFT OUTER JOIN " |
60 |
val join_inner: Source = " INNER JOIN " |
|
65776 | 61 |
def join(outer: Boolean): Source = if (outer) join_outer else join_inner |
65775 | 62 |
|
77370 | 63 |
def infix(op: Source, args: Iterable[Source]): Source = { |
64 |
val body = args.iterator.filter(_.nonEmpty).mkString(" " + op + " ") |
|
65 |
if_proper(body, enclose(body)) |
|
66 |
} |
|
67 |
||
68 |
def AND(args: Iterable[Source]): Source = infix("AND", args) |
|
69 |
def OR(args: Iterable[Source]): Source = infix("OR", args) |
|
70 |
||
71 |
def and(args: Source*): Source = AND(args) |
|
72 |
def or(args: Source*): Source = OR(args) |
|
73 |
||
74 |
val TRUE: Source = "TRUE" |
|
75 |
val FALSE: Source = "FALSE" |
|
76 |
||
78152 | 77 |
def equal(sql: Source, x: Int): Source = sql + " = " + x |
78 |
def equal(sql: Source, x: Long): Source = sql + " = " + x |
|
79 |
def equal(sql: Source, x: String): Source = sql + " = " + string(x) |
|
77375 | 80 |
|
81 |
def member(sql: Source, set: Iterable[String]): Source = |
|
77370 | 82 |
if (set.isEmpty) FALSE |
77375 | 83 |
else OR(set.iterator.map(equal(sql, _)).toList) |
65804 | 84 |
|
77370 | 85 |
def where(sql: Source): Source = if_proper(sql, " WHERE " + sql) |
78153 | 86 |
def where_and(args: Source*): Source = where(and(args:_*)) |
87 |
def where_or(args: Source*): Source = where(or(args:_*)) |
|
77370 | 88 |
|
89 |
||
65008 | 90 |
/* types */ |
91 |
||
75393 | 92 |
object Type extends Enumeration { |
65011 | 93 |
val Boolean = Value("BOOLEAN") |
65008 | 94 |
val Int = Value("INTEGER") |
95 |
val Long = Value("BIGINT") |
|
96 |
val Double = Value("DOUBLE PRECISION") |
|
97 |
val String = Value("TEXT") |
|
98 |
val Bytes = Value("BLOB") |
|
65014 | 99 |
val Date = Value("TIMESTAMP WITH TIME ZONE") |
65008 | 100 |
} |
101 |
||
65730 | 102 |
def sql_type_default(T: Type.Value): Source = T.toString |
65013 | 103 |
|
65730 | 104 |
def sql_type_sqlite(T: Type.Value): Source = |
65019 | 105 |
if (T == Type.Boolean) "INTEGER" |
106 |
else if (T == Type.Date) "TEXT" |
|
107 |
else sql_type_default(T) |
|
65013 | 108 |
|
65730 | 109 |
def sql_type_postgresql(T: Type.Value): Source = |
65019 | 110 |
if (T == Type.Bytes) "BYTEA" |
111 |
else sql_type_default(T) |
|
65008 | 112 |
|
113 |
||
63779 | 114 |
/* columns */ |
115 |
||
75393 | 116 |
object Column { |
65280 | 117 |
def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 118 |
Column(name, Type.Boolean, strict, primary_key) |
65280 | 119 |
def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 120 |
Column(name, Type.Int, strict, primary_key) |
65280 | 121 |
def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 122 |
Column(name, Type.Long, strict, primary_key) |
65280 | 123 |
def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 124 |
Column(name, Type.Double, strict, primary_key) |
65280 | 125 |
def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 126 |
Column(name, Type.String, strict, primary_key) |
65280 | 127 |
def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 128 |
Column(name, Type.Bytes, strict, primary_key) |
65280 | 129 |
def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
65018 | 130 |
Column(name, Type.Date, strict, primary_key) |
63779 | 131 |
} |
132 |
||
65018 | 133 |
sealed case class Column( |
75393 | 134 |
name: String, |
135 |
T: Type.Value, |
|
136 |
strict: Boolean = false, |
|
137 |
primary_key: Boolean = false, |
|
138 |
expr: SQL.Source = "" |
|
139 |
) { |
|
66857 | 140 |
def make_primary_key: Column = copy(primary_key = true) |
141 |
||
65691 | 142 |
def apply(table: Table): Column = |
143 |
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
|
144 |
|
65780 | 145 |
def ident: Source = |
146 |
if (expr == "") SQL.ident(name) |
|
147 |
else enclose(expr) + " AS " + SQL.ident(name) |
|
65695 | 148 |
|
65730 | 149 |
def decl(sql_type: Type.Value => Source): Source = |
65695 | 150 |
ident + " " + sql_type(T) + (if (strict || primary_key) " NOT NULL" else "") |
63781 | 151 |
|
66856 | 152 |
def defined: String = ident + " IS NOT NULL" |
153 |
def undefined: String = ident + " IS NULL" |
|
154 |
||
78152 | 155 |
def equal(x: Int): Source = SQL.equal(ident, x) |
156 |
def equal(x: Long): Source = SQL.equal(ident, x) |
|
157 |
def equal(x: String): Source = SQL.equal(ident, x) |
|
158 |
||
159 |
def where_equal(x: Int): Source = SQL.where(equal(x)) |
|
160 |
def where_equal(x: Long): Source = SQL.where(equal(x)) |
|
161 |
def where_equal(x: String): Source = SQL.where(equal(x)) |
|
162 |
||
77375 | 163 |
def member(set: Iterable[String]): Source = SQL.member(ident, set) |
164 |
def where_member(set: Iterable[String]): Source = SQL.where(member(set)) |
|
65593 | 165 |
|
78151 | 166 |
def max: Column = copy(expr = "MAX(" + ident + ")") |
167 |
||
65730 | 168 |
override def toString: Source = ident |
63779 | 169 |
} |
170 |
||
76870 | 171 |
def order_by(columns: List[Column], descending: Boolean = false): Source = |
172 |
" ORDER BY " + columns.mkString(", ") + (if (descending) " DESC" else "") |
|
173 |
||
63780 | 174 |
|
175 |
/* tables */ |
|
176 |
||
75393 | 177 |
sealed case class Table(name: String, columns: List[Column], body: Source = "") { |
63781 | 178 |
Library.duplicates(columns.map(_.name)) match { |
179 |
case Nil => |
|
180 |
case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name)) |
|
181 |
} |
|
182 |
||
65730 | 183 |
def ident: Source = SQL.ident(name) |
65691 | 184 |
|
65730 | 185 |
def query: Source = |
65696 | 186 |
if (body == "") error("Missing SQL body for table " + quote(name)) |
187 |
else SQL.enclose(body) |
|
65649 | 188 |
|
65778 | 189 |
def query_named: Source = query + " AS " + SQL.ident(name) |
65702 | 190 |
|
78392
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
191 |
def create(sql_type: Type.Value => Source): Source = { |
65325 | 192 |
val primary_key = |
193 |
columns.filter(_.primary_key).map(_.name) match { |
|
194 |
case Nil => Nil |
|
195 |
case keys => List("PRIMARY KEY " + enclosure(keys)) |
|
196 |
} |
|
78392
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
197 |
"CREATE TABLE " + ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key) |
63781 | 198 |
} |
199 |
||
77365 | 200 |
def insert_cmd(cmd: Source = "INSERT", sql: Source = ""): Source = |
77377 | 201 |
cmd + " INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) + SQL.separate(sql) |
63791 | 202 |
|
77365 | 203 |
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
|
204 |
|
65730 | 205 |
def delete(sql: Source = ""): Source = |
77377 | 206 |
"DELETE FROM " + ident + SQL.separate(sql) |
65319 | 207 |
|
77537 | 208 |
def update(update_columns: List[Column] = Nil, sql: Source = ""): Source = |
209 |
"UPDATE " + ident + " SET " + commas(update_columns.map(c => c.ident + " = ?")) + |
|
210 |
SQL.separate(sql) |
|
211 |
||
65774 | 212 |
def select( |
77381
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
213 |
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
|
214 |
distinct: Boolean = false, |
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
215 |
sql: Source = "" |
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
216 |
): Source = SQL.select(select_columns, distinct = distinct, sql = ident + SQL.separate(sql)) |
63790 | 217 |
|
65730 | 218 |
override def toString: Source = ident |
63780 | 219 |
} |
63790 | 220 |
|
221 |
||
77596 | 222 |
/* table groups */ |
223 |
||
224 |
object Tables { |
|
225 |
def list(list: List[Table]): Tables = new Tables(list) |
|
226 |
def apply(args: Table*): Tables = list(args.toList) |
|
227 |
} |
|
228 |
||
229 |
final class Tables private(val list: List[Table]) extends Iterable[Table] { |
|
230 |
override def toString: String = list.mkString("SQL.Tables(", ", ", ")") |
|
231 |
||
232 |
def iterator: Iterator[Table] = list.iterator |
|
233 |
||
234 |
// requires transaction |
|
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
235 |
def lock(db: Database, create: Boolean = false): Boolean = { |
78154 | 236 |
if (create) foreach(db.create_table(_)) |
77596 | 237 |
val sql = db.lock_tables(list) |
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
238 |
if (sql.nonEmpty) { db.execute_statement(sql); true } |
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
239 |
else false |
77596 | 240 |
} |
241 |
} |
|
242 |
||
78187
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
243 |
abstract class Data(table_prefix: String = "") { |
78389
41e8ae87184d
clarified signature: eliminate SQL.Tables.empty to avoid confusion (see also 0bd366fad888);
wenzelm
parents:
78386
diff
changeset
|
244 |
def tables: Tables |
78187
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
245 |
|
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
246 |
def transaction_lock[A]( |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
247 |
db: Database, |
78207 | 248 |
create: Boolean = false, |
78356 | 249 |
label: String = "", |
78369
ba71ea02d965
more robust Java/Scala multithreading: transaction is always connection.synchronized;
wenzelm
parents:
78366
diff
changeset
|
250 |
log: Logger = new System_Logger |
78207 | 251 |
)(body: => A): A = { |
78369
ba71ea02d965
more robust Java/Scala multithreading: transaction is always connection.synchronized;
wenzelm
parents:
78366
diff
changeset
|
252 |
db.transaction_lock(tables, create = create, label = label, log = log)(body) |
78207 | 253 |
} |
78187
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
254 |
|
78266 | 255 |
def make_table(columns: List[Column], body: String = "", name: String = ""): Table = { |
78187
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
256 |
val table_name = |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
257 |
List(proper_string(table_prefix), proper_string(name)).flatten.mkString("_") |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
258 |
require(table_name.nonEmpty, "Undefined database table name") |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
259 |
Table(table_name, columns, body = body) |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
260 |
} |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
261 |
} |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
262 |
|
77596 | 263 |
|
65012 | 264 |
|
265 |
/** SQL database operations **/ |
|
266 |
||
65740 | 267 |
/* statements */ |
268 |
||
78538
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
269 |
class Batch_Error(val results: List[Int]) extends SQLException |
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
270 |
|
75393 | 271 |
class Statement private[SQL](val db: Database, val rep: PreparedStatement) extends AutoCloseable { |
65740 | 272 |
stmt => |
273 |
||
75393 | 274 |
object bool { |
73340 | 275 |
def update(i: Int, x: Boolean): Unit = rep.setBoolean(i, x) |
75393 | 276 |
def update(i: Int, x: Option[Boolean]): Unit = { |
65748 | 277 |
if (x.isDefined) update(i, x.get) |
278 |
else rep.setNull(i, java.sql.Types.BOOLEAN) |
|
279 |
} |
|
65740 | 280 |
} |
75393 | 281 |
object int { |
73340 | 282 |
def update(i: Int, x: Int): Unit = rep.setInt(i, x) |
75393 | 283 |
def update(i: Int, x: Option[Int]): Unit = { |
65748 | 284 |
if (x.isDefined) update(i, x.get) |
285 |
else rep.setNull(i, java.sql.Types.INTEGER) |
|
286 |
} |
|
65740 | 287 |
} |
75393 | 288 |
object long { |
73340 | 289 |
def update(i: Int, x: Long): Unit = rep.setLong(i, x) |
75393 | 290 |
def update(i: Int, x: Option[Long]): Unit = { |
65748 | 291 |
if (x.isDefined) update(i, x.get) |
292 |
else rep.setNull(i, java.sql.Types.BIGINT) |
|
293 |
} |
|
65740 | 294 |
} |
75393 | 295 |
object double { |
73340 | 296 |
def update(i: Int, x: Double): Unit = rep.setDouble(i, x) |
75393 | 297 |
def update(i: Int, x: Option[Double]): Unit = { |
65748 | 298 |
if (x.isDefined) update(i, x.get) |
299 |
else rep.setNull(i, java.sql.Types.DOUBLE) |
|
300 |
} |
|
301 |
} |
|
75393 | 302 |
object string { |
73340 | 303 |
def update(i: Int, x: String): Unit = rep.setString(i, x) |
65748 | 304 |
def update(i: Int, x: Option[String]): Unit = update(i, x.orNull) |
65740 | 305 |
} |
75393 | 306 |
object bytes { |
307 |
def update(i: Int, bytes: Bytes): Unit = { |
|
65748 | 308 |
if (bytes == null) rep.setBytes(i, null) |
309 |
else rep.setBinaryStream(i, bytes.stream(), bytes.length) |
|
310 |
} |
|
311 |
def update(i: Int, bytes: Option[Bytes]): Unit = update(i, bytes.orNull) |
|
65740 | 312 |
} |
75393 | 313 |
object date { |
65748 | 314 |
def update(i: Int, date: Date): Unit = db.update_date(stmt, i, date) |
315 |
def update(i: Int, date: Option[Date]): Unit = update(i, date.orNull) |
|
316 |
} |
|
65740 | 317 |
|
318 |
def execute(): Boolean = rep.execute() |
|
78538
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
319 |
|
78540 | 320 |
def execute_batch(batch: Statement => IterableOnce[Boolean]): Unit = { |
321 |
var proper = false |
|
322 |
for (ok <- batch(this).iterator if ok) { rep.addBatch(); proper = true } |
|
323 |
if (proper) { |
|
324 |
val res = rep.executeBatch() |
|
325 |
if (!res.forall(i => i >= 0 || i == java.sql.Statement.SUCCESS_NO_INFO)) { |
|
326 |
throw new Batch_Error(res.toList) |
|
327 |
} |
|
78538
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
328 |
} |
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
329 |
} |
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
330 |
|
65740 | 331 |
def execute_query(): Result = new Result(this, rep.executeQuery()) |
332 |
||
78353 | 333 |
override def close(): Unit = rep.close() |
65740 | 334 |
} |
335 |
||
336 |
||
63790 | 337 |
/* results */ |
338 |
||
78352 | 339 |
class Result private[SQL](val stmt: Statement, val rep: ResultSet) extends AutoCloseable { |
65740 | 340 |
res => |
341 |
||
342 |
def next(): Boolean = rep.next() |
|
343 |
||
75393 | 344 |
def iterator[A](get: Result => A): Iterator[A] = new Iterator[A] { |
65740 | 345 |
private var _next: Boolean = res.next() |
346 |
def hasNext: Boolean = _next |
|
73337 | 347 |
def next(): A = { val x = get(res); _next = res.next(); x } |
65740 | 348 |
} |
349 |
||
350 |
def bool(column: Column): Boolean = rep.getBoolean(column.name) |
|
351 |
def int(column: Column): Int = rep.getInt(column.name) |
|
352 |
def long(column: Column): Long = rep.getLong(column.name) |
|
353 |
def double(column: Column): Double = rep.getDouble(column.name) |
|
75393 | 354 |
def string(column: Column): String = { |
65740 | 355 |
val s = rep.getString(column.name) |
356 |
if (s == null) "" else s |
|
357 |
} |
|
75393 | 358 |
def bytes(column: Column): Bytes = { |
65740 | 359 |
val bs = rep.getBytes(column.name) |
360 |
if (bs == null) Bytes.empty else Bytes(bs) |
|
361 |
} |
|
362 |
def date(column: Column): Date = stmt.db.date(res, column) |
|
363 |
||
71601 | 364 |
def timing(c1: Column, c2: Column, c3: Column): Timing = |
65741 | 365 |
Timing(Time.ms(long(c1)), Time.ms(long(c2)), Time.ms(long(c3))) |
366 |
||
75393 | 367 |
def get[A](column: Column, f: Column => A): Option[A] = { |
65740 | 368 |
val x = f(column) |
77598 | 369 |
if (rep.wasNull || x == null) None else Some(x) |
65740 | 370 |
} |
71601 | 371 |
def get_bool(column: Column): Option[Boolean] = get(column, bool) |
372 |
def get_int(column: Column): Option[Int] = get(column, int) |
|
373 |
def get_long(column: Column): Option[Long] = get(column, long) |
|
374 |
def get_double(column: Column): Option[Double] = get(column, double) |
|
375 |
def get_string(column: Column): Option[String] = get(column, string) |
|
376 |
def get_bytes(column: Column): Option[Bytes] = get(column, bytes) |
|
377 |
def get_date(column: Column): Option[Date] = get(column, date) |
|
78352 | 378 |
|
379 |
override def close(): Unit = rep.close() |
|
63790 | 380 |
} |
65006 | 381 |
|
65740 | 382 |
|
383 |
/* database */ |
|
384 |
||
75393 | 385 |
trait Database extends AutoCloseable { |
65740 | 386 |
db => |
387 |
||
77542 | 388 |
def is_sqlite: Boolean = isInstanceOf[SQLite.Database] |
389 |
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
|
390 |
|
78389
41e8ae87184d
clarified signature: eliminate SQL.Tables.empty to avoid confusion (see also 0bd366fad888);
wenzelm
parents:
78386
diff
changeset
|
391 |
def vacuum(tables: List[SQL.Table] = Nil): Unit = |
78390
a84f8fca0833
clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents:
78389
diff
changeset
|
392 |
if (is_sqlite) execute_statement("VACUUM") // always FULL |
a84f8fca0833
clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents:
78389
diff
changeset
|
393 |
else if (tables.isEmpty) execute_statement("VACUUM FULL") |
a84f8fca0833
clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents:
78389
diff
changeset
|
394 |
else if (postgresql_major_version.get <= 10) { |
a84f8fca0833
clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents:
78389
diff
changeset
|
395 |
for (t <- tables) execute_statement("VACUUM " + t.ident) |
78273
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
396 |
} |
78390
a84f8fca0833
clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents:
78389
diff
changeset
|
397 |
else execute_statement("VACUUM" + commas(tables.map(_.ident))) |
77348 | 398 |
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
399 |
def now(): Date |
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
400 |
|
65740 | 401 |
|
65008 | 402 |
/* types */ |
403 |
||
65730 | 404 |
def sql_type(T: Type.Value): Source |
65008 | 405 |
|
406 |
||
65006 | 407 |
/* connection */ |
408 |
||
409 |
def connection: Connection |
|
410 |
||
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
411 |
def sqlite_connection: Option[JDBC4Connection] = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
412 |
connection match { case conn: JDBC4Connection => Some(conn) case _ => None } |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
413 |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
414 |
def postgresql_connection: Option[PGConnection] = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
415 |
connection match { case conn: PGConnection => Some(conn) case _ => None } |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
416 |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
417 |
def the_sqlite_connection: JDBC4Connection = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
418 |
sqlite_connection getOrElse |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
419 |
error("SQLite connection expected, but found " + connection.getClass.getName) |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
420 |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
421 |
def the_postgresql_connection: PGConnection = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
422 |
postgresql_connection getOrElse |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
423 |
error("PostgreSQL connection expected, but found " + connection.getClass.getName) |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
424 |
|
78273
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
425 |
def postgresql_major_version: Option[Int] = |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
426 |
if (is_postgresql) { |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
427 |
def err(s: String): Nothing = error("Bad PostgreSQL version " + s) |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
428 |
|
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
429 |
the_postgresql_connection.getParameterStatus("server_version") match { |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
430 |
case null => err("null") |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
431 |
case str => |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
432 |
str.iterator.takeWhile(Symbol.is_ascii_digit).mkString match { |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
433 |
case Value.Int(m) => Some(m) |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
434 |
case _ => err(quote(str)) |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
435 |
} |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
436 |
} |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
437 |
} |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
438 |
else None |
95a3bb4d7e38
clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents:
78271
diff
changeset
|
439 |
|
78353 | 440 |
override def close(): Unit = connection.close() |
65006 | 441 |
|
78369
ba71ea02d965
more robust Java/Scala multithreading: transaction is always connection.synchronized;
wenzelm
parents:
78366
diff
changeset
|
442 |
def transaction[A](body: => A): A = connection.synchronized { |
78383
d032bf604e93
more robust: exclude accidental nesting (synchronized block is re-entrant);
wenzelm
parents:
78381
diff
changeset
|
443 |
require(connection.getAutoCommit(), "transaction already active") |
65006 | 444 |
try { |
445 |
connection.setAutoCommit(false) |
|
65022 | 446 |
try { |
447 |
val result = body |
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
448 |
connection.commit() |
65022 | 449 |
result |
450 |
} |
|
78386
ee588c4b5557
more elementary transaction implementation (despite fda3f7a158b9 and 9da65bc75610);
wenzelm
parents:
78384
diff
changeset
|
451 |
catch { case exn: Throwable => connection.rollback(); throw exn } |
65006 | 452 |
} |
78383
d032bf604e93
more robust: exclude accidental nesting (synchronized block is re-entrant);
wenzelm
parents:
78381
diff
changeset
|
453 |
finally { connection.setAutoCommit(true) } |
65006 | 454 |
} |
455 |
||
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
456 |
def transaction_lock[A]( |
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
457 |
tables: Tables, |
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
458 |
create: Boolean = false, |
78356 | 459 |
label: String = "", |
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
460 |
log: Logger = new System_Logger |
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
461 |
)(body: => A): A = { |
78358
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
462 |
val prop = "isabelle.transaction_trace" |
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
463 |
val trace_min = |
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
464 |
System.getProperty(prop, "") match { |
78365 | 465 |
case Value.Seconds(t) => t |
78358
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
466 |
case "true" => Time.min |
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
467 |
case "false" | "" => Time.max |
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
468 |
case s => error("Bad system property " + prop + ": " + quote(s)) |
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
469 |
} |
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
470 |
|
78362 | 471 |
val trace_count = - SQL.transaction_count() |
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
472 |
val trace_start = Time.now() |
78361 | 473 |
var trace_nl = false |
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
474 |
|
78380 | 475 |
def trace(msg: String): Unit = { |
78358
f5cf8e500dee
clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents:
78356
diff
changeset
|
476 |
val trace_time = Time.now() - trace_start |
78381 | 477 |
if (trace_time >= trace_min) { |
78363 | 478 |
val nl = if (trace_nl) "" else { trace_nl = true; "\n" } |
78361 | 479 |
log(nl + trace_time + " transaction " + trace_count + |
480 |
if_proper(label, " " + label) + ": " + msg) |
|
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
481 |
} |
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
482 |
} |
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
483 |
|
78373 | 484 |
try { |
485 |
val res = |
|
486 |
transaction { |
|
487 |
trace("begin") |
|
488 |
if (tables.lock(db, create = create)) { |
|
78380 | 489 |
trace("locked " + commas_quote(tables.list.map(_.name))) |
78373 | 490 |
} |
491 |
val res = Exn.capture { body } |
|
492 |
trace("end") |
|
493 |
res |
|
78371 | 494 |
} |
78373 | 495 |
trace("commit") |
496 |
Exn.release(res) |
|
497 |
} |
|
498 |
catch { case exn: Throwable => trace("crash"); throw exn } |
|
78355
9fbc6a043268
support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents:
78354
diff
changeset
|
499 |
} |
77596 | 500 |
|
501 |
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
|
502 |
|
65006 | 503 |
|
65740 | 504 |
/* statements and results */ |
505 |
||
506 |
def statement(sql: Source): Statement = |
|
507 |
new Statement(db, connection.prepareStatement(sql)) |
|
65006 | 508 |
|
65740 | 509 |
def using_statement[A](sql: Source)(f: Statement => A): A = |
510 |
using(statement(sql))(f) |
|
65006 | 511 |
|
77541 | 512 |
def execute_statement(sql: Source, body: Statement => Unit = _ => ()): Unit = |
513 |
using_statement(sql) { stmt => body(stmt); stmt.execute() } |
|
77540 | 514 |
|
78538
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
515 |
def execute_batch_statement( |
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
516 |
sql: Source, |
78540 | 517 |
batch: Statement => IterableOnce[Boolean] = _ => Nil |
78538
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
518 |
): Unit = using_statement(sql) { stmt => stmt.execute_batch(batch) } |
56e8458ba262
support for execute_batch: multiple statements in one round-trip;
wenzelm
parents:
78422
diff
changeset
|
519 |
|
77552 | 520 |
def execute_query_statement[A, B]( |
521 |
sql: Source, |
|
522 |
make_result: Iterator[A] => B, |
|
523 |
get: Result => A |
|
78352 | 524 |
): B = { |
525 |
using_statement(sql) { stmt => |
|
526 |
using(stmt.execute_query()) { res => make_result(res.iterator(get)) } |
|
527 |
} |
|
528 |
} |
|
77552 | 529 |
|
530 |
def execute_query_statementO[A](sql: Source, get: Result => A): Option[A] = |
|
531 |
execute_query_statement[A, Option[A]](sql, _.nextOption, get) |
|
532 |
||
533 |
def execute_query_statementB(sql: Source): Boolean = |
|
78352 | 534 |
using_statement(sql)(stmt => using(stmt.execute_query())(_.next())) |
77552 | 535 |
|
65748 | 536 |
def update_date(stmt: Statement, i: Int, date: Date): Unit |
65740 | 537 |
def date(res: Result, column: Column): Date |
65006 | 538 |
|
65730 | 539 |
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
|
540 |
|
65006 | 541 |
|
65669 | 542 |
/* tables and views */ |
65006 | 543 |
|
78375
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
544 |
def get_tables(pattern: String = "%"): List[String] = { |
65740 | 545 |
val result = new mutable.ListBuffer[String] |
78375
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
546 |
val rs = connection.getMetaData.getTables(null, null, pattern, null) |
65740 | 547 |
while (rs.next) { result += rs.getString(3) } |
548 |
result.toList |
|
549 |
} |
|
65006 | 550 |
|
78375
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
551 |
def exists_table(name: String): Boolean = { |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
552 |
val escape = connection.getMetaData.getSearchStringEscape |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
553 |
val pattern = |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
554 |
name.iterator.map(c => |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
555 |
(if (c == '_' || c == '%' || c == escape(0)) escape else "") + c).mkString |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
556 |
get_tables(pattern = pattern).nonEmpty |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
557 |
} |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
558 |
|
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
559 |
def exists_table(table: Table): Boolean = exists_table(table.name) |
234f2ff9afe6
clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents:
78373
diff
changeset
|
560 |
|
78392
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
561 |
def create_table(table: Table, sql: Source = ""): Unit = { |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
562 |
if (!exists_table(table)) { |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
563 |
execute_statement(table.create(sql_type) + SQL.separate(sql)) |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
564 |
if (is_postgresql) { |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
565 |
for (column <- table.columns if column.T == SQL.Type.Bytes) { |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
566 |
execute_statement( |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
567 |
"ALTER TABLE " + table + " ALTER COLUMN " + column + " SET STORAGE EXTERNAL") |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
568 |
} |
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
|
569 |
} |
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
|
570 |
} |
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
|
571 |
} |
65006 | 572 |
|
78392
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
573 |
def create_view(table: Table): Unit = { |
27c2fa1db6ed
more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents:
78391
diff
changeset
|
574 |
if (!exists_table(table)) { |
77540 | 575 |
execute_statement("CREATE VIEW " + table + " AS " + { table.query; table.body }) |
65690 | 576 |
} |
65691 | 577 |
} |
65006 | 578 |
} |
78362 | 579 |
|
580 |
||
581 |
private val transaction_count = Counter.make() |
|
63778 | 582 |
} |
65006 | 583 |
|
584 |
||
585 |
||
586 |
/** SQLite **/ |
|
587 |
||
75393 | 588 |
object SQLite { |
65021 | 589 |
// see https://www.sqlite.org/lang_datefunc.html |
590 |
val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x") |
|
591 |
||
75393 | 592 |
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
|
593 |
val lib_path = Path.explode("$ISABELLE_SQLITE_HOME/" + Platform.jvm_platform) |
76529 | 594 |
val lib_name = File.get_file(lib_path).file_name |
595 |
||
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
|
596 |
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
|
597 |
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
|
598 |
|
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
|
599 |
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
|
600 |
} |
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
601 |
|
78163 | 602 |
def open_database(path: Path, restrict: Boolean = false): Database = { |
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
603 |
init_jdbc |
65006 | 604 |
val path0 = path.expand |
605 |
val s0 = File.platform_path(path0) |
|
606 |
val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0 |
|
607 |
val connection = DriverManager.getConnection("jdbc:sqlite:" + s1) |
|
78163 | 608 |
val db = new Database(path0.toString, connection) |
609 |
||
610 |
try { if (restrict) File.restrict(path0) } |
|
611 |
catch { case exn: Throwable => db.close(); throw exn } |
|
612 |
||
613 |
db |
|
65006 | 614 |
} |
615 |
||
75393 | 616 |
class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database { |
65007 | 617 |
override def toString: String = name |
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
618 |
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
619 |
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
|
620 |
|
65730 | 621 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_sqlite(T) |
65011 | 622 |
|
65748 | 623 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
624 |
if (date == null) stmt.string(i) = (null: String) |
|
625 |
else stmt.string(i) = date_format(date) |
|
65598 | 626 |
|
65740 | 627 |
def date(res: SQL.Result, column: SQL.Column): Date = |
77598 | 628 |
proper_string(res.string(column)) match { |
629 |
case None => null |
|
630 |
case Some(s) => date_format.parse(s) |
|
631 |
} |
|
65021 | 632 |
|
65730 | 633 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
77365 | 634 |
table.insert_cmd(cmd = "INSERT OR IGNORE", sql = sql) |
65006 | 635 |
} |
636 |
} |
|
637 |
||
638 |
||
639 |
||
640 |
/** PostgreSQL **/ |
|
641 |
||
78351 | 642 |
// see https://www.postgresql.org/docs/current/index.html |
643 |
// see https://jdbc.postgresql.org/documentation |
|
644 |
||
75393 | 645 |
object PostgreSQL { |
75967
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
646 |
type Source = SQL.Source |
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
647 |
|
78347 | 648 |
lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver") |
649 |
||
78345 | 650 |
val default_server: SSH.Server = SSH.local_server(port = 5432) |
65006 | 651 |
|
78378 | 652 |
def open_database( |
653 |
user: String, |
|
654 |
password: String, |
|
655 |
database: String = "", |
|
656 |
server: SSH.Server = default_server, |
|
657 |
server_close: Boolean = false, |
|
78400 | 658 |
synchronous_commit: String = "off" |
78378 | 659 |
): Database = { |
660 |
init_jdbc |
|
661 |
||
662 |
if (user.isEmpty) error("Undefined database user") |
|
663 |
if (server.host.isEmpty) error("Undefined database server host") |
|
664 |
if (server.port <= 0) error("Undefined database server port") |
|
665 |
||
666 |
val name = proper_string(database) getOrElse user |
|
667 |
val url = "jdbc:postgresql://" + server.host + ":" + server.port + "/" + name |
|
668 |
val ssh = server.ssh_system.ssh_session |
|
78422 | 669 |
val print = |
670 |
"server " + user + "@" + server + "/" + name + if_proper(ssh, " via ssh " + ssh.get) |
|
78378 | 671 |
|
672 |
val connection = DriverManager.getConnection(url, user, password) |
|
78400 | 673 |
val db = new Database(connection, print, server, server_close) |
674 |
||
675 |
try { |
|
78402 | 676 |
if (synchronous_commit.nonEmpty) { |
677 |
db.execute_statement("SET synchronous_commit = " + SQL.string(synchronous_commit)) |
|
678 |
} |
|
78400 | 679 |
} |
680 |
catch { case exn: Throwable => db.close(); throw exn } |
|
681 |
||
682 |
db |
|
78378 | 683 |
} |
684 |
||
78366 | 685 |
def open_server( |
686 |
options: Options, |
|
687 |
host: String = "", |
|
688 |
port: Int = 0, |
|
689 |
ssh_host: String = "", |
|
690 |
ssh_port: Int = 0, |
|
691 |
ssh_user: String = "" |
|
692 |
): SSH.Server = { |
|
693 |
val server_host = proper_string(host).getOrElse(default_server.host) |
|
694 |
val server_port = if (port > 0) port else default_server.port |
|
695 |
||
696 |
if (ssh_host.isEmpty) SSH.local_server(host = server_host, port = server_port) |
|
697 |
else { |
|
698 |
SSH.open_server(options, host = ssh_host, port = ssh_port, user = ssh_user, |
|
699 |
remote_host = server_host, remote_port = server_port) |
|
700 |
} |
|
701 |
} |
|
702 |
||
78347 | 703 |
def open_database_server( |
704 |
options: Options, |
|
705 |
user: String = "", |
|
706 |
password: String = "", |
|
707 |
database: String = "", |
|
78366 | 708 |
server: SSH.Server = SSH.no_server, |
78347 | 709 |
host: String = "", |
710 |
port: Int = 0, |
|
711 |
ssh_host: String = "", |
|
712 |
ssh_port: Int = 0, |
|
78400 | 713 |
ssh_user: String = "", |
78402 | 714 |
synchronous_commit: String = "" |
78347 | 715 |
): PostgreSQL.Database = { |
78366 | 716 |
val db_server = |
717 |
if (server.defined) server |
|
78347 | 718 |
else { |
78366 | 719 |
open_server(options, host = host, port = port, ssh_host = ssh_host, |
720 |
ssh_port = ssh_port, ssh_user = ssh_user) |
|
78347 | 721 |
} |
78366 | 722 |
val server_close = !server.defined |
78347 | 723 |
try { |
724 |
open_database(user = user, password = password, database = database, |
|
78400 | 725 |
server = db_server, server_close = server_close, synchronous_commit = synchronous_commit) |
78347 | 726 |
} |
78366 | 727 |
catch { case exn: Throwable if server_close => db_server.close(); throw exn } |
78347 | 728 |
} |
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
729 |
|
65009 | 730 |
class Database private[PostgreSQL]( |
75393 | 731 |
val connection: Connection, |
78347 | 732 |
print: String, |
733 |
server: SSH.Server, |
|
734 |
server_close: Boolean |
|
75393 | 735 |
) extends SQL.Database { |
78347 | 736 |
override def toString: String = print |
65008 | 737 |
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
738 |
override def now(): Date = { |
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
739 |
val now = SQL.Column.date("now") |
77552 | 740 |
execute_query_statementO[Date]("SELECT NOW() as " + now.ident, res => res.date(now)) |
741 |
.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
|
742 |
} |
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
743 |
|
65730 | 744 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_postgresql(T) |
65009 | 745 |
|
65021 | 746 |
// see https://jdbc.postgresql.org/documentation/head/8-date-time.html |
65748 | 747 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
65740 | 748 |
if (date == null) stmt.rep.setObject(i, null) |
69980 | 749 |
else stmt.rep.setObject(i, OffsetDateTime.from(date.to(Date.timezone_utc).rep)) |
65598 | 750 |
|
75393 | 751 |
def date(res: SQL.Result, column: SQL.Column): Date = { |
65740 | 752 |
val obj = res.rep.getObject(column.name, classOf[OffsetDateTime]) |
65704 | 753 |
if (obj == null) null else Date.instant(obj.toInstant) |
754 |
} |
|
65021 | 755 |
|
65730 | 756 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
77377 | 757 |
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
|
758 |
|
77039 | 759 |
|
77590
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
760 |
/* 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
|
761 |
// 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
|
762 |
// 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
|
763 |
|
77596 | 764 |
override def lock_tables(tables: List[SQL.Table]): PostgreSQL.Source = |
78253 | 765 |
if_proper(tables, "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
|
766 |
|
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
767 |
|
77039 | 768 |
/* notifications: IPC via database server */ |
769 |
// see https://www.postgresql.org/docs/current/sql-notify.html |
|
770 |
||
771 |
def listen(name: String): Unit = |
|
77541 | 772 |
execute_statement("LISTEN " + SQL.ident(name)) |
77039 | 773 |
|
774 |
def unlisten(name: String = "*"): Unit = |
|
77541 | 775 |
execute_statement("UNLISTEN " + (if (name == "*") name else SQL.ident(name))) |
77039 | 776 |
|
777 |
def notify(name: String, payload: String = ""): Unit = |
|
77543 | 778 |
execute_statement("NOTIFY " + SQL.ident(name) + if_proper(payload, ", " + SQL.string(payload))) |
77039 | 779 |
|
780 |
def get_notifications(): List[PGNotification] = |
|
781 |
the_postgresql_connection.getNotifications() match { |
|
782 |
case null => Nil |
|
783 |
case array => array.toList |
|
784 |
} |
|
785 |
||
786 |
||
78347 | 787 |
override def close(): Unit = { super.close(); if (server_close) server.close() } |
65006 | 788 |
} |
789 |
} |