• Stars
    star
    395
  • Rank 109,040 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 13 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

PostgreSQL extensions for ActiveRecord

Surus

Build Status

Description

Surus adds PostgreSQL specific functionality to ActiveRecord. It adds helper methods for searching PostgreSQL arrays and hstores. It also can control PostgreSQL synchronous commit behavior. By relaxing PostgreSQL's durability guarantee, transaction commit rate can be increased by 50% or more. It can also directly generate JSON in PostgreSQL which can be substantially faster than converting ActiveRecord objects to JSON.

Installation

gem install surus

Or add to your Gemfile. This version of Surus only works on Rails 4.2+.

gem 'surus'

Rails 3

Use the 0.4 line for Rails 3

gem 'surus', '~> 0.4.2'

JSON

PostgreSQL 9.2 added row_to_json and array_to_json functions. These functions can be used to build JSON very quickly. Unfortunately, they are somewhat cumbersome to use. The find_json and all_json methods are easy to use wrappers around the lower level PostgreSQL functions that closely mimic the Rails to_json interface.

User.find_json 1
User.find_json 1, columns: [:id, :name, :email]
Post.find_json 1, include: :author
User.find_json(user.id, include: {posts: {columns: [:id, :subject]}})
User.all_json
User.where(admin: true).all_json
User.all_json(columns: [:id, :name, :email], include: {posts: {columns: [:id, :subject]}})
Post.all_json(include: [:forum, :post])

Hstore

Hstores can be searched with helper scopes.

User.hstore_has_pairs(:properties, "favorite_color" => "green")
User.hstore_has_key(:properties, "favorite_color")
User.hstore_has_all_keys(:properties, "favorite_color", "gender")
User.hstore_has_any_keys(:properties, "favorite_color", "favorite_artist")

Hstore is a PostgreSQL extension. You can generate a migration to install it.

rails g surus:hstore:install
rake db:migrate

Even though the underlying hstore can only use strings for keys and values (and NULL for values) Surus can successfully maintain type for integers, floats, bigdecimals, dates, and any value that YAML can serialize. It does this by storing an extra key value pair (or two) to maintain type information.

Because it falls back to YAML serialization for complex types, this means that nested data structures can be serialized to an hstore. In other words, any hash that can be serialized with the normal Rails YAML serialization can be serialized with Surus.

Serialize example (Rails 3+):

class User < ActiveRecord::Base
  serialize :settings, Surus::Hstore::Serializer.new
end

Store example (Rails 4+):

class User < ActiveRecord::Base
  store :settings, accessors: [:session_timeout], coder: Surus::Hstore::Serializer.new
end

Array

Arrays can be searched with helper scopes.

User.array_has(:permissions, "admin")
User.array_has(:permissions, "manage_accounts", "manage_users")
User.array_has_any(:favorite_integers, 7, 11, 42)

Synchronous Commit

PostgreSQL can trade durability for speed. By disabling synchronous commit, transactions will return before the data is actually stored on the disk. This can be substantially faster, but it entails a short window where a crash could cause data loss (but not data corruption). This can be enabled for an entire session or per transaction.

User.synchronous_commit # -> true

User.transaction do
  User.synchronous_commit false
  @user.save
end # This transaction can return before the data is written to the drive

# synchronous_commit returns to its former value outside of the transaction
User.synchronous_commit # -> true

# synchronous_commit can be turned off permanently
User.synchronous_commit false

Read more in the PostgreSQL asynchronous commit documentation.

Benchmarks

JSON generation is with all_json and find_json is substantially faster than to_json.

jack@hk-47~/dev/surus$ ruby -I lib -I bench bench/json_generation.rb
Generating test data... Done.
                                                              user     system      total        real
find_json: 1 record 500 times                             0.140000   0.010000   0.150000 (  0.205195)
to_json:   1 record 500 times                             0.240000   0.010000   0.250000 (  0.287435)
find_json: 1 record with 3 associations 500 times         0.480000   0.010000   0.490000 (  0.796025)
to_json:   1 record with 3 associations 500 times         1.130000   0.050000   1.180000 (  1.500837)
all_json:  50 records with 3 associations 20 times        0.030000   0.000000   0.030000 (  0.090454)
to_json:   50 records with 3 associations 20 times        1.350000   0.020000   1.370000 (  1.710151)

Disabling synchronous commit can improve commit speed by 50% or more.

