class Sequel::ODBC::Dataset

  # Allows you to do .nolock on a query
  def nolock
    clone_merge(:with => "(NOLOCK)")
  end

  # Formats a SELECT statement using the given options and the dataset
  # options.
  def select_sql(opts = nil)
    opts = opts ? @opts.merge(opts) : @opts

    if sql = opts[:sql]
      return sql
    end

    # ADD TOP to SELECT string for LIMITS
    if limit = opts[:limit]
      select_top = "TOP #{limit}"
      raise SequelError, "Offset not supported" if opts[:offset]
    end

    # ADD WITH to SELECT string for NOLOCK
    if with = opts[:with]
      select_with = "WITH #{with}"
    end

    columns = opts[:select]
    select_columns = columns ? column_list(columns) : WILDCARD
    select_source = source_list(opts[:from])
    sql = opts[:distinct] ? \
      "SELECT DISTINCT #{select_top} #{select_columns} FROM
#{select_source} #{select_with}" : \
      "SELECT #{select_top} #{select_columns} FROM #{select_source}
#{select_with}"

    if join = opts[:join]
      sql << join
    end

    if where = opts[:where]
      sql << " WHERE #{where}"
    end

    if group = opts[:group]
      sql << " GROUP BY #{column_list(group)}"
    end

    if order = opts[:order]
      sql << " ORDER BY #{column_list(order)}"
    end

    if having = opts[:having]
      sql << " HAVING #{having}"
    end

    #if limit = opts[:limit]
    #  sql << " LIMIT #{limit}"
    #  if offset = opts[:offset]
    #    sql << " OFFSET #{offset}"
    #  end
    #end

    if union = opts[:union]
      sql << (opts[:union_all] ? \
        " UNION ALL #{union.sql}" : " UNION #{union.sql}")
    elsif intersect = opts[:intersect]
      sql << (opts[:intersect_all] ? \
        " INTERSECT ALL #{intersect.sql}" : " INTERSECT
#{intersect.sql}")
    elsif except = opts[:except]
      sql << (opts[:except_all] ? \
        " EXCEPT ALL #{except.sql}" : " EXCEPT #{except.sql}")
    end

    sql
  end
  alias sql select_sql

  def fetch_rows(sql, &block)
    @db.synchronize do
      s = @db.execute sql
      begin
        @columns = s.columns(true).map {|c| c.name.to_sym}
        rows = s.fetch_all
        rows.each {|row| yield hash_row(row)}
      ensure
        s.drop unless s.nil? rescue nil
      end
    end
    self
  end

end
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to