Slide 1

Slide 1 text

Ruby and PostgreSQL, a love story RubyKaigi 2015

Slide 2

Slide 2 text

私について Franck さんです San Francisco, CA (しかし、私わフランス人です) My japanese is embarassing (ditto) Senhor Engineer at Omada Health

Slide 3

Slide 3 text

JAPAN IS AMAZING (even the weather)

Slide 4

Slide 4 text

Photo of the train

Slide 5

Slide 5 text

Photo ramen

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Agenda I <3 SQL I <3 Ruby Just enough of PostgreSQL’s APIs Procedural Languages Index Access Methods Foreign Data Wrappers

Slide 9

Slide 9 text

I <3 PostgreSQL •Happy user since 2009 •Fully-featured Relational DBMS •Clean and large codebase •Super active and friendly community

Slide 10

Slide 10 text

When to raw-SQL •Need for speed •Maintaining Business Logic in Ruby isn’t “the best”™ (YMMV)

Slide 11

Slide 11 text

I <3 Ruby • Happy user since 2006 • Designing & Using DSLs in Ruby is efficient • ETL process (“Extract, Transform & Load”) (牙 Kiba) • Workflows, StateMachines (state_machines) • Fake Data (factory_girl) • Ruby on Rails (rails) • Lots of great gems (rubygems)

Slide 12

Slide 12 text

Generating fake data

Slide 13

Slide 13 text

Generating fake data: in Ruby

Slide 14

Slide 14 text

Generating fake data: in SQL 1. Generate the data using a custom script / external tools 2. On-the-fly using functions

Slide 15

Slide 15 text

De-identifying / Anonymizing PCI / Protected Health Information / …

Slide 16

Slide 16 text

De-identifying / Anonymizing: in Ruby 1. Ahead Of Time: duplicates the “safe” content 2. Just In Time: protected data is already in memory

Slide 17

Slide 17 text

De-identifying / Anonymizing: in SQL • Custom views and functions: CREATE VIEW safe_table AS SELECT protect(name) as name, … FROM my_table (views can even be materialized for faster data retrieval)

Slide 18

Slide 18 text

Generating the craziest things

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

“ ” I just wish I could inject some existing gems in PostgreSQL Me, January 2015

Slide 21

Slide 21 text

“ ” I KNOW, I COULD “JUST” USE RUBY AS A PROCEDURAL LANGUAGE!!!1!1! Still me, a few minutes after

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

“postgresql-pgruby”

Slide 27

Slide 27 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 28

Slide 28 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 29

Slide 29 text

