rom-sql 3.7.0 → 3.8.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +233 -250
- data/README.md +1 -1
- data/lib/rom/sql/commands/create.rb +2 -2
- data/lib/rom/sql/dsl.rb +1 -1
- data/lib/rom/sql/errors.rb +2 -0
- data/lib/rom/sql/extensions/postgres/type_builder.rb +2 -2
- data/lib/rom/sql/function.rb +3 -3
- data/lib/rom/sql/gateway.rb +5 -5
- data/lib/rom/sql/migration/migrator.rb +2 -0
- data/lib/rom/sql/migration/sql_migration.rb +111 -0
- data/lib/rom/sql/migration/sql_parser.rb +392 -0
- data/lib/rom/sql/plugin/associates.rb +1 -1
- data/lib/rom/sql/relation/reading.rb +18 -18
- data/lib/rom/sql/schema/index_dsl.rb +0 -2
- data/lib/rom/sql/schema/inferrer.rb +1 -3
- data/lib/rom/sql/version.rb +1 -1
- data/lib/sequel/extensions/sql_migrations.rb +144 -0
- metadata +7 -4
data/README.md
CHANGED
|
@@ -46,7 +46,7 @@ module ROM
|
|
|
46
46
|
# @api private
|
|
47
47
|
def insert(tuples)
|
|
48
48
|
pks = tuples.map { |tuple| relation.insert(tuple) }
|
|
49
|
-
relation.where(relation.primary_key => pks).to_a
|
|
49
|
+
relation.dataset.where(relation.primary_key => pks).to_a
|
|
50
50
|
end
|
|
51
51
|
|
|
52
52
|
# Executes multi_insert statement and returns inserted tuples
|
|
@@ -54,7 +54,7 @@ module ROM
|
|
|
54
54
|
# @api private
|
|
55
55
|
def multi_insert(tuples)
|
|
56
56
|
pks = relation.multi_insert(tuples, return: :primary_key)
|
|
57
|
-
relation.where(relation.primary_key => pks).to_a
|
|
57
|
+
relation.dataset.where(relation.primary_key => pks).to_a
|
|
58
58
|
end
|
|
59
59
|
|
|
60
60
|
# Yields tuples for insertion or return an enumerator
|
data/lib/rom/sql/dsl.rb
CHANGED
|
@@ -89,7 +89,7 @@ module ROM
|
|
|
89
89
|
# @api private
|
|
90
90
|
def select_relations(parameters)
|
|
91
91
|
@picked_relations.fetch_or_store(parameters.hash) do
|
|
92
|
-
keys = parameters.select { |type, _| type
|
|
92
|
+
keys = parameters.select { |type, _| type.equal?(:keyreq) }
|
|
93
93
|
|
|
94
94
|
if keys.empty?
|
|
95
95
|
[relations, nil]
|
data/lib/rom/sql/errors.rb
CHANGED
|
@@ -19,6 +19,8 @@ module ROM
|
|
|
19
19
|
MissingPrimaryKeyError = Class.new(StandardError)
|
|
20
20
|
MigrationError = Class.new(StandardError)
|
|
21
21
|
UnsupportedConversion = Class.new(MigrationError)
|
|
22
|
+
SQLParseError = Class.new(MigrationError)
|
|
23
|
+
SQLEnvError = Class.new(MigrationError)
|
|
22
24
|
|
|
23
25
|
ERROR_MAP = {
|
|
24
26
|
Sequel::DatabaseError => DatabaseError,
|
|
@@ -41,11 +41,11 @@ module ROM
|
|
|
41
41
|
|
|
42
42
|
db_array_type_matcher '[]'
|
|
43
43
|
|
|
44
|
-
def map_pk_type(type, db_type, **
|
|
44
|
+
def map_pk_type(type, db_type, **)
|
|
45
45
|
if numeric?(type, db_type)
|
|
46
46
|
type = self.class.numeric_pk_type
|
|
47
47
|
else
|
|
48
|
-
type = map_type(type, db_type, **
|
|
48
|
+
type = map_type(type, db_type, **)
|
|
49
49
|
end
|
|
50
50
|
|
|
51
51
|
type.meta(primary_key: true)
|
data/lib/rom/sql/function.rb
CHANGED
|
@@ -278,15 +278,15 @@ module ROM
|
|
|
278
278
|
end
|
|
279
279
|
|
|
280
280
|
# @api private
|
|
281
|
-
def method_missing(meth, *
|
|
281
|
+
def method_missing(meth, *)
|
|
282
282
|
if func
|
|
283
283
|
if func.respond_to?(meth)
|
|
284
|
-
meta(func: func.__send__(meth, *
|
|
284
|
+
meta(func: func.__send__(meth, *))
|
|
285
285
|
else
|
|
286
286
|
super
|
|
287
287
|
end
|
|
288
288
|
else
|
|
289
|
-
meta(func: Sequel::SQL::Function.new(meth.to_s.upcase, *
|
|
289
|
+
meta(func: Sequel::SQL::Function.new(meth.to_s.upcase, *))
|
|
290
290
|
end
|
|
291
291
|
end
|
|
292
292
|
end
|
data/lib/rom/sql/gateway.rb
CHANGED
|
@@ -193,8 +193,8 @@ module ROM
|
|
|
193
193
|
# @return [Object]
|
|
194
194
|
#
|
|
195
195
|
# @api public
|
|
196
|
-
def call(function, *
|
|
197
|
-
connection[Sequel.function(function, *
|
|
196
|
+
def call(function, *)
|
|
197
|
+
connection[Sequel.function(function, *)].first.values.first
|
|
198
198
|
end
|
|
199
199
|
|
|
200
200
|
# Execute a statement
|
|
@@ -213,14 +213,14 @@ module ROM
|
|
|
213
213
|
# @return [Database::Sequel] a connection instance
|
|
214
214
|
#
|
|
215
215
|
# @api private
|
|
216
|
-
def connect(uri, *
|
|
216
|
+
def connect(uri, *)
|
|
217
217
|
case uri
|
|
218
218
|
when ::Sequel::Database
|
|
219
219
|
uri
|
|
220
220
|
when Hash
|
|
221
|
-
::Sequel.connect(uri, *
|
|
221
|
+
::Sequel.connect(uri, *)
|
|
222
222
|
else
|
|
223
|
-
::Sequel.connect(uri.to_s, *
|
|
223
|
+
::Sequel.connect(uri.to_s, *)
|
|
224
224
|
end
|
|
225
225
|
end
|
|
226
226
|
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "dry/struct"
|
|
4
|
+
|
|
5
|
+
require "rom/sql/types"
|
|
6
|
+
|
|
7
|
+
module ROM
|
|
8
|
+
module SQL
|
|
9
|
+
module Migration
|
|
10
|
+
# A single executable statement extracted from a `.sql` migration
|
|
11
|
+
# section, paired with the source line where it begins. The line is
|
|
12
|
+
# used to annotate backtraces when execution fails.
|
|
13
|
+
#
|
|
14
|
+
# @api private
|
|
15
|
+
Statement = Data.define(:sql, :line)
|
|
16
|
+
|
|
17
|
+
# A migration translated from a `.sql` file by `SQLParser`.
|
|
18
|
+
#
|
|
19
|
+
# @api private
|
|
20
|
+
class SQLMigration < Dry::Struct
|
|
21
|
+
Filename = Types::Coercible::String
|
|
22
|
+
Settings = Types::Strict::Hash.default { {} }
|
|
23
|
+
Direction = Types::Strict::Symbol.enum(:up, :down)
|
|
24
|
+
Statements = Types::Array.of(Types.Instance(Statement))
|
|
25
|
+
|
|
26
|
+
# Matches `${NAME}` substitution references in statement bodies when the
|
|
27
|
+
# `env=true` pragma is set. Only the braced form is recognized, leaving
|
|
28
|
+
# `$$`-quoted bodies and `$1` positional params untouched.
|
|
29
|
+
SUBSTITUTION = /\$\{(?<name>[A-Za-z_]\w*)\}/
|
|
30
|
+
|
|
31
|
+
attribute :filename, Filename
|
|
32
|
+
attribute :settings, Settings
|
|
33
|
+
|
|
34
|
+
attribute :up, Statements
|
|
35
|
+
attribute? :down, Statements
|
|
36
|
+
|
|
37
|
+
# Return a copy with additional settings merged in.
|
|
38
|
+
#
|
|
39
|
+
# @api private
|
|
40
|
+
def with(**settings)
|
|
41
|
+
new(settings: self.settings.merge(settings))
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Whether to run inside a transaction.
|
|
45
|
+
#
|
|
46
|
+
# @return [true, false, nil] nil leaves the choice to the database default
|
|
47
|
+
#
|
|
48
|
+
# @api private
|
|
49
|
+
def use_transactions
|
|
50
|
+
settings[:transaction]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Execute the statements for the given direction against the database.
|
|
54
|
+
#
|
|
55
|
+
# @param db [Sequel::Database]
|
|
56
|
+
# @param direction [:up, :down]
|
|
57
|
+
#
|
|
58
|
+
# @api private
|
|
59
|
+
def apply(db, direction)
|
|
60
|
+
unless Direction.valid?(direction)
|
|
61
|
+
raise ArgumentError, "Invalid migration direction specified (#{direction.inspect})"
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
statements = public_send(direction) or return
|
|
65
|
+
|
|
66
|
+
# Resolve every statement before running any, so a missing environment
|
|
67
|
+
# variable aborts before producing side effects.
|
|
68
|
+
finalized = statements.map { |statement| apply_env(statement) }
|
|
69
|
+
|
|
70
|
+
finalized.each do |statement|
|
|
71
|
+
db.run(statement.sql)
|
|
72
|
+
rescue Sequel::DatabaseError => e
|
|
73
|
+
raise annotate(e, statement, direction)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
private
|
|
78
|
+
|
|
79
|
+
# Return the statement with `${NAME}` environment-variable substitution
|
|
80
|
+
# applied to its SQL when the `env` pragma is set. Raises `SQLEnvError`
|
|
81
|
+
# for a referenced variable that is not present in `ENV`.
|
|
82
|
+
#
|
|
83
|
+
# @api private
|
|
84
|
+
def apply_env(statement)
|
|
85
|
+
return statement unless settings[:env]
|
|
86
|
+
|
|
87
|
+
sql = statement.sql.gsub(SUBSTITUTION) do
|
|
88
|
+
name = Regexp.last_match[:name]
|
|
89
|
+
ENV.fetch(name) do
|
|
90
|
+
raise SQLEnvError,
|
|
91
|
+
"Undefined environment variable ${#{name}} in #{filename}:#{statement.line}"
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
statement.with(sql:)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Prepend a synthetic frame pointing at the failing statement's source
|
|
99
|
+
# location, so the migration file appears at the top of the backtrace.
|
|
100
|
+
#
|
|
101
|
+
# @api private
|
|
102
|
+
def annotate(error, statement, direction)
|
|
103
|
+
frame = "#{filename}:#{statement.line}:in '#{direction}'"
|
|
104
|
+
trace = error.backtrace || []
|
|
105
|
+
error.set_backtrace([frame, *trace])
|
|
106
|
+
error
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "sql_migration"
|
|
4
|
+
|
|
5
|
+
module ROM
|
|
6
|
+
module SQL
|
|
7
|
+
module Migration
|
|
8
|
+
# SQL migrations have a very simple grammar:
|
|
9
|
+
#
|
|
10
|
+
# 1. Files are organized into two directions (up and down). Each
|
|
11
|
+
# direction may contain one or more `begin..end` sections; all
|
|
12
|
+
# sections for a direction execute sequentially in source order
|
|
13
|
+
# at apply time. Each section keeps its own `split=` setting,
|
|
14
|
+
# so a single direction may mix splitting strategies across
|
|
15
|
+
# sections.
|
|
16
|
+
# 2. Directives are written as SQL line comments using the `-- @migrate`
|
|
17
|
+
# sigil. The leading `--` keeps directive lines valid SQL syntax (so
|
|
18
|
+
# editors, syntax highlighters, and linters treat them as comments);
|
|
19
|
+
# the `@migrate` sigil disambiguates them from author-written `--`
|
|
20
|
+
# comments. Plain `-- ...` comments without the `@migrate` sigil are
|
|
21
|
+
# treated as part of the SQL body and pass through verbatim.
|
|
22
|
+
# 3. Optional settings may be provided in a pragma line before the up/down sections
|
|
23
|
+
# 4. Pragma and begin lines accept `key=value` settings separated by spaces or tabs
|
|
24
|
+
# 5. Each direction begins with a direction directive followed by one
|
|
25
|
+
# or more begin directives
|
|
26
|
+
# 6. The begin directive may itself carry settings (e.g. statement splitting strategy)
|
|
27
|
+
# 7. Each section concludes with an end directive
|
|
28
|
+
# 8. Down migrations are optional, but they always must follow the up migration
|
|
29
|
+
# 9. Empty sections (begin..end with no SQL body) are silently skipped
|
|
30
|
+
#
|
|
31
|
+
# Recognized settings:
|
|
32
|
+
#
|
|
33
|
+
# * Pragma line: `transaction=true|false` controls whether the migration runs
|
|
34
|
+
# inside a transaction. Any other value raises `SQLParseError`. Unknown
|
|
35
|
+
# pragma keys are silently ignored.
|
|
36
|
+
# * Pragma line: `env=true|false` enables environment-variable substitution
|
|
37
|
+
# in statement bodies (see "Variable substitution"). Any other value raises
|
|
38
|
+
# `SQLParseError`.
|
|
39
|
+
# * Begin line: `split=semicolon|line` controls statement splitting for the
|
|
40
|
+
# section's body. Default is to send the entire body to the database in a
|
|
41
|
+
# single call. Any other value raises `SQLParseError`. Unknown begin keys
|
|
42
|
+
# are silently ignored.
|
|
43
|
+
#
|
|
44
|
+
# Variable substitution:
|
|
45
|
+
#
|
|
46
|
+
# * With the `env=true` pragma, occurrences of `${NAME}` in statement bodies
|
|
47
|
+
# are replaced with `ENV["NAME"]` when the migration is applied. Names match
|
|
48
|
+
# `[A-Za-z_][A-Za-z0-9_]*`.
|
|
49
|
+
# * Only the braced form `${NAME}` is substituted. Bare `$NAME`, `$$`-quoted
|
|
50
|
+
# bodies, and `$1` positional parameters are left untouched, so the feature
|
|
51
|
+
# is safe to use alongside PostgreSQL function bodies and prepared params.
|
|
52
|
+
# * Substitution happens at apply time, so values reflect the environment when
|
|
53
|
+
# the migration runs. All of a direction's statements are resolved before
|
|
54
|
+
# any are executed, so a missing variable aborts before any side effects.
|
|
55
|
+
# * A `${NAME}` with no corresponding `ENV` entry raises `SQLEnvError`.
|
|
56
|
+
# * Values are inserted as raw SQL text (not quoted or escaped); the
|
|
57
|
+
# environment is trusted input.
|
|
58
|
+
#
|
|
59
|
+
# Splitting caveats:
|
|
60
|
+
#
|
|
61
|
+
# * `split=semicolon` splits on `;` followed by end of line. It does **not**
|
|
62
|
+
# track string literals or `$$`-quoted bodies; semicolons inside those will
|
|
63
|
+
# be mistaken for statement terminators. Use the default single-statement
|
|
64
|
+
# mode for migrations containing such content.
|
|
65
|
+
# * `split=line` emits each non-empty line as a separate statement. Plain
|
|
66
|
+
# SQL comment lines (`-- ...` without the `@migrate` sigil) are passed
|
|
67
|
+
# through verbatim and will each be sent to the database as their own
|
|
68
|
+
# (no-op) statement.
|
|
69
|
+
# * Adjacent settings on the same directive line are separated by one or
|
|
70
|
+
# more space or tab characters. Trailing whitespace after the last
|
|
71
|
+
# setting is allowed. Any other content on a directive line raises
|
|
72
|
+
# `SQLParseError`.
|
|
73
|
+
# * Windows-style line endings (`\r\n`) are normalized to `\n` at read time.
|
|
74
|
+
# * The directive prefix requires exactly one space between `--` and
|
|
75
|
+
# `@migrate` (i.e. `-- @migrate`). A bare `@migrate` at the start of a
|
|
76
|
+
# line (no `--` prefix) is treated as SQL content.
|
|
77
|
+
# * A body line of the form `[whitespace]word=word` is lexed as a setting,
|
|
78
|
+
# not SQL. Immediately after a begin directive such a line is consumed as
|
|
79
|
+
# a (possibly ignored) section setting rather than emitted as a statement.
|
|
80
|
+
#
|
|
81
|
+
# ABNF Grammar (RFC 5234 core rules: ALPHA, DIGIT, SP, HTAB, WSP, LF):
|
|
82
|
+
#
|
|
83
|
+
# ; The format is line-oriented. A blank line (LF alone) yields no
|
|
84
|
+
# ; tokens and may appear between any lines; blank lines are omitted
|
|
85
|
+
# ; below for clarity. The final line's terminating LF is optional
|
|
86
|
+
# ; (EOF may stand in for it).
|
|
87
|
+
# ;
|
|
88
|
+
# ; Disambiguation is by lexer precedence: each physical line is
|
|
89
|
+
# ; matched against the directive, pragma, then setting productions
|
|
90
|
+
# ; (in that order); a line matching none of them is a sql-line. ABNF
|
|
91
|
+
# ; cannot express that exclusion, so sql-line is descriptive.
|
|
92
|
+
#
|
|
93
|
+
# input = *pragma-line up-direction [down-direction]
|
|
94
|
+
#
|
|
95
|
+
# up-direction = up-line 1*sql-section
|
|
96
|
+
# down-direction = down-line 1*sql-section
|
|
97
|
+
# sql-section = begin-line *sql-line end-line
|
|
98
|
+
#
|
|
99
|
+
# ; Direction directives take no settings; only trailing whitespace
|
|
100
|
+
# ; may follow.
|
|
101
|
+
#
|
|
102
|
+
# up-line = "-- @migrate up" trailer newline
|
|
103
|
+
# down-line = "-- @migrate down" trailer newline
|
|
104
|
+
# end-line = "-- @migrate end" trailer newline
|
|
105
|
+
#
|
|
106
|
+
# ; begin and pragma lines may carry whitespace-separated settings.
|
|
107
|
+
#
|
|
108
|
+
# begin-line = "-- @migrate begin" *( gap setting ) trailer newline
|
|
109
|
+
# pragma-line = "-- @migrate" *( gap setting ) trailer newline
|
|
110
|
+
#
|
|
111
|
+
# setting = word "=" word
|
|
112
|
+
# word = 1*word-char
|
|
113
|
+
# word-char = ALPHA / DIGIT / "_"
|
|
114
|
+
# sql-line = 1*line-char newline
|
|
115
|
+
#
|
|
116
|
+
# ; Terminals
|
|
117
|
+
#
|
|
118
|
+
# newline = LF
|
|
119
|
+
# gap = 1*WSP ; whitespace separating settings
|
|
120
|
+
# trailer = *WSP ; optional trailing whitespace
|
|
121
|
+
# line-char = %x01-09 / %x0B-FF ; any byte except LF
|
|
122
|
+
#
|
|
123
|
+
# @api private
|
|
124
|
+
class SQLParser
|
|
125
|
+
NEWLINE = "\n"
|
|
126
|
+
|
|
127
|
+
# Matches a trailing `;` (with optional trailing horizontal whitespace)
|
|
128
|
+
# at the end of a statement buffer. `split=semicolon` treats an
|
|
129
|
+
# end-of-line `;` as a statement terminator.
|
|
130
|
+
SEMICOLON = /;[ \t]*\z/
|
|
131
|
+
|
|
132
|
+
# Each TOKENS row is `[type, regex]`. Every regex must include a
|
|
133
|
+
# `(?<value>...)` named capture identifying the substring that becomes
|
|
134
|
+
# the token's value and position. The tokenizer reads
|
|
135
|
+
# `match[:value]` for the value and `match.begin(:value)` for the
|
|
136
|
+
# column; `lpos` advances by `match.end(0)`, which may exceed the
|
|
137
|
+
# value's span when the regex consumes more (e.g. leading whitespace
|
|
138
|
+
# as a separator for the `:setting` regex).
|
|
139
|
+
#
|
|
140
|
+
# IMPORTANT: order matters. The `:pragma` regex matches the prefix
|
|
141
|
+
# of every more-specific directive (`:up`, `:down`, `:begin`,
|
|
142
|
+
# `:end`). The tokenizer uses first-match-wins, so the specific
|
|
143
|
+
# directives MUST appear before `:pragma`. When adding a new
|
|
144
|
+
# `-- @migrate <verb>` directive, insert its row above the `:pragma`
|
|
145
|
+
# row or it will be silently tokenized as a pragma.
|
|
146
|
+
TOKENS = [
|
|
147
|
+
[:up, /\A(?<value>-- @migrate up)\b/i],
|
|
148
|
+
[:down, /\A(?<value>-- @migrate down)\b/i],
|
|
149
|
+
[:begin, /\A(?<value>-- @migrate begin)\b/i],
|
|
150
|
+
[:end, /\A(?<value>-- @migrate end)\b/i],
|
|
151
|
+
[:pragma, /\A(?<value>-- @migrate)\b/i],
|
|
152
|
+
[:setting, /\A[ \t]+(?<value>\w+=\w+)\b/i],
|
|
153
|
+
]
|
|
154
|
+
|
|
155
|
+
TRAILING_WHITESPACE = /\A[ \t]*(?:\n|\z)/
|
|
156
|
+
|
|
157
|
+
class Token < String
|
|
158
|
+
attr_reader :type, :line, :pos
|
|
159
|
+
|
|
160
|
+
def initialize(value, type:, line:, pos:)
|
|
161
|
+
super(value)
|
|
162
|
+
|
|
163
|
+
@type = type
|
|
164
|
+
@line = line
|
|
165
|
+
@pos = pos
|
|
166
|
+
|
|
167
|
+
freeze
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def value = to_s
|
|
171
|
+
def inspect = "(#{type} #{super} @#{line_pos})"
|
|
172
|
+
def end = pos + length
|
|
173
|
+
def type?(name) = type == name
|
|
174
|
+
def line_pos = "#{line}:#{pos}"
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# Translate a `.sql` migration file into an `SQLMigration`.
|
|
178
|
+
#
|
|
179
|
+
# @param path [String, Pathname] absolute path to the `.sql` file
|
|
180
|
+
# @return [SQLMigration]
|
|
181
|
+
#
|
|
182
|
+
# @api private
|
|
183
|
+
def call(path)
|
|
184
|
+
@path = path
|
|
185
|
+
tokens = File.open(path, "r") { |file| tokenize(file) }
|
|
186
|
+
|
|
187
|
+
unless tokens.any? { |t| t.type != :line }
|
|
188
|
+
raise SQLParseError, "No @migrate directives found in #{path}"
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
settings = parse_pragmas(tokens)
|
|
192
|
+
up = parse_up(tokens)
|
|
193
|
+
down = parse_down(tokens)
|
|
194
|
+
|
|
195
|
+
if (stray = tokens.first)
|
|
196
|
+
raise SQLParseError,
|
|
197
|
+
"Unexpected content after final section in #{path}: " \
|
|
198
|
+
"#{stray.type} at #{location(path, stray.line, stray.pos)}"
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
attributes = { filename: path, settings:, up:, down: }.compact
|
|
202
|
+
|
|
203
|
+
SQLMigration.new(**attributes)
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
def tokenize(file)
|
|
207
|
+
lno = 0
|
|
208
|
+
tokens = []
|
|
209
|
+
|
|
210
|
+
until file.eof?
|
|
211
|
+
# Normalize line endings
|
|
212
|
+
line = file.gets.sub(/\r\n\z/, NEWLINE)
|
|
213
|
+
lno += 1
|
|
214
|
+
lpos = 0
|
|
215
|
+
|
|
216
|
+
while lpos < line.length
|
|
217
|
+
remainder = line[lpos..]
|
|
218
|
+
|
|
219
|
+
break if remainder == NEWLINE
|
|
220
|
+
|
|
221
|
+
match_type, match_data = nil
|
|
222
|
+
TOKENS.each do |type, regex|
|
|
223
|
+
if (match = remainder.match(regex))
|
|
224
|
+
match_type = type
|
|
225
|
+
match_data = match
|
|
226
|
+
break
|
|
227
|
+
end
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
if match_data
|
|
231
|
+
tokens << Token.new(
|
|
232
|
+
match_data[:value],
|
|
233
|
+
type: match_type,
|
|
234
|
+
line: lno,
|
|
235
|
+
pos: lpos + match_data.begin(:value)
|
|
236
|
+
)
|
|
237
|
+
lpos += match_data.end(0)
|
|
238
|
+
elsif lpos.zero?
|
|
239
|
+
# No directive matched at start of line: treat as a SQL line.
|
|
240
|
+
tokens << Token.new(line.chomp(NEWLINE), type: :line, line: lno, pos: lpos)
|
|
241
|
+
lpos = line.length
|
|
242
|
+
elsif remainder.match?(TRAILING_WHITESPACE)
|
|
243
|
+
# Trailing whitespace after the last setting on a directive
|
|
244
|
+
# line is allowed.
|
|
245
|
+
break
|
|
246
|
+
else
|
|
247
|
+
raise SQLParseError,
|
|
248
|
+
"Unrecognized content #{remainder.chomp.inspect} " \
|
|
249
|
+
"on directive line at #{location(@path, lno, lpos)}"
|
|
250
|
+
end
|
|
251
|
+
end
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
tokens
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def parse_pragmas(tokens)
|
|
258
|
+
settings = {}
|
|
259
|
+
|
|
260
|
+
while next?(:pragma, tokens)
|
|
261
|
+
consume(:pragma, tokens)
|
|
262
|
+
|
|
263
|
+
while next?(:setting, tokens)
|
|
264
|
+
case parse_setting(tokens)
|
|
265
|
+
in [:transaction, "true" | "false" => value]
|
|
266
|
+
settings[:transaction] = value == "true"
|
|
267
|
+
in [:env, "true" | "false" => value]
|
|
268
|
+
settings[:env] = value == "true"
|
|
269
|
+
in [(:transaction | :env) => key, value]
|
|
270
|
+
raise SQLParseError,
|
|
271
|
+
%(#{key}= must be "true" or "false", got #{value.inspect} in #{@path})
|
|
272
|
+
else
|
|
273
|
+
# ignore unknown pragma keys
|
|
274
|
+
end
|
|
275
|
+
end
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
settings
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
def parse_settings(tokens)
|
|
282
|
+
settings = {}
|
|
283
|
+
|
|
284
|
+
while next?(:setting, tokens)
|
|
285
|
+
key, value = parse_setting(tokens)
|
|
286
|
+
settings[key] = value
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
settings
|
|
290
|
+
end
|
|
291
|
+
|
|
292
|
+
def parse_setting(tokens)
|
|
293
|
+
key, value = consume(:setting, tokens).value.split("=", 2)
|
|
294
|
+
[key.to_sym, value]
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
def parse_up(tokens)
|
|
298
|
+
consume(:up, tokens)
|
|
299
|
+
parse_sections(tokens)
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
def parse_down(tokens)
|
|
303
|
+
return unless next?(:down, tokens)
|
|
304
|
+
|
|
305
|
+
consume(:down, tokens)
|
|
306
|
+
parse_sections(tokens)
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
# Parse one or more consecutive `-- @migrate begin..end` sections for
|
|
310
|
+
# the current direction and return their statements as a single flat
|
|
311
|
+
# array.
|
|
312
|
+
#
|
|
313
|
+
# @api private
|
|
314
|
+
def parse_sections(tokens)
|
|
315
|
+
statements = parse_sql(tokens)
|
|
316
|
+
|
|
317
|
+
while next?(:begin, tokens)
|
|
318
|
+
statements += parse_sql(tokens)
|
|
319
|
+
end
|
|
320
|
+
|
|
321
|
+
statements
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
# Parse a single `begin..end` section into an array of `Statement`s,
|
|
325
|
+
# applying the section's `split=` strategy.
|
|
326
|
+
#
|
|
327
|
+
# @api private
|
|
328
|
+
def parse_sql(tokens)
|
|
329
|
+
consume(:begin, tokens)
|
|
330
|
+
settings = parse_settings(tokens)
|
|
331
|
+
|
|
332
|
+
line_tokens = []
|
|
333
|
+
|
|
334
|
+
while next?(:line, tokens)
|
|
335
|
+
line_tokens << consume(:line, tokens)
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
consume(:end, tokens)
|
|
339
|
+
|
|
340
|
+
return [] if line_tokens.empty?
|
|
341
|
+
|
|
342
|
+
case settings.fetch(:split, :absent)
|
|
343
|
+
when :absent
|
|
344
|
+
[Statement.new(sql: join(line_tokens), line: line_tokens.first.line)]
|
|
345
|
+
when "line"
|
|
346
|
+
line_tokens
|
|
347
|
+
.reject { |token| token.value.strip.empty? }
|
|
348
|
+
.map { |token| Statement.new(sql: token.value, line: token.line) }
|
|
349
|
+
when "semicolon"
|
|
350
|
+
line_tokens
|
|
351
|
+
.slice_after { |token| token.value.match?(SEMICOLON) }
|
|
352
|
+
.filter_map { |group|
|
|
353
|
+
sql = join(group).sub(SEMICOLON, "")
|
|
354
|
+
Statement.new(sql: sql, line: group.first.line) unless sql.strip.empty?
|
|
355
|
+
}
|
|
356
|
+
else
|
|
357
|
+
raise SQLParseError, %(Unknown split strategy #{settings[:split].inspect}: expected "semicolon" or "line" in #{@path})
|
|
358
|
+
end
|
|
359
|
+
end
|
|
360
|
+
|
|
361
|
+
# Join line tokens back into a single SQL string.
|
|
362
|
+
#
|
|
363
|
+
# @api private
|
|
364
|
+
def join(line_tokens)
|
|
365
|
+
line_tokens.map(&:value).join(NEWLINE)
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
def next?(type, tokens)
|
|
369
|
+
return false if tokens.empty?
|
|
370
|
+
|
|
371
|
+
tokens.first.type?(type)
|
|
372
|
+
end
|
|
373
|
+
|
|
374
|
+
def consume(type, tokens)
|
|
375
|
+
if next?(type, tokens)
|
|
376
|
+
tokens.shift
|
|
377
|
+
elsif tokens.empty?
|
|
378
|
+
raise SQLParseError,
|
|
379
|
+
"Unexpected end of input in #{@path}, " \
|
|
380
|
+
"expected token of type #{type.inspect}"
|
|
381
|
+
else
|
|
382
|
+
token = tokens[0]
|
|
383
|
+
raise SQLParseError, "Expected #{type}, got #{token.type} " \
|
|
384
|
+
"at #{location(@path, token.line, token.pos)}"
|
|
385
|
+
end
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
def location(path, line, col) = "#{path}:#{line}:#{col}"
|
|
389
|
+
end
|
|
390
|
+
end
|
|
391
|
+
end
|
|
392
|
+
end
|