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