Method: Sequel::Dataset#get

Defined in:
lib/sequel/dataset/actions.rb

#get(column = (no_arg=true; nil), &block) ⇒ Object

Return the column value for the first matching record in the dataset. Raises an error if both an argument and block is given.

DB[:table].get(:id) # SELECT id FROM table LIMIT 1
# => 3

ds.get{sum(id)} # SELECT sum(id) AS v FROM table LIMIT 1
# => 6

You can pass an array of arguments to return multiple arguments, but you must make sure each element in the array has an alias that Sequel can determine:

DB[:table].get([:id, :name]) # SELECT id, name FROM table LIMIT 1
# => [3, 'foo']

DB[:table].get{[sum(id).as(sum), name]} # SELECT sum(id) AS sum, name FROM table LIMIT 1
# => [6, 'foo']

If called on a dataset with raw SQL, returns the first value in the dataset without changing the selection or setting a limit:

DB["SELECT id FROM table"].get # SELECT id FROM table
# =>  3


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/sequel/dataset/actions.rb', line 312

def get(column=(no_arg=true; nil), &block)
  ds = naked
  if block
    raise(Error, 'Must call Dataset#get with an argument or a block, not both') unless no_arg
    ds = ds.select(&block)
    column = ds.opts[:select]
    column = nil if column.is_a?(Array) && column.length < 2
  elsif no_arg && opts[:sql]
    return ds.single_value!
  else
    case column
    when Array
      ds = ds.select(*column)
    when LiteralString, Symbol, SQL::Identifier, SQL::QualifiedIdentifier, SQL::AliasedExpression
      if loader = cached_placeholder_literalizer(:_get_loader) do |pl|
          ds.single_value_ds.select(pl.arg)
        end

        return loader.get(column)
      end

      ds = ds.select(column)
    else
      if loader = cached_placeholder_literalizer(:_get_alias_loader) do |pl|
          ds.single_value_ds.select(Sequel.as(pl.arg, :v))
        end

        return loader.get(column)
      end

      ds = ds.select(Sequel.as(column, :v))
    end
  end

  if column.is_a?(Array)
   if r = ds.single_record
     r.values_at(*hash_key_symbols(column))
   end
  else
    ds.single_value
  end
end