Procedural Language Handlers 101 Datum plmruby_call_handler(PG_FUNCTION_ARGS) { Datum retval; // do some work return retval; }

Slide 30

Slide 30 text

Procedural Language Handlers 101 CREATE FUNCTION plmruby_call_handler() RETURNS language_handler AS ‘…’ LANGUAGE C IMMUTABLE STRICT; CREATE TRUSTED LANGUAGE plmruby HANDLER plmruby_call_handler;

Slide 31

Slide 31 text

Introducing “plmruby” (a version buggy^Wearly of it) λ CREATE EXTENSION plmruby; λ CREATE FUNCTION hello() RETURNS text AS $$ %w[friends! Ruby Hello].sort.join(' ') $$ LANGUAGE plmruby; λ SELECT hello(); hello ------------- Hello Ruby friends! (1 row)

Slide 32

Slide 32 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 33

Slide 33 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 34

Slide 34 text

Index Access Methods Table Row  1  (TID  X) Row  2  (TID  Y) Row  3  (TID  Z) … Index CREATE  INDEX  … USING  [btree |  gist  |  …  ]

Slide 35

Slide 35 text

IAM’s API IndexBuildResult * ambuild (Relation heapRelation, Relation indexRelation, IndexInfo *indexInf bool aminsert (Relation indexRelation, Datum *values, bool *isnull, ItemPointer heap_tid, Rela void amcostestimate (PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartup IndexBulkDeleteResult * ambulkdelete (IndexVacuumInfo *info, IndexBulkDeleteResult *stats, Ind IndexBulkDeleteResult * amvacuumcleanup (IndexVacuumInfo *info, IndexBulkDeleteResult *stats); void ambuildempty (Relation indexRelation); bool amcanreturn (Relation indexRelation); bytea * amoptions (ArrayType *reloptions, bool validate); IndexScanDesc ambeginscan (Relation indexRelation, int nkeys, int norderbys); void amrescan (IndexScanDesc scan, ScanKey keys, int nkeys, ScanKey orderbys, int norderbys); boolean amgettuple (IndexScanDesc scan, ScanDirection direction); int64 amgetbitmap (IndexScanDesc scan, TIDBitmap *tbm); void amendscan (IndexScanDesc scan);

Slide 36

Slide 36 text

Create the custom index CREATE INDEX random_index_on_all_cols ON my_table USING mrb_random (random(my_table.*));

Slide 37

Slide 37 text

Watch it in action # EXPLAIN ANALYZE VERBOSE SELECT * FROM my_table WHERE random(my_table) ==> 'foo'; Index Scan using random_index_on_all_cols on public.my_table (cost information) Output: str Index Cond: (random(my_table.*) ==> 'foo'::text)

Slide 38

Slide 38 text

Interesting example: zombodb Table Row  1  (TID  X) Row  2  (TID  Y) Row  3  (TID  Z) … Index CREATE  INDEX  … USING  zombodb

Slide 39

Slide 39 text

Interesting example: zombodb Table Row  1  (TID  X) Row  2  (TID  Y) Row  3  (TID  Z) … CREATE  INDEX  … USING  zombodb

Slide 40

Slide 40 text

Interesting example: zombodb 1/2 CREATE INDEX idx_zdb_products ON products USING zombodb (zdb('products', products.ctid), zdb(products)) WITH (url='http://some_elastic_search_node:9200/’, shards=5, replicas=1);

Slide 41

Slide 41 text

Interesting example: zombodb 2/2 SELECT * FROM products WHERE zdb('products', ctid) ==> 'keywords:(sports,box) or long_description:(wooden w/5 away) and price < 100000';

Slide 42

Slide 42 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 43

Slide 43 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 44

Slide 44 text

What is a FDW? •A C program •An implementation of the FDW API • Defines “foreign servers” • Defines “foreign tables”

Slide 45

Slide 45 text

Credits:  dalibo.org

Slide 46

Slide 46 text

What are the features supported by a “foreign table”? •Supports reads through SELECTs •Supports writes through INSERTs •Supports predicate pushdown (WHERE) •Supports EXPLAIN [ANALYZE]

Slide 47

Slide 47 text

Lots of existing FDWs •Relational DBMS (PostgreSQL, Oracle, SQL Server, …) •NoSQL (Hadoop, Cassandra, Redis, …) •Files (Flat file, CSV, XML, JSON) •And many more! (MongoDB seems to like it, a lot!)

Slide 48

Slide 48 text

Minimal architecture of a PostgreSQL FDW

Slide 49

Slide 49 text

Datum my_fdw_handler(PG_FUNCTION_ARGS) { FdwRoutine *routine = makeNode(FdwRoutine); # Before reading the table routine->BeginForeignScan = …; # Read next “row” routine->IterateForeignScan = …; # After reading all “rows” routine->EndForeignScan = …;

Slide 50

Slide 50 text

CREATE FUNCTION my_fdw_handler() RETURNS fdw_handler AS ‘MODULE_PATHNAME’ LANGUAGE C STRICT; CREATE FUNCTION my_fdw_validator(text[], oid) RETURNS void AS ‘MODULE_PATHNAME’ LANGUAGE C STRICT; CREATE FOREIGN DATA WRAPPER my_fdw HANDLER my_fdw_handler VALIDATOR my_fdw_validator;

Slide 51

Slide 51 text

IterateForeignScan IterateForeignScan GetForeignRelSize GetForeignPaths GetForeignPlan Begin  Foreign  Scan IterateForeignScan EndForeignScan Foreign Data Wrapper Callback routines life-cycle

Slide 52

Slide 52 text

“ ” We need a general purpose Foreign Data Wrapper that supports Ruby Me, not thinking this would ruin my life

Slide 53

Slide 53 text

Embedding Ruby 101 ruby_init(); ruby_init_loadpath(); ruby_exec_node(ruby_options(2, (char**)options)); code = load_file_in_str("source.rb"); VALUE result = rb_eval_string_protect(code, …);

Slide 54

Slide 54 text

IterateForeignScan IterateForeignScan “Spin up a new VM” “Shutdown the VM” “Iterate over… something” GetForeignRelSize GetForeignPaths GetForeignPlan Begin  Foreign  Scan IterateForeignScan EndForeignScan Foreign Data Wrapper Callback routines life-cycle

Slide 55

Slide 55 text

class Producer def initialize(env = {}) end def each @enum ||= Enumerator.new do |y| 10.times do |t| y.yield [ Time.now ] end end @enum.next end self end Basic data “producer” ¯\_(ツ)_/¯

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

“ ” [You should use mruby instead of CRuby.] The idea would be that it's more “safe” for pg. Terence Lee

Slide 60

Slide 60 text

Embedding CRuby • Challenging • Packaging gems • Parallel executions of the CRuby-powered FDW has serious impacts on PG • Required some tricks (forks) • Only one VM per process (MVM in Ruby 3.0? 4.0?) • Only one chance to boot a VM per process [bug #11423]

Slide 61

Slide 61 text

Embedding mruby • スパーかわいい • Super fast VM startup • Most of the CRuby language is implemented (at least the useful parts) • No need for multi-process/multi-thread manual tuning • Easy setup (very few dependencies) • Downsides • Small amount of gems: lots to rewrite/port

Slide 62

Slide 62 text

Embedding mruby 101 mrb_state *mrb = mrb_open(); struct mrb_parser_state *ps = mrb_parse_string(mrb, “…”, NULL); struct RProc *code = mrb_generate_code(mrb, ps); mrb_value result = mrb_toplevel_run(mrb, code); mrb_close(mrb);

Slide 63

Slide 63 text

Introducing “Holycorn” PostgreSQL multi-purpose Ruby FDW

Slide 64

Slide 64 text

About Holycorn • LGPLv3-licensed • Provides the Redis FDW “for free”

Slide 65

Slide 65 text

Holycorn Redis FDW 1/2 λ redis-cli 127.0.0.1:6379> select 0 OK 127.0.0.1:6379> keys * (empty list or set) 127.0.0.1:6379> set foo 1 OK … 127.0.0.1:6379> keys * 1) "bar" 2) "foo" 3) "baz"

Slide 66

Slide 66 text

Holycorn Redis FDW 2/2 SELECT * from redis_table; key | value -----+------- bar | 2 foo | 1 baz | 3 (3 rows)

Slide 67

Slide 67 text

Integrating foreign technologies into PostgreSQL •Procedural Language Handlers •Index Access Methods •Foreign Data Wrappers

Slide 68

Slide 68 text

ありがとうございます @franckverrot [email protected]