skyward-orm 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +21 -0
  3. data/README.md +247 -60
  4. data/lib/skyward/orm/adapters/postgresql/connection.rb +64 -4
  5. data/lib/skyward/orm/adapters/postgresql.rb +189 -68
  6. data/lib/skyward/orm/adapters/sqlite/connection.rb +87 -0
  7. data/lib/skyward/orm/adapters/sqlite/constraints.rb +32 -14
  8. data/lib/skyward/orm/adapters/sqlite.rb +158 -45
  9. data/lib/skyward/orm/adapters/statement_cache.rb +51 -0
  10. data/lib/skyward/orm/adapters.rb +23 -7
  11. data/lib/skyward/orm/catalog/column.rb +2 -1
  12. data/lib/skyward/orm/cli/boot_file.rb +4 -4
  13. data/lib/skyward/orm/cli/migrate.rb +1 -1
  14. data/lib/skyward/orm/cli/migration.rb +8 -8
  15. data/lib/skyward/orm/cli/scaffold/source.rb +323 -0
  16. data/lib/skyward/orm/cli/scaffold.rb +70 -0
  17. data/lib/skyward/orm/cli/status.rb +5 -3
  18. data/lib/skyward/orm/commands.rb +20 -8
  19. data/lib/skyward/orm/connection/instrumented.rb +71 -0
  20. data/lib/skyward/orm/connection/pool.rb +2 -2
  21. data/lib/skyward/orm/connection/session.rb +74 -5
  22. data/lib/skyward/orm/database/decoders.rb +41 -0
  23. data/lib/skyward/orm/{connection/database → database}/schema_check.rb +22 -10
  24. data/lib/skyward/orm/{connection/database.rb → database.rb} +70 -36
  25. data/lib/skyward/orm/execution.rb +9 -0
  26. data/lib/skyward/orm/migrations/alter_table.rb +6 -2
  27. data/lib/skyward/orm/migrations/definitions.rb +20 -17
  28. data/lib/skyward/orm/migrations/diff.rb +156 -32
  29. data/lib/skyward/orm/migrations/directory.rb +5 -5
  30. data/lib/skyward/orm/migrations/rename_constraint.rb +8 -0
  31. data/lib/skyward/orm/migrations/runner.rb +21 -11
  32. data/lib/skyward/orm/migrations/script.rb +67 -27
  33. data/lib/skyward/orm/migrations/status.rb +38 -9
  34. data/lib/skyward/orm/migrations/summary.rb +23 -26
  35. data/lib/skyward/orm/migrations/versions.rb +3 -4
  36. data/lib/skyward/orm/migrations.rb +1 -1
  37. data/lib/skyward/orm/projection.rb +24 -11
  38. data/lib/skyward/orm/queries/clauses.rb +298 -124
  39. data/lib/skyward/orm/query.rb +2 -2
  40. data/lib/skyward/orm/record.rb +27 -9
  41. data/lib/skyward/orm/{placeholders.rb → statements/placeholders.rb} +4 -4
  42. data/lib/skyward/orm/statements.rb +178 -31
  43. data/lib/skyward/orm/tables/column.rb +2 -1
  44. data/lib/skyward/orm/tables/column_types.rb +63 -16
  45. data/lib/skyward/orm/tables/declarations.rb +43 -15
  46. data/lib/skyward/orm/{members.rb → tables/members.rb} +1 -1
  47. data/lib/skyward/orm/tables/rows.rb +28 -10
  48. data/lib/skyward/orm/tables/sources.rb +63 -0
  49. data/lib/skyward/orm/tables/validation.rb +12 -3
  50. data/lib/skyward/orm/tables/values.rb +124 -14
  51. data/lib/skyward/orm/tables.rb +2 -1
  52. data/lib/skyward/orm/transactional.rb +2 -2
  53. data/lib/skyward/orm/version.rb +1 -1
  54. data/lib/skyward/orm.rb +52 -17
  55. data/sig/generated/skyward/orm/adapters/postgresql/connection.rbs +35 -3
  56. data/sig/generated/skyward/orm/adapters/postgresql.rbs +64 -14
  57. data/sig/generated/skyward/orm/adapters/sqlite/connection.rbs +55 -0
  58. data/sig/generated/skyward/orm/adapters/sqlite/constraints.rbs +6 -0
  59. data/sig/generated/skyward/orm/adapters/sqlite.rbs +72 -7
  60. data/sig/generated/skyward/orm/adapters/statement_cache.rbs +37 -0
  61. data/sig/generated/skyward/orm/adapters.rbs +6 -0
  62. data/sig/generated/skyward/orm/catalog/column.rbs +6 -4
  63. data/sig/generated/skyward/orm/cli/boot_file.rbs +4 -4
  64. data/sig/generated/skyward/orm/cli/migrate.rbs +2 -2
  65. data/sig/generated/skyward/orm/cli/migration.rbs +2 -2
  66. data/sig/generated/skyward/orm/cli/scaffold/source.rbs +158 -0
  67. data/sig/generated/skyward/orm/cli/scaffold.rbs +28 -0
  68. data/sig/generated/skyward/orm/cli/status.rbs +2 -2
  69. data/sig/generated/skyward/orm/connection/instrumented.rbs +47 -0
  70. data/sig/generated/skyward/orm/connection/session.rbs +40 -6
  71. data/sig/generated/skyward/orm/database/decoders.rbs +19 -0
  72. data/sig/generated/skyward/orm/{connection/database → database}/schema_check.rbs +11 -4
  73. data/sig/generated/skyward/orm/{connection/database.rbs → database.rbs} +40 -17
  74. data/sig/generated/skyward/orm/execution.rbs +18 -0
  75. data/sig/generated/skyward/orm/migrations/alter_table.rbs +11 -5
  76. data/sig/generated/skyward/orm/migrations/definitions.rbs +2 -2
  77. data/sig/generated/skyward/orm/migrations/diff.rbs +77 -11
  78. data/sig/generated/skyward/orm/migrations/rename_constraint.rbs +16 -0
  79. data/sig/generated/skyward/orm/migrations/runner.rbs +5 -0
  80. data/sig/generated/skyward/orm/migrations/script.rbs +32 -8
  81. data/sig/generated/skyward/orm/migrations/status.rbs +15 -2
  82. data/sig/generated/skyward/orm/migrations/summary.rbs +0 -1
  83. data/sig/generated/skyward/orm/migrations/versions.rbs +2 -2
  84. data/sig/generated/skyward/orm/migrations.rbs +1 -1
  85. data/sig/generated/skyward/orm/projection.rbs +10 -2
  86. data/sig/generated/skyward/orm/queries/clauses.rbs +129 -40
  87. data/sig/generated/skyward/orm/record.rbs +14 -7
  88. data/sig/generated/skyward/orm/{placeholders.rbs → statements/placeholders.rbs} +2 -2
  89. data/sig/generated/skyward/orm/statements.rbs +84 -8
  90. data/sig/generated/skyward/orm/tables/column.rbs +6 -4
  91. data/sig/generated/skyward/orm/tables/column_types.rbs +18 -4
  92. data/sig/generated/skyward/orm/tables/declarations.rbs +15 -1
  93. data/sig/generated/skyward/orm/{members.rbs → tables/members.rbs} +2 -2
  94. data/sig/generated/skyward/orm/tables/rows.rbs +1 -1
  95. data/sig/generated/skyward/orm/tables/sources.rbs +32 -0
  96. data/sig/generated/skyward/orm/tables/values.rbs +41 -1
  97. data/sig/generated/skyward/orm/tables.rbs +3 -1
  98. data/sig/generated/skyward/orm.rbs +6 -6
  99. data/sig/manual/pg.rbs +22 -0
  100. data/sig/manual/skyward/orm/cli/scaffold/source.rbs +3 -0
  101. data/sig/manual/skyward/orm/cli/scaffold.rbs +3 -0
  102. data/sig/manual/skyward/orm/database/decoders.rbs +3 -0
  103. data/sig/manual/skyward/orm/database/schema_check.rbs +3 -0
  104. data/sig/manual/skyward/orm/statements/placeholders.rbs +3 -0
  105. data/sig/manual/skyward/orm/tables/members.rbs +3 -0
  106. data/sig/manual/skyward/orm/tables/sources.rbs +3 -0
  107. data/sig/manual/skyward/orm.rbs +41 -8
  108. data/sig/manual/sqlite3.rbs +13 -2
  109. metadata +51 -14
  110. data/sig/manual/skyward/orm/connection/database/schema_check.rbs +0 -3
  111. data/sig/manual/skyward/orm/members.rbs +0 -3
  112. data/sig/manual/skyward/orm/placeholders.rbs +0 -3
