How do I set an unsigned integer in my model?
If you want to use unsigned integer on a database level, and you use Ecto + Postgres, I do not think there is a data type in Postgres itself that represents unsigned integers.
https://www.postgresql.org/docs/9.1/static/datatype-numeric.html
is the list of numeric data types, there is no straightforward way to create unsigned int data type as far as I understand.
You work this around by using :integer and adding a validation that checks that given value is greater/equal to 0.
Thanks hubertlepicki. I am using MariaDB/MySQL which has an unsigned attribute, is there a way to enforce this value through Ecto?
yeah, MySQL has the unsinged data type. Probably the simplest / quickest way would be to write the ALTER TABLE query by hand and execute()
it. Then use Integer data type in schema, since I do not believe there is “unsigned integer” data type on Elixir side as well. It’ll work as long as you’ll pass unsigned integers. Not sure what’ll happen when you pass negative value. You probably still need a validation.
You can set an unsigned int by passing the column type directly:
defmodule MyApp.UnsignedMigration do
@moduledoc false
use Ecto.Migration
def change do
create_if_not_exists table(:unsigned_test) do
add :signed_col, :integer, size: 6, null: false
add :unsigned_col, :"int(6) unsigned", null: false
end
end
end
Then you would have to validate in your model as @hubertlepicki says to make sure its >= 0