private void fillLanguageDropDown() {
    Locale guiLocale = Settings.getInstance().getLanguage();
    DisplayLocale currentSortLocale =
        new DisplayLocale(new WbLocale(Settings.getInstance().getSortLocale()));

    Locale[] locales = readLocales();

    localeDropDown.removeAllItems();
    localeDropDown.addItem(new DisplayLocale(null));

    int index = 1; // 1 because we have already added a locale
    int currentIndex = -1;

    for (Locale ls : locales) {
      DisplayLocale wl = new DisplayLocale(new WbLocale(ls));
      wl.setDisplayLocale(guiLocale);
      localeDropDown.addItem(wl);
      if (wl.equals(currentSortLocale)) currentIndex = index;
      index++;
    }

    if (currentIndex != -1) {
      localeDropDown.setSelectedIndex(currentIndex);
    }
  }
 public SequenceDiff(ReportSequence ref, ReportSequence tar, String targetSchema) {
   reference = ref;
   target = tar;
   this.targetSchema = targetSchema;
   includeSource =
       Settings.getInstance().getBoolProperty("workbench.diff.sequence.include_sql", false);
 }
 @Override
 public void saveSettings() {
   int value = StringUtil.getIntValue(multiLineThreshold.getText(), -1);
   if (value > 0) GuiSettings.setMultiLineThreshold(value);
   GuiSettings.setAllowRowHeightResizing(rowHeightResize.isSelected());
   GuiSettings.setMaxColumnWidth(((NumberField) this.maxColSizeField).getValue());
   GuiSettings.setMinColumnWidth(((NumberField) this.minColSizeField).getValue());
   GuiSettings.setAutomaticOptimalWidth(autoColWidth.isSelected());
   GuiSettings.setIncludeHeaderInOptimalWidth(includeHeaderWidth.isSelected());
   GuiSettings.setAutomaticOptimalRowHeight(autoRowHeight.isSelected());
   GuiSettings.setAutRowHeightMaxLines(((NumberField) this.maxRowHeight).getValue());
   GuiSettings.setIgnoreWhitespaceForAutoRowHeight(ignoreEmptyRows.isSelected());
   GuiSettings.setShowSelectionSummary(selectSummary.isSelected());
   GuiSettings.setDefaultMaxRows(StringUtil.getIntValue(defMaxRows.getText(), 0));
   GuiSettings.setRetrieveQueryComments(retrieveComments.isSelected());
   GuiSettings.setShowTableRowNumbers(showRowNumbers.isSelected());
   GuiSettings.setShowMaxRowsReached(showMaxRowsWarn.isSelected());
   GuiSettings.setDisplayNullString(nullString.getText());
   GuiSettings.setShowResultSQL(showGeneratingSQL.isSelected());
   GuiSettings.setShowTableHeaderInBold(boldHeader.isSelected());
   GuiSettings.setWrapMultilineEditor(wrapMultlineEdit.isSelected());
   GuiSettings.setWrapMultilineRenderer(wrapMultineRender.isSelected());
   GuiSettings.setShowMaxRowsTooltip(showMaxRowsTooltip.isSelected());
   GuiSettings.setDefaultAppendResults(appendResults.isSelected());
   GuiSettings.setUseTablenameAsResultName(useTableName.isSelected());
   DisplayLocale dl = (DisplayLocale) localeDropDown.getSelectedItem();
   Settings.getInstance().setSortLocale(dl.getLocale());
   if (alignmentDropDown.getSelectedIndex() == 1) {
     GuiSettings.setNumberDataAlignment("left");
   } else {
     GuiSettings.setNumberDataAlignment("right");
   }
 }
  private DataStore getImportedKeyList(TableIdentifier tbl) throws SQLException {
    // I'm not adding an ORDER BY because the statement is terribly slow anyway
    // and an ORDER BY makes it even slower for large results
    StringBuilder sql = new StringBuilder(baseSql.length() + 50);
    sql.append(getQuery(tbl));
    sql.append("AND f.table_name = ? \n");
    sql.append("AND f.owner = ? \n");

    if (Settings.getInstance().getDebugMetadataSql()) {
      LogMgr.logDebug(
          "OracleFKHandler.getImportedKeyList()",
          "Retrieving imported foreign keys using:\n"
              + SqlUtil.replaceParameters(sql, tbl.getRawTableName(), tbl.getRawSchema()));
    }

    ResultSet rs;
    DataStore result = null;
    try {
      retrievalStatement = this.getConnection().getSqlConnection().prepareStatement(sql.toString());
      retrievalStatement.setString(1, tbl.getRawTableName());
      retrievalStatement.setString(2, tbl.getRawSchema());
      rs = retrievalStatement.executeQuery();
      result = processResult(rs);
    } finally {
      // the result set is closed by processResult
      SqlUtil.closeStatement(retrievalStatement);
      retrievalStatement = null;
    }
    sortResult(result);
    return result;
  }
 public void dispose() {
   reset();
   WbAction.dispose(dropAction, compileAction);
   if (source != null) source.dispose();
   if (findPanel != null) findPanel.dispose();
   if (triggerList != null) {
     triggerList.dispose();
   }
   Settings.getInstance().removePropertyChangeListener(this);
 }
  @Test
  public void testSelectIntoPattern() throws Exception {
    String pgPattern =
        Settings.getInstance().getProperty("workbench.db.postgresql.selectinto.pattern", null);
    assertNotNull(pgPattern);

    Pattern pg = Pattern.compile(pgPattern, Pattern.CASE_INSENSITIVE);
    String sql = "select * from table";
    Matcher m = pg.matcher(sql);
    assertFalse(m.find());

    sql = "wbselectblob blob_column into c:/temp/pic.jpg from mytable";
    m = pg.matcher(sql);
    assertFalse(m.find());

    sql = "select col1, col2, col3 INTO new_table FROM existing_table";
    m = pg.matcher(sql);
    assertTrue(m.find());

    String informixPattern =
        Settings.getInstance()
            .getProperty("workbench.db.informix_dynamic_server.selectinto.pattern", null);
    assertNotNull(informixPattern);

    Pattern ifx = Pattern.compile(informixPattern, Pattern.CASE_INSENSITIVE);
    String ifxsql = "select * from table";
    m = ifx.matcher(ifxsql);
    assertFalse(m.find());

    ifxsql = "wbselectblob blob_column into c:/temp/pic.jpg from mytable";
    m = ifx.matcher(ifxsql);
    assertFalse(m.find());

    ifxsql = "select col1, col2, col3 FROM existing_table INTO new_table";
    m = ifx.matcher(ifxsql);
    assertTrue(m.find());
  }
  @Override
  public DataStore getRawSequenceDefinition(String catalog, String schema, String sequence) {
    StringBuilder sql = new StringBuilder(100);
    sql.append(
        "SELECT db_name() as sequence_catalog,   \n"
            + "       sc.name as sequence_schema,  \n"
            + "       sq.name as sequence_name,         \n"
            + "       cast(sq.minimum_value as bigint) as minimum_value,         \n"
            + "       cast(sq.maximum_value as bigint) as maximum_value,         \n"
            + "       cast(sq.start_value as bigint) as start_value,         \n"
            + "       cast(sq.increment as bigint) as increment,         \n"
            + "       case when is_cycling = 1 then 'CYCLE' else 'NO CYCLE' end as cycle_flag,  \n"
            + "       sq.is_cached,  \n"
            + "       sq.cache_size,  \n"
            + "       type_name(sq.system_type_id) as data_type,  \n"
            + "       type_name(sq.user_type_id) as user_type,  \n"
            + "       sq.precision,  \n"
            + "       cast(sq.current_value  as bigint) as current_value \n"
            + "FROM sys.sequences sq with (nolock)  \n"
            + "   join sys.schemas sc with (nolock) on sq.schema_id = sc.schema_id "
            + "WHERE sc.name = '");
    sql.append(SqlUtil.removeObjectQuotes(schema));
    sql.append("' ");

    if (StringUtil.isNonEmpty(sequence)) {
      SqlUtil.appendAndCondition(sql, "sq.name", sequence, connection);
    }
    sql.append("\n ORDER BY 1,2");

    if (Settings.getInstance().getDebugMetadataSql()) {
      LogMgr.logInfo("SqlServerSequenceReader.getRawSequenceDefinition()", "Using query=\n" + sql);
    }

    Statement stmt = null;
    ResultSet rs = null;
    DataStore result = null;
    try {
      stmt = this.connection.createStatement();
      rs = stmt.executeQuery(sql.toString());
      result = new DataStore(rs, this.connection, true);
    } catch (Exception e) {
      LogMgr.logError(
          "OracleMetaData.getSequenceDefinition()", "Error when retrieving sequence definition", e);
    } finally {
      SqlUtil.closeAll(rs, stmt);
    }

    return result;
  }
  @Override
  public boolean extendObjectList(
      WbConnection con,
      DataStore result,
      String catalog,
      String schemaPattern,
      String objectPattern,
      String[] requestedTypes) {
    if (!DbMetadata.typeIncluded("TYPE", requestedTypes)) return false;

    String select = getSelect(schemaPattern, objectPattern);
    select += " ORDER BY a.alias, s.schemaname ";

    Statement stmt = null;
    ResultSet rs = null;

    if (Settings.getInstance().getDebugMetadataSql()) {
      LogMgr.logDebug("DerbyTypeReader.extendObjectList()", "Using sql=\n" + select);
    }

    try {
      stmt = con.createStatementForQuery();
      rs = stmt.executeQuery(select);
      while (rs.next()) {
        String schema = rs.getString("schemaname");
        String name = rs.getString("type_name");
        String classname = rs.getString("javaclassname");
        String info = rs.getString("aliasinfo");
        int row = result.addRow();
        result.setValue(row, DbMetadata.COLUMN_IDX_TABLE_LIST_CATALOG, null);
        result.setValue(row, DbMetadata.COLUMN_IDX_TABLE_LIST_SCHEMA, schema);
        result.setValue(row, DbMetadata.COLUMN_IDX_TABLE_LIST_NAME, name);
        result.setValue(row, DbMetadata.COLUMN_IDX_TABLE_LIST_TYPE, "TYPE");
        result.setValue(row, DbMetadata.COLUMN_IDX_TABLE_LIST_REMARKS, null);
        DerbyTypeDefinition def = new DerbyTypeDefinition(schema, name, classname, info);
        result.getRow(row).setUserObject(def);
      }
    } catch (Exception e) {
      LogMgr.logError("DerbyTypeReader.extendObjectList()", "Error retrieving object types", e);
    } finally {
      SqlUtil.closeAll(rs, stmt);
    }
    return true;
  }
  @Override
  public CharSequence getSource(WbConnection con) throws SQLException {
    List<ColumnIdentifier> columns = getColumns(con);

    String lineEnd = Settings.getInstance().getInternalEditorLineEnding();
    StringBuilder sql = new StringBuilder(columns.size() * 20 + 100);
    sql.append(FormatterUtil.getKeyword("UPDATE "));
    sql.append(FormatterUtil.getIdentifier(table.getTableExpression(con)));
    sql.append(lineEnd);
    sql.append(FormatterUtil.getKeyword("   SET "));
    int colNr = 0;
    for (int i = 0; i < columns.size(); i++) {
      ColumnIdentifier col = columns.get(i);

      if (!col.isPkColumn() && !col.isAutoGenerated()) {
        if (colNr > 0) {
          sql.append(',');
          sql.append(lineEnd);
          sql.append("       ");
        }
        appendColumnExpression(sql, col, con);
        colNr++;
      }
    }

    sql.append(lineEnd);
    sql.append(FormatterUtil.getKeyword("WHERE "));
    colNr = 0;
    for (int i = 0; i < columns.size(); i++) {
      ColumnIdentifier col = columns.get(i);
      if (col.isPkColumn()) {
        if (colNr > 0) {
          sql.append(lineEnd);
          sql.append("  AND ");
        }
        appendColumnExpression(sql, col, con);
        colNr++;
      }
    }
    sql.append(";");
    return formatSql(sql.toString(), con);
  }
  private String createHtmlFragment(String text) {
    try {
      String defaultCss =
          "table, th, td { border: 1px solid black; border-collapse: collapse; } "
              + "th, td { padding: 5px; text-align: left; } "
              + "table tr:nth-child(even) { background-color: #eee; } table tr:nth-child(odd) { background-color:#fff; } "
              + "table th { background-color: black; color: white; }";

      String css = Settings.getInstance().getCssForClipboardHtml(defaultCss);
      String preHtml = "<html><head><style>" + css + "</style></head><body><table>";
      String postHtml = "</table></body></html>";
      String trOpen = "<tr>";
      String trClose = "</tr>";
      String tdOpen = "<td>";
      String tdClose = "</td>";
      StringReader srctext = new StringReader(text);
      BufferedReader src = new BufferedReader(srctext);
      StringBuilder dst = new StringBuilder(text.length());

      dst.append(preHtml);
      for (String line = src.readLine(); line != null; line = src.readLine()) {
        String[] fields = line.split("\t");
        for (int i = 0; i < fields.length; i++) {
          fields[i] = tdOpen + fields[i] + tdClose;
        }
        dst.append(trOpen);
        for (String tk : fields) {
          dst.append(tk);
        }
        dst.append(trClose);
      }
      dst.append(postHtml);

      return dst.toString();
    } catch (Exception ex) {
      LogMgr.logError(
          "StringSelectionAdapter.createHtmlFragment()", "Could not create HTML fragment", ex);
      return null;
    }
  }
 public DummyUpdate(TableIdentifier tbl, List<ColumnIdentifier> cols) {
   super(tbl, cols);
   doFormat = Settings.getInstance().getDoFormatUpdates();
 }
 public DummyUpdate(TableIdentifier tbl) {
   super(tbl);
   doFormat = Settings.getInstance().getDoFormatUpdates();
 }
  @Override
  public void readSequenceSource(SequenceDefinition def) {
    if (def == null) return;
    if (def.getSource() != null) return;

    StringBuilder result = new StringBuilder(100);
    String nl = Settings.getInstance().getInternalEditorLineEnding();

    result.append("CREATE SEQUENCE ");
    result.append(def.getSequenceName());

    Number minValue = getNumberValue(def, PROP_MIN_VALUE);
    Number maxValue = getNumberValue(def, PROP_MAX_VALUE);
    Number startValue = getNumberValue(def, PROP_START_VALUE);

    Number increment = getNumberValue(def, PROP_INCREMENT);

    Boolean cycle = (Boolean) def.getSequenceProperty(PROP_CYCLE);
    Boolean isCached = (Boolean) def.getSequenceProperty(PROP_IS_CACHED);
    Number cache = (Number) def.getSequenceProperty(PROP_CACHE_SIZE);
    Number precision = (Number) def.getSequenceProperty(PROP_PRECISION);

    String type = (String) def.getSequenceProperty(PROP_DATA_TYPE);
    String userType = (String) def.getSequenceProperty(PROP_USER_DATA_TYPE);
    String typeToUse = type;
    if (!type.equals(userType)) {
      typeToUse = userType;
    }

    result.append(nl).append("       AS ");
    result.append(typeToUse);
    if (needsPrecision(typeToUse) && precision != null) {
      result.append('(');
      result.append(precision.toString());
      result.append(')');
    }

    result.append(nl).append("       INCREMENT BY ");
    result.append(increment);

    if (minValue != null && !isMinValue(typeToUse, minValue)) {
      result.append(nl).append("       MINVALUE ");
      result.append(minValue);
    } else {
      result.append(nl).append("       NO MINVALUE");
    }

    if (maxValue != null && !isMaxValue(typeToUse, maxValue)) {
      result.append(nl).append("       MAXVALUE ");
      result.append(maxValue);
    } else {
      result.append(nl).append("       NO MAXVALUE");
    }

    if (startValue != null) {
      if (minValue != null && !startValue.equals(minValue) || minValue == null) {
        result.append(nl).append("       START WITH ");
        result.append(startValue);
      }
    }

    if (Boolean.TRUE.equals(isCached)) {
      result.append(nl).append("       CACHE ");
      if (cache != null && cache.longValue() > 0) result.append(cache);
    } else {
      result.append(nl).append("       NOCACHE");
    }

    result.append(nl).append("       ");
    result.append(cycle ? "CYCLE" : "NOCYCLE");

    result.append(';');
    result.append(nl);

    def.setSource(result);
  }
 public void restoreSettings() {
   if (initialized) {
     readSettings(Settings.getInstance(), this.getClass().getName() + ".");
     findPanel.restoreSettings();
   }
 }
  private void _initGui() {
    if (initialized) return;

    Reloadable sourceReload =
        () -> {
          if (dbConnection == null) return;
          if (dbConnection.isBusy()) return;
          retrieveCurrentTrigger();
        };

    this.source = new DbObjectSourcePanel(parentWindow, sourceReload);
    if (DbExplorerSettings.allowSourceEditing()) {
      source.allowEditing(true);
    }

    JPanel listPanel = new JPanel();
    this.triggerList = new WbTable(true, false, false);

    this.triggerList.setRendererSetup(RendererSetup.getBaseSetup());
    this.triggerList.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    this.triggerList.setCellSelectionEnabled(false);
    this.triggerList.setColumnSelectionAllowed(false);
    this.triggerList.setRowSelectionAllowed(true);
    this.triggerList.getSelectionModel().addListSelectionListener(this);
    this.triggerList
        .getSelectionModel()
        .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    this.triggerList.addTableModelListener(this);
    triggerList.setReadOnly(true);

    findPanel = new QuickFilterPanel(this.triggerList, false, "triggerlist");
    findPanel.setFilterOnType(DbExplorerSettings.getFilterDuringTyping());
    findPanel.setAlwaysUseContainsFilter(DbExplorerSettings.getUsePartialMatch());

    ReloadAction a = new ReloadAction(this);
    a.setUseLabelIconSize(true);
    this.findPanel.addToToolbar(a, true, false);
    a.getToolbarButton().setToolTipText(ResourceMgr.getString("TxtRefreshTriggerList"));
    listPanel.setLayout(new BorderLayout());
    listPanel.add((JPanel) findPanel, BorderLayout.NORTH);

    this.splitPane = new WbSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    this.splitPane.setOneTouchExpandable(true);
    this.splitPane.setDividerSize(6);
    WbScrollPane scroll = new WbScrollPane(this.triggerList);

    listPanel.add(scroll, BorderLayout.CENTER);

    infoLabel = new SummaryLabel("");
    listPanel.add(infoLabel, BorderLayout.SOUTH);

    this.splitPane.setLeftComponent(listPanel);
    this.splitPane.setRightComponent(source);
    this.splitPane.setDividerBorder(WbSwingUtilities.EMPTY_BORDER);
    this.setLayout(new BorderLayout());
    this.add(splitPane, BorderLayout.CENTER);

    WbTraversalPolicy pol = new WbTraversalPolicy();
    pol.setDefaultComponent((JPanel) findPanel);
    pol.addComponent((JPanel) findPanel);
    pol.addComponent(this.triggerList);
    this.setFocusTraversalPolicy(pol);
    this.reset();

    WbSelectionModel list = WbSelectionModel.Factory.createFacade(triggerList.getSelectionModel());
    this.dropAction = new DropDbObjectAction(this, list, this);
    triggerList.addPopupAction(dropAction, true);
    this.compileAction = new CompileDbObjectAction(this, list);
    triggerList.addPopupAction(compileAction, false);

    if (dbConnection != null) {
      setConnection(dbConnection);
    }
    this.splitPane.setDividerLocation(0.5d);

    initialized = true;

    restoreSettings();
    if (workspaceProperties != null) {
      readSettings(workspaceProperties, workspaceProperties.getFilterPrefix());
      workspaceProperties = null;
    }
    Settings.getInstance()
        .addPropertyChangeListener(this, DbExplorerSettings.PROP_ALLOW_SOURCE_EDITING);
  }