@@ -3,13 +3,22 @@
3
3
  # PG::Connection runs SQL with exec_params, which returns a PG::Result, so this
4
4
  # gives it the execute every adapter's connection has.
5
5
  class Skyward::ORM::Adapters::PostgreSQL::Connection
6
+ # What PostgreSQL reports when a migration changed a column a kept statement
7
+ # returns. Other errors share its SQLSTATE, 0A000.
8
+ REVALIDATE = 'RevalidateCachedQuery' #: String
9
+
6
10
  # @rbs @connection: PG::Connection
11
+ # @rbs @statements: Skyward::ORM::Adapters::StatementCache[String]
12
+ # @rbs @prepared: Integer
7
13
  # @rbs @changes: Integer
8
14
 
9
15
  # @rbs connection: PG::Connection
16
+ # @rbs statements: Skyward::ORM::Adapters::StatementCache[String]
10
17
  # @rbs return: void
11
- def initialize(connection)
18
+ def initialize(connection, statements)
12
19
  @connection = connection
20
+ @statements = statements
21
+ @prepared = 0
13
22
  @changes = 0
14
23
  end
15
24
 
@@ -17,9 +26,10 @@ class Skyward::ORM::Adapters::PostgreSQL::Connection
17
26
  # rows it changed are kept for changes, as SQLite keeps them for its own.
18
27
  # @rbs sql: String
19
28
  # @rbs binds: Array[untyped]
29
+ # @rbs prepare: bool
20
30
  # @rbs return: Array[Array[String?]]
