module SQLTree::Node
# The DeleteQuery node represents an SQL DELETE query.
#
# This node has two children: table and where.
class DeleteQuery < Base
# The table (SQLTree::Node::TableReference) from which to delete records.
child :table
# The SQLTree::Node::Expression instance that defines what
# nodes to delete.
child :where
# Initializes a new DeleteQuery instance.
def initialize(table, where = nil)
@table, @where = table, where
end
# Generates an SQL DELETE query from this node.
def to_sql(options = {})
sql = "DELETE FROM #{table.to_sql(options)}"
sql << " WHERE #{where.to_sql(options)}" if self.where
sql
end
# Parses a DELETE query from a stream of tokens.
# tokens:: The token stream to parse from, which is an instance
# of SQLTree::Parser.
def self.parse(tokens)
tokens.consume(SQLTree::Token::DELETE)
tokens.consume(SQLTree::Token::FROM)
delete_query = self.new(SQLTree::Node::TableReference.parse(tokens))
if SQLTree::Token::WHERE === tokens.peek
tokens.consume(SQLTree::Token::WHERE)
delete_query.where = SQLTree::Node::Expression.parse(tokens)
end
return delete_query
end
end
end