Sha256: 8684279239729b36cfd2a9dba1d67c485b71df7218e98476489ddcd15a844137

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

# The query extension adds Sequel::Dataset#query which allows
# a different way to construct queries instead of the usual
# method chaining.
#
# To load the extension, do:
#
#   Sequel.extension :query
#
# This extension uses Object#extend at runtime, which can hurt performance.

module Sequel
  class Database
    # Return a dataset modified by the query block
    def query(&block)
      dataset.query(&block)
    end
  end

  class Dataset
    # Translates a query block into a dataset. Query blocks can be useful
    # when expressing complex SELECT statements, e.g.:
    #
    #   dataset = DB[:items].query do
    #     select :x, :y, :z
    #     filter{(x > 1) & (y > 2)}
    #     reverse :z
    #   end
    #
    # Which is the same as:
    #
    #  dataset = DB[:items].select(:x, :y, :z).filter{(x > 1) & (y > 2)}.reverse(:z)
    #
    # Note that inside a call to query, you cannot call each, insert, update,
    # or delete (or any method that calls those), or Sequel will raise an
    # error.
    def query(&block)
      copy = clone({})
      copy.extend(QueryBlockCopy)
      copy.instance_eval(&block)
      clone(copy.opts)
    end

    # Module used by Dataset#query that has the effect of making all
    # dataset methods into !-style methods that modify the receiver.
    module QueryBlockCopy
      %w'each insert update delete'.each do |meth|
        define_method(meth){|*args| raise Error, "##{meth} cannot be invoked inside a query block."}
      end

      # Merge the given options into the receiver's options and return the receiver
      # instead of cloning the receiver.
      def clone(opts = {})
        @opts.merge!(opts)
        self
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sequel-3.44.0 lib/sequel/extensions/query.rb
sequel-3.43.0 lib/sequel/extensions/query.rb