21
- def execute(sql, binds = [])
22
- @connection.exec_params(sql, binds) do |result|
31
+ def execute(sql, binds = [], prepare: false)
32
+ run(sql, binds, prepare) do |result|
23
33
  @changes = result.cmd_tuples
24
34
  result.values
25
35
  end
@@ -30,8 +40,9 @@ class Skyward::ORM::Adapters::PostgreSQL::Connection
30
40
 
31
41
  # @rbs sql: String
32
42
  # @rbs *binds: untyped
43
+ # @rbs prepare: bool
33
44
  # @rbs return: Array[Array[String?]]
34
- def execute2(sql, *binds) = @connection.exec_params(sql, binds) { |result| [result.fields, *result.values] }
45
+ def execute2(sql, *binds, prepare: false) = run(sql, binds, prepare) { |result| [result.fields, *result.values] }
35
46
 
36
47
  # exec, unlike exec_params, runs every statement in the SQL.
37
48
  # @rbs sql: String
@@ -49,4 +60,53 @@ class Skyward::ORM::Adapters::PostgreSQL::Connection
49
60
  def close
50
61
  @connection.close
51
62
  end
63
+
64
+ private
65
+
66
+ # @rbs [T] (String sql, Array[untyped] binds, bool prepare) { (PG::Result result) -> T } -> T
67
+ def run(sql, binds, prepare, &)
68
+ return @connection.exec_params(sql, binds, &) unless prepare && @statements.keeps?(binds)
69
+
70
+ name = @statements.fetch(sql) || keep(sql)
71
+ begin
72
+ @connection.exec_prepared(name, binds, &)
73
+ rescue PG::InvalidSqlStatementName, PG::FeatureNotSupported => e
74
+ raise unless stale?(e)
75
+
76
+ @statements.clear
77
+ # The failed run aborted the transaction it was in, which refuses to
78
+ # deallocate, so the statements stay on the server, unkept, until it
79
+ # closes. Only outside one can it run again, and it never executed, so a
80
+ # write isn't repeated.
81
+ raise if transaction_active?
82
+
83
+ @connection.exec('DEALLOCATE ALL').clear
84
+ @connection.exec_prepared(keep(sql), binds, &)
85
+ end
86
+ end
87
+
88
+ # Prepared before the evicted one is closed, so in an aborted transaction,
89
+ # which refuses to prepare, nothing is evicted. It's closed with the
90
+ # protocol's Close, which PgBouncer tracks as it does a prepare, and which,
91
+ # unlike DEALLOCATE, succeeds on a name DISCARD ALL dropped, so it can't
92
+ # abort a transaction. A name is never used again, so a statement an
93
+ # exception left on the server unkept can't collide.
94
+ # @rbs sql: String
95
+ # @rbs return: String
96
+ def keep(sql)
97
+ name = "skyward_#{@prepared += 1}"
98
+ @connection.prepare(name, sql).clear
99
+ evicted = @statements.store(sql, name)
100
+ @connection.close_prepared(evicted).clear if evicted
101
+ name
102
+ end
103
+
104
+ # A statement DISCARD ALL dropped is missing, and one a migration changed the
105
+ # result of is refused.
106
+ # @rbs error: PG::Error
107
+ # @rbs return: bool
108
+ def stale?(error)
109
+ error.is_a?(PG::InvalidSqlStatementName) ||
110
+ error.result&.error_field(PG::PG_DIAG_SOURCE_FUNCTION) == REVALIDATE
111
+ end
52
112
  end
@@ -4,72 +4,107 @@ module Skyward::ORM::Adapters::PostgreSQL
4
4
  extend self
5
5
 
6
6
  SQL_TYPES = {
7
- integer: "bigint",
8
- float: "double precision",
9
- string: "text",
10
- bool: "boolean",
11
- date: "date",
12
- time: "timestamptz",
13
- enum: "text"
7
+ integer: 'bigint',
8
+ float: 'double precision',
9
+ decimal: 'numeric',
10
+ string: 'text',
11
+ bool: 'boolean',
12
+ date: 'date',
13
+ time: 'timestamptz',
14
+ enum: 'text',
15
+ uuid: 'uuid',
16
+ int32: 'integer',
17
+ int16: 'smallint',
18
+ json: 'jsonb'
14
19
  }.freeze #: Hash[Skyward::ORM::Tables::column_type, String]
15
20
 
16
21
  # As the catalog spells each type, which compatible? is given.
17
22
  COMPATIBLE = {
18
23
  integer: %w[bigint integer smallint],
19
- float: ["double precision", "real"],
20
- string: ["text", "character varying", "uuid", "citext"],
21
- bool: ["boolean"],
22
- date: ["date"],
23
- time: ["timestamp with time zone", "timestamp without time zone"],
24
- enum: ["text", "character varying"]
24
+ float: ['double precision', 'real'],
25
+ decimal: ['numeric'],
26
+ string: ['text', 'character varying', 'uuid', 'citext'],
27
+ bool: ['boolean'],
28
+ date: ['date'],
29
+ time: ['timestamp with time zone', 'timestamp without time zone'],
30
+ enum: ['text', 'character varying'],
31
+ uuid: ['uuid'],
32
+ int32: ['integer'],
33
+ int16: ['smallint'],
34
+ json: %w[jsonb json]
25
35
  }.freeze #: Hash[Skyward::ORM::Tables::column_type, Array[String]]
