DB::ModelGuidesGetting Started

Getting Started

This guide explains how to use db-model for database schemas.

Installation

Add the gem to your project:

$ bundle add db-model

Core Concepts

db-model has several core concepts:

Connecting to Postgres

Add the Postgres adaptor to your project:

$ bundle add db-postgres

Set up the client with the appropriate credentials:

require 'async'
require 'db/client'
require 'db/postgres'

# Create the client and connection pool:
client = DB::Client.new(DB::Postgres::Adapter.new(database: 'test'))

# This is our database schema:
class TestSchema
	include DB::Model::Schema
	
	class User
		include DB::Model::Record
		
		property :id
		property :name
		
		def posts
			scope(Post, user_id: self.id)
		end
	end
	
	class Post
		include DB::Model::Record
		
		property :id
		property :user_id
		
		def user
			scope(User, id: self.user_id)
		end
	end
	
	def users
		table(User)
	end
	
	def posts
		table(Post)
	end
end

# Create an event loop:
Sync do
	# Connect to the database:
	client.transaction do |context|
		schema = TestSchema.new(context)
		
		# Create a user:
		user = schema.users.create(name: "Posty McPostface")
		
		# Insert several posts:
		user.posts.insert([:body], [
			["Hello World"],
			["Goodbye World"]
		])
	end
end