Skip to content

Commit

Permalink
Migrator: create columns with NOT NULL as appropriate (#429)
Browse files Browse the repository at this point in the history
The built-in Model.migrator.create_sql will create columns
with NOT NULL unless the types are in fact nullable.
  • Loading branch information
Ryan Westlund committed Dec 15, 2020
1 parent 54365a8 commit f986984
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
21 changes: 21 additions & 0 deletions spec/granite/migrator/migrator_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ describe Granite::Migrator do
"uuid" UUID PRIMARY KEY) ;\n
SQL

Character.migrator.create_sql.should eq <<-SQL
CREATE TABLE "characters"(
"character_id" SERIAL PRIMARY KEY,
"name" TEXT NOT NULL
) ;\n
SQL

# Also check Array types for pg
ArrayModel.migrator.create_sql.should eq <<-SQL
CREATE TABLE "array_model"(
Expand Down Expand Up @@ -91,6 +98,13 @@ describe Granite::Migrator do
) ;\n
SQL

Character.migrator.create_sql.should eq <<-SQL
CREATE TABLE `characters`(
`character_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL
) ;\n
SQL

UUIDModel.migrator.create_sql.should eq <<-SQL
CREATE TABLE `uuids`(
`uuid` CHAR(36) PRIMARY KEY) ;\n
Expand Down Expand Up @@ -122,6 +136,13 @@ describe Granite::Migrator do
) ;\n
SQL

Character.migrator.create_sql.should eq <<-SQL
CREATE TABLE "characters"(
"character_id" INTEGER NOT NULL PRIMARY KEY,
"name" VARCHAR(255) NOT NULL
) ;\n
SQL

UUIDModel.migrator.create_sql.should eq <<-SQL
CREATE TABLE "uuids"(
"uuid" CHAR(36) PRIMARY KEY) ;\n
Expand Down
4 changes: 3 additions & 1 deletion src/granite/migrator.cr
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ module Granite::Migrator
"{{ann[:column_type].id}}"
{% elsif ivar.name.id == "created_at" || ivar.name.id == "updated_at" %}
resolve.call("{{ivar.name}}")
{% else %}
{% elsif ann[:nilable] %}
resolve.call("{{ivar.type.union_types.find { |t| t != Nil }.id}}")
{% else %}
resolve.call("{{ivar.type.union_types.find { |t| t != Nil }.id}}") + " NOT NULL"
{% end %}
s.puts "#{k} #{v}"
{% end %}
Expand Down

0 comments on commit f986984

Please sign in to comment.