| author | wenzelm |
| Mon, 13 Feb 2023 10:49:33 +0100 | |
| changeset 77287 | d060545f01a2 |
| parent 77039 | 2f09dc0e6dda |
| child 77346 | cf2ef4be3630 |
| permissions | -rw-r--r-- |
| 63788 | 1 |
/* Title: Pure/General/sql.scala |
| 63778 | 2 |
Author: Makarius |
3 |
||
| 65006 | 4 |
Support for SQL databases: SQLite and PostgreSQL. |
| 63778 | 5 |
*/ |
6 |
||
7 |
package isabelle |
|
8 |
||
|
69393
ed0824ef337e
static type for Library.using: avoid Java 11 warnings on "Illegal reflective access";
wenzelm
parents:
69327
diff
changeset
|
9 |
|
| 65021 | 10 |
import java.time.OffsetDateTime |
11 |
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet}
|
|
| 63779 | 12 |
|
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
13 |
import org.sqlite.jdbc4.JDBC4Connection |
| 77039 | 14 |
import org.postgresql.{PGConnection, PGNotification}
|
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
15 |
|
| 65740 | 16 |
import scala.collection.mutable |
17 |
||
| 63779 | 18 |
|
| 75393 | 19 |
object SQL {
|
| 65006 | 20 |
/** SQL language **/ |
21 |
||
| 65730 | 22 |
type Source = String |
23 |
||
24 |
||
| 63778 | 25 |
/* concrete syntax */ |
26 |
||
| 65321 | 27 |
def escape_char(c: Char): String = |
| 63778 | 28 |
c match {
|
29 |
case '\u0000' => "\\0" |
|
30 |
case '\'' => "\\'" |
|
31 |
case '\"' => "\\\"" |
|
32 |
case '\b' => "\\b" |
|
33 |
case '\n' => "\\n" |
|
34 |
case '\r' => "\\r" |
|
35 |
case '\t' => "\\t" |
|
36 |
case '\u001a' => "\\Z" |
|
37 |
case '\\' => "\\\\" |
|
38 |
case _ => c.toString |
|
39 |
} |
|
40 |
||
| 65730 | 41 |
def string(s: String): Source = |
| 71601 | 42 |
s.iterator.map(escape_char).mkString("'", "", "'")
|
| 63778 | 43 |
|
| 65730 | 44 |
def ident(s: String): Source = |
|
65677
7d25b8dbdbfa
proper quote (amending 546020a98a91): e.g. relevant for "ISABELLE_BUILD_OPTIONS";
wenzelm
parents:
65673
diff
changeset
|
45 |
Long_Name.implode(Long_Name.explode(s).map(a => quote(a.replace("\"", "\"\""))))
|
| 63779 | 46 |
|
| 65730 | 47 |
def enclose(s: Source): Source = "(" + s + ")"
|
48 |
def enclosure(ss: Iterable[Source]): Source = ss.mkString("(", ", ", ")")
|
|
| 63791 | 49 |
|
| 65774 | 50 |
def select(columns: List[Column] = Nil, distinct: Boolean = false): Source = |
51 |
"SELECT " + (if (distinct) "DISTINCT " else "") + |
|
52 |
(if (columns.isEmpty) "*" else commas(columns.map(_.ident))) + " FROM " |
|
|
65644
7ef438495a02
support for qualified names, which are not quoted (e.g. for SQLite);
wenzelm
parents:
65641
diff
changeset
|
53 |
|
| 65775 | 54 |
val join_outer: Source = " LEFT OUTER JOIN " |
55 |
val join_inner: Source = " INNER JOIN " |
|
| 65776 | 56 |
def join(outer: Boolean): Source = if (outer) join_outer else join_inner |
| 65775 | 57 |
|
| 65804 | 58 |
def member(x: Source, set: Iterable[String]): Source = |
59 |
set.iterator.map(a => x + " = " + SQL.string(a)).mkString("(", " OR ", ")")
|
|
60 |
||
| 63779 | 61 |
|
| 65008 | 62 |
/* types */ |
63 |
||
| 75393 | 64 |
object Type extends Enumeration {
|
| 65011 | 65 |
val Boolean = Value("BOOLEAN")
|
| 65008 | 66 |
val Int = Value("INTEGER")
|
67 |
val Long = Value("BIGINT")
|
|
68 |
val Double = Value("DOUBLE PRECISION")
|
|
69 |
val String = Value("TEXT")
|
|
70 |
val Bytes = Value("BLOB")
|
|
| 65014 | 71 |
val Date = Value("TIMESTAMP WITH TIME ZONE")
|
| 65008 | 72 |
} |
73 |
||
| 65730 | 74 |
def sql_type_default(T: Type.Value): Source = T.toString |
| 65013 | 75 |
|
| 65730 | 76 |
def sql_type_sqlite(T: Type.Value): Source = |
| 65019 | 77 |
if (T == Type.Boolean) "INTEGER" |
78 |
else if (T == Type.Date) "TEXT" |
|
79 |
else sql_type_default(T) |
|
| 65013 | 80 |
|
| 65730 | 81 |
def sql_type_postgresql(T: Type.Value): Source = |
| 65019 | 82 |
if (T == Type.Bytes) "BYTEA" |
83 |
else sql_type_default(T) |
|
| 65008 | 84 |
|
85 |
||
| 63779 | 86 |
/* columns */ |
87 |
||
| 75393 | 88 |
object Column {
|
| 65280 | 89 |
def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 90 |
Column(name, Type.Boolean, strict, primary_key) |
| 65280 | 91 |
def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 92 |
Column(name, Type.Int, strict, primary_key) |
| 65280 | 93 |
def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 94 |
Column(name, Type.Long, strict, primary_key) |
| 65280 | 95 |
def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 96 |
Column(name, Type.Double, strict, primary_key) |
| 65280 | 97 |
def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 98 |
Column(name, Type.String, strict, primary_key) |
| 65280 | 99 |
def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 100 |
Column(name, Type.Bytes, strict, primary_key) |
| 65280 | 101 |
def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column = |
| 65018 | 102 |
Column(name, Type.Date, strict, primary_key) |
| 63779 | 103 |
} |
104 |
||
| 65018 | 105 |
sealed case class Column( |
| 75393 | 106 |
name: String, |
107 |
T: Type.Value, |
|
108 |
strict: Boolean = false, |
|
109 |
primary_key: Boolean = false, |
|
110 |
expr: SQL.Source = "" |
|
111 |
) {
|
|
| 66857 | 112 |
def make_primary_key: Column = copy(primary_key = true) |
113 |
||
| 65691 | 114 |
def apply(table: Table): Column = |
115 |
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
|
116 |
|
| 65780 | 117 |
def ident: Source = |
118 |
if (expr == "") SQL.ident(name) |
|
119 |
else enclose(expr) + " AS " + SQL.ident(name) |
|
| 65695 | 120 |
|
| 65730 | 121 |
def decl(sql_type: Type.Value => Source): Source = |
| 65695 | 122 |
ident + " " + sql_type(T) + (if (strict || primary_key) " NOT NULL" else "") |
| 63781 | 123 |
|
| 66856 | 124 |
def defined: String = ident + " IS NOT NULL" |
125 |
def undefined: String = ident + " IS NULL" |
|
126 |
||
| 68091 | 127 |
def equal(s: String): Source = ident + " = " + string(s) |
128 |
def where_equal(s: String): Source = "WHERE " + equal(s) |
|
| 65593 | 129 |
|
| 65730 | 130 |
override def toString: Source = ident |
| 63779 | 131 |
} |
132 |
||
| 76870 | 133 |
def order_by(columns: List[Column], descending: Boolean = false): Source = |
134 |
" ORDER BY " + columns.mkString(", ") + (if (descending) " DESC" else "")
|
|
135 |
||
| 63780 | 136 |
|
137 |
/* tables */ |
|
138 |
||
| 75393 | 139 |
sealed case class Table(name: String, columns: List[Column], body: Source = "") {
|
| 63781 | 140 |
Library.duplicates(columns.map(_.name)) match {
|
141 |
case Nil => |
|
142 |
case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name))
|
|
143 |
} |
|
144 |
||
| 65730 | 145 |
def ident: Source = SQL.ident(name) |
| 65691 | 146 |
|
| 65730 | 147 |
def query: Source = |
| 65696 | 148 |
if (body == "") error("Missing SQL body for table " + quote(name))
|
149 |
else SQL.enclose(body) |
|
| 65649 | 150 |
|
| 65778 | 151 |
def query_named: Source = query + " AS " + SQL.ident(name) |
| 65702 | 152 |
|
| 75966 | 153 |
def create(strict: Boolean, sql_type: Type.Value => Source): Source = {
|
| 65325 | 154 |
val primary_key = |
155 |
columns.filter(_.primary_key).map(_.name) match {
|
|
156 |
case Nil => Nil |
|
157 |
case keys => List("PRIMARY KEY " + enclosure(keys))
|
|
158 |
} |
|
| 65701 | 159 |
"CREATE TABLE " + (if (strict) "" else "IF NOT EXISTS ") + |
160 |
ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key) |
|
| 63781 | 161 |
} |
162 |
||
| 65698 | 163 |
def create_index(index_name: String, index_columns: List[Column], |
| 65730 | 164 |
strict: Boolean = false, unique: Boolean = false): Source = |
| 63791 | 165 |
"CREATE " + (if (unique) "UNIQUE " else "") + "INDEX " + |
| 65695 | 166 |
(if (strict) "" else "IF NOT EXISTS ") + SQL.ident(index_name) + " ON " + |
167 |
ident + " " + enclosure(index_columns.map(_.name)) |
|
| 63791 | 168 |
|
| 65730 | 169 |
def insert_cmd(cmd: Source, sql: Source = ""): Source = |
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
170 |
cmd + " INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) + |
| 65698 | 171 |
(if (sql == "") "" else " " + sql) |
| 63791 | 172 |
|
| 65730 | 173 |
def insert(sql: Source = ""): Source = insert_cmd("INSERT", sql)
|
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
174 |
|
| 65730 | 175 |
def delete(sql: Source = ""): Source = |
| 65698 | 176 |
"DELETE FROM " + ident + |
177 |
(if (sql == "") "" else " " + sql) |
|
| 65319 | 178 |
|
| 65774 | 179 |
def select( |
180 |
select_columns: List[Column] = Nil, sql: Source = "", distinct: Boolean = false): Source = |
|
| 65698 | 181 |
SQL.select(select_columns, distinct = distinct) + ident + |
182 |
(if (sql == "") "" else " " + sql) |
|
| 63790 | 183 |
|
| 65730 | 184 |
override def toString: Source = ident |
| 63780 | 185 |
} |
| 63790 | 186 |
|
187 |
||
| 65012 | 188 |
|
189 |
/** SQL database operations **/ |
|
190 |
||
| 65740 | 191 |
/* statements */ |
192 |
||
| 75393 | 193 |
class Statement private[SQL](val db: Database, val rep: PreparedStatement) extends AutoCloseable {
|
| 65740 | 194 |
stmt => |
195 |
||
| 75393 | 196 |
object bool {
|
| 73340 | 197 |
def update(i: Int, x: Boolean): Unit = rep.setBoolean(i, x) |
| 75393 | 198 |
def update(i: Int, x: Option[Boolean]): Unit = {
|
| 65748 | 199 |
if (x.isDefined) update(i, x.get) |
200 |
else rep.setNull(i, java.sql.Types.BOOLEAN) |
|
201 |
} |
|
| 65740 | 202 |
} |
| 75393 | 203 |
object int {
|
| 73340 | 204 |
def update(i: Int, x: Int): Unit = rep.setInt(i, x) |
| 75393 | 205 |
def update(i: Int, x: Option[Int]): Unit = {
|
| 65748 | 206 |
if (x.isDefined) update(i, x.get) |
207 |
else rep.setNull(i, java.sql.Types.INTEGER) |
|
208 |
} |
|
| 65740 | 209 |
} |
| 75393 | 210 |
object long {
|
| 73340 | 211 |
def update(i: Int, x: Long): Unit = rep.setLong(i, x) |
| 75393 | 212 |
def update(i: Int, x: Option[Long]): Unit = {
|
| 65748 | 213 |
if (x.isDefined) update(i, x.get) |
214 |
else rep.setNull(i, java.sql.Types.BIGINT) |
|
215 |
} |
|
| 65740 | 216 |
} |
| 75393 | 217 |
object double {
|
| 73340 | 218 |
def update(i: Int, x: Double): Unit = rep.setDouble(i, x) |
| 75393 | 219 |
def update(i: Int, x: Option[Double]): Unit = {
|
| 65748 | 220 |
if (x.isDefined) update(i, x.get) |
221 |
else rep.setNull(i, java.sql.Types.DOUBLE) |
|
222 |
} |
|
223 |
} |
|
| 75393 | 224 |
object string {
|
| 73340 | 225 |
def update(i: Int, x: String): Unit = rep.setString(i, x) |
| 65748 | 226 |
def update(i: Int, x: Option[String]): Unit = update(i, x.orNull) |
| 65740 | 227 |
} |
| 75393 | 228 |
object bytes {
|
229 |
def update(i: Int, bytes: Bytes): Unit = {
|
|
| 65748 | 230 |
if (bytes == null) rep.setBytes(i, null) |
231 |
else rep.setBinaryStream(i, bytes.stream(), bytes.length) |
|
232 |
} |
|
233 |
def update(i: Int, bytes: Option[Bytes]): Unit = update(i, bytes.orNull) |
|
| 65740 | 234 |
} |
| 75393 | 235 |
object date {
|
| 65748 | 236 |
def update(i: Int, date: Date): Unit = db.update_date(stmt, i, date) |
237 |
def update(i: Int, date: Option[Date]): Unit = update(i, date.orNull) |
|
238 |
} |
|
| 65740 | 239 |
|
240 |
def execute(): Boolean = rep.execute() |
|
241 |
def execute_query(): Result = new Result(this, rep.executeQuery()) |
|
242 |
||
| 73367 | 243 |
def close(): Unit = rep.close() |
| 65740 | 244 |
} |
245 |
||
246 |
||
| 63790 | 247 |
/* results */ |
248 |
||
| 75393 | 249 |
class Result private[SQL](val stmt: Statement, val rep: ResultSet) {
|
| 65740 | 250 |
res => |
251 |
||
252 |
def next(): Boolean = rep.next() |
|
253 |
||
| 75393 | 254 |
def iterator[A](get: Result => A): Iterator[A] = new Iterator[A] {
|
| 65740 | 255 |
private var _next: Boolean = res.next() |
256 |
def hasNext: Boolean = _next |
|
| 73337 | 257 |
def next(): A = { val x = get(res); _next = res.next(); x }
|
| 65740 | 258 |
} |
259 |
||
260 |
def bool(column: Column): Boolean = rep.getBoolean(column.name) |
|
261 |
def int(column: Column): Int = rep.getInt(column.name) |
|
262 |
def long(column: Column): Long = rep.getLong(column.name) |
|
263 |
def double(column: Column): Double = rep.getDouble(column.name) |
|
| 75393 | 264 |
def string(column: Column): String = {
|
| 65740 | 265 |
val s = rep.getString(column.name) |
266 |
if (s == null) "" else s |
|
267 |
} |
|
| 75393 | 268 |
def bytes(column: Column): Bytes = {
|
| 65740 | 269 |
val bs = rep.getBytes(column.name) |
270 |
if (bs == null) Bytes.empty else Bytes(bs) |
|
271 |
} |
|
272 |
def date(column: Column): Date = stmt.db.date(res, column) |
|
273 |
||
| 71601 | 274 |
def timing(c1: Column, c2: Column, c3: Column): Timing = |
| 65741 | 275 |
Timing(Time.ms(long(c1)), Time.ms(long(c2)), Time.ms(long(c3))) |
276 |
||
| 75393 | 277 |
def get[A](column: Column, f: Column => A): Option[A] = {
|
| 65740 | 278 |
val x = f(column) |
279 |
if (rep.wasNull) None else Some(x) |
|
280 |
} |
|
| 71601 | 281 |
def get_bool(column: Column): Option[Boolean] = get(column, bool) |
282 |
def get_int(column: Column): Option[Int] = get(column, int) |
|
283 |
def get_long(column: Column): Option[Long] = get(column, long) |
|
284 |
def get_double(column: Column): Option[Double] = get(column, double) |
|
285 |
def get_string(column: Column): Option[String] = get(column, string) |
|
286 |
def get_bytes(column: Column): Option[Bytes] = get(column, bytes) |
|
287 |
def get_date(column: Column): Option[Date] = get(column, date) |
|
| 63790 | 288 |
} |
| 65006 | 289 |
|
| 65740 | 290 |
|
291 |
/* database */ |
|
292 |
||
| 75393 | 293 |
trait Database extends AutoCloseable {
|
| 65740 | 294 |
db => |
295 |
||
|
76363
f7174238b5e3
no compression for database server: let PostgreSQL/TOAST do the job;
wenzelm
parents:
76122
diff
changeset
|
296 |
def is_server: Boolean |
|
f7174238b5e3
no compression for database server: let PostgreSQL/TOAST do the job;
wenzelm
parents:
76122
diff
changeset
|
297 |
|
| 65740 | 298 |
|
| 65008 | 299 |
/* types */ |
300 |
||
| 65730 | 301 |
def sql_type(T: Type.Value): Source |
| 65008 | 302 |
|
303 |
||
| 65006 | 304 |
/* connection */ |
305 |
||
306 |
def connection: Connection |
|
307 |
||
|
77037
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
308 |
def sqlite_connection: Option[JDBC4Connection] = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
309 |
connection match { case conn: JDBC4Connection => Some(conn) case _ => None }
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
310 |
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
311 |
def postgresql_connection: Option[PGConnection] = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
312 |
connection match { case conn: PGConnection => Some(conn) case _ => None }
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
313 |
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
314 |
def the_sqlite_connection: JDBC4Connection = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
315 |
sqlite_connection getOrElse |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
316 |
error("SQLite connection expected, but found " + connection.getClass.getName)
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
317 |
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
318 |
def the_postgresql_connection: PGConnection = |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
319 |
postgresql_connection getOrElse |
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
320 |
error("PostgreSQL connection expected, but found " + connection.getClass.getName)
|
|
164a21e5d568
support specific connection types, for additional operations;
wenzelm
parents:
76870
diff
changeset
|
321 |
|
| 73367 | 322 |
def close(): Unit = connection.close() |
| 65006 | 323 |
|
| 75393 | 324 |
def transaction[A](body: => A): A = {
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
325 |
val auto_commit = connection.getAutoCommit() |
| 65006 | 326 |
try {
|
327 |
connection.setAutoCommit(false) |
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
328 |
val savepoint = connection.setSavepoint() |
| 65022 | 329 |
try {
|
330 |
val result = body |
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
331 |
connection.commit() |
| 65022 | 332 |
result |
333 |
} |
|
334 |
catch { case exn: Throwable => connection.rollback(savepoint); throw exn }
|
|
| 65006 | 335 |
} |
336 |
finally { connection.setAutoCommit(auto_commit) }
|
|
337 |
} |
|
338 |
||
339 |
||
| 65740 | 340 |
/* statements and results */ |
341 |
||
342 |
def statement(sql: Source): Statement = |
|
343 |
new Statement(db, connection.prepareStatement(sql)) |
|
| 65006 | 344 |
|
| 65740 | 345 |
def using_statement[A](sql: Source)(f: Statement => A): A = |
346 |
using(statement(sql))(f) |
|
| 65006 | 347 |
|
| 65748 | 348 |
def update_date(stmt: Statement, i: Int, date: Date): Unit |
| 65740 | 349 |
def date(res: Result, column: Column): Date |
| 65006 | 350 |
|
| 65730 | 351 |
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
|
352 |
|
| 65006 | 353 |
|
| 65669 | 354 |
/* tables and views */ |
| 65006 | 355 |
|
| 75393 | 356 |
def tables: List[String] = {
|
| 65740 | 357 |
val result = new mutable.ListBuffer[String] |
358 |
val rs = connection.getMetaData.getTables(null, null, "%", null) |
|
359 |
while (rs.next) { result += rs.getString(3) }
|
|
360 |
result.toList |
|
361 |
} |
|
| 65006 | 362 |
|
| 65730 | 363 |
def create_table(table: Table, strict: Boolean = false, sql: Source = ""): Unit = |
| 65698 | 364 |
using_statement( |
365 |
table.create(strict, sql_type) + (if (sql == "") "" else " " + sql))(_.execute()) |
|
| 65006 | 366 |
|
| 65018 | 367 |
def create_index(table: Table, name: String, columns: List[Column], |
| 65280 | 368 |
strict: Boolean = false, unique: Boolean = false): Unit = |
| 65698 | 369 |
using_statement(table.create_index(name, columns, strict, unique))(_.execute()) |
| 65006 | 370 |
|
| 75393 | 371 |
def create_view(table: Table, strict: Boolean = false): Unit = {
|
| 65691 | 372 |
if (strict || !tables.contains(table.name)) {
|
| 65731 | 373 |
val sql = "CREATE VIEW " + table + " AS " + { table.query; table.body }
|
| 65698 | 374 |
using_statement(sql)(_.execute()) |
| 65690 | 375 |
} |
| 65691 | 376 |
} |
| 65006 | 377 |
} |
| 63778 | 378 |
} |
| 65006 | 379 |
|
380 |
||
381 |
||
382 |
/** SQLite **/ |
|
383 |
||
| 75393 | 384 |
object SQLite {
|
| 65021 | 385 |
// see https://www.sqlite.org/lang_datefunc.html |
386 |
val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x")
|
|
387 |
||
| 75393 | 388 |
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
|
389 |
val lib_path = Path.explode("$ISABELLE_SQLITE_HOME/" + Platform.jvm_platform)
|
| 76529 | 390 |
val lib_name = File.get_file(lib_path).file_name |
391 |
||
|
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
|
392 |
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
|
393 |
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
|
394 |
|
|
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
|
395 |
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
|
396 |
} |
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
397 |
|
| 75393 | 398 |
def open_database(path: Path): Database = {
|
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
399 |
init_jdbc |
| 65006 | 400 |
val path0 = path.expand |
401 |
val s0 = File.platform_path(path0) |
|
402 |
val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
|
|
403 |
val connection = DriverManager.getConnection("jdbc:sqlite:" + s1)
|
|
| 65007 | 404 |
new Database(path0.toString, connection) |
| 65006 | 405 |
} |
406 |
||
| 75393 | 407 |
class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database {
|
| 65007 | 408 |
override def toString: String = name |
|
76363
f7174238b5e3
no compression for database server: let PostgreSQL/TOAST do the job;
wenzelm
parents:
76122
diff
changeset
|
409 |
override def is_server: Boolean = false |
| 65006 | 410 |
|
| 65730 | 411 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_sqlite(T) |
| 65011 | 412 |
|
| 65748 | 413 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
414 |
if (date == null) stmt.string(i) = (null: String) |
|
415 |
else stmt.string(i) = date_format(date) |
|
| 65598 | 416 |
|
| 65740 | 417 |
def date(res: SQL.Result, column: SQL.Column): Date = |
418 |
date_format.parse(res.string(column)) |
|
| 65021 | 419 |
|
| 65730 | 420 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
421 |
table.insert_cmd("INSERT OR IGNORE", sql = sql)
|
|
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
422 |
|
|
75776
72e77c8307ec
tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents:
75393
diff
changeset
|
423 |
def rebuild(): Unit = using_statement("VACUUM")(_.execute())
|
| 65006 | 424 |
} |
425 |
} |
|
426 |
||
427 |
||
428 |
||
429 |
/** PostgreSQL **/ |
|
430 |
||
| 75393 | 431 |
object PostgreSQL {
|
|
75967
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
432 |
type Source = SQL.Source |
|
ff164add75cd
maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents:
75966
diff
changeset
|
433 |
|
| 65006 | 434 |
val default_port = 5432 |
435 |
||
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
436 |
lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver")
|
|
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
437 |
|
| 65006 | 438 |
def open_database( |
439 |
user: String, |
|
440 |
password: String, |
|
441 |
database: String = "", |
|
442 |
host: String = "", |
|
| 65594 | 443 |
port: Int = 0, |
|
65636
df804cdba5f9
ssh_close for proper termination after use of database;
wenzelm
parents:
65620
diff
changeset
|
444 |
ssh: Option[SSH.Session] = None, |
| 75393 | 445 |
ssh_close: Boolean = false |
446 |
): Database = {
|
|
|
65292
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
447 |
init_jdbc |
|
e3bd1e7ddd23
more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents:
65280
diff
changeset
|
448 |
|
| 65641 | 449 |
if (user == "") error("Undefined database user")
|
| 65009 | 450 |
|
| 65717 | 451 |
val db_host = proper_string(host) getOrElse "localhost" |
| 65594 | 452 |
val db_port = if (port > 0 && port != default_port) ":" + port else "" |
| 65717 | 453 |
val db_name = "/" + (proper_string(database) getOrElse user) |
| 65009 | 454 |
|
| 65010 | 455 |
val (url, name, port_forwarding) = |
| 65009 | 456 |
ssh match {
|
| 65010 | 457 |
case None => |
458 |
val spec = db_host + db_port + db_name |
|
459 |
val url = "jdbc:postgresql://" + spec |
|
460 |
val name = user + "@" + spec |
|
461 |
(url, name, None) |
|
| 65009 | 462 |
case Some(ssh) => |
| 65594 | 463 |
val fw = |
464 |
ssh.port_forwarding(remote_host = db_host, |
|
|
65636
df804cdba5f9
ssh_close for proper termination after use of database;
wenzelm
parents:
65620
diff
changeset
|
465 |
remote_port = if (port > 0) port else default_port, |
|
df804cdba5f9
ssh_close for proper termination after use of database;
wenzelm
parents:
65620
diff
changeset
|
466 |
ssh_close = ssh_close) |
|
76122
b8f26c20d3b1
ssh client via regular OpenSSH tools, with authentic use of .ssh/config (notably proxy configuration);
wenzelm
parents:
75967
diff
changeset
|
467 |
val url = "jdbc:postgresql://localhost:" + fw.port + db_name |
| 65010 | 468 |
val name = user + "@" + fw + db_name + " via ssh " + ssh |
469 |
(url, name, Some(fw)) |
|
| 65009 | 470 |
} |
471 |
try {
|
|
| 65010 | 472 |
val connection = DriverManager.getConnection(url, user, password) |
473 |
new Database(name, connection, port_forwarding) |
|
| 65009 | 474 |
} |
| 73367 | 475 |
catch { case exn: Throwable => port_forwarding.foreach(_.close()); throw exn }
|
| 65006 | 476 |
} |
477 |
||
| 65009 | 478 |
class Database private[PostgreSQL]( |
| 75393 | 479 |
name: String, |
480 |
val connection: Connection, |
|
481 |
port_forwarding: Option[SSH.Port_Forwarding] |
|
482 |
) extends SQL.Database {
|
|
| 65010 | 483 |
override def toString: String = name |
|
76363
f7174238b5e3
no compression for database server: let PostgreSQL/TOAST do the job;
wenzelm
parents:
76122
diff
changeset
|
484 |
override def is_server: Boolean = true |
| 65008 | 485 |
|
| 65730 | 486 |
def sql_type(T: SQL.Type.Value): SQL.Source = SQL.sql_type_postgresql(T) |
| 65009 | 487 |
|
| 65021 | 488 |
// see https://jdbc.postgresql.org/documentation/head/8-date-time.html |
| 65748 | 489 |
def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit = |
| 65740 | 490 |
if (date == null) stmt.rep.setObject(i, null) |
| 69980 | 491 |
else stmt.rep.setObject(i, OffsetDateTime.from(date.to(Date.timezone_utc).rep)) |
| 65598 | 492 |
|
| 75393 | 493 |
def date(res: SQL.Result, column: SQL.Column): Date = {
|
| 65740 | 494 |
val obj = res.rep.getObject(column.name, classOf[OffsetDateTime]) |
| 65704 | 495 |
if (obj == null) null else Date.instant(obj.toInstant) |
496 |
} |
|
| 65021 | 497 |
|
| 65730 | 498 |
def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source = |
|
65703
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
499 |
table.insert_cmd("INSERT",
|
|
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
500 |
sql = sql + (if (sql == "") "" else " ") + "ON CONFLICT DO NOTHING") |
|
cead65c19f2e
more direct insert_permissive statement, which avoids somewhat fragile nested transactions;
wenzelm
parents:
65702
diff
changeset
|
501 |
|
| 77039 | 502 |
|
503 |
/* notifications: IPC via database server */ |
|
504 |
// see https://www.postgresql.org/docs/current/sql-notify.html |
|
505 |
||
506 |
def listen(name: String): Unit = |
|
507 |
using_statement("LISTEN " + SQL.ident(name))(_.execute())
|
|
508 |
||
509 |
def unlisten(name: String = "*"): Unit = |
|
510 |
using_statement("UNLISTEN " + (if (name == "*") name else SQL.ident(name)))(_.execute())
|
|
511 |
||
512 |
def notify(name: String, payload: String = ""): Unit = |
|
513 |
using_statement( |
|
514 |
"NOTIFY " + SQL.ident(name) + |
|
515 |
(if (payload.isEmpty) "" else ", " + SQL.string(payload)))(_.execute()) |
|
516 |
||
517 |
def get_notifications(): List[PGNotification] = |
|
518 |
the_postgresql_connection.getNotifications() match {
|
|
519 |
case null => Nil |
|
520 |
case array => array.toList |
|
521 |
} |
|
522 |
||
523 |
||
| 73367 | 524 |
override def close(): Unit = { super.close(); port_forwarding.foreach(_.close()) }
|
| 65006 | 525 |
} |
526 |
} |