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