jack@moya:~/work/surus$ ruby -I lib -I bench bench/synchronous_commit.rb
Generating random data before test to avoid bias... Done.

Writing 1000 narrow records
                                     user     system      total        real
enabled                          0.550000   0.870000   1.420000 (  3.025896)
disabled                         0.700000   0.580000   1.280000 (  1.788585)
disabled per transaction         0.870000   0.580000   1.450000 (  2.072150)
enabled / single transaction     0.700000   0.330000   1.030000 (  1.280455)
disabled / single transaction    0.660000   0.340000   1.000000 (  1.252301)

Writing 1000 wide records
                                     user     system      total        real
enabled                          1.030000   0.870000   1.900000 (  3.559709)
disabled                         0.930000   0.780000   1.710000 (  2.259340)
disabled per transaction         0.970000   0.850000   1.820000 (  2.478290)
enabled / single transaction     0.890000   0.500000   1.390000 (  1.693629)
disabled / single transaction    0.820000   0.450000   1.270000 (  1.554767)

Many more benchmarks are in the bench directory. Most accept parameters to adjust the amount of test data.

Running the benchmarks

  1. Create a database
  2. Configure bench/database.yml to connect to it.
  3. Load bench/database_structure.sql into your bench database.
  4. Run benchmark scripts from root of gem directory (remember pass ruby the include paths for lib and bench)

License

MIT

More Repositories

1

pgx

PostgreSQL driver and toolkit for Go
Go
8,422
star
2

tern

The SQL Fan's Migrator
Go
656
star
3

tod

Time of day and shift types for Ruby
Ruby
415
star
4

sqlfmt

SQL Formatter
Yacc
337
star
5

pglogrepl

PostgreSQL logical replication library for Go.
Go
325
star
6

pgtype

Go
308
star
7

puddle

Generic resource pool for Go
Go
294
star
8

pgconn

Go
180
star
9

pgproto3

Go
160
star
10

pgerrcode

Package pgerrcode contains constants for PostgreSQL error codes.
Go
148
star
11

pgmock

Go
119
star
12

edge

Edge provides graph functionality to ActiveRecord.
Ruby
89
star
13

mat-view-strat-pg

Materialized View Strategies Using PostgreSQL
PLpgSQL
61
star
14

go_db_bench

Benchmarks for database/drivers from Go
Go
52
star
15

json_api_bench

Benchmark of Rails and PostgreSQL JSON generation techniques
Ruby
32
star
16

pgxlisten

pgxlisten provides higher level PostgreSQL LISTEN / NOTIFY tooling built on pgx.
Go
29
star
17

tpr

The Pithy Reader - a fast, simple, and lightweight feed aggregator and reader
Go
22
star
18

pgxutil

Go
20
star
19

pgx-top-to-bottom

HTML
18
star
20

pgxjob

pgxjob provides a job queue implementation using PostgreSQL.
Go
16
star
21

pg-custom-aggregate-grt

PostgreSQL custom aggregate greatest running total implemented in PL/pgSQL and C
PLpgSQL
16
star
22

react2fs

Run command in reaction to file system events
Go
15
star
23

chunkreader

Go
14
star
24

overload

HTTP load tester
Go
14
star
25

pgxrecord

pgxrecord is a tiny framework for CRUD operations and data mapping.
Go
14
star
26

pgx-zerolog

Go
13
star
27

pgio

Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol.
Go
12
star
28

command_model

CommandModel - when update_attributes isn't enough.
Ruby
12
star
29

booklog

Go
10
star
30

pgtocsv

pgtocsv executes a query on a PostgreSQL database and outputs the results in CSV.
Go
10
star
31

pgx-shopspring-decimal

Go
9
star
32

writable-cte-examples

Examples of Writable Common Table Expressions in PostgreSQL
Ruby
9
star
33

pgxdata

Go
9
star
34

pgx-zap

Go
9
star
35

numfmt

Number formatting in Go
Go
9
star
36

pgservicefile

pgservicefile is a parser PostgreSQL for service files (e.g. .pg_service.conf)
Go
8
star
37

pgsql

Go
8
star
38

pgx-gofrs-uuid

Go
8
star
39

go_map_vs_switch

Benchmark for Go map of functions vs. switch
Go
7
star
40

pg-extid

Go
7
star
41

go-extid

Go
7
star
42

pgundolog

