Skip to content

Commit

Permalink
Generate UUID primary keys in the database
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewmcgarvey committed Dec 28, 2020
1 parent f667249 commit 6d2129c
Show file tree
Hide file tree
Showing 5 changed files with 9 additions and 6 deletions.
2 changes: 2 additions & 0 deletions db/migrations/20180625202051_create_line_item.cr
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
class CreateLineItem::V20180625202051 < Avram::Migrator::Migration::V1
def migrate
enable_extension "pgcrypto"

create :line_items do
primary_key id : UUID
add_timestamps
Expand Down
3 changes: 0 additions & 3 deletions db/migrations/20180628193054_create_product.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ class CreateProduct::V20180628193054 < Avram::Migrator::Migration::V1
primary_key id : UUID
add_timestamps
end

enable_extension "uuid-ossp"
execute("ALTER TABLE products ALTER COLUMN id SET DEFAULT uuid_generate_v4();")
end

def rollback
Expand Down
2 changes: 1 addition & 1 deletion spec/migrator/create_table_statement_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe Avram::Migrator::CreateTableStatement do
built.statements.size.should eq 1
built.statements.first.should eq <<-SQL
CREATE TABLE users (
id uuid PRIMARY KEY);
id uuid PRIMARY KEY DEFAULT gen_random_uuid());
SQL

built = Avram::Migrator::CreateTableStatement.new(:users).build do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ private class TableWithoutUUIDPrimaryKey < BaseModel
end

private class TableWithoutDefaultUUID < BaseModel
table :line_items do
table :prices do
end
end

Expand All @@ -23,7 +23,7 @@ describe Avram::SchemaEnforcer::EnsureUUIDPrimaryKeyHasDefault do
end

it "raises when table's uuid primary key does not have default" do
expect_schema_mismatch "Primary key on the 'line_items' table has the type set as uuid but does not have a default value." do
expect_schema_mismatch "Primary key on the 'prices' table has the type set as uuid but does not have a default value." do
Avram::SchemaEnforcer::EnsureUUIDPrimaryKeyHasDefault.new(TableWithoutDefaultUUID).validate!
end
end
Expand Down
4 changes: 4 additions & 0 deletions src/avram/migrator/columns/primary_keys/uuid_primary_key.cr
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@ module Avram::Migrator::Columns::PrimaryKeys
def column_type : String
"uuid"
end

def build : String
%( #{name} #{column_type} PRIMARY KEY DEFAULT gen_random_uuid())
end
end
end

0 comments on commit 6d2129c

Please # to comment.