• Stars
    star
    22
  • Rank 1,048,934 (Top 21 %)
  • Language
    Crystal
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

driver for rethinkdb / rebirthdb

Crystal RethinkDB

This is a RethinkDB Driver for the Crystal Language.

CI Crystal Version

Installation

Add this to your application's shard.yml:

dependencies:
  rethinkdb:
    github: kingsleyh/crystal-rethinkdb

Usage

This library is meant to be compatible with RethinkDB's Ruby API. Thus, all official documentation should be valid here. If you find something that behaves differently, please open an issue.

require "rethinkdb"
include RethinkDB::Shortcuts

# Let’s connect and create a table:

conn = r.connect(host: "localhost")
r.db("test").table_create("tv_shows").run(conn)

# Now, let’s insert some JSON documents into the table:

r.table("tv_shows").insert([
  {name: "Star Trek TNG", episodes: 178},
  {name: "Battlestar Galactica", episodes: 75}
]).run(conn)

# We’ve just inserted two rows into the tv_shows table. Let’s verify the number of rows inserted:

pp r.table("tv_shows").count().run(conn)

# Finally, let’s do a slightly more sophisticated query. Let’s find all shows with more than 100 episodes.

p r.table("tv_shows").filter {|show| show["episodes"] > 100 }.run(conn).to_a

# As a result, we of course get the best science fiction show in existence.

Connecting as a user

If you made a user called bob with password secret in the rethinkdb system table users e.g.:

r.db('rethinkdb').table('users').insert({id: 'bob', password: 'secret'})
require "rethinkdb"
include RethinkDB::Shortcuts

conn = r.connect(host: "localhost", db: "my_database", user: "bob", password: "secret")

Read more about users and permissions here: https://rethinkdb.com/docs/permissions-and-accounts/

Useful Queries

Here are some more complex queries - mostly as a reminder to myself on how to do various more complicated things:

Something to note is that depending on the query you write you could get back one of these 3 things:

  • RethinkDB::QueryResult
  • RethinkDB:Cursor
  • RethinkDB::Array(RethinkDB::QueryResult)
Inserting
r.table("users").insert({
                      name: name, email: email, password: password,
                      activeChannel: {} of String => String,
                      channels: [] of String, groups: [] of String,
                      isOnline: false
                      }
                    ).run(@connection)
r.table("messages").insert({channelId: channelId, userId: userId, content: content, date: r.now.to_iso8601}).run(@connection)
Finding All
r.table("users").map{|u|
         {id: u["id"], name: u["name"], isOnline: u["isOnline"]}
      }.run(@connection) }
r.table("users").filter{|u| r.expr(u["groups"]).contains(groupId) }.map{|u|
         {id: u["id"], name: u["name"], isOnline: u["isOnline"]}
      }.run(@connection)
r.table("groups").map{|g|
         {id: g["id"], name: g["name"], landingChannel: r.table("channels").filter({isLanding: true, groupId: g["id"]})[0]["id"]}
      }.run(@connection)
r.table("users").filter({id: userId}).map{|user|
                        {
                         channels: r.table("channels").filter{|ch| ch["groupId"] == groupId}.coerce_to("array"),
                         activeChannel: r.branch(user["activeChannel"].has_fields("channelId"),
                                          {groupId: user["activeChannel"]["groupId"], channelId: user["activeChannel"]["channelId"], name: r.table("channels").get(user["activeChannel"]["channelId"])["name"]},
                                          {groupId: "", channelId: "", name: ""}),
                         groupId: r.table("groups").get(groupId)["id"],
                         name: r.table("groups").get(groupId)["name"]
                         }
                       }.run(@connection)
