package util.sqlparse.visitor.mysql.test;

import bean.DataBase;
import bean.Schema;
import bean.View;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.parser.SQLParserFeature;
import java.util.ArrayList;
import java.util.List;
import util.sqlparse.visitor.common.Context;
import util.sqlparse.visitor.common.scope.Scope;
import util.sqlparse.visitor.mysql.visitor.CompoundVisitor;

public class ProcedureTest {
   public static void main(String[] args) {
      String sql = "CREATE PROCEDURE curdemo()\nBEGIN\n DECLARE done INT DEFAULT FALSE;\n DECLARE a CHAR(16);\n DECLARE b, c INT; DECLARE cur1 CURSOR FOR SELECT id,data FROM test.t1;\n DECLARE cur2 CURSOR FOR SELECT i FROM test.t2;\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;\n OPEN cur1;\n OPEN cur2;\n read_loop: LOOP\n FETCH cur1 INTO a, b;\n FETCH cur2 INTO c;\n IF done THEN\n LEAVE read_loop;\n END IF;\n IF b < c THEN\n INSERT INTO test.t3 VALUES (a,b);\n ELSE\n INSERT INTO test.t3 VALUES (a,c);\n END IF;\n END LOOP;\n CLOSE cur1;\n CLOSE cur2;\nEND;";
      Context context = new Context();
      DataBase db = new DataBase();
      context.setDataBase(db);
      db.setSchemaList(new ArrayList());
      Schema schema = new Schema("test");
      schema.setViewList(new ArrayList());
      View view = new View("vtest", "create or replace view vtest  as with a as (select login_name as lname,dept_id as did from vtest1) select b.dept_id as did,b.dept_name as dept_name, a.lname as account from a left join sys_dept b on a.did=b.dept_id");
      View view1 = new View("vtest1", "create or replace view vtest1 as select a.user_id,a.user_name,a.login_name,a.dept_id from sys_user a");
      schema.getViewList().add(view);
      schema.getViewList().add(view1);
      db.getSchemaList().add(schema);
      context.initialize(db, "test", "mysql");
      Scope scope = new Scope();
      scope.context = context;
      CompoundVisitor visitor = new CompoundVisitor(scope);
      List<SQLStatement> statements = SQLUtils.parseStatements(sql, "mysql", SQLParserFeature.SkipComments);
      int i = 0;

      for(SQLStatement statement : statements) {
         System.out.println(i + ":" + statement.getClass().toString() + "\n" + statement + "\n");
      }

      visitor.perform(statements);
      scope.reset();
   }
}
