author | wenzelm |
Sun, 16 Jul 2023 09:34:30 +0200 | |
changeset 78351 | 9f2cfb9873bb |
parent 78348 | cd9c91ecbcb4 |
child 78352 | 10f8f12c61b0 |
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 |
13 |
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet} |
|
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 |
|
75966 | 191 |
def create(strict: Boolean, 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 |
} |
|
65701 | 197 |
"CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") + |
198 |
ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key) |
|
63781 | 199 |
} |
200 |
||
65698 | 201 |
def create_index(index_name: String, index_columns: List[Column], |
65730 | 202 |
strict: Boolean = false, unique: Boolean = false): Source = |
63791 | 203 |
"CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " + |
65695 | 204 |
(if (strict) "" else "IF NOT EXISTS ") + SQL.ident(index_name) + " ON " + |
205 |
ident + " " + enclosure(index_columns.map(_.name)) |
|
63791 | 206 |
|
77365 | 207 |
def insert_cmd(cmd: Source = "INSERT", sql: Source = ""): Source = |
77377 | 208 |
cmd + " INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) + SQL.separate(sql) |
63791 | 209 |
|
77365 | 210 |
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
|
211 |
|
65730 | 212 |
def delete(sql: Source = ""): Source = |
77377 | 213 |
"DELETE FROM " + ident + SQL.separate(sql) |
65319 | 214 |
|
77537 | 215 |
def update(update_columns: List[Column] = Nil, sql: Source = ""): Source = |
216 |
"UPDATE " + ident + " SET " + commas(update_columns.map(c => c.ident + " = ?")) + |
|
217 |
SQL.separate(sql) |
|
218 |
||
65774 | 219 |
def select( |
77381
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
220 |
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
|
221 |
distinct: Boolean = false, |
a86e346b20d8
misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents:
77377
diff
changeset
|
222 |
sql: Source = "" |
77403
be8e14c7da80
clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents:
77381
diff
changeset
|
223 |
): Source = SQL.select(select_columns, distinct = distinct, sql = ident + SQL.separate(sql)) |
63790 | 224 |
|
65730 | 225 |
override def toString: Source = ident |
63780 | 226 |
} |
63790 | 227 |
|
228 |
||
77596 | 229 |
/* table groups */ |
230 |
||
231 |
object Tables { |
|
232 |
def list(list: List[Table]): Tables = new Tables(list) |
|
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
233 |
val empty: Tables = list(Nil) |
77596 | 234 |
def apply(args: Table*): Tables = list(args.toList) |
235 |
} |
|
236 |
||
237 |
final class Tables private(val list: List[Table]) extends Iterable[Table] { |
|
238 |
override def toString: String = list.mkString("SQL.Tables(", ", ", ")") |
|
239 |
||
77665 | 240 |
def ::: (other: Tables): Tables = new Tables(other.list ::: list) |
241 |
||
77596 | 242 |
def iterator: Iterator[Table] = list.iterator |
243 |
||
244 |
// requires transaction |
|
78154 | 245 |
def lock(db: Database, create: Boolean = false): Unit = { |
246 |
if (create) foreach(db.create_table(_)) |
|
77596 | 247 |
val sql = db.lock_tables(list) |
248 |
if (sql.nonEmpty) db.execute_statement(sql) |
|
249 |
} |
|
250 |
} |
|
251 |
||
78187
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
252 |
abstract class Data(table_prefix: String = "") { |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
253 |
def tables: Tables = Tables.empty |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
254 |
|
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
255 |
def transaction_lock[A]( |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
256 |
db: Database, |
78207 | 257 |
create: Boolean = false, |
258 |
synchronized: Boolean = false, |
|
259 |
)(body: => A): A = { |
|
78264
c8fde312c895
clarified signature: ensure disjoint data spaces;
wenzelm
parents:
78263
diff
changeset
|
260 |
def run: A = db.transaction { tables.lock(db, create = create); body } |
78207 | 261 |
if (synchronized) db.synchronized { run } else run |
262 |
} |
|
78187
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
263 |
|
78266 | 264 |
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
|
265 |
val table_name = |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
266 |
List(proper_string(table_prefix), proper_string(name)).flatten.mkString("_") |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
267 |
require(table_name.nonEmpty, "Undefined database table name") |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
268 |
Table(table_name, columns, body = body) |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
269 |
} |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
270 |
} |
2df0f3604a67
clarified signature: more explicit class SQL.Data;
wenzelm
parents:
78167
diff
changeset
|
271 |
|
77596 | 272 |
|
65012 | 273 |
|
274 |
/** SQL database operations **/ |
|
275 |
||
65740 | 276 |
/* statements */ |
277 |
||
75393 | 278 |
class Statement private[SQL](val db: Database, val rep: PreparedStatement) extends AutoCloseable { |
65740 | 279 |
stmt => |
280 |
||
75393 | 281 |
object bool { |
73340 | 282 |
def update(i: Int, x: Boolean): Unit = rep.setBoolean(i, x) |
75393 | 283 |
def update(i: Int, x: Option[Boolean]): Unit = { |
65748 | 284 |
if (x.isDefined) update(i, x.get) |
285 |
else rep.setNull(i, java.sql.Types.BOOLEAN) |
|
286 |
} |
|
65740 | 287 |
} |
75393 | 288 |
object int { |
73340 | 289 |
def update(i: Int, x: Int): Unit = rep.setInt(i, x) |
75393 | 290 |
def update(i: Int, x: Option[Int]): Unit = { |
65748 | 291 |
if (x.isDefined) update(i, x.get) |
292 |
else rep.setNull(i, java.sql.Types.INTEGER) |
|
293 |
} |
|
65740 | 294 |
} |
75393 | 295 |
object long { |
73340 | 296 |
def update(i: Int, x: Long): Unit = rep.setLong(i, x) |
75393 | 297 |
def update(i: Int, x: Option[Long]): Unit = { |
65748 | 298 |
if (x.isDefined) update(i, x.get) |
299 |
else rep.setNull(i, java.sql.Types.BIGINT) |
|
300 |
} |
|
65740 | 301 |
} |
75393 | 302 |
object double { |
73340 | 303 |
def update(i: Int, x: Double): Unit = rep.setDouble(i, x) |
75393 | 304 |
def update(i: Int, x: Option[Double]): Unit = { |
65748 | 305 |
if (x.isDefined) update(i, x.get) |
306 |
else rep.setNull(i, java.sql.Types.DOUBLE) |
|
307 |
} |
|
308 |
} |
|
75393 | 309 |
object string { |
73340 | 310 |
def update(i: Int, x: String): Unit = rep.setString(i, x) |
65748 | 311 |
def update(i: Int, x: Option[String]): Unit = update(i, x.orNull) |
65740 | 312 |
} |
75393 | 313 |
object bytes { |
314 |
def update(i: Int, bytes: Bytes): Unit = { |
|
65748 | 315 |
if (bytes == null) rep.setBytes(i, null) |
316 |
else rep.setBinaryStream(i, bytes.stream(), bytes.length) |
|
317 |
} |
|
318 |
def update(i: Int, bytes: Option[Bytes]): Unit = update(i, bytes.orNull) |
|
65740 | 319 |
} |
75393 | 320 |
object date { |
65748 | 321 |
def update(i: Int, date: Date): Unit = db.update_date(stmt, i, date) |
322 |
def update(i: Int, date: Option[Date]): Unit = update(i, date.orNull) |
|
323 |
} |
|
65740 | 324 |
|
325 |
def execute(): Boolean = rep.execute() |
|
326 |
def execute_query(): Result = new Result(this, rep.executeQuery()) |
|
327 |
||
73367 | 328 |
def close(): Unit = rep.close() |
65740 | 329 |
} |
330 |
||
331 |
||
63790 | 332 |
/* results */ |
333 |
||
75393 | 334 |
class Result private[SQL](val stmt: Statement, val rep: ResultSet) { |
65740 | 335 |
res => |
336 |
||
337 |
def next(): Boolean = rep.next() |
|
338 |
||
75393 | 339 |
def iterator[A](get: Result => A): Iterator[A] = new Iterator[A] { |
65740 | 340 |
private var _next: Boolean = res.next() |
341 |
def hasNext: Boolean = _next |
|
73337 | 342 |
def next(): A = { val x = get(res); _next = res.next(); x } |
65740 | 343 |
} |
344 |
||
345 |
def bool(column: Column): Boolean = rep.getBoolean(column.name) |
|
346 |
def int(column: Column): Int = rep.getInt(column.name) |
|
347 |
def long(column: Column): Long = rep.getLong(column.name) |
|
348 |
def double(column: Column): Double = rep.getDouble(column.name) |
|
75393 | 349 |
def string(column: Column): String = { |
65740 | 350 |
val s = rep.getString(column.name) |
351 |
if (s == null) "" else s |
|
352 |
} |
|
75393 | 353 |
def bytes(column: Column): Bytes = { |
65740 | 354 |
val bs = rep.getBytes(column.name) |
355 |
if (bs == null) Bytes.empty else Bytes(bs) |
|
356 |
} |
|
357 |
def date(column: Column): Date = stmt.db.date(res, column) |
|
358 |
||
71601 | 359 |
def timing(c1: Column, c2: Column, c3: Column): Timing = |
65741 | 360 |
Timing(Time.ms(long(c1)), Time.ms(long(c2)), Time.ms(long(c3))) |
361 |
||
75393 | 362 |
def get[A](column: Column, f: Column => A): Option[A] = { |
65740 | 363 |
val x = f(column) |
77598 | 364 |
if (rep.wasNull || x == null) None else Some(x) |
65740 | 365 |
} |
71601 | 366 |
def get_bool(column: Column): Option[Boolean] = get(column, bool) |
367 |
def get_int(column: Column): Option[Int] = get(column, int) |
|
368 |
def get_long(column: Column): Option[Long] = get(column, long) |
|
369 |
def get_double(column: Column): Option[Double] = get(column, double) |
|
370 |
def get_string(column: Column): Option[String] = get(column, string) |
|
371 |
def get_bytes(column: Column): Option[Bytes] = get(column, bytes) |
|
372 |
def get_date(column: Column): Option[Date] = get(column, date) |
|
63790 | 373 |
} |
65006 | 374 |
|
65740 | 375 |
|
376 |
/* database */ |
|
377 |
||
75393 | 378 |
trait Database extends AutoCloseable { |
65740 | 379 |
db => |
380 |
||
77542 | 381 |
def is_sqlite: Boolean = isInstanceOf[SQLite.Database] |
382 |
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
|
383 |
|
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
|
384 |
def vacuum(tables: SQL.Tables = SQL.Tables.empty): Unit = |
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
|
385 |
if (tables.list.nonEmpty) { |
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
|
386 |
postgresql_major_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
|
387 |
case Some(m) if m <= 10 => |
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
|
388 |
for (table <- tables) execute_statement("VACUUM " + table.ident) |
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
|
389 |
case Some(_) => |
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
|
390 |
execute_statement("VACUUM" + commas(tables.list.map(_.ident))) |
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
|
391 |
case None => execute_statement("VACUUM") |
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
|
392 |
} |
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
|
393 |
} |
77348 | 394 |
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
395 |
def now(): Date |
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
396 |
|
65740 | 397 |
|
65008 | 398 |
/* types */ |
399 |
||
65730 | 400 |
def sql_type(T: Type.Value): Source |
65008 | 401 |
|
402 |
||
65006 | 403 |
/* connection */ |
404 |
||
405 |
def connection: Connection |
|
406 |
||
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
407 |
def sqlite_connection: Option[JDBC4Connection] = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
408 |
connection match { case conn: JDBC4Connection => Some(conn) case _ => None } |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
409 |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
410 |
def postgresql_connection: Option[PGConnection] = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
411 |
connection match { case conn: PGConnection => Some(conn) case _ => None } |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
412 |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
413 |
def the_sqlite_connection: JDBC4Connection = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
414 |
sqlite_connection getOrElse |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
415 |
error("SQLite connection expected, but found " + connection.getClass.getName) |
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_postgresql_connection: PGConnection = |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
418 |
postgresql_connection getOrElse |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
419 |
error("PostgreSQL connection expected, but found " + connection.getClass.getName) |
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
420 |
|
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
|
421 |
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
|
422 |
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
|
423 |
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
|
424 |
|
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 |
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
|
426 |
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
|
427 |
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
|
428 |
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
|
429 |
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
|
430 |
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
|
431 |
} |
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 |
} |
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 |
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
|
435 |
|
73367 | 436 |
def close(): Unit = connection.close() |
65006 | 437 |
|
75393 | 438 |
def transaction[A](body: => A): A = { |
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
439 |
val auto_commit = connection.getAutoCommit() |
65006 | 440 |
try { |
441 |
connection.setAutoCommit(false) |
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
442 |
val savepoint = connection.setSavepoint() |
65022 | 443 |
try { |
444 |
val result = body |
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
445 |
connection.commit() |
65022 | 446 |
result |
447 |
} |
|
448 |
catch { case exn: Throwable => connection.rollback(savepoint); throw exn } |
|
65006 | 449 |
} |
450 |
finally { connection.setAutoCommit(auto_commit) } |
|
451 |
} |
|
452 |
||
78154 | 453 |
def transaction_lock[A](tables: Tables, create: Boolean = false)(body: => A): A = |
454 |
transaction { tables.lock(db, create = create); body } |
|
77596 | 455 |
|
456 |
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
|
457 |
|
65006 | 458 |
|
65740 | 459 |
/* statements and results */ |
460 |
||
461 |
def statement(sql: Source): Statement = |
|
462 |
new Statement(db, connection.prepareStatement(sql)) |
|
65006 | 463 |
|
65740 | 464 |
def using_statement[A](sql: Source)(f: Statement => A): A = |
465 |
using(statement(sql))(f) |
|
65006 | 466 |
|
77541 | 467 |
def execute_statement(sql: Source, body: Statement => Unit = _ => ()): Unit = |
468 |
using_statement(sql) { stmt => body(stmt); stmt.execute() } |
|
77540 | 469 |
|
77552 | 470 |
def execute_query_statement[A, B]( |
471 |
sql: Source, |
|
472 |
make_result: Iterator[A] => B, |
|
473 |
get: Result => A |
|
474 |
): B = using_statement(sql)(stmt => make_result(stmt.execute_query().iterator(get))) |
|
475 |
||
476 |
def execute_query_statementO[A](sql: Source, get: Result => A): Option[A] = |
|
477 |
execute_query_statement[A, Option[A]](sql, _.nextOption, get) |
|
478 |
||
479 |
def execute_query_statementB(sql: Source): Boolean = |
|
480 |
using_statement(sql)(stmt => stmt.execute_query().next()) |
|
481 |
||
65748 | 482 |
def update_date(stmt: Statement, i: Int, date: Date): Unit |
65740 | 483 |
def date(res: Result, column: Column): Date |
65006 | 484 |
|
65730 | 485 |
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
|
486 |
|
65006 | 487 |
|
65669 | 488 |
/* tables and views */ |
65006 | 489 |
|
75393 | 490 |
def tables: List[String] = { |
65740 | 491 |
val result = new mutable.ListBuffer[String] |
492 |
val rs = connection.getMetaData.getTables(null, null, "%", null) |
|
493 |
while (rs.next) { result += rs.getString(3) } |
|
494 |
result.toList |
|
495 |
} |
|
65006 | 496 |
|
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
|
497 |
def create_table(table: Table, strict: Boolean = false, sql: Source = ""): Unit = { |
77540 | 498 |
execute_statement(table.create(strict, sql_type) + SQL.separate(sql)) |
77681
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
499 |
if (is_postgresql) { |
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
500 |
for (column <- table.columns if column.T == SQL.Type.Bytes) { |
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
501 |
execute_statement( |
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
502 |
"ALTER TABLE " + table + " ALTER COLUMN " + column + " SET STORAGE EXTERNAL") |
1db732e6c3d2
back to compression in Isabelle/Scala (in contrast to f7174238b5e3), e.g. relevant for old_command_timings_blob, but also for prospective heaps;
wenzelm
parents:
77665
diff
changeset
|
503 |
} |
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
|
504 |
} |
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
|
505 |
} |
65006 | 506 |
|
65018 | 507 |
def create_index(table: Table, name: String, columns: List[Column], |
65280 | 508 |
strict: Boolean = false, unique: Boolean = false): Unit = |
77540 | 509 |
execute_statement(table.create_index(name, columns, strict, unique)) |
65006 | 510 |
|
75393 | 511 |
def create_view(table: Table, strict: Boolean = false): Unit = { |
65691 | 512 |
if (strict || !tables.contains(table.name)) { |
77540 | 513 |
execute_statement("CREATE VIEW " + table + " AS " + { table.query; table.body }) |
65690 | 514 |
} |
65691 | 515 |
} |
65006 | 516 |
} |
63778 | 517 |
} |
65006 | 518 |
|
519 |
||
520 |
||
521 |
/** SQLite **/ |
|
522 |
||
75393 | 523 |
object SQLite { |
65021 | 524 |
// see https://www.sqlite.org/lang_datefunc.html |
525 |
val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x") |
|
526 |
||
75393 | 527 |
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
|
528 |
val lib_path = Path.explode("$ISABELLE_SQLITE_HOME/" + Platform.jvm_platform) |
76529 | 529 |
val lib_name = File.get_file(lib_path).file_name |
530 |
||
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
|
531 |
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
|
532 |
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
|
533 |
|
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
|
534 |
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
|
535 |
} |
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
536 |
|
78163 | 537 |
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
|
538 |
init_jdbc |
65006 | 539 |
val path0 = path.expand |
540 |
val s0 = File.platform_path(path0) |
|
541 |
val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0 |
|
542 |
val connection = DriverManager.getConnection("jdbc:sqlite:" + s1) |
|
78163 | 543 |
val db = new Database(path0.toString, connection) |
544 |
||
545 |
try { if (restrict) File.restrict(path0) } |
|
546 |
catch { case exn: Throwable => db.close(); throw exn } |
|
547 |
||
548 |
db |
|
65006 | 549 |
} |
550 |
||
75393 | 551 |
class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database { |
65007 | 552 |
override def toString: String = name |
77664
f5d3ade80d15
more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents:
77598
diff
changeset
|
553 |
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
554 |
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
|
555 |
|
65730 | 556 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_sqlite(T) |
65011 | 557 |
|
65748 | 558 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
559 |
if (date == null) stmt.string(i) = (null: String) |
|
560 |
else stmt.string(i) = date_format(date) |
|
65598 | 561 |
|
65740 | 562 |
def date(res: SQL.Result, column: SQL.Column): Date = |
77598 | 563 |
proper_string(res.string(column)) match { |
564 |
case None => null |
|
565 |
case Some(s) => date_format.parse(s) |
|
566 |
} |
|
65021 | 567 |
|
65730 | 568 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
77365 | 569 |
table.insert_cmd(cmd = "INSERT OR IGNORE", sql = sql) |
65006 | 570 |
} |
571 |
} |
|
572 |
||
573 |
||
574 |
||
575 |
/** PostgreSQL **/ |
|
576 |
||
78351 | 577 |
// see https://www.postgresql.org/docs/current/index.html |
578 |
// see https://jdbc.postgresql.org/documentation |
|
579 |
||
75393 | 580 |
object PostgreSQL { |
75967
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
581 |
type Source = SQL.Source |
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
582 |
|
78347 | 583 |
lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver") |
584 |
||
78345 | 585 |
val default_server: SSH.Server = SSH.local_server(port = 5432) |
65006 | 586 |
|
78347 | 587 |
def open_database_server( |
588 |
options: Options, |
|
589 |
user: String = "", |
|
590 |
password: String = "", |
|
591 |
database: String = "", |
|
592 |
host: String = "", |
|
593 |
port: Int = 0, |
|
594 |
ssh_host: String = "", |
|
595 |
ssh_port: Int = 0, |
|
596 |
ssh_user: String = "", |
|
597 |
server: SSH.Server = SSH.no_server |
|
598 |
): PostgreSQL.Database = { |
|
599 |
val (db_server, server_close) = |
|
600 |
if (server.defined) (server, false) |
|
601 |
else { |
|
602 |
val server_host = proper_string(host).getOrElse(default_server.host) |
|
603 |
val server_port = if (port > 0) port else default_server.port |
|
604 |
val db_server = |
|
605 |
if (ssh_host.isEmpty) SSH.local_server(host = server_host, port = server_port) |
|
606 |
else { |
|
607 |
SSH.open_server(options, host = ssh_host, port = ssh_port, user = ssh_user, |
|
608 |
remote_host = server_host, remote_port = server_port) |
|
609 |
} |
|
610 |
(db_server, true) |
|
611 |
} |
|
612 |
||
613 |
try { |
|
614 |
open_database(user = user, password = password, database = database, |
|
615 |
server = db_server, server_close = server_close) |
|
616 |
} |
|
617 |
catch { case exn: Throwable => if (server_close) db_server.close(); throw exn } |
|
618 |
} |
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
619 |
|
65006 | 620 |
def open_database( |
621 |
user: String, |
|
622 |
password: String, |
|
623 |
database: String = "", |
|
78347 | 624 |
server: SSH.Server = default_server, |
625 |
server_close: Boolean = false, |
|
75393 | 626 |
): Database = { |
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
627 |
init_jdbc |
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
628 |
|
78347 | 629 |
if (user.isEmpty) error("Undefined database user") |
630 |
if (server.host.isEmpty) error("Undefined database server host") |
|
631 |
if (server.port <= 0) error("Undefined database server port") |
|
65009 | 632 |
|
78347 | 633 |
val name = proper_string(database) getOrElse user |
634 |
val url = "jdbc:postgresql://" + server.host + ":" + server.port + "/" + name |
|
635 |
val ssh = server.ssh_system.ssh_session |
|
636 |
val print = user + "@" + server + "/" + name + if_proper(ssh, " via ssh " + ssh.get) |
|
637 |
||
638 |
val connection = DriverManager.getConnection(url, user, password) |
|
639 |
new Database(connection, print, server, server_close) |
|
65006 | 640 |
} |
641 |
||
65009 | 642 |
class Database private[PostgreSQL]( |
75393 | 643 |
val connection: Connection, |
78347 | 644 |
print: String, |
645 |
server: SSH.Server, |
|
646 |
server_close: Boolean |
|
75393 | 647 |
) extends SQL.Database { |
78347 | 648 |
override def toString: String = print |
65008 | 649 |
|
77527
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
650 |
override def now(): Date = { |
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
651 |
val now = SQL.Column.date("now") |
77552 | 652 |
execute_query_statementO[Date]("SELECT NOW() as " + now.ident, res => res.date(now)) |
653 |
.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
|
654 |
} |
790085b1002f
more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents:
77403
diff
changeset
|
655 |
|
65730 | 656 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_postgresql(T) |
65009 | 657 |
|
65021 | 658 |
// see https://jdbc.postgresql.org/documentation/head/8-date-time.html |
65748 | 659 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
65740 | 660 |
if (date == null) stmt.rep.setObject(i, null) |
69980 | 661 |
else stmt.rep.setObject(i, OffsetDateTime.from(date.to(Date.timezone_utc).rep)) |
65598 | 662 |
|
75393 | 663 |
def date(res: SQL.Result, column: SQL.Column): Date = { |
65740 | 664 |
val obj = res.rep.getObject(column.name, classOf[OffsetDateTime]) |
65704 | 665 |
if (obj == null) null else Date.instant(obj.toInstant) |
666 |
} |
|
65021 | 667 |
|
65730 | 668 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
77377 | 669 |
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
|
670 |
|
77039 | 671 |
|
77590
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
672 |
/* 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
|
673 |
// 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
|
674 |
// 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
|
675 |
|
77596 | 676 |
override def lock_tables(tables: List[SQL.Table]): PostgreSQL.Source = |
78253 | 677 |
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
|
678 |
|
edc96be6b939
explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents:
77552
diff
changeset
|
679 |
|
77039 | 680 |
/* notifications: IPC via database server */ |
681 |
// see https://www.postgresql.org/docs/current/sql-notify.html |
|
682 |
||
683 |
def listen(name: String): Unit = |
|
77541 | 684 |
execute_statement("LISTEN " + SQL.ident(name)) |
77039 | 685 |
|
686 |
def unlisten(name: String = "*"): Unit = |
|
77541 | 687 |
execute_statement("UNLISTEN " + (if (name == "*") name else SQL.ident(name))) |
77039 | 688 |
|
689 |
def notify(name: String, payload: String = ""): Unit = |
|
77543 | 690 |
execute_statement("NOTIFY " + SQL.ident(name) + if_proper(payload, ", " + SQL.string(payload))) |
77039 | 691 |
|
692 |
def get_notifications(): List[PGNotification] = |
|
693 |
the_postgresql_connection.getNotifications() match { |
|
694 |
case null => Nil |
|
695 |
case array => array.toList |
|
696 |
} |
|
697 |
||
698 |
||
78347 | 699 |
override def close(): Unit = { super.close(); if (server_close) server.close() } |
65006 | 700 |
} |
701 |
} |