Skip to content

Commit

Permalink
Document String primary keys. Fixes #1294
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink committed Jul 21, 2024
1 parent 5922f1a commit b8063ea
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/actions/guides/database/migrations.cr
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,14 @@ class Guides::Database::Migrations < GuideAction
* `Int64` - Maps to postgres `bigint`.
* `Time` - Maps to postgres `timestamptz`.
* `Bool` - Maps to postgres `boolean`.
* `Float64` - Maps to postgres `decimal`. With options for precision and scale.
* `Float64` - Maps to postgres `numeric`. With options for precision and scale.
* `UUID` - Maps to postgres `uuid`.
* `Bytes` - Maps to postgres `bytea`.
* `JSON::Any` - Maps to postgres `jsonb`.
* `Array(T)` - Maps to postgres array fields where `T` is any of the other datatypes.
> Enums are also support on the Crystal side. They map to an Int that you specify for the postgres side
### Adding a column
To add a new column, you'll use the `add` macro inside of a `create` block
Expand Down Expand Up @@ -314,6 +316,7 @@ class Guides::Database::Migrations < GuideAction
* `Int32` - maps to postgres `serial`.
* `Int64` - maps to postgres `bigserial`.
* `UUID` - maps to postgres `uuid`. Generates V4 UUID (requires the "pgcrypto" extension)
* `String` - maps to postgres `text`.
To specify your primary key, you'll use the `primary_key` method.
Expand Down
14 changes: 13 additions & 1 deletion src/actions/guides/database/models.cr
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ class Guides::Database::Models < GuideAction
### Setting the primary key
The primary key is `Int64` by default. If that's what you need, then everything is already set for
you. If you need `Int32`, `Int16`, `UUID`, or your own custom set one, you'll need to update the
you. If you need `Int32`, `Int16`, `UUID`, or your own custom `String`, you'll need to update the
`primary_key` in your `BaseModel` or set one in the `table` macro.
Setting your primary key with the `primary_key` method works the same as you did in
Expand All @@ -187,6 +187,18 @@ class Guides::Database::Models < GuideAction
end
```
For `String` primary keys, you will need to define a method that generates the value when the record is saved.
```crystal
abstract class BaseModel < Avram::Model
macro default_columns
# Sets the type for `id` to `text`
primary_key id : String = UUID.v7.to_s
timestamps
end
end
```
### Adding a column
Inside of the `table` block, you'll add the columns your model will define using the `column` method.
Expand Down

0 comments on commit b8063ea

Please sign in to comment.