Module: BetterAuth::Sinatra::Migration

Defined in:
lib/better_auth/sinatra/migration.rb

Defined Under Namespace

Classes: UnsupportedAdapterError

Constant Summary collapse

DEFAULT_MIGRATIONS_PATH =
"db/better_auth/migrate"
MISSING_MIGRATIONS_TABLE_MESSAGES =
[
  /no such table/i,
  /relation .* does not exist/i,
  /table .* doesn't exist/i,
  /undefined table/i,
  /invalid object name/i
].freeze

Class Method Summary collapse

Class Method Details

.applied_migrations(connection, dialect) ⇒ Object



90
91
92
93
94
95
96
97
98
99
# File 'lib/better_auth/sinatra/migration.rb', line 90

def applied_migrations(connection, dialect)
  rows = execute_sql(connection, "SELECT #{quote("version", dialect)} FROM #{quote("better_auth_schema_migrations", dialect)};")
  Array(rows).map { |row| row["version"] || row[:version] }
rescue UnsupportedAdapterError
  raise
rescue => error
  raise error unless missing_schema_migrations_table?(error)

  []
end

.auth_for(value) ⇒ Object



70
71
72
73
74
# File 'lib/better_auth/sinatra/migration.rb', line 70

def auth_for(value)
  return value if value.is_a?(BetterAuth::Auth)

  BetterAuth.auth(value)
end

.configuration_for(options) ⇒ Object



63
64
65
66
67
68
# File 'lib/better_auth/sinatra/migration.rb', line 63

def configuration_for(options)
  return options.options if options.is_a?(BetterAuth::Auth)
  return options if options.is_a?(BetterAuth::Configuration)

  BetterAuth::Configuration.new(options)
end

.dollar_quote_tag_at(sql, index) ⇒ Object



221
222
223
224
# File 'lib/better_auth/sinatra/migration.rb', line 221

def dollar_quote_tag_at(sql, index)
  match = sql[index..]&.match(/\A\$[A-Za-z_][A-Za-z0-9_]*\$|\A\$\$/)
  match&.[](0)
end

.ensure_schema_migrations!(connection, dialect) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/better_auth/sinatra/migration.rb', line 76

