A simple and useful db wrapper for Crystal-lang
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
bin
db
samples
spec
src
.gitignore
.travis.yml
LICENSE
Makefile
README.md
shard.yml

README.md

Topaz Build Status GitHub release

Dependency Status devDependency Status

Topaz is a simple and useful db wrapper for crystal lang. Topaz is inspired by active record design pattern, but not fully implemented. See sample code for detail. Here is another sample that shows how Topaz works in Kemal.
Depends on crystal-lang/crystal-mysql, crystal-lang/crystal-sqlite3 and crystal-pg

Usage

1. Setup DB

Topaz::Db.setup("mysql://root@localhost/topaz") # For MySQL
Topaz::Db.setup("postgres://root@localhost/topaz") # For PostgreSQL
Topaz::Db.setup("sqlite3://./db/data.db") # For SQLite3

2. Define models

class SampleModel < Topaz::Model
  columns(
    name: String
  )
end

# You can drop or create a table
SampleModel.create_table
SampleModel.drop_table

3. Create, find, update and delete models

s = SampleModel.create("Sample Name")

SampleModel.find(1).name
# => "Sample Name"
SampleModel.where("name = 'Sample Name'").size
# => 1

See sample code for detail.

4. Define associations between models

require "topaz"

class SampleParent < Topaz::Model
  columns # Empty columns
  has_many(children: {model: SampleChild, key: parent_id})
end

class SampleChild < Topaz::Model
  columns( # Define foreign key
    parent_id: Int32
  )
  belongs_to(parent: {model: SampleParent, key: parent_id})
end

p = SampleParent.create

child1 = SampleChild.create(p.id)
child2 = SampleChild.create(p.id)
child3 = SampleChild.create(p.id)

p.children.size
# => 3

child1.parent.id
# => 1

See sample code for detail.

Other features

  • Transaction
  • Table migration
  • Model#to_json and Model#from_json
  • created_at and updated_at column
  • Nullable column
  • Column with default value
  • Change id from Int32 to Int64

See sample codes for detail.

Supported data types.
String, Int32, Int64, Float32, Float64

Development

Setting up PostgreSQL:

$ psql
  # CREATE USER root WITH CREATEDB;
  # CREATE DATABASE topaz_test WITH OWNER = root;

Setting up MySQL:

$ mysql -u root
mysql> create database topaz_test;

Contributing

  1. Fork it ( https://github.com/topaz-crystal/topaz/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

  • tbrand Taichiro Suzuki - creator, maintainer