src/Pure/General/sql.scala
author wenzelm
Thu, 04 Apr 2024 11:40:45 +0200
changeset 80083 e2174bf626b8
parent 80082 4f9e4527a4e3
child 80357 fe123d033e76
permissions -rw-r--r--
more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
63788
3160826b92f8 clarified modules;
wenzelm
parents: 63784
diff changeset
     1
/*  Title:      Pure/General/sql.scala
63778
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
     2
    Author:     Makarius
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
     3
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
     4
Support for SQL databases: SQLite and PostgreSQL.
78351
9f2cfb9873bb tuned comments;
wenzelm
parents: 78348
diff changeset
     5
79724
54d0f6edfe3a clarified versions for documentation;
wenzelm
parents: 79722
diff changeset
     6
See https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/Connection.html
63778
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
     7
*/
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
     8
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
     9
package isabelle
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
    10
69393
ed0824ef337e static type for Library.using: avoid Java 11 warnings on "Illegal reflective access";
wenzelm
parents: 69327
diff changeset
    11
65021
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
    12
import java.time.OffsetDateTime
78538
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
    13
import java.sql.{DriverManager, Connection, PreparedStatement, ResultSet, SQLException}
63779
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
    14
78891
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    15
import org.sqlite.SQLiteConfig
77037
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
    16
import org.sqlite.jdbc4.JDBC4Connection
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
    17
import org.postgresql.PGConnection
77037
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
    18
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
    19
import scala.collection.mutable
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
    20
63779
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
    21
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
    22