def ensure_schema_migrations!(connection, dialect)
  sql = case dialect
  when :postgres, :sqlite
    %(CREATE TABLE IF NOT EXISTS #{quote("better_auth_schema_migrations", dialect)} (#{quote("version", dialect)} text PRIMARY KEY);)
  when :mysql
    %(CREATE TABLE IF NOT EXISTS #{quote("better_auth_schema_migrations", dialect)} (#{quote("version", dialect)} varchar(191) PRIMARY KEY) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;)
  when :mssql
    %(IF OBJECT_ID(N'#{quote("better_auth_schema_migrations", dialect)}', N'U') IS NULL CREATE TABLE #{quote("better_auth_schema_migrations", dialect)} (#{quote("version", dialect)} varchar(255) PRIMARY KEY);)
  else
    raise UnsupportedAdapterError, "Unsupported SQL dialect for better_auth-sinatra migrations: #{dialect}"
  end
  execute_sql(connection, sql)
end

.execute_sql(connection, sql) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/better_auth/sinatra/migration.rb', line 106

def execute_sql(connection, sql)
  statements(sql).each_with_object([]) do |statement, results|
    result =
      if connection.respond_to?(:exec)
        connection.exec(statement)
      elsif connection.respond_to?(:execute)
        connection.execute(statement)
      elsif connection.respond_to?(:query)
        connection.query(statement)
      else
        raise UnsupportedAdapterError, "SQL connection does not support exec, execute, or query"
      end
    results.concat(result.to_a) if result.respond_to?(:to_a)
  end
end

.generate(options, dialect:, migrations_path: DEFAULT_MIGRATIONS_PATH, timestamp: Time.now.utc.strftime("%Y%m%d%H%M%S")) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/better_auth/sinatra/migration.rb', line 34

def generate(options, dialect:, migrations_path: DEFAULT_MIGRATIONS_PATH, timestamp: Time.now.utc.strftime("%Y%m%d%H%M%S"))
  dialect = normalize_dialect(dialect)
  FileUtils.mkdir_p(migrations_path)
  path = File.join(migrations_path, "#{timestamp}_create_better_auth_tables.sql")
  return path if File.exist?(path)

  File.write(path, render(options, dialect: dialect))
  path
end

.literal(value) ⇒ Object



235
236
237
# File 'lib/better_auth/sinatra/migration.rb', line 235

def literal(value)
  "'#{value.to_s.gsub("'", "''")}'"
end

.migrate(auth_or_options, migrations_path: DEFAULT_MIGRATIONS_PATH) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/better_auth/sinatra/migration.rb', line 44

def migrate(auth_or_options, migrations_path: DEFAULT_MIGRATIONS_PATH)
  auth = auth_for(auth_or_options)
  adapter = auth.context.adapter
  unless adapter.respond_to?(:dialect) && adapter.respond_to?(:connection)
    raise UnsupportedAdapterError, "better_auth-sinatra migrations require core SQL adapters with connection and dialect support"
  end

  connection = adapter.connection
  dialect = normalize_dialect(adapter.dialect)
  files = Dir[File.join(migrations_path, "*.sql")].sort
  ensure_schema_migrations!(connection, dialect)
  applied = applied_migrations(connection, dialect)

  files.reject { |file| applied.include?(File.basename(file)) }.each do |file|
    execute_sql(connection, File.read(file))
    record_migration(connection, dialect, File.basename(file))
  end
end

.missing_schema_migrations_table?(error) ⇒ Boolean

Returns:

  • (Boolean)


226
227
228
229
# File 'lib/better_auth/sinatra/migration.rb', line 226

def missing_schema_migrations_table?(error)
  message = error.message.to_s
  MISSING_MIGRATIONS_TABLE_MESSAGES.any? { |pattern| message.match?(pattern) }
end

.normalize_dialect(value) ⇒ Object



239
240
241
242
243
244
245
246
247
248
# File 'lib/better_auth/sinatra/migration.rb', line 239

def normalize_dialect(value)
  case value.to_s.downcase
  when "postgresql"
    :postgres
  when "sqlite3"
    :sqlite
  else
    value.to_sym
  end
end

.quote(identifier, dialect) ⇒ Object



231
232
233
# File 'lib/better_auth/sinatra/migration.rb', line 231

def quote(identifier, dialect)
  BetterAuth::Schema::SQL.quote(identifier, dialect)
end

.record_migration(connection, dialect, version) ⇒ Object



101
102
103
104
# File 'lib/better_auth/sinatra/migration.rb', line 101

def record_migration(connection, dialect, version)
  sql = "INSERT INTO #{quote("better_auth_schema_migrations", dialect)} (#{quote("version", dialect)}) VALUES (#{literal(version)});"
  execute_sql(connection, sql)
end

.render(options, dialect:) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/better_auth/sinatra/migration.rb', line 21

def render(options, dialect:)
  dialect = normalize_dialect(dialect)
  config = configuration_for(options)
  statements = BetterAuth::Schema::SQL.create_statements(config, dialect: dialect)
  [
    "-- Generated by better_auth-sinatra",
    "-- Dialect: #{dialect}",
    "",
    statements.join("\n\n"),
    ""
  ].join("\n")
end

.scan_block_comment(buffer, index, char, next_char, quote, line_comment, dollar_tag) ⇒ Object



189
190
191
192
193
194
195
196
197
# File 'lib/better_auth/sinatra/migration.rb', line 189

def scan_block_comment(buffer, index, char, next_char, quote, line_comment, dollar_tag)
  buffer << char
  if char == "*" && next_char == "/"
    buffer << next_char
    [index + 2, quote, line_comment, false, dollar_tag]
  else
    [index + 1, quote, line_comment, true, dollar_tag]
  end
end

.scan_dollar_quote(sql, buffer, index, char, quote, line_comment, block_comment, dollar_tag) ⇒ Object



199
200
201
202
203
204
205
206
207
# File 'lib/better_auth/sinatra/migration.rb', line 199

def scan_dollar_quote(sql, buffer, index, char, quote, line_comment, block_comment, dollar_tag)
  if sql[index, dollar_tag.length] == dollar_tag
    buffer << dollar_tag
    [index + dollar_tag.length, quote, line_comment, block_comment, nil]
  else
    buffer << char
    [index + 1, quote, line_comment, block_comment, dollar_tag]
  end
end

.scan_line_comment(buffer, index, char) ⇒ Object



184
185
186
187
# File 'lib/better_auth/sinatra/migration.rb', line 184

def scan_line_comment(buffer, index, char)
  buffer << char
  [index + 1]
end

.scan_quoted_string(sql, buffer, index, char, quote, line_comment, block_comment, dollar_tag) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
# File 'lib/better_auth/sinatra/migration.rb', line 209

def scan_quoted_string(sql, buffer, index, char, quote, line_comment, block_comment, dollar_tag)
  buffer << char
  if char == quote && sql[index + 1] == quote
    buffer << sql[index + 1]
    [index + 2, quote, line_comment, block_comment, dollar_tag]
  elsif char == quote
    [index + 1, nil, line_comment, block_comment, dollar_tag]
  else
    [index + 1, quote, line_comment, block_comment, dollar_tag]
  end
end

.scan_sql_character(sql, buffer, index, state, output) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/better_auth/sinatra/migration.rb', line 153

def scan_sql_character(sql, buffer, index, state, output)
  char = sql[index]
  next_char = sql[index + 1]
  quote = state[:quote]
  line_comment = state[:line_comment]
  block_comment = state[:block_comment]
  dollar_tag = state[:dollar_tag]

  return scan_line_comment(buffer, index, char) + [quote, false, block_comment, dollar_tag] if line_comment && char == "\n"
  return scan_line_comment(buffer, index, char) + [quote, true, block_comment, dollar_tag] if line_comment
  return scan_block_comment(buffer, index, char, next_char, quote, line_comment, dollar_tag) if block_comment
  return scan_dollar_quote(sql, buffer, index, char, quote, line_comment, block_comment, dollar_tag) if dollar_tag
  return scan_quoted_string(sql, buffer, index, char, quote, line_comment, block_comment, dollar_tag) if quote
  return [index + 2, quote, true, block_comment, dollar_tag].tap { buffer << char << next_char } if char == "-" && next_char == "-"
  return [index + 2, quote, line_comment, true, dollar_tag].tap { buffer << char << next_char } if char == "/" && next_char == "*"

  tag = dollar_quote_tag_at(sql, index)
  return [index + tag.length, quote, line_comment, block_comment, tag].tap { buffer << tag } if tag
  return [index + 1, char, line_comment, block_comment, dollar_tag].tap { buffer << char } if char == "'" || char == "\""

  if char == ";"
    statement = buffer.strip
    output << statement unless statement.empty?
    buffer.clear
    return [index + 1, quote, line_comment, block_comment, dollar_tag]
  end

  buffer << char
  [index + 1, quote, line_comment, block_comment, dollar_tag]
end

.split_sql_statements(sql) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/better_auth/sinatra/migration.rb', line 129

def split_sql_statements(sql)
  output = []
  buffer = +""
  index = 0
  quote = nil
  line_comment = false
  block_comment = false
  dollar_tag = nil

  while index < sql.length
    state = {
      quote: quote,
      line_comment: line_comment,
      block_comment: block_comment,
      dollar_tag: dollar_tag
    }
    index, quote, line_comment, block_comment, dollar_tag = scan_sql_character(sql, buffer, index, state, output)
  end

  tail = buffer.strip
  output << tail unless tail.empty?
  output
end

.statements(sql) ⇒ Object



122
123
124
125
126
127
# File 'lib/better_auth/sinatra/migration.rb', line 122

def statements(sql)
  normalized = sql.to_s.gsub("\r\n", "\n").strip
  return [] if normalized.empty?

  split_sql_statements(normalized)
end