Method: Sequel::Dataset#first
- Defined in:
- lib/sequel/dataset/actions.rb
#first(*args, &block) ⇒ Object
Returns the first matching record if no arguments are given. If a integer argument is given, it is interpreted as a limit, and then returns all matching records up to that limit. If any other type of argument(s) is passed, it is treated as a filter and the first matching record is returned. If a block is given, it is used to filter the dataset before returning anything.
If there are no records in the dataset, returns nil (or an empty array if an integer argument is given).
Examples:
DB[:table].first # SELECT * FROM table LIMIT 1
# => {:id=>7}
DB[:table].first(2) # SELECT * FROM table LIMIT 2
# => [{:id=>6}, {:id=>4}]
DB[:table].first(id: 2) # SELECT * FROM table WHERE (id = 2) LIMIT 1
# => {:id=>2}
DB[:table].first(Sequel.lit("id = 3")) # SELECT * FROM table WHERE (id = 3) LIMIT 1
# => {:id=>3}
DB[:table].first(Sequel.lit("id = ?", 4)) # SELECT * FROM table WHERE (id = 4) LIMIT 1
# => {:id=>4}
DB[:table].first{id > 2} # SELECT * FROM table WHERE (id > 2) LIMIT 1
# => {:id=>5}
DB[:table].first(Sequel.lit("id > ?", 4)){id < 6} # SELECT * FROM table WHERE ((id > 4) AND (id < 6)) LIMIT 1
# => {:id=>5}
DB[:table].first(2){id < 2} # SELECT * FROM table WHERE (id < 2) LIMIT 2
# => [{:id=>1}]
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/sequel/dataset/actions.rb', line 216 def first(*args, &block) case args.length when 0 unless block return(@opts[:sql] ? single_record! : single_record) end when 1 arg = args[0] if arg.is_a?(Integer) res = if block if loader = cached_placeholder_literalizer(:_first_integer_cond_loader) do |pl| where(pl.arg).limit(pl.arg) end loader.all(filter_expr(&block), arg) else where(&block).limit(arg).all end else if loader = cached_placeholder_literalizer(:_first_integer_loader) do |pl| limit(pl.arg) end loader.all(arg) else limit(arg).all end end return res end where_args = args args = arg end if loader = cached_where_placeholder_literalizer(where_args||args, block, :_first_cond_loader) do |pl| _single_record_ds.where(pl.arg) end loader.first(filter_expr(args, &block)) else _single_record_ds.where(args, &block).single_record! end end |