pgundolog is a system for rolling back changes to a PostgreSQL database without using transactions.
PLpgSQL
7
star
43

hannibal

Experimental PostgreSQL web application server
Go
5
star
44

cavein

TCP tunnel that designed for testing applications with random connection losses
Go
5
star
45

pgxrepl

Replication client library for PostgreSQL in Go using the pgx driver
Go
5
star
46

quo_vadis

Really simple and fast HTTP Router
Go
5
star
47

text_tunnel

Use your local text editor to edit files on remote servers.
Ruby
5
star
48

pgpassfile

Go
4
star
49

csvtopg

csvtopg copies a CSV to a PostgreSQL database.
Go
4
star
50

chicagolang-feb-2015

Slides for Building Command Line Applications in Go
Go
4
star
51

go_router_tutorial

Tutorial to build a simple HTTP router in Go
Go
4
star
52

doublecheck

Doublecheck your database before it is too late
Go
4
star
53

why-pgx

Slides for lightning talk on pgx
4
star
54

gel

Go Compiled Templates
Go
3
star
55

ego

Experimental shorthand for Go error handling.
Go
3
star
56

pgx_notify_lost_connection

Test for PGX WaitForNotification when connection is lost
Go
3
star
57

pigeon-exp-xmlpp

Experimenting with pigeon PEG generator for Go
Go
3
star
58

doublecheck_view

Ruby gem for integrating doublecheck view pattern with database integration tests
Ruby
3
star
59

envconf

Envconf is a simple, zero dependency library for managing configuration from the environment.
Go
3
star
60

cachet

The cache for all your Ts
Go
2
star
61

go-hello

Go program to practice packaging
Go
2
star
62

pgxsql

Go
2
star
63

flex

Go
2
star
64

cgol-rust

Quick, experimental port of Go cgol to Rust
Rust
2
star
65

assert_db_rejects

Test database level constraints with ActiveRecord
Ruby
2
star
66

dailyprogrammer

Go
2
star
67

imperator

Imperator is an imperative normalization and validation library for Go.
Go
2
star
68

pg95-whats-new

What's new in PostgreSQL 9.5
PLpgSQL
2
star
69

go-intro

Quick introduction to Go -- sample project and speaker notes
Go
2
star
70

pgxbench

PLSQL
2
star
71

react2fs-deb

react2fs Debian package
Go
2
star
72

sadpath

sadpath provides a simple way to centralize error handling and reduce boilerplate.
Go
2
star
73

ppg

ppg runs a SQL file multiple times in parallel
Go
2
star
74

box

Go
2
star
75

tern-deb

Build scripts for debian package for tern
Go
2
star
76

sqlfmt-deb

sqlfmt Debian package
Go
2
star
77

ctxio

Go
2
star
78

jchat

Go
2
star
79

exp-go-repl

Experimenting with yacc
Go
2
star
80

webby-template-minimal-website

Minimal possible website template for Webby
2
star
81

go-server-closed-tcp-conn-os-inconsistencies

Example of differing server closed TCP connections on Linux and Windows
2
star
82

form

HTTP forms for Go
Go
2
star
83

tpr-deb

The Pithy Reader Debian Package
Go
2
star
84

mp

mp (map parser) provides a parser that parses maps into types defined at runtime.
Go
2
star
85

pgx_issues

Test and example cases for pgx issues
Go
1
star
86

context-rows-cancel

Test of Go database/sql context cancelation
Go
1
star
87

pgx845

This is a test application for https://github.com/jackc/pgx/issues/845.
Go
1
star
88

markovbot

Go
1
star
89

reggie

Regular expression builder and tester for Ruby
Ruby
1
star
90

snake_case

Go
1
star
91

cbc-sinatra-crash

Test app demonstrating a crash
Ruby
1
star
92

hackers-delight

Hacker's Delight Exercises and Experiments
Go
1
star
93

pg_pl_bench

Go
1
star
94

booklogh

Experimental port of Booklog to Hannibal
PLpgSQL
1
star
95

alt_record

An alternative implementation of the active record pattern for Ruby
Ruby
1
star
96

structify

Go
1
star
97

testdb

Test database manager
Go
1
star
98

form_model

Ruby
1
star
99

homebrew-formulas

Jack Christensen's Formulas
Ruby
1
star
100

go_database_sql_retry_bug

Test application to determine if database/sql auto-retry logic is safe
Go
1
star