skyward-orm 0.2.0 → 0.4.0

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 (206) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +351 -75
  3. data/lib/skyward/orm/adapters/postgresql/connection.rb +52 -0
  4. data/lib/skyward/orm/adapters/postgresql.rb +385 -0
  5. data/lib/skyward/orm/adapters/sqlite/constraints.rb +190 -0
  6. data/lib/skyward/orm/adapters/sqlite.rb +426 -0
  7. data/lib/skyward/orm/adapters.rb +48 -0
  8. data/lib/skyward/orm/catalog/column.rb +13 -0
  9. data/lib/skyward/orm/catalog/constraint.rb +13 -0
  10. data/lib/skyward/orm/catalog/index.rb +11 -0
  11. data/lib/skyward/orm/catalog/table.rb +10 -0
  12. data/lib/skyward/orm/catalog.rb +6 -0
  13. data/lib/skyward/orm/cli/boot_file.rb +43 -0
  14. data/lib/skyward/orm/cli/migrate.rb +30 -0
  15. data/lib/skyward/orm/cli/migration.rb +111 -0
  16. data/lib/skyward/orm/cli/rollback.rb +18 -0
  17. data/lib/skyward/orm/cli/scaffold/source.rb +304 -0
  18. data/lib/skyward/orm/cli/scaffold.rb +70 -0
  19. data/lib/skyward/orm/cli/status.rb +38 -0
  20. data/lib/skyward/orm/cli.rb +4 -0
  21. data/lib/skyward/orm/commands.rb +76 -0
  22. data/lib/skyward/orm/connection/instrumented.rb +69 -0
  23. data/lib/skyward/orm/connection/pool.rb +102 -0
  24. data/lib/skyward/orm/connection/session.rb +107 -0
  25. data/lib/skyward/orm/connection.rb +7 -0
  26. data/lib/skyward/orm/database/schema_check.rb +79 -0
  27. data/lib/skyward/orm/database.rb +357 -0
  28. data/lib/skyward/orm/execution.rb +9 -0
  29. data/lib/skyward/orm/migration_error.rb +4 -0
  30. data/lib/skyward/orm/migrations/add_column.rb +7 -0
  31. data/lib/skyward/orm/migrations/add_constraint.rb +7 -0
  32. data/lib/skyward/orm/migrations/add_index.rb +7 -0
  33. data/lib/skyward/orm/migrations/alter_table.rb +16 -0
  34. data/lib/skyward/orm/migrations/change_default.rb +9 -0
  35. data/lib/skyward/orm/migrations/change_nullable.rb +8 -0
  36. data/lib/skyward/orm/migrations/change_type.rb +9 -0
  37. data/lib/skyward/orm/migrations/create_table.rb +8 -0
  38. data/lib/skyward/orm/migrations/definitions.rb +179 -0
  39. data/lib/skyward/orm/migrations/diff.rb +337 -0
  40. data/lib/skyward/orm/migrations/directory.rb +48 -0
  41. data/lib/skyward/orm/migrations/discovery.rb +14 -0
  42. data/lib/skyward/orm/migrations/drop_column.rb +7 -0
  43. data/lib/skyward/orm/migrations/drop_constraint.rb +7 -0
  44. data/lib/skyward/orm/migrations/drop_index.rb +7 -0
  45. data/lib/skyward/orm/migrations/rename_column.rb +8 -0
  46. data/lib/skyward/orm/migrations/rename_constraint.rb +8 -0
  47. data/lib/skyward/orm/migrations/runner/edited.rb +7 -0
  48. data/lib/skyward/orm/migrations/runner/failed.rb +8 -0
  49. data/lib/skyward/orm/migrations/runner/irreversible.rb +7 -0
  50. data/lib/skyward/orm/migrations/runner/locked.rb +8 -0
  51. data/lib/skyward/orm/migrations/runner/migration.rb +11 -0
  52. data/lib/skyward/orm/migrations/runner/missing.rb +7 -0
  53. data/lib/skyward/orm/migrations/runner/raced.rb +7 -0
  54. data/lib/skyward/orm/migrations/runner.rb +237 -0
  55. data/lib/skyward/orm/migrations/script.rb +390 -0
  56. data/lib/skyward/orm/migrations/status.rb +122 -0
  57. data/lib/skyward/orm/migrations/summary.rb +107 -0
  58. data/lib/skyward/orm/migrations/versions.rb +19 -0
  59. data/lib/skyward/orm/migrations.rb +8 -0
  60. data/lib/skyward/orm/pool_timeout.rb +4 -0
  61. data/lib/skyward/orm/projection.rb +86 -0
  62. data/lib/skyward/orm/queries/clauses.rb +673 -0
  63. data/lib/skyward/orm/queries.rb +4 -0
  64. data/lib/skyward/orm/query.rb +26 -0
  65. data/lib/skyward/orm/record.rb +118 -0
  66. data/lib/skyward/orm/schema_mismatch.rb +4 -0
  67. data/lib/skyward/orm/statements/placeholders.rb +37 -0
  68. data/lib/skyward/orm/statements.rb +238 -0
  69. data/lib/skyward/orm/tables/check.rb +8 -0
  70. data/lib/skyward/orm/tables/column.rb +11 -0
  71. data/lib/skyward/orm/tables/column_types.rb +121 -0
  72. data/lib/skyward/orm/tables/declarations.rb +200 -0
  73. data/lib/skyward/orm/tables/length.rb +8 -0
  74. data/lib/skyward/orm/tables/loaded.rb +21 -0
  75. data/lib/skyward/orm/tables/members.rb +16 -0
  76. data/lib/skyward/orm/tables/reference.rb +9 -0
  77. data/lib/skyward/orm/tables/rows.rb +52 -0
  78. data/lib/skyward/orm/tables/schema.rb +14 -0
  79. data/lib/skyward/orm/tables/sources.rb +63 -0
  80. data/lib/skyward/orm/tables/sql.rb +7 -0
  81. data/lib/skyward/orm/tables/validation.rb +38 -0
  82. data/lib/skyward/orm/tables/values.rb +212 -0
  83. data/lib/skyward/orm/tables.rb +8 -0
  84. data/lib/skyward/orm/transactional.rb +18 -0
  85. data/lib/skyward/orm/version.rb +1 -1
  86. data/lib/skyward/orm/violation.rb +13 -0
  87. data/lib/skyward/orm/violation_error.rb +13 -0
  88. data/lib/skyward/orm.rb +106 -1
  89. data/sig/generated/skyward/orm/adapters/postgresql/connection.rbs +41 -0
  90. data/sig/generated/skyward/orm/adapters/postgresql.rbs +177 -0
  91. data/sig/generated/skyward/orm/adapters/sqlite/constraints.rbs +93 -0
  92. data/sig/generated/skyward/orm/adapters/sqlite.rbs +226 -0
  93. data/sig/generated/skyward/orm/adapters.rbs +18 -0
  94. data/sig/generated/skyward/orm/catalog/column.rbs +22 -0
  95. data/sig/generated/skyward/orm/catalog/constraint.rbs +22 -0
  96. data/sig/generated/skyward/orm/catalog/index.rbs +20 -0
  97. data/sig/generated/skyward/orm/catalog/table.rbs +20 -0
  98. data/sig/generated/skyward/orm/catalog.rbs +5 -0
  99. data/sig/generated/skyward/orm/cli/boot_file.rbs +21 -0
  100. data/sig/generated/skyward/orm/cli/migrate.rbs +15 -0
  101. data/sig/generated/skyward/orm/cli/migration.rbs +45 -0
  102. data/sig/generated/skyward/orm/cli/rollback.rbs +7 -0
  103. data/sig/generated/skyward/orm/cli/scaffold/source.rbs +147 -0
  104. data/sig/generated/skyward/orm/cli/scaffold.rbs +28 -0
  105. data/sig/generated/skyward/orm/cli/status.rbs +17 -0
  106. data/sig/generated/skyward/orm/cli.rbs +4 -0
  107. data/sig/generated/skyward/orm/commands.rbs +2 -0
  108. data/sig/generated/skyward/orm/connection/instrumented.rbs +45 -0
  109. data/sig/generated/skyward/orm/connection/pool.rbs +54 -0
  110. data/sig/generated/skyward/orm/connection/session.rbs +59 -0
  111. data/sig/generated/skyward/orm/connection.rbs +7 -0
  112. data/sig/generated/skyward/orm/database/schema_check.rbs +38 -0
  113. data/sig/generated/skyward/orm/database.rbs +225 -0
  114. data/sig/generated/skyward/orm/execution.rbs +18 -0
  115. data/sig/generated/skyward/orm/migration_error.rbs +4 -0
  116. data/sig/generated/skyward/orm/migrations/add_column.rbs +14 -0
  117. data/sig/generated/skyward/orm/migrations/add_constraint.rbs +14 -0
  118. data/sig/generated/skyward/orm/migrations/add_index.rbs +14 -0
  119. data/sig/generated/skyward/orm/migrations/alter_table.rbs +28 -0
  120. data/sig/generated/skyward/orm/migrations/change_default.rbs +18 -0
  121. data/sig/generated/skyward/orm/migrations/change_nullable.rbs +16 -0
  122. data/sig/generated/skyward/orm/migrations/change_type.rbs +18 -0
  123. data/sig/generated/skyward/orm/migrations/create_table.rbs +16 -0
  124. data/sig/generated/skyward/orm/migrations/definitions.rbs +81 -0
  125. data/sig/generated/skyward/orm/migrations/diff.rbs +165 -0
  126. data/sig/generated/skyward/orm/migrations/directory.rbs +37 -0
  127. data/sig/generated/skyward/orm/migrations/discovery.rbs +9 -0
  128. data/sig/generated/skyward/orm/migrations/drop_column.rbs +14 -0
  129. data/sig/generated/skyward/orm/migrations/drop_constraint.rbs +14 -0
  130. data/sig/generated/skyward/orm/migrations/drop_index.rbs +14 -0
  131. data/sig/generated/skyward/orm/migrations/rename_column.rbs +16 -0
  132. data/sig/generated/skyward/orm/migrations/rename_constraint.rbs +16 -0
  133. data/sig/generated/skyward/orm/migrations/runner/edited.rbs +14 -0
  134. data/sig/generated/skyward/orm/migrations/runner/failed.rbs +16 -0
  135. data/sig/generated/skyward/orm/migrations/runner/irreversible.rbs +14 -0
  136. data/sig/generated/skyward/orm/migrations/runner/locked.rbs +16 -0
  137. data/sig/generated/skyward/orm/migrations/runner/migration.rbs +22 -0
  138. data/sig/generated/skyward/orm/migrations/runner/missing.rbs +14 -0
  139. data/sig/generated/skyward/orm/migrations/runner/raced.rbs +14 -0
  140. data/sig/generated/skyward/orm/migrations/runner.rbs +78 -0
  141. data/sig/generated/skyward/orm/migrations/script.rbs +185 -0
  142. data/sig/generated/skyward/orm/migrations/status.rbs +62 -0
  143. data/sig/generated/skyward/orm/migrations/summary.rbs +49 -0
  144. data/sig/generated/skyward/orm/migrations/versions.rbs +11 -0
  145. data/sig/generated/skyward/orm/migrations.rbs +7 -0
  146. data/sig/generated/skyward/orm/pool_timeout.rbs +4 -0
  147. data/sig/generated/skyward/orm/projection.rbs +50 -0
  148. data/sig/generated/skyward/orm/queries/clauses.rbs +403 -0
  149. data/sig/generated/skyward/orm/queries.rbs +4 -0
  150. data/sig/generated/skyward/orm/query.rbs +20 -0
  151. data/sig/generated/skyward/orm/record.rbs +88 -0
  152. data/sig/generated/skyward/orm/schema_mismatch.rbs +4 -0
  153. data/sig/generated/skyward/orm/statements/placeholders.rbs +21 -0
  154. data/sig/generated/skyward/orm/statements.rbs +131 -0
  155. data/sig/generated/skyward/orm/tables/check.rbs +16 -0
  156. data/sig/generated/skyward/orm/tables/column.rbs +22 -0
  157. data/sig/generated/skyward/orm/tables/column_types.rbs +53 -0
  158. data/sig/generated/skyward/orm/tables/declarations.rbs +101 -0
  159. data/sig/generated/skyward/orm/tables/length.rbs +16 -0
  160. data/sig/generated/skyward/orm/tables/loaded.rbs +14 -0
  161. data/sig/generated/skyward/orm/tables/members.rbs +9 -0
  162. data/sig/generated/skyward/orm/tables/reference.rbs +18 -0
  163. data/sig/generated/skyward/orm/tables/rows.rbs +24 -0
  164. data/sig/generated/skyward/orm/tables/schema.rbs +28 -0
  165. data/sig/generated/skyward/orm/tables/sources.rbs +32 -0
  166. data/sig/generated/skyward/orm/tables/sql.rbs +14 -0
  167. data/sig/generated/skyward/orm/tables/validation.rbs +9 -0
  168. data/sig/generated/skyward/orm/tables/values.rbs +89 -0
  169. data/sig/generated/skyward/orm/tables.rbs +9 -0
  170. data/sig/generated/skyward/orm/transactional.rbs +11 -0
  171. data/sig/generated/skyward/orm/violation.rbs +22 -0
  172. data/sig/generated/skyward/orm/violation_error.rbs +10 -0
  173. data/sig/generated/skyward/orm.rbs +29 -0
  174. data/sig/manual/pg.rbs +43 -0
  175. data/sig/manual/skyward/orm/adapters/postgresql.rbs +3 -0
  176. data/sig/manual/skyward/orm/adapters/sqlite/constraints.rbs +3 -0
  177. data/sig/manual/skyward/orm/adapters/sqlite.rbs +3 -0
  178. data/sig/manual/skyward/orm/adapters.rbs +3 -0
  179. data/sig/manual/skyward/orm/cli/boot_file.rbs +3 -0
  180. data/sig/manual/skyward/orm/cli/migrate.rbs +3 -0
  181. data/sig/manual/skyward/orm/cli/migration.rbs +3 -0
  182. data/sig/manual/skyward/orm/cli/rollback.rbs +3 -0
  183. data/sig/manual/skyward/orm/cli/scaffold/source.rbs +3 -0
  184. data/sig/manual/skyward/orm/cli/scaffold.rbs +3 -0
  185. data/sig/manual/skyward/orm/cli/status.rbs +3 -0
  186. data/sig/manual/skyward/orm/database/schema_check.rbs +3 -0
  187. data/sig/manual/skyward/orm/migrations/definitions.rbs +3 -0
  188. data/sig/manual/skyward/orm/migrations/diff.rbs +3 -0
  189. data/sig/manual/skyward/orm/migrations/directory.rbs +3 -0
  190. data/sig/manual/skyward/orm/migrations/discovery.rbs +3 -0
  191. data/sig/manual/skyward/orm/migrations/runner.rbs +3 -0
  192. data/sig/manual/skyward/orm/migrations/script.rbs +3 -0
  193. data/sig/manual/skyward/orm/migrations/status.rbs +3 -0
  194. data/sig/manual/skyward/orm/migrations/summary.rbs +3 -0
  195. data/sig/manual/skyward/orm/migrations/versions.rbs +3 -0
  196. data/sig/manual/skyward/orm/statements/placeholders.rbs +3 -0
  197. data/sig/manual/skyward/orm/statements.rbs +3 -0
  198. data/sig/manual/skyward/orm/tables/loaded.rbs +3 -0
  199. data/sig/manual/skyward/orm/tables/members.rbs +3 -0
  200. data/sig/manual/skyward/orm/tables/rows.rbs +3 -0
  201. data/sig/manual/skyward/orm/tables/sources.rbs +3 -0
  202. data/sig/manual/skyward/orm/tables/validation.rbs +3 -0
  203. data/sig/manual/skyward/orm/tables/values.rbs +3 -0
  204. data/sig/manual/skyward/orm.rbs +72 -0
  205. data/sig/manual/sqlite3.rbs +23 -0
  206. metadata +217 -3
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # PG::Connection runs SQL with exec_params, which returns a PG::Result, so this
4
+ # gives it the execute every adapter's connection has.
5
+ class Skyward::ORM::Adapters::PostgreSQL::Connection
6
+ # @rbs @connection: PG::Connection
7
+ # @rbs @changes: Integer
8
+
9
+ # @rbs connection: PG::Connection
10
+ # @rbs return: void
11
+ def initialize(connection)
12
+ @connection = connection
13
+ @changes = 0
14
+ end
15
+
16
+ # The block form clears each result as soon as its rows are read, so the
17
+ # rows it changed are kept for changes, as SQLite keeps them for its own.
18
+ # @rbs sql: String
19
+ # @rbs binds: Array[untyped]
20
+ # @rbs return: Array[Array[String?]]
21
+ def execute(sql, binds = [])
22
+ @connection.exec_params(sql, binds) do |result|
23
+ @changes = result.cmd_tuples
24
+ result.values
25
+ end
26
+ end
27
+
28
+ # @dynamic changes
29
+ attr_reader :changes #: Integer
30
+
31
+ # @rbs sql: String
32
+ # @rbs *binds: untyped
33
+ # @rbs return: Array[Array[String?]]
34
+ def execute2(sql, *binds) = @connection.exec_params(sql, binds) { |result| [result.fields, *result.values] }
35
+
36
+ # exec, unlike exec_params, runs every statement in the SQL.
37
+ # @rbs sql: String
38
+ # @rbs return: void
39
+ def execute_batch(sql)
40
+ @connection.exec(sql).clear
41
+ end
42
+
43
+ # Anything but idle counts, so a connection left mid-command or broken isn't
44
+ # reused either.
45
+ # @rbs return: bool
46
+ def transaction_active? = @connection.transaction_status != PG::PQTRANS_IDLE
47
+
48
+ # @rbs return: void
49
+ def close
50
+ @connection.close
51
+ end
52
+ end
@@ -0,0 +1,385 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Skyward::ORM::Adapters::PostgreSQL
4
+ extend self
5
+
6
+ SQL_TYPES = {
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"
19
+ }.freeze #: Hash[Skyward::ORM::Tables::column_type, String]
20
+
21
+ # As the catalog spells each type, which compatible? is given.
22
+ COMPATIBLE = {
23
+ integer: %w[bigint integer smallint],
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]
35
+ }.freeze #: Hash[Skyward::ORM::Tables::column_type, Array[String]]
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
+
57
+ # The catalog puts a length or precision in parentheses.
58
+ MODIFIER = /\(\d+(?:,\d+)?\)/ #: Regexp
59
+
60
+ # UTC, so a timestamp column, which has no zone, holds the same instant as a
61
+ # timestamptz, and to the microsecond, as PostgreSQL keeps it. Its trailing
62
+ # zeros go, as PostgreSQL writes a time back, so a default compares as text.
63
+ TIME_FORMAT = "%Y-%m-%d %H:%M:%S.%6N" #: String
64
+ TRAILING_ZEROS = /\.?0+\z/ #: Regexp
65
+
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
70
+ NUMERIC = /\A(?:smallint|integer|bigint|numeric|real|double precision)\z/ #: Regexp
71
+
72
+ # Float() refuses the special values PostgreSQL writes out.
73
+ SPECIAL_FLOATS = {
74
+ "Infinity" => Float::INFINITY,
75
+ "-Infinity" => -Float::INFINITY,
76
+ "NaN" => Float::NAN
77
+ }.freeze #: Hash[String, Float]
78
+
79
+ MIGRATION_LOCK = 7_310_420_115 #: Integer
80
+
81
+ # Each value comes back as text, and a boolean as t or f.
82
+ TRUE_TEXT = "t" #: String
83
+ FALSE_TEXT = "f" #: String
84
+
85
+ VIOLATIONS = {
86
+ "23505" => :unique,
87
+ "23503" => :foreign_key,
88
+ "23502" => :not_null,
89
+ "23514" => :check
90
+ }.freeze #: Hash[String, Skyward::ORM::violation_kind]
91
+
92
+ CONSTRAINT_KINDS = {
93
+ "p" => :primary_key,
94
+ "u" => :unique,
95
+ "f" => :foreign_key,
96
+ "c" => :check
97
+ }.freeze #: Hash[String, Skyward::ORM::Catalog::constraint_kind]
98
+
99
+ # The tables an unqualified name finds, as every query names them.
100
+ TABLES = "t.relkind IN ('r', 'p') AND t.relnamespace <> 'pg_catalog'::regnamespace " \
101
+ "AND pg_table_is_visible(t.oid)" #: String
102
+
103
+ # pg_attrdef holds a generated column's expression as if it were its default.
104
+ COLUMNS = <<~SQL.freeze #: String
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
108
+ FROM pg_catalog.pg_class AS t
109
+ JOIN pg_catalog.pg_attribute AS a ON a.attrelid = t.oid AND a.attnum > 0 AND NOT a.attisdropped
110
+ LEFT JOIN pg_catalog.pg_attrdef AS d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
111
+ WHERE #{TABLES}
112
+ ORDER BY t.relname, a.attnum
113
+ SQL
114
+
115
+ # Leaves out the indexes primary keys and unique constraints make, as SQLite's does.
116
+ INDEXES = <<~SQL.freeze #: String
117
+ SELECT t.relname, i.relname, x.indisunique, a.attname, pg_get_indexdef(x.indexrelid)
118
+ FROM pg_catalog.pg_index AS x
119
+ JOIN pg_catalog.pg_class AS t ON t.oid = x.indrelid
120
+ JOIN pg_catalog.pg_class AS i ON i.oid = x.indexrelid
121
+ CROSS JOIN LATERAL unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, position)
122
+ LEFT JOIN pg_catalog.pg_attribute AS a ON a.attrelid = t.oid AND a.attnum = k.attnum
123
+ WHERE #{TABLES} AND k.position <= x.indnkeyatts AND NOT EXISTS (
124
+ SELECT FROM pg_catalog.pg_constraint AS c WHERE c.conindid = x.indexrelid AND c.contype IN ('p', 'u')
125
+ )
126
+ ORDER BY t.relname, i.relname, k.position
127
+ SQL
128
+
129
+ # A check on no column has no conkey, so the join keeps it with no columns.
130
+ CONSTRAINTS = <<~SQL.freeze #: String
131
+ SELECT t.relname, c.conname, c.contype, a.attname, r.relname, pg_get_constraintdef(c.oid)
132
+ FROM pg_catalog.pg_constraint AS c
133
+ JOIN pg_catalog.pg_class AS t ON t.oid = c.conrelid
134
+ LEFT JOIN pg_catalog.pg_class AS r ON r.oid = c.confrelid
135
+ LEFT JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, position) ON true
136
+ LEFT JOIN pg_catalog.pg_attribute AS a ON a.attrelid = t.oid AND a.attnum = k.attnum
137
+ WHERE #{TABLES} AND c.contype IN ('p', 'u', 'f', 'c')
138
+ ORDER BY t.relname, c.conname, k.position
139
+ SQL
140
+
141
+ # @rbs return: String
142
+ def driver = "pg"
143
+
144
+ # @rbs return: Symbol
145
+ def adapter_name = :postgresql
146
+
147
+ # Values are decoded from PostgreSQL's ISO text, whatever the server's
148
+ # defaults, and times read and written in UTC. libpq prints each notice the
149
+ # server sends, so only warnings and worse are sent, or `skyward migrate`
150
+ # would print that schema_migrations already exists.
151
+ # @rbs location: String
152
+ # @rbs return: Skyward::ORM::_Connection
153
+ def connect(location)
154
+ connection = PG.connect("postgresql://#{location}")
155
+ connection.exec("SET TimeZone = 'UTC'; SET DateStyle = 'ISO'; SET client_min_messages = warning")
156
+ Connection.new(connection)
157
+ end
158
+
159
+ # @rbs (String _location, Integer size) -> Integer
160
+ def pool_size(_location, size) = size
161
+
162
+ # @rbs position: Integer
163
+ # @rbs return: String
164
+ def placeholder(position) = "$#{position}"
165
+
166
+ # The protocol counts a statement's parameters in 16 bits.
167
+ # @rbs return: Integer
168
+ def bind_limit = 65_535
169
+
170
+ # PostgreSQL takes an OFFSET with no LIMIT before it.
171
+ # @rbs return: String?
172
+ def unlimited = nil
173
+
174
+ # @rbs column: Skyward::ORM::Tables::Column
175
+ # @rbs return: String?
176
+ def sql_type(column)
177
+ element = column.element
178
+ element ? "#{SQL_TYPES.fetch(element)}[]" : SQL_TYPES[column.type]
179
+ end
180
+
181
+ # @rbs return: String?
182
+ def identity = "GENERATED ALWAYS AS IDENTITY"
183
+
184
+ # @rbs return: bool
185
+ def alters_in_place? = true
186
+
187
+ # A second migrator waits at the lock until the first commits, and then sees
188
+ # what it ran. Any fixed key will do: the lock is the database's own.
189
+ # @rbs return: String
190
+ def begin_migration = "BEGIN; SELECT pg_advisory_xact_lock(#{MIGRATION_LOCK})"
191
+
192
+ # PostgreSQL checks each foreign key as the migration writes.
193
+ # @rbs (Skyward::ORM::_Connection _connection) -> Array[String]
194
+ def foreign_key_violations(_connection) = []
195
+
196
+ # Ending the transaction released the lock, and nothing else was set.
197
+ # @rbs return: String?
198
+ def end_migration = nil
199
+
200
+ # @rbs expression: String
201
+ # @rbs return: String
202
+ def default_expression(expression) = expression
203
+
204
+ # @rbs default: String
205
+ # @rbs return: String
206
+ def catalog_default(default)
207
+ cast = CAST.match(default)
208
+ return default unless cast
209
+
210
+ literal = cast[:literal].to_s
211
+ NUMERIC.match?(cast[:type].to_s) ? literal.delete("'") : literal
212
+ end
213
+
214
+ # @rbs column: Skyward::ORM::Tables::Column
215
+ # @rbs sql_type: String
216
+ # @rbs return: bool
217
+ def compatible?(column, sql_type)
218
+ element = column.element
219
+ return accepts?(column.type, sql_type) unless element
220
+
221
+ sql_type.end_with?("[]") && accepts?(element, sql_type.delete_suffix("[]"))
222
+ end
223
+
224
+ # PostgreSQL compares numeric as it is.
225
+ # @rbs (Skyward::ORM::Tables::column_type _type, String column) -> String
226
+ def comparable(_type, column) = column
227
+
228
+ # @rbs sql_type: String
229
+ # @rbs return: Skyward::ORM::Tables::column_type?
230
+ def column_type(sql_type) = COLUMN_TYPES[sql_type.sub(MODIFIER, "")]
231
+
232
+ # The driver sends every other value as its to_s, which PostgreSQL reads.
233
+ # @rbs value: untyped
234
+ # @rbs return: untyped
235
+ def encode(value)
236
+ case value
237
+ when Symbol then value.name
238
+ # Without the exponent BigDecimal#to_s writes, as 0.15e1, so both adapters
239
+ # bind the same text.
240
+ # -0.0 is 0, but would be written "-0.0" and miss an = against 0 on SQLite.
241
+ when BigDecimal then (value.zero? ? BigDecimal(0) : value).to_s("F")
242
+ when Time then "#{value.getutc.strftime(TIME_FORMAT).sub(TRAILING_ZEROS, "")}+00"
243
+ else value
244
+ end
245
+ end
246
+
247
+ # The encoder quotes each item that needs it, the string NULL included. A
248
+ # boolean is written as PostgreSQL writes one back, so a default reads back
249
+ # as it was written.
250
+ # @rbs items: Array[untyped]
251
+ # @rbs return: String
252
+ def encode_array(items)
253
+ PG::TextEncoder::Array.new.encode(
254
+ items.map do |item|
255
+ case item
256
+ when true then TRUE_TEXT
257
+ when false then FALSE_TEXT
258
+ else encode(item)
259
+ end
260
+ end
261
+ )
262
+ end
263
+
264
+ # @rbs column: Skyward::ORM::Tables::Column
265
+ # @rbs value: untyped
266
+ # @rbs return: untyped
267
+ def decode(column, value)
268
+ element = column.element
269
+ return scalar(column.type, value) unless element
270
+
271
+ # Other SQL can write a NULL item, which the ORM never does; it stays nil rather than reading as false.
272
+ PG::TextDecoder::Array.new.decode(value).map { |item| item.nil? ? nil : scalar(element, item).freeze }.freeze
273
+ end
274
+
275
+ # @rbs (Skyward::ORM::_Connection connection) -> Array[Skyward::ORM::Catalog::Table]
276
+ def tables(connection)
277
+ index_rows = connection.execute(INDEXES).group_by(&:first)
278
+ constraint_rows = connection.execute(CONSTRAINTS).group_by(&:first)
279
+ connection.execute(COLUMNS).group_by(&:first).map do |name, rows|
280
+ Skyward::ORM::Catalog::Table.new(
281
+ name: name.to_sym,
282
+ columns: rows.map do |_, column, type, not_null, default, generated|
283
+ Skyward::ORM::Catalog::Column.new(
284
+ name: column.to_sym,
285
+ type:,
286
+ nullable: not_null != TRUE_TEXT,
287
+ default: default && catalog_default(default),
288
+ generated:
289
+ )
290
+ end,
291
+ indexes: indexes(index_rows.fetch(name, [])),
292
+ constraints: constraints(constraint_rows.fetch(name, []))
293
+ )
294
+ end
295
+ end
296
+
297
+ # @rbs (StandardError error, Array[Skyward::ORM::Catalog::Table] tables, Symbol? _table)
298
+ # -> Skyward::ORM::Violation?
299
+ def violation(error, tables, _table)
300
+ result = error.result if error.is_a?(PG::Error)
301
+ kind = VIOLATIONS[result&.error_field(PG::PG_DIAG_SQLSTATE).to_s]
302
+ return unless result && kind
303
+
304
+ constraint = result.error_field(PG::PG_DIAG_CONSTRAINT_NAME)
305
+ Skyward::ORM::Violation.new(
306
+ kind:,
307
+ constraint:,
308
+ columns: if kind == :not_null
309
+ [result.error_field(PG::PG_DIAG_COLUMN_NAME)].compact.map(&:to_sym)
310
+ else
311
+ constrained(tables, result.error_field(PG::PG_DIAG_TABLE_NAME), constraint)
312
+ end,
313
+ message: result.error_field(PG::PG_DIAG_MESSAGE_PRIMARY).to_s
314
+ )
315
+ end
316
+
317
+ private
318
+
319
+ # @rbs type: Skyward::ORM::Tables::column_type
320
+ # @rbs sql_type: String
321
+ # @rbs return: bool
322
+ def accepts?(type, sql_type)
323
+ accepted = COMPATIBLE[type]
324
+ accepted.nil? || accepted.include?(sql_type.sub(MODIFIER, ""))
325
+ end
326
+
327
+ # @rbs type: Skyward::ORM::Tables::column_type
328
+ # @rbs value: untyped
329
+ # @rbs return: untyped
330
+ def scalar(type, value)
331
+ case type
332
+ when :integer, :int32, :int16 then Integer(value, 10)
333
+ when :float then SPECIAL_FLOATS.fetch(value) { Float(value) }
334
+ when :decimal then BigDecimal(value)
335
+ when :bool then value == TRUE_TEXT
336
+ when :date then Date.iso8601(value)
337
+ # A timestamp column's text has no zone, so it's read as the UTC it was written in.
338
+ when :time then Time.new(value, in: "UTC").getutc
339
+ # An Array's item may be NULL, or an Array of its own, which names no Symbol.
340
+ when :enum then String.try_convert(value)&.to_sym
341
+ when :json then JSON.parse(value, freeze: true)
342
+ else value.freeze
343
+ end
344
+ end
345
+
346
+ # @rbs rows: Array[Array[untyped]]
347
+ # @rbs return: Array[Skyward::ORM::Catalog::Index]
348
+ def indexes(rows)
349
+ rows.group_by { |row| row.fetch(1) }.map do |name, keys|
350
+ Skyward::ORM::Catalog::Index.new(
351
+ name:,
352
+ # An index on an expression has no column there.
353
+ columns: keys.filter_map { |row| row.fetch(3)&.to_sym },
354
+ unique: keys.fetch(0).fetch(2) == TRUE_TEXT,
355
+ definition: keys.fetch(0).fetch(4)
356
+ )
357
+ end
358
+ end
359
+
360
+ # @rbs rows: Array[Array[untyped]]
361
+ # @rbs return: Array[Skyward::ORM::Catalog::Constraint]
362
+ def constraints(rows)
363
+ rows.group_by { |row| row.fetch(1) }.map do |name, keys|
364
+ first = keys.fetch(0)
365
+ Skyward::ORM::Catalog::Constraint.new(
366
+ name:,
367
+ kind: CONSTRAINT_KINDS.fetch(first.fetch(2)),
368
+ columns: keys.filter_map { |row| row.fetch(3)&.to_sym },
369
+ references: first.fetch(4)&.to_sym,
370
+ definition: first.fetch(5)
371
+ )
372
+ end
373
+ end
374
+
375
+ # @rbs tables: Array[Skyward::ORM::Catalog::Table]
376
+ # @rbs table: String?
377
+ # @rbs name: String?
378
+ # @rbs return: Array[Symbol]
379
+ def constrained(tables, table, name)
380
+ found = tables.find { |candidate| candidate.name.name == table }
381
+ return [] unless found
382
+
383
+ [*found.constraints, *found.indexes].find { |key| key.name == name }&.columns || []
384
+ end
385
+ end
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SQLite keeps no catalog of constraints, only each table's CREATE TABLE
4
+ # statement, so their names, kinds, columns and definitions are read from that.
5
+ module Skyward::ORM::Adapters::SQLite::Constraints
6
+ extend self
7
+
8
+ # A token's kind, its text with any quotes removed, and where it starts and
9
+ # ends in the statement, so a definition can be cut from the statement as written.
10
+ # @rbs!
11
+ # type token = [Symbol, String, Integer, Integer]
12
+
13
+ TOKEN = Regexp.union(
14
+ %r{\s+|--[^\n]*|/\*.*?\*/}m,
15
+ /"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]/,
16
+ /'(?:[^']|'')*'/,
17
+ /[\p{L}_][\p{L}\p{N}_$]*/,
18
+ /./m
19
+ ) #: Regexp
20
+
21
+ DEPTH = { open: 1, close: -1 }.freeze #: Hash[Symbol, Integer]
22
+
23
+ NAMES = %i[word name].freeze #: Array[Symbol]
24
+
25
+ TABLE_CONSTRAINTS = %w[CONSTRAINT PRIMARY UNIQUE CHECK FOREIGN].freeze #: Array[String]
26
+
27
+ KINDS = {
28
+ "PRIMARY" => :primary_key,
29
+ "UNIQUE" => :unique,
30
+ "CHECK" => :check,
31
+ "FOREIGN" => :foreign_key,
32
+ "REFERENCES" => :foreign_key
33
+ }.freeze #: Hash[String, Skyward::ORM::Catalog::constraint_kind]
34
+
35
+ # The words that start a column's next constraint, or its default or collation.
36
+ COLUMN_CLAUSES = %w[
37
+ CONSTRAINT PRIMARY NOT NULL UNIQUE CHECK DEFAULT COLLATE REFERENCES GENERATED AS
38
+ ].freeze #: Array[String]
39
+
40
+ # A reference's ON DELETE SET NULL and SET DEFAULT end in these.
41
+ SET_TO = %w[NULL DEFAULT].freeze #: Array[String]
42
+
43
+ # @rbs sql: String
44
+ # @rbs columns: Array[Symbol]
45
+ # @rbs return: Array[Skyward::ORM::Catalog::Constraint]
46
+ def read(sql, columns) = definitions(sql).flat_map { |definition| constraints(sql, definition, columns) }
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
+
66
+ private
67
+
68
+ # The scan covers every character, since its last alternative matches any
69
+ # one, so each token starts where the one before it ends.
70
+ # @rbs sql: String
71
+ # @rbs return: Array[Array[[token, Integer]]]
72
+ def definitions(sql)
73
+ texts = sql.scan(TOKEN) #: Array[String]
74
+ starts = texts.each_with_object([0]) { |text, offsets| offsets << (offsets.fetch(-1) + text.length) }
75
+ tokens = texts.each_with_index.filter_map { |text, index| token(text, starts.fetch(index)) }
76
+ body = tokens.drop_while { |token| token.first != :open }.drop(1)
77
+ depths = body.each_with_object([0]) { |token, levels| levels << (levels.fetch(-1) + DEPTH.fetch(token.first, 0)) }
78
+ paired = body.each_with_index.map { |token, index| [token, depths.fetch(index)] } #: Array[[token, Integer]]
79
+ paired.take_while { |token, depth| !(depth.zero? && token.first == :close) }
80
+ .chunk { |token, depth| depth.zero? && token.first == :comma ? :_separator : true }
81
+ .map { |_, definition| definition }
82
+ end
83
+
84
+ # @rbs text: String
85
+ # @rbs start: Integer
86
+ # @rbs return: token?
87
+ def token(text, start)
88
+ finish = start + text.length
89
+ case text
90
+ when %r{\A(?:\s|--|/\*)} then nil
91
+ 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]
93
+ when /\A\[/ then [:name, text[1...-1].to_s, start, finish]
94
+ when /\A'/ then [:string, text, start, finish]
95
+ when "(" then [:open, text, start, finish]
96
+ when ")" then [:close, text, start, finish]
97
+ when "," then [:comma, text, start, finish]
98
+ when /\A[\p{L}_]/ then [:word, text, start, finish]
99
+ else [:other, text, start, finish]
100
+ end
101
+ end
102
+
103
+ # A column's own constraints are on that column. A table constraint names
104
+ # its columns in parentheses, and a check is on the columns its expression
105
+ # mentions.
106
+ # @rbs sql: String
107
+ # @rbs definition: Array[[token, Integer]]
108
+ # @rbs columns: Array[Symbol]
109
+ # @rbs return: Array[Skyward::ORM::Catalog::Constraint]
110
+ def constraints(sql, definition, columns)
111
+ tokens = definition.map(&:first)
112
+ first = tokens.fetch(0)
113
+ column = first[1].to_sym unless TABLE_CONSTRAINTS.include?(word(first))
114
+ definition.each_with_index.filter_map do |(token, depth), index|
115
+ kind = KINDS[word(token).to_s] if depth.zero?
116
+ # A table's FOREIGN KEY is followed by its REFERENCES.
117
+ next if kind.nil? || (column.nil? && word(token) == "REFERENCES")
118
+
119
+ Skyward::ORM::Catalog::Constraint.new(
120
+ name: (tokens.fetch(index - 1)[1] if index > 1 && word(tokens.fetch(index - 2)) == "CONSTRAINT"),
121
+ kind:,
122
+ columns: column ? [column] : mentioned(first_parenthesized(definition.drop(index + 1)), columns),
123
+ references: (referenced(tokens.drop(index)) if kind == :foreign_key),
124
+ definition: column ? on_column(sql, kind, column, definition.drop(index)) : text(sql, tokens.drop(index))
125
+ )
126
+ end
127
+ end
128
+
129
+ # A column's constraint, written as the table constraint it's the same as.
130
+ # @rbs sql: String
131
+ # @rbs kind: Skyward::ORM::Catalog::constraint_kind
132
+ # @rbs column: Symbol
133
+ # @rbs rest: Array[[token, Integer]]
134
+ # @rbs return: String
135
+ def on_column(sql, kind, column, rest)
136
+ case kind
137
+ when :primary_key then "PRIMARY KEY (#{column})"
138
+ when :unique then "UNIQUE (#{column})"
139
+ when :check then text(sql, own(rest))
140
+ else "FOREIGN KEY (#{column}) #{text(sql, own(rest))}"
141
+ end
142
+ end
143
+
144
+ # A column constraint runs until the column's next clause. ON DELETE SET
145
+ # NULL and NOT DEFERRABLE are inside a reference, though, not clauses of
146
+ # their own.
147
+ # @rbs rest: Array[[token, Integer]]
148
+ # @rbs return: Array[token]
149
+ def own(rest)
150
+ tokens = rest.map(&:first)
151
+ ending = rest.each_index.find do |index|
152
+ next false if index.zero? || rest.fetch(index).last.positive?
153
+
154
+ clause = word(tokens.fetch(index))
155
+ following = tokens[index + 1]
156
+ COLUMN_CLAUSES.include?(clause.to_s) &&
157
+ !(SET_TO.include?(clause) && word(tokens.fetch(index - 1)) == "SET") &&
158
+ !(clause == "NOT" && following && word(following) == "DEFERRABLE")
159
+ end
160
+ tokens.take(ending || tokens.size)
161
+ end
162
+
163
+ # @rbs sql: String
164
+ # @rbs tokens: Array[token]
165
+ # @rbs return: String
166
+ def text(sql, tokens) = sql[tokens.fetch(0)[2]...tokens.fetch(-1)[3]].to_s
167
+
168
+ # @rbs token: token
169
+ # @rbs return: String?
170
+ def word(token) = (token[1].upcase if token.first == :word)
171
+
172
+ # @rbs rest: Array[[token, Integer]]
173
+ # @rbs return: Array[token]
174
+ def first_parenthesized(rest)
175
+ rest.drop_while { |token, _| token.first != :open }.drop(1).take_while { |_, depth| depth.positive? }.map(&:first)
176
+ end
177
+
178
+ # @rbs tokens: Array[token]
179
+ # @rbs columns: Array[Symbol]
180
+ # @rbs return: Array[Symbol]
181
+ def mentioned(tokens, columns)
182
+ tokens.filter_map do |kind, text|
183
+ columns.find { |column| column.name.casecmp?(text) } if NAMES.include?(kind)
184
+ end.uniq
185
+ end
186
+
187
+ # @rbs tokens: Array[token]
188
+ # @rbs return: Symbol
189
+ def referenced(tokens) = tokens.drop_while { |token| word(token) != "REFERENCES" }.fetch(1)[1].to_sym
190
+ end