Skip to content

Commit

Permalink
Add ability to switch to "default" schema
Browse files Browse the repository at this point in the history
  • Loading branch information
pnomolos committed Sep 12, 2022
1 parent 188c0a4 commit 6a2aa61
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
1 change: 1 addition & 0 deletions lib/chrono_model/adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ def on_history_schema(&block)

def on_schema(schema, recurse: :follow)
schema_stack_ensure_default
schema = schema_stack.first if schema == :default

# Keep the value outside of the closure so we can track when
# we need to pop the value for recurse: :ignore
Expand Down
36 changes: 21 additions & 15 deletions lib/chrono_model/adapter/ddl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,36 +14,42 @@ def chrono_public_view_ddl(table, options = nil)
history = [HISTORY_SCHEMA, table].join('.')

options ||= chrono_metadata_for(table)
columns = columns(table).reject { |c| c.name == pk }

# SELECT - return only current data
#
on_schema("DEFAULT") do
# We use :default here in the case of being already inside an `on_schema` call
on_schema(:default) do
execute "DROP VIEW #{table}" if data_source_exists? table
execute "CREATE VIEW #{table} AS SELECT * FROM ONLY #{current}"

chrono_metadata_set(table, options.merge(chronomodel: VERSION))

end
# Set default values on the view (closes #12)
#
columns(table).each do |column|
default = if column.default.nil?
column.default_function
else
quote(column.default)
end
statements = columns.map do |column|
default = if column.default.nil?
column.default_function
else
quote(column.default)
end

next if column.name == pk || default.nil?
next if default.nil?

execute "ALTER VIEW #{table} ALTER COLUMN #{quote_column_name(column.name)} SET DEFAULT #{default}"
end
"ALTER VIEW #{table} ALTER COLUMN #{quote_column_name(column.name)} SET DEFAULT #{default}"
end.compact

on_schema(:default) do
statements.each { |stmt| execute stmt }
end

columns = self.columns(table).map {|c| quote_column_name(c.name)}
columns.delete(quote_column_name(pk))
quoted_columns = columns.map { |c| quote_column_name(c.name) }

fields, values = columns.join(', '), columns.map {|c| "NEW.#{c}"}.join(', ')
fields, values = quoted_columns.join(', '), quoted_columns.map {|c| "NEW.#{c}"}.join(', ')

on_schema(:default) do
chrono_create_INSERT_trigger(table, pk, current, history, fields, values)
chrono_create_UPDATE_trigger(table, pk, current, history, fields, values, options, columns)
chrono_create_UPDATE_trigger(table, pk, current, history, fields, values, options, quoted_columns)
chrono_create_DELETE_trigger(table, pk, current, history)
end
end
Expand Down

0 comments on commit 6a2aa61

Please sign in to comment.