26
36
 
37
+ # COMPATIBLE read backwards, taking the narrowest type for each.
38
+ COLUMN_TYPES = {
39
+ 'bigint' => :integer,
40
+ 'integer' => :int32,
41
+ 'smallint' => :int16,
42
+ 'double precision' => :float,
43
+ 'real' => :float,
44
+ 'numeric' => :decimal,
45
+ 'text' => :string,
46
+ 'character varying' => :string,
47
+ 'citext' => :string,
48
+ 'uuid' => :uuid,
49
+ 'boolean' => :bool,
50
+ 'date' => :date,
51
+ 'timestamp with time zone' => :time,
52
+ 'timestamp without time zone' => :time,
53
+ 'jsonb' => :json,
54
+ 'json' => :json
55
+ }.freeze #: Hash[String, Skyward::ORM::Tables::column_type]
56
+
27
57
  # The catalog puts a length or precision in parentheses.
28
58
  MODIFIER = /\(\d+(?:,\d+)?\)/ #: Regexp
29
59
 
30
60
  # UTC, so a timestamp column, which has no zone, holds the same instant as a
31
61
  # timestamptz, and to the microsecond, as PostgreSQL keeps it. Its trailing
32
62
  # zeros go, as PostgreSQL writes a time back, so a default compares as text.
33
- TIME_FORMAT = "%Y-%m-%d %H:%M:%S.%6N" #: String
63
+ TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%6N' #: String
34
64
  TRAILING_ZEROS = /\.?0+\z/ #: Regexp
35
65
 
36
- # PostgreSQL reads a literal default back cast to its type, as 'normal'::text,
37
- # and quotes a number that isn't a plain integer or decimal, as '-1'::integer.
38
- CAST = /\A(?<literal>'(?:[^']|'')*')::(?<type>[a-z ]+)\z/ #: Regexp
66
+ # PostgreSQL reads a literal default back cast to its type, as 'normal'::text
67
+ # or '{}'::text[], and quotes a number that isn't a plain integer or decimal,
68
+ # as '-1'::integer.
69
+ CAST = /\A(?<literal>'(?:[^']|'')*')::(?<type>[a-z ]+(?:\[\])?)\z/ #: Regexp
39
70
  NUMERIC = /\A(?:smallint|integer|bigint|numeric|real|double precision)\z/ #: Regexp
40
71
 
41
72
  # Float() refuses the special values PostgreSQL writes out.
42
73
  SPECIAL_FLOATS = {
43
- "Infinity" => Float::INFINITY,
44
- "-Infinity" => -Float::INFINITY,
45
- "NaN" => Float::NAN
74
+ 'Infinity' => Float::INFINITY,
75
+ '-Infinity' => -Float::INFINITY,
76
+ 'NaN' => Float::NAN
46
77
  }.freeze #: Hash[String, Float]
47
78
 
48
79
  MIGRATION_LOCK = 7_310_420_115 #: Integer
49
80
 
50
81
  # Each value comes back as text, and a boolean as t or f.
51
- TRUE_TEXT = "t" #: String
82
+ TRUE_TEXT = 't' #: String
83
+ FALSE_TEXT = 'f' #: String
52
84
 
53
85
  VIOLATIONS = {
54
- "23505" => :unique,
55
- "23503" => :foreign_key,
56
- "23502" => :not_null,
57
- "23514" => :check
86
+ '23505' => :unique,
87
+ '23503' => :foreign_key,
88
+ '23502' => :not_null,
89
+ '23514' => :check
58
90
  }.freeze #: Hash[String, Skyward::ORM::violation_kind]
59
91
 
60
92
  CONSTRAINT_KINDS = {
61
- "p" => :primary_key,
62
- "u" => :unique,
63
- "f" => :foreign_key,
64
- "c" => :check
93
+ 'p' => :primary_key,
94
+ 'u' => :unique,
95
+ 'f' => :foreign_key,
96
+ 'c' => :check
65
97
  }.freeze #: Hash[String, Skyward::ORM::Catalog::constraint_kind]
66
98
 
67
99
  # The tables an unqualified name finds, as every query names them.
68
100
  TABLES = "t.relkind IN ('r', 'p') AND t.relnamespace <> 'pg_catalog'::regnamespace " \
69
- "AND pg_table_is_visible(t.oid)" #: String
101
+ 'AND pg_table_is_visible(t.oid)' #: String
70
102
 
103
+ # pg_attrdef holds a generated column's expression as if it were its default.
71
104
  COLUMNS = <<~SQL.freeze #: String
72
- SELECT t.relname, a.attname, format_type(a.atttypid, a.atttypmod), a.attnotnull, pg_get_expr(d.adbin, d.adrelid)
105
+ SELECT t.relname, a.attname, format_type(a.atttypid, a.atttypmod), a.attnotnull,
106
+ CASE WHEN a.attgenerated = '' THEN pg_get_expr(d.adbin, d.adrelid) END,
107
+ CASE WHEN a.attgenerated <> '' THEN pg_get_expr(d.adbin, d.adrelid) END
73
108
  FROM pg_catalog.pg_class AS t
