Skip to content

Commit

Permalink
[Tests only] Expand trigger populated PK test case to run against mor…
Browse files Browse the repository at this point in the history
…e DBs
  • Loading branch information
nvasilevski committed Jan 18, 2024
1 parent 5703463 commit 2457067
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 21 deletions.
2 changes: 1 addition & 1 deletion activerecord/test/cases/persistence_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1581,7 +1581,7 @@ def test_model_with_no_auto_populated_fields_still_returns_primary_key_after_ins

assert_not_nil record.id
assert record.id > 0
end if current_adapter?(:PostgreSQLAdapter)
end if supports_insert_returning? && !current_adapter?(:SQLite3Adapter)
end

class QueryConstraintsTest < ActiveRecord::TestCase
Expand Down
51 changes: 31 additions & 20 deletions activerecord/test/schema/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1483,30 +1483,41 @@
end
end

if ActiveRecord::TestCase.current_adapter?(:PostgreSQLAdapter)
if ActiveRecord::Base.connection.supports_insert_returning? && !ActiveRecord::TestCase.current_adapter?(:SQLite3Adapter)
ActiveRecord::Base.connection.create_table :pk_autopopulated_by_a_trigger_records, force: true, id: false do |t|
t.integer :id, null: false
end

ActiveRecord::Base.connection.execute(
<<-SQL
CREATE OR REPLACE FUNCTION populate_column()
RETURNS TRIGGER AS $$
DECLARE
max_value INTEGER;
BEGIN
SELECT MAX(id) INTO max_value FROM pk_autopopulated_by_a_trigger_records;
NEW.id = COALESCE(max_value, 0) + 1;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER before_insert_trigger
BEFORE INSERT ON pk_autopopulated_by_a_trigger_records
FOR EACH ROW
EXECUTE FUNCTION populate_column();
SQL
)
if ActiveRecord::TestCase.current_adapter?(:PostgreSQLAdapter)
ActiveRecord::Base.connection.execute(
<<-SQL
CREATE OR REPLACE FUNCTION populate_column()
RETURNS TRIGGER AS $$
DECLARE
max_value INTEGER;
BEGIN
SELECT MAX(id) INTO max_value FROM pk_autopopulated_by_a_trigger_records;
NEW.id = COALESCE(max_value, 0) + 1;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER before_insert_trigger
BEFORE INSERT ON pk_autopopulated_by_a_trigger_records
FOR EACH ROW
EXECUTE FUNCTION populate_column();
SQL
)
elsif ActiveRecord::TestCase.current_adapter?(:Mysql2Adapter, :TrilogyAdapter)
ActiveRecord::Base.connection.execute(
<<-SQL
CREATE TRIGGER before_insert_trigger
BEFORE INSERT ON pk_autopopulated_by_a_trigger_records
FOR EACH ROW
SET NEW.id = (SELECT COALESCE(MAX(id), 0) + 1 FROM pk_autopopulated_by_a_trigger_records);
SQL
)
end
end

Course.connection.create_table :courses, force: true do |t|
Expand Down

0 comments on commit 2457067

Please sign in to comment.