/* 
 * © 2007-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
#include "stdafx.h"


#include "editor_view.h"
/**
 * @file  editor_view.cpp
 * @brief 
 */

using namespace grt;
using namespace bec;


ViewEditorBE::ViewEditorBE(GRTManager *grtm, const db_ViewRef &view, const db_mgmt_RdbmsRef &rdbms)
  : DBObjectEditorBE(grtm, view, rdbms), _view(view), _has_syntax_error(true)
{
}

std::string ViewEditorBE::get_query()
{
  std::string ret = get_view()->sqlDefinition();
  if ( ret.empty() )
  {
    ret = "CREATE VIEW `";
    ret += get_schema_name() + "`.`" + get_name() + "` AS\n";
  }
  
  return ret;
}

void ViewEditorBE::set_query(const std::string &sql)
{
  if (get_query() != sql)
  {
    set_sql_parser_task_cb(sigc::mem_fun(this, &ViewEditorBE::parse_sql));
    set_sql(sql, _view);
  }
}

grt::ValueRef ViewEditorBE::parse_sql(grt::GRT* grt, grt::StringRef sql)
{
  grt::AutoUndo undo(grt);

  int err_count= _sql_parser->parse_view(_view, sql.c_str());
  _has_syntax_error= 0 < err_count;

  undo.end(strfmt(_("Edit view `%s`.`%s`"), get_schema_name().c_str(), get_name().c_str()));

  return grt::IntegerRef(err_count);
}

Sql_editor * ViewEditorBE::get_sql_editor()
{
  Sql_editor * sql_editor= DBObjectEditorBE::get_sql_editor();
  if (sql_editor)
  {
    sql_editor->sql_checker()->only_object_type_of(Sql_syntax_check::ot_view);
    sql_editor->sql_checker()->context_object(_view);
  }
  return sql_editor;
}