74
109
  JOIN pg_catalog.pg_attribute AS a ON a.attrelid = t.oid AND a.attnum > 0 AND NOT a.attisdropped
75
110
  LEFT JOIN pg_catalog.pg_attrdef AS d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
@@ -104,7 +139,10 @@ module Skyward::ORM::Adapters::PostgreSQL
104
139
  SQL
105
140
 
106
141
  # @rbs return: String
107
- def driver = "pg"
142
+ def driver = 'pg'
143
+
144
+ # @rbs return: Symbol
145
+ def adapter_name = :postgresql
108
146
 
109
147
  # Values are decoded from PostgreSQL's ISO text, whatever the server's
110
148
  # defaults, and times read and written in UTC. libpq prints each notice the
@@ -113,9 +151,22 @@ module Skyward::ORM::Adapters::PostgreSQL
113
151
  # @rbs location: String
114
152
  # @rbs return: Skyward::ORM::_Connection
115
153
  def connect(location)
154
+ require_close_prepared(PG::Connection)
116
155
  connection = PG.connect("postgresql://#{location}")
117
156
  connection.exec("SET TimeZone = 'UTC'; SET DateStyle = 'ISO'; SET client_min_messages = warning")
118
- Connection.new(connection)
157
+ Connection.new(connection, Skyward::ORM::Adapters::StatementCache.new)
158
+ end
159
+
160
+ # A connection closes each statement it evicts with close_prepared, which pg
161
+ # compiles only against libpq 17 and later.
162
+ # @rbs connection: Module
163
+ # @rbs return: void
164
+ def require_close_prepared(connection)
165
+ return if connection.method_defined?(:close_prepared)
166
+
167
+ raise Skyward::Core::BootError,
168
+ 'Skyward ORM needs the pg gem 1.6 or later, built against libpq 17 or later, for ' \
169
+ "PG::Connection#close_prepared. Update the pg gem, or the libpq it's built against."
119
170
  end
120
171
 
121
172
  # @rbs (String _location, Integer size) -> Integer
@@ -125,16 +176,23 @@ module Skyward::ORM::Adapters::PostgreSQL
125
176
  # @rbs return: String
126
177
  def placeholder(position) = "$#{position}"
127
178
 
179
+ # The protocol counts a statement's parameters in 16 bits.
180
+ # @rbs return: Integer
181
+ def bind_limit = 65_535
182
+
128
183
  # PostgreSQL takes an OFFSET with no LIMIT before it.
129
184
  # @rbs return: String?
130
185
  def unlimited = nil
131
186
 
132
- # @rbs type: Skyward::ORM::Tables::column_type
187
+ # @rbs column: Skyward::ORM::Tables::Column
133
188
  # @rbs return: String?
134
- def sql_type(type) = SQL_TYPES[type]
189
+ def sql_type(column)
190
+ element = column.element
191
+ element ? "#{SQL_TYPES.fetch(element)}[]" : SQL_TYPES[column.type]
192
+ end
135
193
 
136
194
  # @rbs return: String?
137
- def identity = "GENERATED ALWAYS AS IDENTITY"
195
+ def identity = 'GENERATED ALWAYS AS IDENTITY'
138
196
 
139
197
  # @rbs return: bool
140
198
  def alters_in_place? = true
@@ -149,47 +207,89 @@ module Skyward::ORM::Adapters::PostgreSQL
149
207
  def foreign_key_violations(_connection) = []
150
208
 
151
209
  # Ending the transaction released the lock, and nothing else was set.
152
- # @rbs return: String
153
- def end_migration = ""
210
+ # @rbs return: String?
211
+ def end_migration = nil
154
212
 
155
213
  # @rbs expression: String
156
214
  # @rbs return: String
157
215
  def default_expression(expression) = expression
158
216
 
159
- # @rbs type: Skyward::ORM::Tables::column_type
217
+ # @rbs default: String
218
+ # @rbs return: String
219
+ def catalog_default(default)
220
+ cast = CAST.match(default)
221
+ return default unless cast
222
+
223
+ literal = cast[:literal].to_s
224
+ NUMERIC.match?(cast[:type].to_s) ? literal.delete("'") : literal
225
+ end
226
+
227
+ # @rbs column: Skyward::ORM::Tables::Column
160
228
  # @rbs sql_type: String
161
229
  # @rbs return: bool
162
- def compatible?(type, sql_type)
163
- accepted = COMPATIBLE[type]
164
- accepted.nil? || accepted.include?(sql_type.sub(MODIFIER, ""))
230
+ def compatible?(column, sql_type)
231
+ element = column.element
232
+ return accepts?(column.type, sql_type) unless element
233
+
234
+ sql_type.end_with?('[]') && accepts?(element, sql_type.delete_suffix('[]'))
165
235
  end
166
236
 
237
+ # PostgreSQL compares numeric as it is.
238
+ # @rbs (Skyward::ORM::Tables::column_type _type, String column) -> String
239
+ def comparable(_type, column) = column
240
+
241
+ # @rbs sql_type: String
242
+ # @rbs return: Skyward::ORM::Tables::column_type?
243
+ def column_type(sql_type) = COLUMN_TYPES[sql_type.sub(MODIFIER, '')]
244
+
167
245
  # The driver sends every other value as its to_s, which PostgreSQL reads.