object SQL {
78547
7f564f33172b tuned messages;
wenzelm
parents: 78544
diff changeset
    23
  lazy val time_start = Time.now()
7f564f33172b tuned messages;
wenzelm
parents: 78544
diff changeset
    24
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
    25
  /** SQL language **/
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
    26
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
    27
  type Source = String
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
    28
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
    29
63778
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
    30
  /* concrete syntax */
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
    31
78891
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    32
  def string(s: String): Source = {
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    33
    val q = '\''
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    34
    val result = new StringBuilder(s.length + 10)
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    35
    result += q
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    36
    for (c <- s.iterator) {
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    37
      if (c == '\u0000') error("Illegal NUL character in SQL string literal")
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    38
      if (c == q) result += q
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    39
      result += c
63778
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
    40
    }
78891
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    41
    result += q
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    42
    result.toString
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
    43
  }
63778
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
    44
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
    45
  def ident(s: String): Source =
65677
7d25b8dbdbfa proper quote (amending 546020a98a91): e.g. relevant for "ISABELLE_BUILD_OPTIONS";
wenzelm
parents: 65673
diff changeset
    46
    Long_Name.implode(Long_Name.explode(s).map(a => quote(a.replace("\"", "\"\""))))
63779
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
    47
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
    48
  def enclose(s: Source): Source = "(" + s + ")"
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
    49
  def enclosure(ss: Iterable[Source]): Source = ss.mkString("(", ", ", ")")
63791
c6cbdfaae19e more operations;
wenzelm
parents: 63790
diff changeset
    50
77381
a86e346b20d8 misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents: 77377
diff changeset
    51
  def separate(sql: Source): Source =
79858
ee4864e17c11 tuned: prefer if_proper expression;
wenzelm
parents: 79854
diff changeset
    52
    if_proper(sql.nonEmpty && sql(0) != ' ', " ") + sql
77381
a86e346b20d8 misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents: 77377
diff changeset
    53
77403
be8e14c7da80 clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents: 77381
diff changeset
    54
  def select(columns: List[Column] = Nil, distinct: Boolean = false, sql: Source = ""): Source =
79858
ee4864e17c11 tuned: prefer if_proper expression;
wenzelm
parents: 79854
diff changeset
    55
    "SELECT " + if_proper(distinct, "DISTINCT ") +
77403
be8e14c7da80 clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents: 77381
diff changeset
    56
    (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
    57
65775
123f2c0995b8 tuned signature;
wenzelm
parents: 65774
diff changeset
    58
  val join_outer: Source = " LEFT OUTER JOIN "
123f2c0995b8 tuned signature;
wenzelm
parents: 65774
diff changeset
    59
  val join_inner: Source = " INNER JOIN "
123f2c0995b8 tuned signature;
wenzelm
parents: 65774
diff changeset
    60
78544
3be0437759cf more operations;
wenzelm
parents: 78540
diff changeset
    61
  def MULTI(args: Iterable[Source]): Source =
3be0437759cf more operations;
wenzelm
parents: 78540
diff changeset
    62
    args.iterator.filter(_.nonEmpty).mkString(";\n")
3be0437759cf more operations;
wenzelm
parents: 78540
diff changeset
    63
  def multi(args: Source*): Source = MULTI(args)
3be0437759cf more operations;
wenzelm
parents: 78540
diff changeset
    64
77370
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    65
  def infix(op: Source, args: Iterable[Source]): Source = {
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    66
    val body = args.iterator.filter(_.nonEmpty).mkString(" " + op + " ")
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    67
    if_proper(body, enclose(body))
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    68
  }
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    69
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    70
  def AND(args: Iterable[Source]): Source = infix("AND", args)
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    71
  def OR(args: Iterable[Source]): Source = infix("OR", args)
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    72
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    73
  def and(args: Source*): Source = AND(args)
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    74
  def or(args: Source*): Source = OR(args)
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    75
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    76
  val TRUE: Source = "TRUE"
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    77
  val FALSE: Source = "FALSE"
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    78
78152
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
    79
  def equal(sql: Source, x: Int): Source = sql + " = " + x
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
    80
  def equal(sql: Source, x: Long): Source = sql + " = " + x
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
    81
  def equal(sql: Source, x: String): Source = sql + " = " + string(x)
77375
324f5821a4a4 clarified signature: more concise operations;
wenzelm
parents: 77370
diff changeset
    82
79849
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
    83
  def member_int(sql: Source, set: Iterable[Int]): Source =
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
    84
    if (set.isEmpty) FALSE else OR(set.iterator.map(equal(sql, _)).toList)
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
    85
  def member_long(sql: Source, set: Iterable[Long]): Source =
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
    86
    if (set.isEmpty) FALSE else OR(set.iterator.map(equal(sql, _)).toList)
77375
324f5821a4a4 clarified signature: more concise operations;
wenzelm
parents: 77370
diff changeset
    87
  def member(sql: Source, set: Iterable[String]): Source =
79849
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
    88
    if (set.isEmpty) FALSE else OR(set.iterator.map(equal(sql, _)).toList)
65804
wenzelm
parents: 65780
diff changeset
    89
77370
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    90
  def where(sql: Source): Source = if_proper(sql, " WHERE " + sql)
78153
55a6aa77f3d8 tuned signature: more operations;
wenzelm
parents: 78152
diff changeset
    91
  def where_and(args: Source*): Source = where(and(args:_*))
55a6aa77f3d8 tuned signature: more operations;
wenzelm
parents: 78152
diff changeset
    92
  def where_or(args: Source*): Source = where(or(args:_*))
77370
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    93
47c2ac81ddd4 clarified signature: more robust operations;
wenzelm
parents: 77368
diff changeset
    94
65008
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
    95
  /* types */
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
    96
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
    97
  enum Type { case Boolean, Int, Long, Double, String, Bytes, Date }
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
    98
78607
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
    99
  val sql_type_postgresql: Type => Source =
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   100
    {
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   101
      case Type.Boolean => "BOOLEAN"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   102
      case Type.Int => "INTEGER"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   103
      case Type.Long => "BIGINT"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   104
      case Type.Double => "DOUBLE PRECISION"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   105
      case Type.String => "TEXT"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   106
      case Type.Bytes => "BYTEA"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   107
      case Type.Date => "TIMESTAMP WITH TIME ZONE"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   108
    }
65008
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   109
78607
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   110
  val sql_type_sqlite: Type => Source =
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   111
    {
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   112
      case Type.Boolean => "INTEGER"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   113
      case Type.Bytes => "BLOB"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   114
      case Type.Date => "TEXT"
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   115
      case t => sql_type_postgresql(t)
3f3add5eef91 tuned indentation;
wenzelm
parents: 78598
diff changeset
   116
    }
65008
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   117
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   118
63779
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
   119
  /* columns */
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
   120
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   121
  object Column {
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   122
    def bool(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   123
      Column(name, Type.Boolean, strict, primary_key)
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   124
    def int(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   125
      Column(name, Type.Int, strict, primary_key)
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   126
    def long(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   127
      Column(name, Type.Long, strict, primary_key)
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   128
    def double(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   129
      Column(name, Type.Double, strict, primary_key)
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   130
    def string(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   131
      Column(name, Type.String, strict, primary_key)
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   132
    def bytes(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   133
      Column(name, Type.Bytes, strict, primary_key)
65280
ef37f5236794 prefer non-strict default;
wenzelm
parents: 65022
diff changeset
   134
    def date(name: String, strict: Boolean = false, primary_key: Boolean = false): Column =
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   135
      Column(name, Type.Date, strict, primary_key)
63779
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
   136
  }
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
   137
65018
8b36f225bbee clarified signature;
wenzelm
parents: 65014
diff changeset
   138
  sealed case class Column(
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   139
    name: String,
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
   140
    T: Type,
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   141
    strict: Boolean = false,
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   142
    primary_key: Boolean = false,
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   143
    expr: SQL.Source = ""
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   144
  ) {
79861
47705d905420 tuned signature;
wenzelm
parents: 79860
diff changeset
   145
    def equals_name(other: Column): Boolean = name == other.name
47705d905420 tuned signature;
wenzelm
parents: 79860
diff changeset
   146
66857
f8f42289c4df tuned signature;
wenzelm
parents: 66856
diff changeset
   147
    def make_primary_key: Column = copy(primary_key = true)
f8f42289c4df tuned signature;
wenzelm
parents: 66856
diff changeset
   148
65691
2229276a1f99 eliminated redundant type SQL.View;
wenzelm
parents: 65690
diff changeset
   149
    def apply(table: Table): Column =
2229276a1f99 eliminated redundant type SQL.View;
wenzelm
parents: 65690
diff changeset
   150
      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
   151
65780
8baf789b1537 allow column with defining expression;
wenzelm
parents: 65778
diff changeset
   152
    def ident: Source =
79860
c49cb2a1ec44 tuned: prefer if_proper expression;
wenzelm
parents: 79859
diff changeset
   153
      if_proper(expr, enclose(expr) + " AS ") + SQL.ident(name)
65695
4edac706bc5e tuned signature;
wenzelm
parents: 65691
diff changeset
   154
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
   155
    def decl(sql_type: Type => Source): Source =
79858
ee4864e17c11 tuned: prefer if_proper expression;
wenzelm
parents: 79854
diff changeset
   156
      ident + " " + sql_type(T) + if_proper(strict || primary_key, " NOT NULL")
63781
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   157
66856
6b90c688a6dc tuned signature;
wenzelm
parents: 65918
diff changeset
   158
    def defined: String = ident + " IS NOT NULL"
6b90c688a6dc tuned signature;
wenzelm
parents: 65918
diff changeset
   159
    def undefined: String = ident + " IS NULL"
6b90c688a6dc tuned signature;
wenzelm
parents: 65918
diff changeset
   160
78152
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   161
    def equal(x: Int): Source = SQL.equal(ident, x)
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   162
    def equal(x: Long): Source = SQL.equal(ident, x)
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   163
    def equal(x: String): Source = SQL.equal(ident, x)
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   164
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   165
    def where_equal(x: Int): Source = SQL.where(equal(x))
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   166
    def where_equal(x: Long): Source = SQL.where(equal(x))
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   167
    def where_equal(x: String): Source = SQL.where(equal(x))
d4f387339494 tuned signature: more operations;
wenzelm
parents: 78151
diff changeset
   168
79849
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
   169
    def member_int(set: Iterable[Int]): Source = SQL.member_int(ident, set)
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
   170
    def member_long(set: Iterable[Long]): Source = SQL.member_long(ident, set)
77375
324f5821a4a4 clarified signature: more concise operations;
wenzelm
parents: 77370
diff changeset
   171
    def member(set: Iterable[String]): Source = SQL.member(ident, set)
79849
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
   172
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
   173
    def where_member_int(set: Iterable[Int]): Source = SQL.where(member_int(set))
e932bf884346 more operations;
wenzelm
parents: 79846
diff changeset
   174
    def where_member_long(set: Iterable[Long]): Source = SQL.where(member_long(set))
77375
324f5821a4a4 clarified signature: more concise operations;
wenzelm
parents: 77370
diff changeset
   175
    def where_member(set: Iterable[String]): Source = SQL.where(member(set))
65593
607f7ad07a60 tuned signature;
wenzelm
parents: 65327
diff changeset
   176
79859
bc979e334c7d tuned signature;
wenzelm
parents: 79858
diff changeset
   177
    def make_expr(e: SQL.Source): Column = copy(expr = e)
bc979e334c7d tuned signature;
wenzelm
parents: 79858
diff changeset
   178
    def max: Column = make_expr("MAX(" + ident + ")")
78151
2fdf3d8a94e6 clarified signature;
wenzelm
parents: 77681
diff changeset
   179
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   180
    override def toString: Source = ident
63779
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
   181
  }
9da65bc75610 more operations;
wenzelm
parents: 63778
diff changeset
   182
76870
c6cdf2a641f4 clarified signature: more explicit types;
wenzelm
parents: 76529
diff changeset
   183
  def order_by(columns: List[Column], descending: Boolean = false): Source =
79858
ee4864e17c11 tuned: prefer if_proper expression;
wenzelm
parents: 79854
diff changeset
   184
    " ORDER BY " + columns.mkString(", ") + if_proper(descending, " DESC")
76870
c6cdf2a641f4 clarified signature: more explicit types;
wenzelm
parents: 76529
diff changeset
   185
63780
163244cefb4e more operations;
wenzelm
parents: 63779
diff changeset
   186
163244cefb4e more operations;
wenzelm
parents: 63779
diff changeset
   187
  /* tables */
163244cefb4e more operations;
wenzelm
parents: 63779
diff changeset
   188
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   189
  sealed case class Table(name: String, columns: List[Column], body: Source = "") {
63781
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   190
    Library.duplicates(columns.map(_.name)) match {
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   191
      case Nil =>
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   192
      case bad => error("Duplicate column names " + commas_quote(bad) + " for table " + quote(name))
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   193
    }
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   194
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   195
    def ident: Source = SQL.ident(name)
65691
2229276a1f99 eliminated redundant type SQL.View;
wenzelm
parents: 65690
diff changeset
   196
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   197
    def query: Source =
65696
3f53a05c1266 tuned signature;
wenzelm
parents: 65695
diff changeset
   198
      if (body == "") error("Missing SQL body for table " + quote(name))
3f53a05c1266 tuned signature;
wenzelm
parents: 65695
diff changeset
   199
      else SQL.enclose(body)
65649
0818da4f67bb tuned signature;
wenzelm
parents: 65648
diff changeset
   200
65778
666a1bac126b tuned signature;
wenzelm
parents: 65776
diff changeset
   201
    def query_named: Source = query + " AS " + SQL.ident(name)
65702
7c6a91deb212 tuned signature;
wenzelm
parents: 65701
diff changeset
   202
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
   203
    def create(sql_type: Type => Source): Source = {
65325
981df08de0ab more general primary_key;
wenzelm
parents: 65323
diff changeset
   204
      val primary_key =
981df08de0ab more general primary_key;
wenzelm
parents: 65323
diff changeset
   205
        columns.filter(_.primary_key).map(_.name) match {
981df08de0ab more general primary_key;
wenzelm
parents: 65323
diff changeset
   206
          case Nil => Nil
981df08de0ab more general primary_key;
wenzelm
parents: 65323
diff changeset
   207
          case keys => List("PRIMARY KEY " + enclosure(keys))
981df08de0ab more general primary_key;
wenzelm
parents: 65323
diff changeset
   208
        }
78392
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   209
      "CREATE TABLE " + ident + " " + enclosure(columns.map(_.decl(sql_type)) ::: primary_key)
63781
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   210
    }
af9fe0b6b78e support for (single) primary key;
wenzelm
parents: 63780
diff changeset
   211
77365
a10fa2112854 clarified signature;
wenzelm
parents: 77364
diff changeset
   212
    def insert_cmd(cmd: Source = "INSERT", sql: Source = ""): Source =
77377
82fdc7cf9d44 tuned whitespace in generated SQL;
wenzelm
parents: 77375
diff changeset
   213
      cmd + " INTO " + ident + " VALUES " + enclosure(columns.map(_ => "?")) + SQL.separate(sql)
63791
c6cbdfaae19e more operations;
wenzelm
parents: 63790
diff changeset
   214
77365
a10fa2112854 clarified signature;
wenzelm
parents: 77364
diff changeset
   215
    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
   216
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   217
    def delete(sql: Source = ""): Source =
77377
82fdc7cf9d44 tuned whitespace in generated SQL;
wenzelm
parents: 77375
diff changeset
   218
      "DELETE FROM " + ident + SQL.separate(sql)
65319
64da14387b2c more operations;
wenzelm
parents: 65292
diff changeset
   219
77537
1bbf29ec9ce3 more operations;
wenzelm
parents: 77527
diff changeset
   220
    def update(update_columns: List[Column] = Nil, sql: Source = ""): Source =
1bbf29ec9ce3 more operations;
wenzelm
parents: 77527
diff changeset
   221
      "UPDATE " + ident + " SET " + commas(update_columns.map(c => c.ident + " = ?")) +
1bbf29ec9ce3 more operations;
wenzelm
parents: 77527
diff changeset
   222
        SQL.separate(sql)
1bbf29ec9ce3 more operations;
wenzelm
parents: 77527
diff changeset
   223
65774
1001fb86d7f7 clarified signature;
wenzelm
parents: 65748
diff changeset
   224
    def select(
77381
a86e346b20d8 misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents: 77377
diff changeset
   225
      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
   226
      distinct: Boolean = false,
a86e346b20d8 misc tuning and clarification: more uniform use of optional "sql" in SQL.Table.delete/select;
wenzelm
parents: 77377
diff changeset
   227
      sql: Source = ""
77403
be8e14c7da80 clarified signature, although "sql" argument is de-facto mandatory;
wenzelm
parents: 77381
diff changeset
   228
    ): Source = SQL.select(select_columns, distinct = distinct, sql = ident + SQL.separate(sql))
63790
3d723062dc70 more operations;
wenzelm
parents: 63788
diff changeset
   229
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   230
    override def toString: Source = ident
63780
163244cefb4e more operations;
wenzelm
parents: 63779
diff changeset
   231
  }
63790
3d723062dc70 more operations;
wenzelm
parents: 63788
diff changeset
   232
3d723062dc70 more operations;
wenzelm
parents: 63788
diff changeset
   233
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   234
  /* table groups */
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   235
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   236
  object Tables {
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   237
    def list(list: List[Table]): Tables = new Tables(list)
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   238
    def apply(args: Table*): Tables = list(args.toList)
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   239
  }
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   240
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   241
  final class Tables private(val list: List[Table]) extends Iterable[Table] {
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   242
    override def toString: String = list.mkString("SQL.Tables(", ", ", ")")
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   243
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   244
    def iterator: Iterator[Table] = list.iterator
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   245
79839
f425bbc4b2eb record updates within database, based on serial;
wenzelm
parents: 79775
diff changeset
   246
    def index(table: Table): Int =
f425bbc4b2eb record updates within database, based on serial;
wenzelm
parents: 79775
diff changeset
   247
      iterator.zipWithIndex
f425bbc4b2eb record updates within database, based on serial;
wenzelm
parents: 79775
diff changeset
   248
        .collectFirst({ case (t, i) if t.name == table.name => i })
f425bbc4b2eb record updates within database, based on serial;
wenzelm
parents: 79775
diff changeset
   249
        .getOrElse(error("No table " + quote(table.name)))
f425bbc4b2eb record updates within database, based on serial;
wenzelm
parents: 79775
diff changeset
   250
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   251
    // requires transaction
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   252
    def lock(db: Database, create: Boolean = false): Boolean = {
78154
8a7df40375ae tuned signature: more operations;
wenzelm
parents: 78153
diff changeset
   253
      if (create) foreach(db.create_table(_))
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   254
      val sql = db.lock_tables(list)
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   255
      if (sql.nonEmpty) { db.execute_statement(sql); true }
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   256
      else false
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   257
    }
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   258
  }
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   259
79775
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   260
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   261
  /* access data */
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   262
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   263
  def transaction_logger(): Logger =
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   264
    new System_Logger(guard_time = Time.guard_property("isabelle.transaction_trace"))
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   265
78187
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   266
  abstract class Data(table_prefix: String = "") {
78389
41e8ae87184d clarified signature: eliminate SQL.Tables.empty to avoid confusion (see also 0bd366fad888);
wenzelm
parents: 78386
diff changeset
   267
    def tables: Tables
78187
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   268
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   269
    def transaction_lock[A](
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   270
      db: Database,
78207
8e1941d3f703 clarified signature: more options;
wenzelm
parents: 78187
diff changeset
   271
      create: Boolean = false,
78356
974dbe256a37 more informative trace;
wenzelm
parents: 78355
diff changeset
   272
      label: String = "",
79775
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   273
      log: Logger = transaction_logger()
78207
8e1941d3f703 clarified signature: more options;
wenzelm
parents: 78187
diff changeset
   274
    )(body: => A): A = {
78369
ba71ea02d965 more robust Java/Scala multithreading: transaction is always connection.synchronized;
wenzelm
parents: 78366
diff changeset
   275
      db.transaction_lock(tables, create = create, label = label, log = log)(body)
78207
8e1941d3f703 clarified signature: more options;
wenzelm
parents: 78187
diff changeset
   276
    }
78187
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   277
78266
d8c99a497502 clarified signature;
wenzelm
parents: 78264
diff changeset
   278
    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
   279
      val table_name =
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   280
        List(proper_string(table_prefix), proper_string(name)).flatten.mkString("_")
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   281
      require(table_name.nonEmpty, "Undefined database table name")
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   282
      Table(table_name, columns, body = body)
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   283
    }
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   284
  }
2df0f3604a67 clarified signature: more explicit class SQL.Data;
wenzelm
parents: 78167
diff changeset
   285
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   286
65012
wenzelm
parents: 65011
diff changeset
   287
wenzelm
parents: 65011
diff changeset
   288
  /** SQL database operations **/
wenzelm
parents: 65011
diff changeset
   289
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   290
  /* statements */
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   291
78538
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   292
  class Batch_Error(val results: List[Int]) extends SQLException
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   293
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   294
  class Statement private[SQL](val db: Database, val rep: PreparedStatement) extends AutoCloseable {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   295
    stmt =>
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   296
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   297
    object bool {
73340
0ffcad1f6130 tuned --- fewer warnings;
wenzelm
parents: 73337
diff changeset
   298
      def update(i: Int, x: Boolean): Unit = rep.setBoolean(i, x)
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   299
      def update(i: Int, x: Option[Boolean]): Unit = {
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   300
        if (x.isDefined) update(i, x.get)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   301
        else rep.setNull(i, java.sql.Types.BOOLEAN)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   302
      }
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   303
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   304
    object int {
73340
0ffcad1f6130 tuned --- fewer warnings;
wenzelm
parents: 73337
diff changeset
   305
      def update(i: Int, x: Int): Unit = rep.setInt(i, x)
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   306
      def update(i: Int, x: Option[Int]): Unit = {
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   307
        if (x.isDefined) update(i, x.get)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   308
        else rep.setNull(i, java.sql.Types.INTEGER)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   309
      }
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   310
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   311
    object long {
73340
0ffcad1f6130 tuned --- fewer warnings;
wenzelm
parents: 73337
diff changeset
   312
      def update(i: Int, x: Long): Unit = rep.setLong(i, x)
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   313
      def update(i: Int, x: Option[Long]): Unit = {
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   314
        if (x.isDefined) update(i, x.get)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   315
        else rep.setNull(i, java.sql.Types.BIGINT)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   316
      }
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   317
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   318
    object double {
73340
0ffcad1f6130 tuned --- fewer warnings;
wenzelm
parents: 73337
diff changeset
   319
      def update(i: Int, x: Double): Unit = rep.setDouble(i, x)
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   320
      def update(i: Int, x: Option[Double]): Unit = {
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   321
        if (x.isDefined) update(i, x.get)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   322
        else rep.setNull(i, java.sql.Types.DOUBLE)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   323
      }
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   324
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   325
    object string {
73340
0ffcad1f6130 tuned --- fewer warnings;
wenzelm
parents: 73337
diff changeset
   326
      def update(i: Int, x: String): Unit = rep.setString(i, x)
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   327
      def update(i: Int, x: Option[String]): Unit = update(i, x.orNull)
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   328
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   329
    object bytes {
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   330
      def update(i: Int, bytes: Bytes): Unit = {
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   331
        if (bytes == null) rep.setBytes(i, null)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   332
        else rep.setBinaryStream(i, bytes.stream(), bytes.length)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   333
      }
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   334
      def update(i: Int, bytes: Option[Bytes]): Unit = update(i, bytes.orNull)
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   335
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   336
    object date {
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   337
      def update(i: Int, date: Date): Unit = db.update_date(stmt, i, date)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   338
      def update(i: Int, date: Option[Date]): Unit = update(i, date.orNull)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   339
    }
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   340
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   341
    def execute(): Boolean = rep.execute()
78538
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   342
78554
54991440905e clarified signature: proper treatment of implicit state (amending d0c9d277620e);
wenzelm
parents: 78551
diff changeset
   343
    def execute_batch(batch: IterableOnce[Statement => Unit]): Unit = {
54991440905e clarified signature: proper treatment of implicit state (amending d0c9d277620e);
wenzelm
parents: 78551
diff changeset
   344
      val it = batch.iterator
54991440905e clarified signature: proper treatment of implicit state (amending d0c9d277620e);
wenzelm
parents: 78551
diff changeset
   345
      if (it.nonEmpty) {
54991440905e clarified signature: proper treatment of implicit state (amending d0c9d277620e);
wenzelm
parents: 78551
diff changeset
   346
        for (body <- it) { body(this); rep.addBatch() }
78540
a6d079e0575d clarified signature: filter batch;
wenzelm
parents: 78538
diff changeset
   347
        val res = rep.executeBatch()
a6d079e0575d clarified signature: filter batch;
wenzelm
parents: 78538
diff changeset
   348
        if (!res.forall(i => i >= 0 || i == java.sql.Statement.SUCCESS_NO_INFO)) {
a6d079e0575d clarified signature: filter batch;
wenzelm
parents: 78538
diff changeset
   349
          throw new Batch_Error(res.toList)
a6d079e0575d clarified signature: filter batch;
wenzelm
parents: 78538
diff changeset
   350
        }
78538
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   351
      }
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   352
    }
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   353
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   354
    def execute_query(): Result = new Result(this, rep.executeQuery())
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   355
78353
wenzelm
parents: 78352
diff changeset
   356
    override def close(): Unit = rep.close()
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   357
  }
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   358
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   359
63790
3d723062dc70 more operations;
wenzelm
parents: 63788
diff changeset
   360
  /* results */
3d723062dc70 more operations;
wenzelm
parents: 63788
diff changeset
   361
78352
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   362
  class Result private[SQL](val stmt: Statement, val rep: ResultSet) extends AutoCloseable {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   363
    res =>
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   364
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   365
    def next(): Boolean = rep.next()
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   366
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   367
    def iterator[A](get: Result => A): Iterator[A] = new Iterator[A] {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   368
      private var _next: Boolean = res.next()
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   369
      def hasNext: Boolean = _next
73337
0af9e7e4476f tuned --- fewer warnings;
wenzelm
parents: 71601
diff changeset
   370
      def next(): A = { val x = get(res); _next = res.next(); x }
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   371
    }
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   372
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   373
    def bool(column: Column): Boolean = rep.getBoolean(column.name)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   374
    def int(column: Column): Int = rep.getInt(column.name)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   375
    def long(column: Column): Long = rep.getLong(column.name)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   376
    def double(column: Column): Double = rep.getDouble(column.name)
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   377
    def string(column: Column): String = {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   378
      val s = rep.getString(column.name)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   379
      if (s == null) "" else s
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   380
    }
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   381
    def bytes(column: Column): Bytes = {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   382
      val bs = rep.getBytes(column.name)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   383
      if (bs == null) Bytes.empty else Bytes(bs)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   384
    }
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   385
    def date(column: Column): Date = stmt.db.date(res, column)
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   386
71601
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   387
    def timing(c1: Column, c2: Column, c3: Column): Timing =
65741
wenzelm
parents: 65740
diff changeset
   388
      Timing(Time.ms(long(c1)), Time.ms(long(c2)), Time.ms(long(c3)))
wenzelm
parents: 65740
diff changeset
   389
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   390
    def get[A](column: Column, f: Column => A): Option[A] = {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   391
      val x = f(column)
77598
6370d9e5ab50 proper support for Option[Date] columns;
wenzelm
parents: 77596
diff changeset
   392
      if (rep.wasNull || x == null) None else Some(x)
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   393
    }
71601
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   394
    def get_bool(column: Column): Option[Boolean] = get(column, bool)
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   395
    def get_int(column: Column): Option[Int] = get(column, int)
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   396
    def get_long(column: Column): Option[Long] = get(column, long)
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   397
    def get_double(column: Column): Option[Double] = get(column, double)
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   398
    def get_string(column: Column): Option[String] = get(column, string)
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   399
    def get_bytes(column: Column): Option[Bytes] = get(column, bytes)
97ccf48c2f0c misc tuning based on hints by IntelliJ IDEA;
wenzelm
parents: 69980
diff changeset
   400
    def get_date(column: Column): Option[Date] = get(column, date)
78352
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   401
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   402
    override def close(): Unit = rep.close()
63790
3d723062dc70 more operations;
wenzelm
parents: 63788
diff changeset
   403
  }
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   404
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   405
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   406
  /* notifications: IPC via database server */
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   407
79728
df4eb4b05ecd tuned signature;
wenzelm
parents: 79727
diff changeset
   408
  sealed case class Notification(channel: String, payload: String = "") {
79882
6f9ae0f052bc tuned signature: fewer warnings in IntelliJ IDEA;
wenzelm
parents: 79861
diff changeset
   409
    override def toString: String =
79728
df4eb4b05ecd tuned signature;
wenzelm
parents: 79727
diff changeset
   410
      "Notification(" + channel + if_proper(payload, "," + payload) + ")"
df4eb4b05ecd tuned signature;
wenzelm
parents: 79727
diff changeset
   411
  }
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   412
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   413
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   414
  /* database */
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   415
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   416
  trait Database extends AutoCloseable {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   417
    db =>
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   418
77542
2da5562114c5 clarified signature: more uniform operations;
wenzelm
parents: 77541
diff changeset
   419
    def is_sqlite: Boolean = isInstanceOf[SQLite.Database]
2da5562114c5 clarified signature: more uniform operations;
wenzelm
parents: 77541
diff changeset
   420
    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
   421
78389
41e8ae87184d clarified signature: eliminate SQL.Tables.empty to avoid confusion (see also 0bd366fad888);
wenzelm
parents: 78386
diff changeset
   422
    def vacuum(tables: List[SQL.Table] = Nil): Unit =
78390
a84f8fca0833 clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents: 78389
diff changeset
   423
      if (is_sqlite) execute_statement("VACUUM")  // always FULL
a84f8fca0833 clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents: 78389
diff changeset
   424
      else if (tables.isEmpty) execute_statement("VACUUM FULL")
a84f8fca0833 clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents: 78389
diff changeset
   425
      else if (postgresql_major_version.get <= 10) {
a84f8fca0833 clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents: 78389
diff changeset
   426
        for (t <- tables) execute_statement("VACUUM " + t.ident)
78273
95a3bb4d7e38 clarified "vacuum" operation for various database versions (PostgreSQL <= 10 is strictly speaking obsolete, but still used on some test machines);
wenzelm
parents: 78271
diff changeset
   427
      }
78390
a84f8fca0833 clarified "vacuum" (again, reverting 0bd366fad888);
wenzelm
parents: 78389
diff changeset
   428
      else execute_statement("VACUUM" + commas(tables.map(_.ident)))
77348
885842575e2a more uniform operations;
wenzelm
parents: 77346
diff changeset
   429
77527
790085b1002f more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents: 77403
diff changeset
   430
    def now(): Date
790085b1002f more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents: 77403
diff changeset
   431
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   432
65008
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   433
    /* types */
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   434
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
   435
    def sql_type(T: Type): Source
65008
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   436
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   437
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   438
    /* connection */
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   439
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   440
    def connection: Connection
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   441
77037
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   442
    def sqlite_connection: Option[JDBC4Connection] =
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   443
      connection match { case conn: JDBC4Connection => Some(conn) case _ => None }
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   444
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   445
    def postgresql_connection: Option[PGConnection] =
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   446
      connection match { case conn: PGConnection => Some(conn) case _ => None }
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   447
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   448
    def the_sqlite_connection: JDBC4Connection =
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   449
      sqlite_connection getOrElse
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   450
        error("SQLite connection expected, but found " + connection.getClass.getName)
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   451
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   452
    def the_postgresql_connection: PGConnection =
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   453
      postgresql_connection getOrElse
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   454
        error("PostgreSQL connection expected, but found " + connection.getClass.getName)
164a21e5d568 support specific connection types, for additional operations;
wenzelm
parents: 76870
diff changeset
   455
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
   456
    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
   457
      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
   458
        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
   459
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
   460
        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
   461
          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
   462
          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
   463
            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
   464
              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
   465
              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
   466
            }
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
   467
        }
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
   468
      }
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
   469
      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
   470
78353
wenzelm
parents: 78352
diff changeset
   471
    override def close(): Unit = connection.close()
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   472
78369
ba71ea02d965 more robust Java/Scala multithreading: transaction is always connection.synchronized;
wenzelm
parents: 78366
diff changeset
   473
    def transaction[A](body: => A): A = connection.synchronized {
78383
d032bf604e93 more robust: exclude accidental nesting (synchronized block is re-entrant);
wenzelm
parents: 78381
diff changeset
   474
      require(connection.getAutoCommit(), "transaction already active")
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   475
      try {
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   476
        connection.setAutoCommit(false)
65022
cda3d36aceb2 proper transaction for PostgreSQL;
wenzelm
parents: 65021
diff changeset
   477
        try {
cda3d36aceb2 proper transaction for PostgreSQL;
wenzelm
parents: 65021
diff changeset
   478
          val result = body
75776
72e77c8307ec tuned signature, following hints by IntelliJ IDEA;
wenzelm
parents: 75393
diff changeset
   479
          connection.commit()
65022
cda3d36aceb2 proper transaction for PostgreSQL;
wenzelm
parents: 65021
diff changeset
   480
          result
cda3d36aceb2 proper transaction for PostgreSQL;
wenzelm
parents: 65021
diff changeset
   481
        }
78386
ee588c4b5557 more elementary transaction implementation (despite fda3f7a158b9 and 9da65bc75610);
wenzelm
parents: 78384
diff changeset
   482
        catch { case exn: Throwable => connection.rollback(); throw exn }
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   483
      }
78383
d032bf604e93 more robust: exclude accidental nesting (synchronized block is re-entrant);
wenzelm
parents: 78381
diff changeset
   484
      finally { connection.setAutoCommit(true) }
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   485
    }
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   486
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   487
    def transaction_lock[A](
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   488
      tables: Tables,
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   489
      create: Boolean = false,
78356
974dbe256a37 more informative trace;
wenzelm
parents: 78355
diff changeset
   490
      label: String = "",
79775
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   491
      log: Logger = transaction_logger()
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   492
    )(body: => A): A = {
78362
8da30ae02dda global transaction_count;
wenzelm
parents: 78361
diff changeset
   493
      val trace_count = - SQL.transaction_count()
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   494
      val trace_start = Time.now()
78361
b625cdabf963 tuned output;
wenzelm
parents: 78358
diff changeset
   495
      var trace_nl = false
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   496
78380
f8e3b228670c tuned output;
wenzelm
parents: 78378
diff changeset
   497
      def trace(msg: String): Unit = {
78358
f5cf8e500dee clarified isabelle.transaction_log: support time_min (in ms);
wenzelm
parents: 78356
diff changeset
   498
        val trace_time = Time.now() - trace_start
79775
752806151432 clarified signature: incorporate guard into Logger;
wenzelm
parents: 79728
diff changeset
   499
        if (log.guard(trace_time)) {
78557
131e2a220c78 proper sequential evaluation;
wenzelm
parents: 78554
diff changeset
   500
          time_start
131e2a220c78 proper sequential evaluation;
wenzelm
parents: 78554
diff changeset
   501
          val nl =
131e2a220c78 proper sequential evaluation;
wenzelm
parents: 78554
diff changeset
   502
            if (trace_nl) ""
131e2a220c78 proper sequential evaluation;
wenzelm
parents: 78554
diff changeset
   503
            else { trace_nl = true; "\nnow = " + (Time.now() - time_start).toString + "\n" }
78361
b625cdabf963 tuned output;
wenzelm
parents: 78358
diff changeset
   504
          log(nl + trace_time + " transaction " + trace_count +
b625cdabf963 tuned output;
wenzelm
parents: 78358
diff changeset
   505
            if_proper(label, " " + label) + ": " + msg)
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   506
        }
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   507
      }
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   508
78373
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   509
      try {
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   510
        val res =
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   511
          transaction {
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   512
            trace("begin")
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   513
            if (tables.lock(db, create = create)) {
78380
f8e3b228670c tuned output;
wenzelm
parents: 78378
diff changeset
   514
              trace("locked " + commas_quote(tables.list.map(_.name)))
78373
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   515
            }
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   516
            val res = Exn.capture { body }
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   517
            trace("end")
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   518
            res
78371
928e031b7c52 tuned output;
wenzelm
parents: 78370
diff changeset
   519
          }
78373
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   520
        trace("commit")
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   521
        Exn.release(res)
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   522
      }
2deecde7f1f6 more informative trace;
wenzelm
parents: 78371
diff changeset
   523
      catch { case exn: Throwable => trace("crash"); throw exn }
78355
9fbc6a043268 support trace of transaction_lock via property "isabelle.transaction_log";
wenzelm
parents: 78354
diff changeset
   524
    }
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   525
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   526
    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
   527
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   528
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   529
    /* statements and results */
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   530
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   531
    def statement(sql: Source): Statement =
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   532
      new Statement(db, connection.prepareStatement(sql))
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   533
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   534
    def using_statement[A](sql: Source)(f: Statement => A): A =
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   535
      using(statement(sql))(f)
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   536
77541
9d9b30741fc4 tuned signature: reduce boilerplate;
wenzelm
parents: 77540
diff changeset
   537
    def execute_statement(sql: Source, body: Statement => Unit = _ => ()): Unit =
9d9b30741fc4 tuned signature: reduce boilerplate;
wenzelm
parents: 77540
diff changeset
   538
      using_statement(sql) { stmt => body(stmt); stmt.execute() }
77540
c537905c2125 tuned signature;
wenzelm
parents: 77537
diff changeset
   539
78538
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   540
    def execute_batch_statement(
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   541
      sql: Source,
78554
54991440905e clarified signature: proper treatment of implicit state (amending d0c9d277620e);
wenzelm
parents: 78551
diff changeset
   542
      batch: IterableOnce[Statement => Unit] = Nil
78538
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   543
    ): Unit = using_statement(sql) { stmt => stmt.execute_batch(batch) }
56e8458ba262 support for execute_batch: multiple statements in one round-trip;
wenzelm
parents: 78422
diff changeset
   544
77552
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   545
    def execute_query_statement[A, B](
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   546
      sql: Source,
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   547
      make_result: Iterator[A] => B,
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   548
      get: Result => A
78352
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   549
    ): B = {
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   550
      using_statement(sql) { stmt =>
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   551
        using(stmt.execute_query()) { res => make_result(res.iterator(get)) }
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   552
      }
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   553
    }
77552
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   554
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   555
    def execute_query_statementO[A](sql: Source, get: Result => A): Option[A] =
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   556
      execute_query_statement[A, Option[A]](sql, _.nextOption, get)
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   557
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   558
    def execute_query_statementB(sql: Source): Boolean =
78352
10f8f12c61b0 proper close() operation;
wenzelm
parents: 78351
diff changeset
   559
      using_statement(sql)(stmt => using(stmt.execute_query())(_.next()))
77552
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   560
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   561
    def update_date(stmt: Statement, i: Int, date: Date): Unit
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   562
    def date(res: Result, column: Column): Date
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   563
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   564
    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
   565
79846
3d83a2554a71 more operations;
wenzelm
parents: 79839
diff changeset
   566
    def destroy(table: Table): Source = "DROP TABLE IF EXISTS " + table
3d83a2554a71 more operations;
wenzelm
parents: 79839
diff changeset
   567
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   568
65669
d2f19b4a16ae support for views;
wenzelm
parents: 65668
diff changeset
   569
    /* tables and views */
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   570
80082
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   571
    def name_pattern(name: String): String = {
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   572
      val escape = connection.getMetaData.getSearchStringEscape
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   573
      name.iterator.map(c =>
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   574
        if_proper(c == '_' || c == '%' || c == escape(0), escape) + c).mkString
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   575
    }
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   576
78375
234f2ff9afe6 clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents: 78373
diff changeset
   577
    def get_tables(pattern: String = "%"): List[String] = {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   578
      val result = new mutable.ListBuffer[String]
78375
234f2ff9afe6 clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents: 78373
diff changeset
   579
      val rs = connection.getMetaData.getTables(null, null, pattern, null)
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   580
      while (rs.next) { result += rs.getString(3) }
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   581
      result.toList
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   582
    }
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   583
80083
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   584
    def get_table_columns(
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   585
      table_pattern: String = "%",
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   586
      pattern: String = "%"
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   587
    ): List[(String, String)] = {
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   588
      val result = new mutable.ListBuffer[(String, String)]
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   589
      val rs = connection.getMetaData.getColumns(null, null, table_pattern, pattern)
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   590
      while (rs.next) { result += (rs.getString(3) -> rs.getString(4)) }
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   591
      result.toList
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   592
    }
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   593
80082
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   594
    def exists_table(name: String): Boolean =
4f9e4527a4e3 tuned signature;
wenzelm
parents: 79882
diff changeset
   595
      get_tables(pattern = name_pattern(name)).nonEmpty
78375
234f2ff9afe6 clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents: 78373
diff changeset
   596
234f2ff9afe6 clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents: 78373
diff changeset
   597
    def exists_table(table: Table): Boolean = exists_table(table.name)
234f2ff9afe6 clarified signature: more specific exists_table --- avoid retrieving full list beforehand;
wenzelm
parents: 78373
diff changeset
   598
80083
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   599
    def exists_table_column(table_name: String, name: String): Boolean =
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   600
      get_table_columns(table_pattern = name_pattern(table_name), pattern = name_pattern(name))
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   601
        .nonEmpty
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   602
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   603
    def exists_table_column(table: Table, column: Column): Boolean =
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   604
      exists_table_column(table.name, column.name)
e2174bf626b8 more portable: prefer official JDBC operation DatabaseMetaData.getColumns();
wenzelm
parents: 80082
diff changeset
   605
78392
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   606
    def create_table(table: Table, sql: Source = ""): Unit = {
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   607
      if (!exists_table(table)) {
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   608
        execute_statement(table.create(sql_type) + SQL.separate(sql))
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   609
        if (is_postgresql) {
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   610
          for (column <- table.columns if column.T == SQL.Type.Bytes) {
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   611
            execute_statement(
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   612
              "ALTER TABLE " + table + " ALTER COLUMN " + column + " SET STORAGE EXTERNAL")
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   613
          }
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
   614
        }
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
   615
      }
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
   616
    }
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   617
78392
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   618
    def create_view(table: Table): Unit = {
27c2fa1db6ed more uniform guard (!exists_table(table)): avoid "ALTER TABLE" on already existing table, which could lead to deadlocks if this is presently locked;
wenzelm
parents: 78391
diff changeset
   619
      if (!exists_table(table)) {
77540
c537905c2125 tuned signature;
wenzelm
parents: 77537
diff changeset
   620
        execute_statement("CREATE VIEW " + table + " AS " + { table.query; table.body })
65690
wenzelm
parents: 65677
diff changeset
   621
      }
65691
2229276a1f99 eliminated redundant type SQL.View;
wenzelm
parents: 65690
diff changeset
   622
    }
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   623
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   624
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   625
    /* notifications (PostgreSQL only) */
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   626
79727
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   627
    def listen(channel: String): Unit = ()
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   628
    def unlisten(channel: String = "*"): Unit = ()
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   629
    def send(channel: String, payload: String): Unit = ()
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   630
    final def send(channel: String): Unit = send(channel, "")
79725
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   631
    final def send(notification: Notification): Unit =
79727
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   632
      send(notification.channel, notification.payload)
79725
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   633
    def receive(filter: Notification => Boolean): Option[List[Notification]] = None
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   634
  }
78362
8da30ae02dda global transaction_count;
wenzelm
parents: 78361
diff changeset
   635
8da30ae02dda global transaction_count;
wenzelm
parents: 78361
diff changeset
   636
8da30ae02dda global transaction_count;
wenzelm
parents: 78361
diff changeset
   637
  private val transaction_count = Counter.make()
63778
e06e899b78d0 clarified modules;
wenzelm
parents:
diff changeset
   638
}
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   639
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   640
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   641
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   642
/** SQLite **/
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   643
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   644
object SQLite {
65021
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
   645
  // see https://www.sqlite.org/lang_datefunc.html
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
   646
  val date_format: Date.Format = Date.Format("uuuu-MM-dd HH:mm:ss.SSS x")
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
   647
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   648
  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
   649
    val lib_path = Path.explode("$ISABELLE_SQLITE_HOME/" + Platform.jvm_platform)
76529
ded37aade88e clarified signature;
wenzelm
parents: 76363
diff changeset
   650
    val lib_name = File.get_file(lib_path).file_name
ded37aade88e clarified signature;
wenzelm
parents: 76363
diff changeset
   651
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
   652
    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
   653
    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
   654
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
   655
    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
   656
  }
65292
e3bd1e7ddd23 more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents: 65280
diff changeset
   657
78163
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   658
  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
   659
    init_jdbc
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   660
    val path0 = path.expand
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   661
    val s0 = File.platform_path(path0)
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   662
    val s1 = if (Platform.is_windows) s0.replace('\\', '/') else s0
78891
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   663
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   664
    val config = new SQLiteConfig()
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   665
    config.setEncoding(SQLiteConfig.Encoding.UTF8)
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   666
    val connection = config.createConnection("jdbc:sqlite:" + s1)
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   667
78163
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   668
    val db = new Database(path0.toString, connection)
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   669
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   670
    try { if (restrict) File.restrict(path0) }
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   671
    catch { case exn: Throwable => db.close(); throw exn }
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   672
c6d4b1a00ad7 clarified signature;
wenzelm
parents: 78154
diff changeset
   673
    db
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   674
  }
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   675
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   676
  class Database private[SQLite](name: String, val connection: Connection) extends SQL.Database {
65007
b6a1a1d42f5d clarified toString;
wenzelm
parents: 65006
diff changeset
   677
    override def toString: String = name
77664
f5d3ade80d15 more specific vacuum operation, which is also relevant to PostgreSQL;
wenzelm
parents: 77598
diff changeset
   678
77527
790085b1002f more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents: 77403
diff changeset
   679
    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
   680
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
   681
    def sql_type(T: SQL.Type): SQL.Source = SQL.sql_type_sqlite(T)
65011
42bffd1637f0 support for type Boolean;
wenzelm
parents: 65010
diff changeset
   682
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   683
    def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit =
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   684
      if (date == null) stmt.string(i) = (null: String)
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   685
      else stmt.string(i) = date_format(date)
65598
5deef985e38e allow null;
wenzelm
parents: 65594
diff changeset
   686
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   687
    def date(res: SQL.Result, column: SQL.Column): Date =
77598
6370d9e5ab50 proper support for Option[Date] columns;
wenzelm
parents: 77596
diff changeset
   688
      proper_string(res.string(column)) match {
6370d9e5ab50 proper support for Option[Date] columns;
wenzelm
parents: 77596
diff changeset
   689
        case None => null
6370d9e5ab50 proper support for Option[Date] columns;
wenzelm
parents: 77596
diff changeset
   690
        case Some(s) => date_format.parse(s)
6370d9e5ab50 proper support for Option[Date] columns;
wenzelm
parents: 77596
diff changeset
   691
      }
65021
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
   692
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   693
    def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source =
77365
a10fa2112854 clarified signature;
wenzelm
parents: 77364
diff changeset
   694
      table.insert_cmd(cmd = "INSERT OR IGNORE", sql = sql)
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   695
  }
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   696
}
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   697
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   698
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   699
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   700
/** PostgreSQL **/
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   701
79724
54d0f6edfe3a clarified versions for documentation;
wenzelm
parents: 79722
diff changeset
   702
// see https://www.postgresql.org/docs/14/index.html
78351
9f2cfb9873bb tuned comments;
wenzelm
parents: 78348
diff changeset
   703
// see https://jdbc.postgresql.org/documentation
9f2cfb9873bb tuned comments;
wenzelm
parents: 78348
diff changeset
   704
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   705
object PostgreSQL {
75967
ff164add75cd maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents: 75966
diff changeset
   706
  type Source = SQL.Source
ff164add75cd maintain "uuid" column in session build database, to identity the original build process uniquely;
wenzelm
parents: 75966
diff changeset
   707
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   708
  lazy val init_jdbc: Unit = Class.forName("org.postgresql.Driver")
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   709
78345
545da61f5989 clarified signature;
wenzelm
parents: 78344
diff changeset
   710
  val default_server: SSH.Server = SSH.local_server(port = 5432)
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   711
78378
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   712
  def open_database(
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   713
    user: String,
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   714
    password: String,
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   715
    database: String = "",
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   716
    server: SSH.Server = default_server,
79722
5938158733bb clarified signature: avoid hardwired values;
wenzelm
parents: 79721
diff changeset
   717
    server_close: Boolean = false,
5938158733bb clarified signature: avoid hardwired values;
wenzelm
parents: 79721
diff changeset
   718
    receiver_delay: Time = Time.seconds(0.5)
78378
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   719
  ): Database = {
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   720
    init_jdbc
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   721
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   722
    if (user.isEmpty) error("Undefined database user")
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   723
    if (server.host.isEmpty) error("Undefined database server host")
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   724
    if (server.port <= 0) error("Undefined database server port")
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   725
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   726
    val name = proper_string(database) getOrElse user
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   727
    val url = "jdbc:postgresql://" + server.host + ":" + server.port + "/" + name
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   728
    val ssh = server.ssh_system.ssh_session
78422
dcaf6f33d94d tuned output;
wenzelm
parents: 78402
diff changeset
   729
    val print =
78561
c06a0396b09d tuned output;
wenzelm
parents: 78557
diff changeset
   730
      "server " + quote(user + "@" + server + "/" + name) +
c06a0396b09d tuned output;
wenzelm
parents: 78557
diff changeset
   731
        if_proper(ssh, " via ssh " + quote(ssh.get.toString))
78378
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   732
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   733
    val connection = DriverManager.getConnection(url, user, password)
79722
5938158733bb clarified signature: avoid hardwired values;
wenzelm
parents: 79721
diff changeset
   734
    val db = new Database(connection, print, server, server_close, receiver_delay)
78891
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   735
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   736
    try { db.execute_statement("SET standard_conforming_strings = on") }
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   737
    catch { case exn: Throwable => db.close(); throw exn }
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   738
76d1382d6077 proper SQL.string syntax, following actual SQL standard instead of historic variations before PostgreSQL 9.1;
wenzelm
parents: 78863
diff changeset
   739
    db
78378
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   740
  }
2f16f23baefd tuned source structure;
wenzelm
parents: 78375
diff changeset
   741
78366
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   742
  def open_server(
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   743
    options: Options,
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   744
    host: String = "",
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   745
    port: Int = 0,
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   746
    ssh_host: String = "",
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   747
    ssh_port: Int = 0,
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   748
    ssh_user: String = ""
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   749
  ): SSH.Server = {
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   750
    val server_host = proper_string(host).getOrElse(default_server.host)
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   751
    val server_port = if (port > 0) port else default_server.port
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   752
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   753
    if (ssh_host.isEmpty) SSH.local_server(host = server_host, port = server_port)
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   754
    else {
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   755
      SSH.open_server(options, host = ssh_host, port = ssh_port, user = ssh_user,
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   756
        remote_host = server_host, remote_port = server_port)
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   757
    }
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   758
  }
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   759
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   760
  def open_database_server(
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   761
    options: Options,
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   762
    user: String = "",
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   763
    password: String = "",
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   764
    database: String = "",
78366
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   765
    server: SSH.Server = SSH.no_server,
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   766
    host: String = "",
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   767
    port: Int = 0,
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   768
    ssh_host: String = "",
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   769
    ssh_port: Int = 0,
78863
f627ab8c276c discontinued pointless option (reverting 63d55ba90a9f): performance tuning works better via SQL.Database.execute_batch_statement;
wenzelm
parents: 78607
diff changeset
   770
    ssh_user: String = ""
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   771
  ): PostgreSQL.Database = {
78366
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   772
    val db_server =
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   773
      if (server.defined) server
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   774
      else {
78366
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   775
        open_server(options, host = host, port = port, ssh_host = ssh_host,
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   776
          ssh_port = ssh_port, ssh_user = ssh_user)
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   777
      }
78366
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   778
    val server_close = !server.defined
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   779
    try {
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   780
      open_database(user = user, password = password, database = database,
78863
f627ab8c276c discontinued pointless option (reverting 63d55ba90a9f): performance tuning works better via SQL.Database.execute_batch_statement;
wenzelm
parents: 78607
diff changeset
   781
        server = db_server, server_close = server_close)
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   782
    }
78366
aa4ea5398ab8 clarified signature: more operations;
wenzelm
parents: 78365
diff changeset
   783
    catch { case exn: Throwable if server_close => db_server.close(); throw exn }
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   784
  }
65292
e3bd1e7ddd23 more robust JDBC initialization, e.g. required for Isabelle/jEdit startup;
wenzelm
parents: 65280
diff changeset
   785
65009
eda9366bbfac remote database access via ssh port forwarding;
wenzelm
parents: 65008
diff changeset
   786
  class Database private[PostgreSQL](
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   787
    val connection: Connection,
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   788
    print: String,
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   789
    server: SSH.Server,
79722
5938158733bb clarified signature: avoid hardwired values;
wenzelm
parents: 79721
diff changeset
   790
    server_close: Boolean,
5938158733bb clarified signature: avoid hardwired values;
wenzelm
parents: 79721
diff changeset
   791
    receiver_delay: Time
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   792
  ) extends SQL.Database {
78347
72fc2ff08e07 clarified signature: more operations;
wenzelm
parents: 78345
diff changeset
   793
    override def toString: String = print
65008
ed2eedf786f3 clarified handling of SQL.Type;
wenzelm
parents: 65007
diff changeset
   794
77527
790085b1002f more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents: 77403
diff changeset
   795
    override def now(): Date = {
790085b1002f more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents: 77403
diff changeset
   796
      val now = SQL.Column.date("now")
77552
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   797
      execute_query_statementO[Date]("SELECT NOW() as " + now.ident, res => res.date(now))
080422b3d914 clarified signature: reduce boilerplate;
wenzelm
parents: 77543
diff changeset
   798
        .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
   799
    }
790085b1002f more detailed table "isabelle_build_serial": allow to monitor activity of build_process instances;
wenzelm
parents: 77403
diff changeset
   800
78598
e1a19c7778e0 clarified signature: prefer enum types;
wenzelm
parents: 78561
diff changeset
   801
    def sql_type(T: SQL.Type): SQL.Source = SQL.sql_type_postgresql(T)
65009
eda9366bbfac remote database access via ssh port forwarding;
wenzelm
parents: 65008
diff changeset
   802
65021
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
   803
    // see https://jdbc.postgresql.org/documentation/head/8-date-time.html
65748
1f4a80e80c88 tuned signature;
wenzelm
parents: 65741
diff changeset
   804
    def update_date(stmt: SQL.Statement, i: Int, date: Date): Unit =
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   805
      if (date == null) stmt.rep.setObject(i, null)
69980
f2e3adfd916f tuned signature;
wenzelm
parents: 69393
diff changeset
   806
      else stmt.rep.setObject(i, OffsetDateTime.from(date.to(Date.timezone_utc).rep))
65598
5deef985e38e allow null;
wenzelm
parents: 65594
diff changeset
   807
75393
87ebf5a50283 clarified formatting, for the sake of scala3;
wenzelm
parents: 73367
diff changeset
   808
    def date(res: SQL.Result, column: SQL.Column): Date = {
65740
83388f09e9ab clarified signature;
wenzelm
parents: 65739
diff changeset
   809
      val obj = res.rep.getObject(column.name, classOf[OffsetDateTime])
65704
aa9a7a753296 more robust;
wenzelm
parents: 65703
diff changeset
   810
      if (obj == null) null else Date.instant(obj.toInstant)
aa9a7a753296 more robust;
wenzelm
parents: 65703
diff changeset
   811
    }
65021
da8ae577d171 clarified Date storage;
wenzelm
parents: 65020
diff changeset
   812
65730
7ae61e72a678 clarified signature;
wenzelm
parents: 65729
diff changeset
   813
    def insert_permissive(table: SQL.Table, sql: SQL.Source = ""): SQL.Source =
77377
82fdc7cf9d44 tuned whitespace in generated SQL;
wenzelm
parents: 77375
diff changeset
   814
      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
   815
79846
3d83a2554a71 more operations;
wenzelm
parents: 79839
diff changeset
   816
    override def destroy(table: SQL.Table): SQL.Source =
3d83a2554a71 more operations;
wenzelm
parents: 79839
diff changeset
   817
      super.destroy(table) + " CASCADE"
3d83a2554a71 more operations;
wenzelm
parents: 79839
diff changeset
   818
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   819
77590
edc96be6b939 explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents: 77552
diff changeset
   820
    /* explicit locking: only applicable to PostgreSQL within transaction context */
79724
54d0f6edfe3a clarified versions for documentation;
wenzelm
parents: 79722
diff changeset
   821
    // see https://www.postgresql.org/docs/14/sql-lock.html
54d0f6edfe3a clarified versions for documentation;
wenzelm
parents: 79722
diff changeset
   822
    // see https://www.postgresql.org/docs/14/explicit-locking.html
77590
edc96be6b939 explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents: 77552
diff changeset
   823
77596
dd8b08729458 clarified signature;
wenzelm
parents: 77591
diff changeset
   824
    override def lock_tables(tables: List[SQL.Table]): PostgreSQL.Source =
78253
12d54a78bc0e more robust;
wenzelm
parents: 78207
diff changeset
   825
      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
   826
edc96be6b939 explicit locking for PostgreSQL --- neither available nor required for SQLite;
wenzelm
parents: 77552
diff changeset
   827
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   828
    /* notifications: IPC via database server */
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   829
    /*
79724
54d0f6edfe3a clarified versions for documentation;
wenzelm
parents: 79722
diff changeset
   830
      - see https://www.postgresql.org/docs/14/sql-notify.html
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   831
      - self-notifications and repeated notifications are suppressed
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   832
      - notifications are sorted by local system time (nano seconds)
79725
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   833
      - receive() == None means that IPC is inactive or unavailable (SQLite)
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   834
    */
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   835
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   836
    private var _receiver_buffer: Option[Map[SQL.Notification, Long]] = None
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   837
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   838
    private lazy val _receiver_thread =
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   839
      Isabelle_Thread.fork(name = "PostgreSQL.receiver", daemon = true, uninterruptible = true) {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   840
        val conn = the_postgresql_connection
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   841
        val self_pid = conn.getBackendPID
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   842
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   843
        try {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   844
          while (true) {
79726
621676d7fb9a more robust shutdown: interruptible database connection;
wenzelm
parents: 79725
diff changeset
   845
            Isabelle_Thread.interruptible { receiver_delay.sleep(); Option(conn.getNotifications())}
621676d7fb9a more robust shutdown: interruptible database connection;
wenzelm
parents: 79725
diff changeset
   846
            match {
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   847
              case Some(array) if array.nonEmpty =>
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   848
                synchronized {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   849
                  var received = _receiver_buffer.getOrElse(Map.empty)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   850
                  for (a <- array.iterator if a.getPID != self_pid) {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   851
                    val msg = SQL.Notification(a.getName, a.getParameter)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   852
                    if (!received.isDefinedAt(msg)) {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   853
                      val stamp = System.nanoTime()
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   854
                      received = received + (msg -> stamp)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   855
                    }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   856
                  }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   857
                  _receiver_buffer = Some(received)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   858
                }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   859
              case _ =>
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   860
            }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   861
          }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   862
        }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   863
        catch { case Exn.Interrupt() => }
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   864
      }
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   865
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   866
    private def receiver_shutdown(): Unit = synchronized {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   867
      if (_receiver_buffer.isDefined) {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   868
        _receiver_thread.interrupt()
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   869
        Some(_receiver_thread)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   870
      }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   871
      else None
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   872
    }.foreach(_.join())
77039
2f09dc0e6dda support IPC via database server;
wenzelm
parents: 77037
diff changeset
   873
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   874
    private def synchronized_receiver[A](body: => A): A = synchronized {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   875
      if (_receiver_buffer.isEmpty) {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   876
        _receiver_buffer = Some(Map.empty)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   877
        _receiver_thread
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   878
      }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   879
      body
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   880
    }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   881
79727
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   882
    override def listen(channel: String): Unit = synchronized_receiver {
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   883
      execute_statement("LISTEN " + SQL.ident(channel))
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   884
    }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   885
79727
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   886
    override def unlisten(channel: String = "*"): Unit = synchronized_receiver {
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   887
      execute_statement("UNLISTEN " + (if (channel == "*") channel else SQL.ident(channel)))
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   888
    }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   889
79727
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   890
    override def send(channel: String, payload: String): Unit = synchronized_receiver {
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   891
      execute_statement(
79727
529a6e35aaa9 tuned signature: follow PostgreSQL syntax instead of JDBC API;
wenzelm
parents: 79726
diff changeset
   892
        "NOTIFY " + SQL.ident(channel) + if_proper(payload, ", " + SQL.string(payload)))
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   893
    }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   894
79725
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   895
    override def receive(
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   896
      filter: SQL.Notification => Boolean = _ => true
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   897
    ): Option[List[SQL.Notification]] = synchronized {
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   898
      _receiver_buffer.map { received =>
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   899
        val filtered = received.keysIterator.filter(filter).toList
79725
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   900
        if (filtered.nonEmpty) {
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   901
          _receiver_buffer = Some(received -- filtered)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   902
          filtered.map(msg => msg -> received(msg)).sortBy(_._2).map(_._1)
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   903
        }
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   904
        else Nil
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   905
      }
79725
abb5eedfeecf clarified signature: more convenient send/receive operations;
wenzelm
parents: 79724
diff changeset
   906
    }
79721
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   907
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   908
    override def close(): Unit = {
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   909
      receiver_shutdown()
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   910
      super.close()
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   911
      if (server_close) server.close()
a5629eade476 clarified IPC via database server: receive notifications quasi-spontaneously via auxiliary thread;
wenzelm
parents: 78891
diff changeset
   912
    }
65006
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   913
  }
632bdf7b8bab clarified modules;
wenzelm
parents: 65004
diff changeset
   914
}