Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Sequel - BRUG 21 Feb 2015

Sergey Nartimov
February 21, 2015
77

Sequel - BRUG 21 Feb 2015

Sergey Nartimov

February 21, 2015
Tweet

Transcript

  1. Database # memory database DB = Sequel.sqlite # connection string

    DB = Sequel.connect('postgres://host/database')
  2. Dataset dataset = DB[:users] # SELECT * FROM "table" dataset

    = DB.from(:users) # SELECT * FROM "table" dataset = DB.select(:column) # SELECT "column"
  3. Model class User < Sequel::Model def before_create # do something

    super end def after_update super # do something end end
  4. pg_array_associa+ons # Database schema: # tags albums # :id (int4)

    <--\ :id # :name \-- :tag_ids (int4[]) # :name class Album plugin :pg_array_associations pg_array_to_many :tags end class Tag plugin :pg_array_associations many_to_pg_array :albums end
  5. Func%ons/Triggers DB.create_function(:set_updated_at, <<-SQL, language: :plpgsql, returns: :trigger) BEGIN NEW.updated_at :=

    CURRENT_TIMESTAMP; RETURN NEW; END; SQL # CREATE FUNCTION set_updated_at() RETURNS trigger LANGUAGE plpgsql AS ' # BEGIN # NEW.updated_at := CURRENT_TIMESTAMP; # RETURN NEW; # END;' DB.drop_function(:set_updated_at) # DROP FUNCTION set_updated_at()
  6. Func%ons/Triggers DB.create_trigger(:table, :trg_updated_at, :set_updated_at, events: :update, each_row: true, when: {

    new__updated_at: :old__updated_at }) # CREATE TRIGGER trg_updated_at BEFORE UPDATE ON "table" # FOR EACH ROW WHEN ("new"."updated_at" = "old"."updated_at") # EXECUTE PROCEDURE set_updated_at() DB.drop_trigger(:table, :trg_updated_at) # DROP TRIGGER trg_updated_at ON "table"
  7. Common%Table%Expressions WITH moved_rows AS ( DELETE FROM products WHERE "date"

    BETWEEN '2010-10-01' AND '2010-10-31' RETURNING * ) INSERT INTO products_log SELECT * FROM moved_rows; DB[:products_log]. with(:moved_rows, DB[:products]. where(date: Date.new(2010, 10, 1)..Date.new(2010, 10, 31)). returning. with_sql(:delete_sql)). insert(DB[:moved_rows])
  8. Cursors DB[:table].use_cursor.each { |row| } # BEGIN; # DECLARE sequel_cursor

    NO SCROLL CURSOR WITHOUT HOLD FOR SELECT * FROM "table"; # FETCH FORWARD 1000 FROM sequel_cursor # FETCH FORWARD 1000 FROM sequel_cursor # ... # FETCH FORWARD 1000 FROM sequel_cursor # CLOSE sequel_cursor # COMMIT DB[:table].paged_each { |row| }