168
246
  # @rbs value: untyped
169
247
  # @rbs return: untyped
170
248
  def encode(value)
171
249
  case value
172
250
  when Symbol then value.name
173
- when Time then "#{value.getutc.strftime(TIME_FORMAT).sub(TRAILING_ZEROS, "")}+00"
251
+ # Without the exponent BigDecimal#to_s writes, as 0.15e1, so both adapters
252
+ # bind the same text.
253
+ # -0.0 is 0, but would be written "-0.0" and miss an = against 0 on SQLite.
254
+ when BigDecimal then (value.zero? ? BigDecimal(0) : value).to_s('F')
255
+ when Time then "#{value.getutc.strftime(TIME_FORMAT).sub(TRAILING_ZEROS, '')}+00"
174
256
  else value
175
257
  end
176
258
  end
177
259
 
178
- # @rbs type: Skyward::ORM::Tables::column_type
260
+ # The encoder quotes each item that needs it, the string NULL included. A
261
+ # boolean is written as PostgreSQL writes one back, so a default reads back
262
+ # as it was written.
263
+ # @rbs items: Array[untyped]
264
+ # @rbs return: String
265
+ def encode_array(items)
266
+ PG::TextEncoder::Array.new.encode(
267
+ items.map do |item|
268
+ case item
269
+ when true then TRUE_TEXT
270
+ when false then FALSE_TEXT
271
+ else encode(item)
272
+ end
273
+ end
274
+ )
275
+ end
276
+
277
+ # @rbs column: Skyward::ORM::Tables::Column
278
+ # @rbs value: String
279
+ # @rbs return: String
280
+ def decoding(column, value)
281
+ element = column.element
282
+ return scalar(column.type, value) unless element
283
+
284
+ decoded = scalar(element, 'item')
285
+ # Other SQL can write a NULL item, which the ORM never does; it stays nil rather than reading as false.
286
+ "::PG::TextDecoder::Array.new.decode(#{value}).map { |item| item.nil? ? nil : (#{decoded}).freeze }.freeze"
287
+ end
288
+
289
+ # @rbs column: Skyward::ORM::Tables::Column
179
290
  # @rbs value: untyped
180
291
  # @rbs return: untyped
181
- def decode(type, value)
182
- case type
183
- when :integer then Integer(value, 10)
184
- when :float then SPECIAL_FLOATS.fetch(value) { Float(value) }
185
- when :bool then value == TRUE_TEXT
186
- when :date then Date.iso8601(value)
187
- # A timestamp column's text has no zone, so it's read as the UTC it was written in.
188
- when :time then Time.new(value, in: "UTC").getutc
189
- when :enum then value.to_sym
190
- else value.freeze
191
- end
192
- end
292
+ def decode(column, value) = Skyward::ORM::Adapters.decode(self, column, value)
193
293
 
194
294
  # @rbs (Skyward::ORM::_Connection connection) -> Array[Skyward::ORM::Catalog::Table]
195
295
  def tables(connection)
@@ -198,9 +298,13 @@ module Skyward::ORM::Adapters::PostgreSQL
198
298
  connection.execute(COLUMNS).group_by(&:first).map do |name, rows|
