Granite

This section is based on Granite Documentation

Installation

Add this library to your projects dependencies along with the driver in your shard.yml. This can be used with any framework but was originally designed to work with the maze framework in mind. This library will work with kemal or any other framework as well.

dependencies:
  granite_orm:
    github: mazeframework/granite-orm

  # Pick your database
  mysql:
    github: crystal-lang/crystal-mysql

  sqlite3:
    github: crystal-lang/crystal-sqlite3

  pg:
    github: will/crystal-pg

Next you will need to set the database_url to point to your database.

You will set this in the config/environments/development.yml and config/environments/test.yml

Or you can set the DATABASE_URL environment variable. This will override the environments setting.

Usage

Here is an example using Granite ORM Model

You can disable the timestamps for SqlLite since TIMESTAMP is not supported for this database:

id, created_at, updated_at

The primary key is automatically created for you and if you use timestamps they will be automatically updated for you.

Here are the MySQL field definitions for id, created_at, updated_at

Custom Primary Key

For legacy database mappings, you may already have a table and the primary key is not named id or Int64.

We have a macro called primary to help you out:

This will override the default primary key of id : Int64.

Natural Keys

For natural keys, you can set auto: false option to disable auto increment insert.

UUIDs

For databases that utilize UUIDs as the primary key, the primary macro can be used again with the auto: false option. A before_create callback can be added to the model to randomly generate and set a secure UUID on the record before it is saved to the database.

Last updated