Finding One
r.table("users").get(userId).run(@connection)
  r.table("users").filter({id: userId}).map{|user|
                        {
                        channels: r.table("channels").filter{|ch| r.expr(user["channels"]).contains(ch["id"])}.filter{|ch| ch["groupId"] == groupId}.coerce_to("array"),
                        groups: r.table("groups").filter{|g| r.expr(user["groups"]).contains(g["id"])}.map{|g| {id: g["id"], name: g["name"], landingChannel: r.table("channels").filter({isLanding: true, groupId: g["id"]})[0]["id"]}}.coerce_to("array"),
                        messages: r.table("messages").filter{|m| m["channelId"] == channelId }.map{|m| {messageId: m["id"], userId: m["userId"], name: r.table("users").get(m["userId"])["name"], content: m["content"], date: m["date"]} }.coerce_to("array"),
                        channel: r.table("channels").get(channelId),
                        group: r.table("groups").get(groupId),
                        userIsOnline: user["isOnline"]
                        }
                      }.run(@connection).to_a.first
Updates
r.table("users").get(userId).update({isOnline: isOnline}).run(@connection)
r.table("users").get(userId).update{|u|
        {channels: u.get_field("channels").set_insert(channelId),
         groups: u.get_field("groups").set_insert(groupId),
         activeChannel: {groupId: groupId, channelId: channelId}
        }
      }.run(@connection) }
r.table("users").get(userId).update{|u| {groups: u.get_field("groups").set_insert(groupId)}}.run(@connection)
Creating a database
def recreate_database
  puts "dropping database: #{@env.database.name}"

  begin
    r.db_drop(@env.database.name).run( @connection)
  rescue ex
    puts ex.message
  end

  puts "creating database: #{@env.database.name}"
  r.db_create(@env.database.name).run(@connection)

  # add tables
  puts "adding tables: users, groups, channels, messages"
  r.db(@env.database.name).table_create("users").run(@connection)
  r.db(@env.database.name).table_create("groups").run(@connection)
  r.db(@env.database.name).table_create("channels").run(@connection)
  r.db(@env.database.name).table_create("messages").run(@connection)

  puts "done"
end

Contributing

  1. Fork it (https://github.com/kingsleyh/crystal-rethinkdb/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

  • kingsleyh Kingsley Hendrickse - creator, maintainer
  • caspiano Caspian Baska - contributor, maintainer
  • fenicks Christian Kakesa - contributor

Thanks

More Repositories

1

rspec_reports_formatter

Rspec custom formatter to produce beautiful reports from rspec
Ruby
31
star
2

dtanks

dtanks
C++
11
star
3

erika

Scala phantomjs wrapper
Scala
10
star
4

reloaded

Dub reload script to recompile project if any of the d or dt files change
D
9
star
5

gherka

Generates pretty html files from cucumber and Jbehave feature files
Java
8
star
6

rainbow

A terminal ansi colorizer for D programming language
D
8
star
7

humanhash

HumanHash implementation
Crystal
8
star
8

intellij-mint

Intellij language support for Mint
Java
7
star
9

crystal-yescrypt

Crystal implementation of yescrypt
JavaScript
5
star
10

array-extra

Extra Array functions for mint
JavaScript
5
star
11

cucumber-jvm-example

Example cucumber jvm maven project
Java
4
star
12

key-solver

Tool to help recover NEO WIF
Elm
3
star
13

erik

D driver for phantomjs
D
3
star
14

shield-system

Generate status badges and sparklines - similar to the travis github build status badges
Ruby
2
star
15

kemal-session-rethinkdb

RethinkDB store for kemal-session
Crystal
2
star
16

language-mint

Atom plugin for the mint language
CoffeeScript
2
star
17

totally_lazy

Ruby port of totally_lazy
Ruby
1
star
18

tracksuit

deft ui
D
1
star
19

thundercat

Rack application container management designed for use with rappa .rap archives
CSS
1
star
20

mint-packages

list of mint packages
HTML
1
star
21

element-size

Elm package to track changes to the size of an HTML element
JavaScript
1
star
22

masterblog

Blog for Masterthought
JavaScript
1
star
23

elm-reload

Elm reload - simple build tool
JavaScript
1
star
24

json_store

Simple key/value in memory db using json
Ruby
1
star