199
299
  Skyward::ORM::Catalog::Table.new(
200
300
  name: name.to_sym,
201
- columns: rows.map do |_, column, type, not_null, default|
301
+ columns: rows.map do |_, column, type, not_null, default, generated|
202
302
  Skyward::ORM::Catalog::Column.new(
203
- name: column.to_sym, type:, nullable: not_null != TRUE_TEXT, default: default(default)
303
+ name: column.to_sym,
304
+ type:,
305
+ nullable: not_null != TRUE_TEXT,
306
+ default: default && catalog_default(default),
307
+ generated:
204
308
  )
205
309
  end,
206
310
  indexes: indexes(index_rows.fetch(name, [])),
@@ -231,6 +335,33 @@ module Skyward::ORM::Adapters::PostgreSQL
231
335
 
232
336
  private
233
337
 
338
+ # @rbs type: Skyward::ORM::Tables::column_type
339
+ # @rbs sql_type: String
340
+ # @rbs return: bool
341
+ def accepts?(type, sql_type)
342
+ accepted = COMPATIBLE[type]
343
+ accepted.nil? || accepted.include?(sql_type.sub(MODIFIER, ''))
344
+ end
345
+
346
+ # @rbs type: Skyward::ORM::Tables::column_type
347
+ # @rbs value: String
348
+ # @rbs return: String
349
+ def scalar(type, value)
350
+ case type
351
+ when :integer, :int32, :int16 then "Integer(#{value}, 10)"
352
+ when :float then "::Skyward::ORM::Adapters::PostgreSQL::SPECIAL_FLOATS.fetch(#{value}) { Float(#{value}) }"
353
+ when :decimal then "BigDecimal(#{value})"
354
+ when :bool then "#{value} == ::Skyward::ORM::Adapters::PostgreSQL::TRUE_TEXT"
355
+ when :date then "::Date.iso8601(#{value})"
356
+ # A timestamp column's text has no zone, so it's read as the UTC it was written in.
357
+ when :time then "::Time.new(#{value}, in: \"UTC\").getutc"
358
+ # An Array's item may be NULL, or an Array of its own, which names no Symbol.
359
+ when :enum then "::String.try_convert(#{value})&.to_sym"
360
+ when :json then "::JSON.parse(#{value}, freeze: true)"
361
+ else "#{value}.freeze"
362
+ end
363
+ end
364
+
234
365
  # @rbs rows: Array[Array[untyped]]
235
366
  # @rbs return: Array[Skyward::ORM::Catalog::Index]
236
367
  def indexes(rows)
@@ -260,16 +391,6 @@ module Skyward::ORM::Adapters::PostgreSQL
260
391
  end
261
392
  end
262
393
 
263
- # @rbs expression: String?
264
- # @rbs return: String?
265
- def default(expression)
266
- cast = CAST.match(expression.to_s)
267
- return expression unless cast
268
-
269
- literal = cast[:literal].to_s
270
- NUMERIC.match?(cast[:type].to_s) ? literal.delete("'") : literal
271
- end
272
-
273
394
  # @rbs tables: Array[Skyward::ORM::Catalog::Table]
274
395
  # @rbs table: String?
275
396
  # @rbs name: String?
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SQLite3::Database#execute prepares, runs and closes a new statement on every
4
+ # call, so this keeps the statements it's asked to prepare, to run again.
5
+ class Skyward::ORM::Adapters::SQLite::Connection
6
+ # @rbs @database: SQLite3::Database[SQLite3::result_as_array]
7
+ # @rbs @statements: Skyward::ORM::Adapters::StatementCache[SQLite3::Statement]
8
+
9
+ # @rbs database: SQLite3::Database[SQLite3::result_as_array]
10
+ # @rbs statements: Skyward::ORM::Adapters::StatementCache[SQLite3::Statement]
11
+ # @rbs return: void
12
+ def initialize(database, statements)
13
+ @database = database
14
+ @statements = statements
15
+ end
16
+
17
+ # @rbs sql: String
18
+ # @rbs binds: Array[untyped]
19
+ # @rbs prepare: bool
20
+ # @rbs return: Array[Array[untyped]]
21
+ def execute(sql, binds = [], prepare: false)
22
+ statement = kept(sql, binds, prepare)
23
+ return @database.execute(sql, binds) unless statement
24
+
25
+ run(statement, binds)
26
+ end
27
+
28
+ # @rbs sql: String
29
+ # @rbs *binds: untyped
30
+ # @rbs prepare: bool
31
+ # @rbs return: Array[Array[untyped]]
32
+ def execute2(sql, *binds, prepare: false)
33
+ statement = kept(sql, binds, prepare)
34
+ return @database.execute2(sql, *binds) unless statement
35
+
36
+ rows = run(statement, binds)
37
+ # Read after the run, rather than through Statement#columns, which caches
38
+ # them: SQLite prepares a statement again once the schema changes, so a
39
+ # SELECT * returns a column a migration added.
40
+ [Array.new(statement.column_count) { |index| statement.column_name(index) }, *rows]
41
+ end
42
+
43
+ # @rbs sql: String
44
+ # @rbs return: void
45
+ def execute_batch(sql)
46
+ @database.execute_batch(sql)
47
+ end
48
+
49
+ # @rbs return: Integer
50
+ def changes = @database.changes
51
+
52
+ # @rbs return: bool
53
+ def transaction_active? = @database.transaction_active?
54
+
55
+ # SQLite holds a closed database open until each of its statements is closed too.
56
+ # @rbs return: void
57
+ def close
58
+ @statements.clear.each(&:close)
59
+ @database.close
60
+ end
61
+
62
+ private
63
+
64
+ # @rbs sql: String
65
+ # @rbs binds: Array[untyped]
66
+ # @rbs prepare: bool
67
+ # @rbs return: SQLite3::Statement?
68
+ def kept(sql, binds, prepare)
69
+ return unless prepare && @statements.keeps?(binds)
70
+
71
+ @statements.fetch(sql) || @database.prepare(sql).tap do |statement|
72
+ @statements.store(sql, statement)&.close
73
+ end
74
+ end
75
+
76
+ # Reset however it ends, so no kept statement is left running, where it would
77
+ # stop a migration's DROP TABLE with "database table is locked".
78
+ # @rbs statement: SQLite3::Statement
79
+ # @rbs binds: Array[untyped]
80
+ # @rbs return: Array[Array[untyped]]
81
+ def run(statement, binds)
82
+ statement.bind_params(binds)
83
+ statement.to_a
84
+ ensure
85
+ statement.reset!
86
+ end
87
+ end
@@ -25,11 +25,11 @@ module Skyward::ORM::Adapters::SQLite::Constraints
25
25
  TABLE_CONSTRAINTS = %w[CONSTRAINT PRIMARY UNIQUE CHECK FOREIGN].freeze #: Array[String]
26
26
 
27
27
  KINDS = {
28
- "PRIMARY" => :primary_key,
29
- "UNIQUE" => :unique,
30
- "CHECK" => :check,
31
- "FOREIGN" => :foreign_key,
32
- "REFERENCES" => :foreign_key
28
+ 'PRIMARY' => :primary_key,
29
+ 'UNIQUE' => :unique,
30
+ 'CHECK' => :check,
31
+ 'FOREIGN' => :foreign_key,
32
+ 'REFERENCES' => :foreign_key
33
33
  }.freeze #: Hash[String, Skyward::ORM::Catalog::constraint_kind]
34
34
 
35
35
  # The words that start a column's next constraint, or its default or collation.
@@ -45,6 +45,24 @@ module Skyward::ORM::Adapters::SQLite::Constraints
45
45
  # @rbs return: Array[Skyward::ORM::Catalog::Constraint]
46
46
  def read(sql, columns) = definitions(sql).flat_map { |definition| constraints(sql, definition, columns) }
47
47
 
48
+ # SQLite's grammar makes GENERATED ALWAYS AS a column constraint, and
49
+ # table_xinfo doesn't give its expression, so that's read from here too.
50
+ # @rbs sql: String
51
+ # @rbs return: Hash[Symbol, String]
52
+ def generated(sql)
53
+ definitions(sql).filter_map do |definition|
54
+ tokens = definition.map(&:first)
55
+ as = definition.each_index.find do |index|
56
+ index.positive? && definition.fetch(index).last.zero? && word(tokens.fetch(index)) == 'AS'
57
+ end
58
+ next unless as
59
+
60
+ # The parenthesized tokens end with the closing parenthesis.
61
+ expression = first_parenthesized(definition.drop(as + 1))
62
+ [tokens.fetch(0)[1].to_sym, text(sql, expression.take(expression.size - 1))]
63
+ end.to_h
64
+ end
65
+
48
66
  private
49
67
 
50
68
  # The scan covers every character, since its last alternative matches any
@@ -71,12 +89,12 @@ module Skyward::ORM::Adapters::SQLite::Constraints
71
89
  case text
72
90
  when %r{\A(?:\s|--|/\*)} then nil
73
91
  when /\A"/ then [:name, text[1...-1].to_s.gsub('""', '"'), start, finish]
74
- when /\A`/ then [:name, text[1...-1].to_s.gsub("``", "`"), start, finish]
92
+ when /\A`/ then [:name, text[1...-1].to_s.gsub('``', '`'), start, finish]
75
93
  when /\A\[/ then [:name, text[1...-1].to_s, start, finish]
76
94
  when /\A'/ then [:string, text, start, finish]
77
- when "(" then [:open, text, start, finish]
78
- when ")" then [:close, text, start, finish]
79
- when "," then [:comma, text, start, finish]
95
+ when '(' then [:open, text, start, finish]
96
+ when ')' then [:close, text, start, finish]
97
+ when ',' then [:comma, text, start, finish]
80
98
  when /\A[\p{L}_]/ then [:word, text, start, finish]
81
99
  else [:other, text, start, finish]
82
100
  end
@@ -96,10 +114,10 @@ module Skyward::ORM::Adapters::SQLite::Constraints
96
114
  definition.each_with_index.filter_map do |(token, depth), index|
97
115
  kind = KINDS[word(token).to_s] if depth.zero?
98
116
  # A table's FOREIGN KEY is followed by its REFERENCES.
99
- next if kind.nil? || (column.nil? && word(token) == "REFERENCES")
117
+ next if kind.nil? || (column.nil? && word(token) == 'REFERENCES')
100
118
 
101
119
  Skyward::ORM::Catalog::Constraint.new(
102
- name: (tokens.fetch(index - 1)[1] if index > 1 && word(tokens.fetch(index - 2)) == "CONSTRAINT"),
120
+ name: (tokens.fetch(index - 1)[1] if index > 1 && word(tokens.fetch(index - 2)) == 'CONSTRAINT'),
103
121
  kind:,
104
122
  columns: column ? [column] : mentioned(first_parenthesized(definition.drop(index + 1)), columns),
105
123
  references: (referenced(tokens.drop(index)) if kind == :foreign_key),
@@ -136,8 +154,8 @@ module Skyward::ORM::Adapters::SQLite::Constraints
136
154
  clause = word(tokens.fetch(index))
137
155
  following = tokens[index + 1]
138
156
  COLUMN_CLAUSES.include?(clause.to_s) &&
139
- !(SET_TO.include?(clause) && word(tokens.fetch(index - 1)) == "SET") &&
140
- !(clause == "NOT" && following && word(following) == "DEFERRABLE")
157
+ !(SET_TO.include?(clause) && word(tokens.fetch(index - 1)) == 'SET') &&
158
+ !(clause == 'NOT' && following && word(following) == 'DEFERRABLE')
141
159
  end
142
160
  tokens.take(ending || tokens.size)
143
161
  end
@@ -168,5 +186,5 @@ module Skyward::ORM::Adapters::SQLite::Constraints
168
186
 
169
187
  # @rbs tokens: Array[token]
170
188
  # @rbs return: Symbol
171
- def referenced(tokens) = tokens.drop_while { |token| word(token) != "REFERENCES" }.fetch(1)[1].to_sym
189
+ def referenced(tokens) = tokens.drop_while { |token| word(token) != 'REFERENCES' }.fetch(1)[1].to_sym
172
190
  end