Module: BetterAuth::Schema::SQL

Defined in:
lib/better_auth/schema/sql.rb

Class Method Summary collapse

Class Method Details

.column_definition(table_name, logical_field, attributes, dialect) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/better_auth/schema/sql.rb', line 37

def column_definition(table_name, logical_field, attributes, dialect)
  column = quote(attributes[:field_name] || physical_name(logical_field), dialect)
  parts = [column, sql_type(logical_field, attributes, dialect)]
  parts << "PRIMARY KEY" if logical_field == "id"
  if attributes[:required]
    parts << "NOT NULL"
  elsif dialect == :mssql
    parts << "NULL"
  end
  default = default_sql(attributes, dialect)
  parts << "DEFAULT #{default}" if default
  parts.join(" ")
end

.create_statements(options, dialect:) ⇒ Object



8
9
10
11
12
13
# File 'lib/better_auth/schema/sql.rb', line 8

def create_statements(options, dialect:)
  dialect = dialect.to_sym
  tables = Schema.auth_tables(options)
  statements = tables.map { |logical_name, table| create_table_statement(logical_name, table, dialect, tables) }
  statements.concat(tables.flat_map { |_logical_name, table| index_statements(table, dialect) })
end

.create_table_statement(logical_name, table, dialect, tables = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/better_auth/schema/sql.rb', line 15

def create_table_statement(logical_name, table, dialect, tables = nil)
  table_name = table.fetch(:model_name)
  columns = table.fetch(:fields).map do |logical_field, attributes|
    column_definition(table_name, logical_field, attributes, dialect)
  end
  constraints = table.fetch(:fields).flat_map do |logical_field, attributes|
    field_constraints(table_name, logical_field, attributes, dialect, tables)
  end
  body = (columns + constraints).join(",\n  ")

  case dialect
  when :postgres, :sqlite
    %(CREATE TABLE IF NOT EXISTS #{quote(table_name, dialect)} (\n  #{body}\n);)
  when :mysql
    %(CREATE TABLE IF NOT EXISTS #{quote(table_name, dialect)} (\n  #{body}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;)
  when :mssql
    %(IF OBJECT_ID(N'#{quote(table_name, dialect)}', N'U') IS NULL\nCREATE TABLE #{quote(table_name, dialect)} (\n  #{body}\n);)
  else
    raise ArgumentError, "Unsupported SQL dialect: #{dialect}"
  end
end

.default_sql(attributes, dialect) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/better_auth/schema/sql.rb', line 124

def default_sql(attributes, dialect)
  default = attributes[:default_value]
  return unless default == false || default == true || default.is_a?(Numeric) || default.is_a?(String) || default.respond_to?(:call)

  if attributes[:type] == "date" && default.respond_to?(:call)
    return (dialect == :mysql) ? "CURRENT_TIMESTAMP(6)" : "CURRENT_TIMESTAMP"
  end

  case default
  when true
    (dialect == :mysql || dialect == :sqlite || dialect == :mssql) ? "1" : "true"
  when false
    (dialect == :mysql || dialect == :sqlite || dialect == :mssql) ? "0" : "false"
  when Numeric
    default.to_s
  when String
    "'#{default.gsub("'", "''")}'"
  end
end

.field_constraints(table_name, logical_field, attributes, dialect, tables = nil) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/better_auth/schema/sql.rb', line 51

def field_constraints(table_name, logical_field, attributes, dialect, tables = nil)
  constraints = []
  column = attributes[:field_name] || physical_name(logical_field)

  if attributes[:unique] && logical_field != "id"
    constraints << unique_constraint(table_name, column, dialect)
  end

  reference = attributes[:references]
  if reference
    constraints << foreign_key_constraint(table_name, column, reference, dialect, tables)
  end

  constraints
end

.foreign_key_constraint(table_name, column, reference, dialect, tables = nil) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/better_auth/schema/sql.rb', line 155

def foreign_key_constraint(table_name, column, reference, dialect, tables = nil)
  target_model = tables&.fetch(reference.fetch(:model).to_s, nil)&.fetch(:model_name) || reference.fetch(:model)
  target_field = reference.fetch(:field)
  on_delete = reference[:on_delete] ? " ON DELETE #{reference[:on_delete].to_s.upcase}" : ""

  case dialect
  when :postgres, :sqlite
    %(FOREIGN KEY (#{quote(column, dialect)}) REFERENCES #{quote(target_model, dialect)} (#{quote(target_field, dialect)})#{on_delete})
  when :mysql
    %(CONSTRAINT #{quote("fk_#{table_name}_#{column}", dialect)} FOREIGN KEY (#{quote(column, dialect)}) REFERENCES #{quote(target_model, dialect)} (#{quote(target_field, dialect)})#{on_delete})
  when :mssql
    %(CONSTRAINT #{quote("fk_#{table_name}_#{column}", dialect)} FOREIGN KEY (#{quote(column, dialect)}) REFERENCES #{quote(target_model, dialect)} (#{quote(target_field, dialect)})#{on_delete})
  end
end

.index_statements(table, dialect) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/better_auth/schema/sql.rb', line 67

def index_statements(table, dialect)
  table_name = table.fetch(:model_name)
  table.fetch(:fields).filter_map do |logical_field, attributes|
    next unless attributes[:index]

    column = attributes[:field_name] || Schema.physical_name(logical_field)
    name = "index_#{table_name}_on_#{column}"
    case dialect
    when :postgres, :sqlite
      %(CREATE INDEX IF NOT EXISTS #{quote(name, dialect)} ON #{quote(table_name, dialect)} (#{quote(column, dialect)});)
    when :mysql
      %(CREATE INDEX #{quote(name, dialect)} ON #{quote(table_name, dialect)} (#{quote(column, dialect)});)
    when :mssql
      %(IF NOT EXISTS (SELECT name FROM sys.indexes WHERE name = '#{name.gsub("'", "''")}' AND object_id = OBJECT_ID(N'#{quote(table_name, dialect)}')) CREATE INDEX #{quote(name, dialect)} ON #{quote(table_name, dialect)} (#{quote(column, dialect)});)
    end
  end
end

.physical_name(value) ⇒ Object



183
184
185
186
187
188
# File 'lib/better_auth/schema/sql.rb', line 183

def physical_name(value)
  value.to_s
    .gsub(/([a-z\d])([A-Z])/, "\\1_\\2")
    .tr("-", "_")
    .downcase
end

.quote(identifier, dialect) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/better_auth/schema/sql.rb', line 170

def quote(identifier, dialect)
  case dialect
  when :postgres, :sqlite
    %("#{identifier.to_s.gsub("\"", "\"\"")}")
  when :mysql
    "`#{identifier.to_s.gsub("`", "``")}`"
  when :mssql
    "[#{identifier.to_s.gsub("]", "]]")}]"
  else
    raise ArgumentError, "Unsupported SQL dialect: #{dialect}"
  end
end

.sql_type(logical_field, attributes, dialect) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/better_auth/schema/sql.rb', line 85

def sql_type(logical_field, attributes, dialect)
  case attributes[:type]
  when "boolean"
    case dialect
    when :mysql
      "tinyint(1)"
    when :sqlite
      "integer"
    when :mssql
      "smallint"
    else
      "boolean"
    end
  when "date"
    case dialect
    when :mysql
      "datetime(6)"
    when :sqlite
      "date"
    when :mssql
      "datetime2(3)"
    else
      "timestamptz"
    end
  when "number"
    attributes[:bigint] ? "bigint" : "integer"
  else
    if dialect == :mysql
      indexed = logical_field == "id" || attributes[:unique] || attributes[:index] || attributes[:references]
      indexed ? "varchar(191)" : "text"
    elsif dialect == :mssql
      indexed = logical_field == "id" || attributes[:unique] || attributes[:index] || attributes[:references] || attributes[:sortable]
      indexed ? "varchar(255)" : "varchar(8000)"
    else
      "text"
    end
  end
end

.unique_constraint(table_name, column, dialect) ⇒ Object



144
145
146
147
148
149
150
151
152
153
# File 'lib/better_auth/schema/sql.rb', line 144

def unique_constraint(table_name, column, dialect)
  case dialect
  when :postgres, :sqlite
    %(UNIQUE (#{quote(column, dialect)}))
  when :mysql
    %(UNIQUE KEY #{quote("uniq_#{table_name}_#{column}", dialect)} (#{quote(column, dialect)}))
  when :mssql
    %(CONSTRAINT #{quote("uniq_#{table_name}_#{column}", dialect)} UNIQUE (#{quote(column, dialect)}))
  end
end