/* (non-Javadoc)
   * @see com.hangum.tadpole.rdb.core.editors.objects.table.scripts.RDBDDLScript#getTableScript(com.hangum.tadpole.dao.mysql.TableDAO)
   */
  @Override
  public String getTableScript(TableDAO tableDAO) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);

    Map srcList = (HashMap) client.queryForObject("getTableScript", tableDAO.getName());
    return "" + srcList.get("Create Table");
  }
  private String buildDeleteSQL() {
    StringBuffer resultSQL = new StringBuffer();
    if (chkComment.getSelection()) resultSQL.append("/* Tadpole SQL Generator */"); // $NON-NLS-1$

    int cnt = 0;

    resultSQL.append("DELETE FROM  " + tableDAO.getSysName()); // $NON-NLS-1$
    for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {
      if ("PK".equals(allDao.getKey())) { // $NON-NLS-1$

        if (cnt == 0) resultSQL.append(" WHERE "); // $NON-NLS-1$
        else resultSQL.append("\t AND "); // $NON-NLS-1$

        resultSQL.append(allDao.getSysName()).append(" = ? "); // $NON-NLS-1$
        if (chkComment.getSelection()) {
          resultSQL.append("/* " + allDao.getType() + " */"); // $NON-NLS-1$ //$NON-NLS-2$
        }
        cnt++;
      }
    }

    return lastSQLGen(resultSQL.toString());
  }
  /* (non-Javadoc)
   * @see com.hangum.tadpole.rdb.core.editors.objects.table.scripts.RDBDDLScript#getTableScript(com.hangum.tadpole.dao.mysql.TableDAO)
   */
  @Override
  public String getTableScript(TableDAO tableDAO) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);

    List<HashMap> srcList = client.queryForList("getTableScript", tableDAO.getName());

    StringBuilder result = new StringBuilder("");
    result.append("/* DROP TABLE " + tableDAO.getName() + " CASCADE CONSTRAINT; */ \n\n");
    result.append("CREATE TABLE " + tableDAO.getName() + "( \n");
    for (int i = 0; i < srcList.size(); i++) {
      HashMap<String, Object> source = srcList.get(i);

      result.append("\t");
      if (i > 0) result.append(",");
      result.append(source.get("COLUMN_NAME")).append(" ");
      result.append(source.get("DATA_TYPE"));

      if (source.get("DATA_PRECISION") != null
          && ((Integer) source.get("DATA_PRECISION")).intValue() > 0) {
        result.append("(" + source.get("DATA_PRECISION"));
        if (source.get("DATA_SCALE") != null
            && ((Integer) source.get("DATA_SCALE")).intValue() > 0) {
          result.append("," + source.get("DATA_SCALE"));
        }

        result.append(")");
      } else if (!StringUtils.contains((String) source.get("DATA_TYPE"), "DATE")
          && !StringUtils.contains((String) source.get("DATA_TYPE"), "NUMBER")
          && ((Integer) source.get("DATA_LENGTH")).intValue() > 0) {
        result.append("(" + source.get("DATA_LENGTH") + ")");
      } else {
        result.append(" ");
      }

      if (source.get("DATA_DEFAULT") != null) {

        if (StringUtils.contains((String) source.get("DATA_TYPE"), "CHAR")) {
          result.append(" DEFAULT '" + (String) source.get("DATA_DEFAULT") + "'");
        } else {
          result.append(" DEFAULT " + (String) source.get("DATA_DEFAULT"));
        }
      }

      if ("NO".equals(source.get("NULLABLE"))) {
        result.append(" NOT NULL ");
      }

      result.append("\n");
    }

    // primary key
    List<HashMap> srcPkList = client.queryForList("getTableScript.pk", tableDAO.getName());
    for (int i = 0; i < srcPkList.size(); i++) {
      HashMap<String, Object> source = srcPkList.get(i);
      if (i == 0) {
        result
            .append("\t,CONSTRAINT ")
            .append(source.get("CONSTRAINT_NAME"))
            .append(" PRIMARY KEY ");
        if ("CLUSTERED".equals(source.get("INDEX_TYPE"))) {
          result.append(" CLUSTERED ");
        }
        result.append(" ( ").append(source.get("COLUMN_NAME"));

        if ((Boolean) source.get("DESCENDING")) {
          result.append(" DESC ");
        }
      } else {
        result.append(", " + source.get("COLUMN_NAME"));
        if ((Boolean) source.get("DESCENDING")) {
          result.append(" DESC ");
        }
      }

      if (i == srcPkList.size() - 1) {
        result.append(") \n");
      }
    }

    result.append("); \n\n");

    // table, column comments
    List<String> srcCommentList =
        client.queryForList("getTableScript.comments", tableDAO.getName());
    for (int i = 0; i < srcCommentList.size(); i++) {
      result.append(srcCommentList.get(i) + "\n");
    }

    // foreign key

    // column constraint (사용자 정의 컬럼 제약조건)

    // partition table define

    // storage option

    // iot_type table define

    // table grant

    // table trigger

    // table synonyms

    return result.toString();
  }
 @Override
 protected void configureShell(Shell newShell) {
   super.configureShell(newShell);
   newShell.setText(tableDAO.getName() + Messages.GenerateStatmentDMLDialog_1);
 }
  /**
   * Generate INSERT statement
   *
   * @return
   */
  private String buildInsertSQL() {
    StringBuffer resultSQL = new StringBuffer();
    if (chkComment.getSelection()) resultSQL.append("/* Tadpole SQL Generator */"); // $NON-NLS-1$

    int cnt = 0;

    resultSQL.append("INSERT INTO " + tableDAO.getSysName() + " ( "); // $NON-NLS-1$ //$NON-NLS-2$

    ExtendTableColumnDAO firstDao = (ExtendTableColumnDAO) tableViewer.getElementAt(0);
    if (firstDao.isCheck()) {
      for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {
        if ("*".equals(allDao.getField())) continue; // $NON-NLS-1$

        if (cnt > 0) resultSQL.append(", "); // $NON-NLS-1$
        resultSQL.append(allDao.getSysName());

        cnt++;
      }

    } else {

      for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {
        if (allDao.isCheck()) {
          if (cnt > 0) resultSQL.append(", "); // $NON-NLS-1$
          resultSQL.append(allDao.getSysName());

          cnt++;
        }
      }
    }
    resultSQL.append(
        ")" + PublicTadpoleDefine.LINE_SEPARATOR + " VALUES ( "); // $NON-NLS-1$ //$NON-NLS-2$
    cnt = 0;

    if (firstDao.isCheck()) {
      for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {
        if ("*".equals(allDao.getSysName())) continue; // $NON-NLS-1$

        if (cnt > 0) resultSQL.append(", "); // $NON-NLS-1$
        resultSQL.append("?"); // $NON-NLS-1$

        if (chkComment.getSelection()) {
          resultSQL.append(
              "/* "
                  + allDao.getField()
                  + ":"
                  + allDao.getType()
                  + " */"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }

        cnt++;
      }

    } else {

      for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {
        if (allDao.isCheck()) {
          if (cnt > 0) resultSQL.append(", "); // $NON-NLS-1$

          resultSQL.append("?"); // $NON-NLS-1$
          if (chkComment.getSelection()) {
            resultSQL.append(
                "/* "
                    + allDao.getField()
                    + ":"
                    + allDao.getType()
                    + " */"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          }
          cnt++;
        }
      }
    }

    resultSQL.append(")"); // $NON-NLS-1$

    return lastSQLGen(resultSQL.toString());
  }
  /**
   * Create contents of the dialog.
   *
   * @param parent
   */
  @Override
  protected Control createDialogArea(Composite parent) {
    Composite container = (Composite) super.createDialogArea(parent);
    GridLayout gridLayout = (GridLayout) container.getLayout();
    gridLayout.verticalSpacing = 2;
    gridLayout.horizontalSpacing = 2;
    gridLayout.marginHeight = 2;
    gridLayout.marginWidth = 2;

    Composite compositeBody = new Composite(container, SWT.NONE);
    GridLayout gl_compositeBody = new GridLayout(1, false);
    gl_compositeBody.verticalSpacing = 2;
    gl_compositeBody.horizontalSpacing = 2;
    gl_compositeBody.marginHeight = 2;
    gl_compositeBody.marginWidth = 2;
    compositeBody.setLayout(gl_compositeBody);
    compositeBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Composite compositeTable = new Composite(compositeBody, SWT.NONE);
    compositeTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
    compositeTable.setLayout(new GridLayout(3, false));

    lblTableName = new Label(compositeTable, SWT.NONE);
    lblTableName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblTableName.setText(tableDAO.getName());

    Label lblAs = new Label(compositeTable, SWT.NONE);
    lblAs.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblAs.setText(" as "); // $NON-NLS-1$

    textTableAlias = new Text(compositeTable, SWT.BORDER);
    textTableAlias.addModifyListener(
        new ModifyListener() {
          public void modifyText(ModifyEvent event) {
            if (tableViewer.getInput() != null) {
              for (ExtendTableColumnDAO dao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {

                dao.setTableAlias(textTableAlias.getText());
              }
              tableViewer.refresh();
              queryGenetation();
            }
          }
        });
    textTableAlias.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    new Label(compositeTable, SWT.NONE);
    new Label(compositeTable, SWT.NONE);

    Text textTBNameCmt = new Text(compositeTable, SWT.BORDER | SWT.WRAP | SWT.MULTI);
    GridData gd_textTBNameCmt = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
    gd_textTBNameCmt.heightHint = 33;
    textTBNameCmt.setLayoutData(gd_textTBNameCmt);
    textTBNameCmt.setText(tableDAO.getComment());

    Composite compositeDML = new Composite(compositeBody, SWT.NONE);
    compositeDML.setLayout(new GridLayout(5, false));
    compositeDML.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    Label lblDml = new Label(compositeDML, SWT.NONE);
    lblDml.setText("DML"); // $NON-NLS-1$

    rdoSelect = new Button(compositeDML, SWT.RADIO);
    rdoSelect.setSelection(true);
    rdoSelect.setText("SELECT"); // $NON-NLS-1$

    rdoUpdate = new Button(compositeDML, SWT.RADIO);
    rdoUpdate.setText("UPDATE"); // $NON-NLS-1$

    rdoInsert = new Button(compositeDML, SWT.RADIO);
    rdoInsert.setText("INSERT"); // $NON-NLS-1$

    rdoDelete = new Button(compositeDML, SWT.RADIO);
    rdoDelete.setText("DELETE"); // $NON-NLS-1$

    assignSelectionAdapter(rdoSelect);
    assignSelectionAdapter(rdoUpdate);
    assignSelectionAdapter(rdoInsert);
    assignSelectionAdapter(rdoDelete);

    tableViewer = new TableViewer(compositeBody, SWT.BORDER | SWT.FULL_SELECTION);
    Table table = tableViewer.getTable();
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    table.setLinesVisible(true);
    table.setHeaderVisible(true);

    TableViewerColumn tvColumnName = new TableViewerColumn(tableViewer, SWT.NONE);
    TableColumn tcColumnName = tvColumnName.getColumn();
    tcColumnName.setWidth(130);
    tcColumnName.setText(Messages.GenerateStatmentDMLDialog_8);
    tvColumnName.setEditingSupport(new DMLColumnEditingSupport(tableViewer, 0, this));

    TableViewerColumn tvColumnDataType = new TableViewerColumn(tableViewer, SWT.LEFT);
    TableColumn tcDataType = tvColumnDataType.getColumn();
    tcDataType.setWidth(85);
    tcDataType.setText(Messages.GenerateStatmentDMLDialog_9);

    TableViewerColumn tvColumnKey = new TableViewerColumn(tableViewer, SWT.CENTER);
    TableColumn tcKey = tvColumnKey.getColumn();
    tcKey.setWidth(50);
    tcKey.setText(Messages.GenerateStatmentDMLDialog_10);

    TableViewerColumn tvColumnAlias = new TableViewerColumn(tableViewer, SWT.NONE);
    TableColumn tcAlias = tvColumnAlias.getColumn();
    tcAlias.setWidth(100);
    tcAlias.setText(Messages.GenerateStatmentDMLDialog_11);
    tvColumnAlias.setEditingSupport(new DMLColumnEditingSupport(tableViewer, 3, this));

    TableViewerColumn tvColumnCmt = new TableViewerColumn(tableViewer, SWT.LEFT);
    TableColumn tcCmt = tvColumnCmt.getColumn();
    tcCmt.setWidth(300);
    tcCmt.setText(Messages.GenerateStatmentDMLDialog_12);

    Composite composite_3 = new Composite(compositeBody, SWT.NONE);
    composite_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    GridLayout gl_composite_3 = new GridLayout(2, false);
    gl_composite_3.verticalSpacing = 2;
    gl_composite_3.horizontalSpacing = 2;
    gl_composite_3.marginHeight = 2;
    gl_composite_3.marginWidth = 2;
    composite_3.setLayout(gl_composite_3);

    final Button btnAllCheck = new Button(composite_3, SWT.CHECK);
    btnAllCheck.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            for (ExtendTableColumnDAO dao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) {
              if ("*".equals(dao.getField())) { // $NON-NLS-1$
                dao.setCheck(!btnAllCheck.getSelection());
              } else {
                dao.setCheck(btnAllCheck.getSelection());
              }
            }
            tableViewer.refresh();
            queryGenetation();
          }
        });
    btnAllCheck.setText(Messages.GenerateStatmentDMLDialog_14);

    chkComment = new Button(composite_3, SWT.CHECK);
    chkComment.setText(Messages.GenerateStatmentDMLDialog_15);
    assignSelectionAdapter(chkComment);

    Composite previewComposite = new Composite(compositeBody, SWT.BORDER);
    previewComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    GridLayout gl_previewComposite = new GridLayout(1, false);
    gl_previewComposite.verticalSpacing = 2;
    gl_previewComposite.horizontalSpacing = 2;
    gl_previewComposite.marginHeight = 2;
    gl_previewComposite.marginWidth = 2;
    previewComposite.setLayout(gl_previewComposite);

    textQuery =
        new Text(
            previewComposite,
            SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
    GridData gd_textQuery = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
    gd_textQuery.minimumHeight = 120;
    textQuery.setLayoutData(gd_textQuery);

    tableViewer.setContentProvider(new ArrayContentProvider());
    tableViewer.setLabelProvider(new GenerateLabelProvider());

    initData();
    queryGenetation();

    // google analytic
    AnalyticCaller.track(this.getClass().getName());

    textTableAlias.setFocus();

    return container;
  }
  @Override
  public void run(IStructuredSelection selection, UserDBDAO userDB, OBJECT_TYPE actionType) {
    try {
      PublicTadpoleDefine.QUERY_DML_TYPE queryType = QUERY_DML_TYPE.INSERT;
      if (queryType == QUERY_DML_TYPE.INSERT) {
        if (PublicTadpoleDefine.YES_NO
            .YES
            .name()
            .equals(userDB.getDbAccessCtl().getInsert_lock())) {
          throw new Exception(Messages.get().MainEditor_21);
        }
      }
      queryType = QUERY_DML_TYPE.UPDATE;
      if (queryType == QUERY_DML_TYPE.UPDATE) {
        if (PublicTadpoleDefine.YES_NO
            .YES
            .name()
            .equals(userDB.getDbAccessCtl().getUpdate_lock())) {
          throw new Exception(Messages.get().MainEditor_21);
        }
      }
      queryType = QUERY_DML_TYPE.DELETE;
      if (queryType == QUERY_DML_TYPE.DELETE) {
        if (PublicTadpoleDefine.YES_NO
            .YES
            .name()
            .equals(userDB.getDbAccessCtl().getDelete_locl())) {
          throw new Exception(Messages.get().MainEditor_21);
        }
      }
    } catch (Exception e) {
      MessageDialog.openError(
          getWindow().getShell(), Messages.get().ObjectDeleteAction_2, e.getMessage());
      return;
    }

    try {
      if (!GrantCheckerUtils.ifExecuteQuery(userDB)) return;
    } catch (Exception e) {
      MessageDialog.openError(
          getWindow().getShell(), Messages.get().ObjectDeleteAction_2, e.getMessage());
      return;
    }

    TableDAO tableDAO = (TableDAO) selection.getFirstElement();
    try {
      // get the table columns
      SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
      Map<String, String> mapParam = new HashMap<String, String>();
      mapParam.put("db", userDB.getDb()); // $NON-NLS-1$
      mapParam.put("table", tableDAO.getName()); // $NON-NLS-1$
      List showTableColumns = sqlClient.queryForList("tableColumnList", mapParam); // $NON-NLS-1$

      // Open the table director editor
      IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

      DBTableEditorInput dbEditorInput = new DBTableEditorInput(tableDAO, userDB, showTableColumns);
      page.openEditor(dbEditorInput, TableInformationEditor.ID, false);
    } catch (Exception e) {
      logger.error("Load the table data", e); // $NON-NLS-1$

      Status errStatus =
          new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); // $NON-NLS-1$
      ExceptionDetailsErrorDialog.openError(
          null, "Error", Messages.get().ExplorerViewer_39, errStatus); // $NON-NLS-1$
    }
  }