use of com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult in project cubrid-manager by CUBRID.
the class QueryExecuter method updateValues.
/**
* Update values on the query result editor.
*
* @param queryConn Connection
* @return
* @throws SQLException
* @throws ParamSetException
*/
private Map<String, Map<String, CellValue>> updateValues() throws SQLException, ParamSetException {
Map<String, Map<String, CellValue>> successedMap = new HashMap<String, Map<String, CellValue>>();
ParamSetter paramSetter = new ParamSetter();
if (oldValues == null || oldValues.size() == 0) {
return successedMap;
}
if (newValues == null || newValues.size() == 0) {
return successedMap;
}
Connection conn = connection.checkAndConnect();
try {
String tableName = UIQueryUtil.getTableNameFromQuery(conn, query);
String escapedTable = QuerySyntax.escapeKeyword(tableName);
if (tableName == null) {
CommonUITool.openErrorBox(Messages.errModifiedOneTable);
return successedMap;
}
List<ColumnInfo> colInfoList = getAllColumnList();
PreparedStatement pstmt = null;
for (String key : oldValues.keySet()) {
try {
Map<String, CellValue> oldValueMap = oldValues.get(key);
Map<String, CellValue> newValueMap = newValues.get(key);
if (oldValueMap == null || oldValueMap.size() == 0 || newValueMap == null || newValueMap.size() == 0) {
continue;
}
StringBuilder updateSQLBuffer = new StringBuilder();
List<ColumnInfo> updatedColInfoList = new ArrayList<ColumnInfo>();
List<CellValue> newValueList = new ArrayList<CellValue>();
for (int i = 0; i < colInfoList.size(); i++) {
ColumnInfo colInfo = colInfoList.get(i);
CellValue newValue = newValueMap.get(colInfo.getIndex());
CellValue oldValue = oldValueMap.get(colInfo.getIndex());
if ((oldValue == null && newValue != null) || (newValue == null && oldValue != null)) {
newValueList.add(newValue);
updatedColInfoList.add(colInfo);
} else if (oldValue != null && newValue != null && !oldValue.equals(newValue)) {
newValueList.add(newValue);
updatedColInfoList.add(colInfo);
}
}
if (updatedColInfoList.isEmpty()) {
continue;
}
updateSQLBuffer.append("UPDATE ").append(escapedTable).append(" SET ");
StringBuilder setSQLBf = new StringBuilder();
List<PstmtParameter> pstmtParaList = new ArrayList<PstmtParameter>();
int valueParamIndex = 1;
for (int i = 0; i < updatedColInfoList.size(); i++) {
ColumnInfo colInfo = updatedColInfoList.get(i);
CellValue newValue = newValueMap.get(colInfo.getIndex());
String colName = colInfo.getName();
if (queryEditor.isIgnoreType(colInfo.getType())) {
continue;
}
if (setSQLBf.length() > 0) {
setSQLBf.append(", ");
}
CellValue cellValue = newValueMap.get(colInfo.getIndex());
if (DataType.DATATYPE_NATIONAL_CHARACTER.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_NCHAR_VARYING.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_NCHAR.equalsIgnoreCase(colInfo.getType())) {
String dataType = DataType.makeType(colInfo.getType(), colInfo.getChildElementType(), colInfo.getPrecision(), colInfo.getScale());
String charset = getDatabaseInfo() != null ? getDatabaseInfo().getCharSet() : null;
FormatDataResult result = DBAttrTypeFormatter.format(dataType, cellValue.getStringValue(), null, false, charset, false);
if (result.isSuccess()) {
setSQLBf.append(QuerySyntax.escapeKeyword(colName));
setSQLBf.append(" = ").append(result.getFormatedString());
} else {
throw new ParamSetException("Format data \"" + cellValue.getStringValue() + "\"error for data type " + dataType);
}
} else if ((DataType.DATATYPE_BIT.equalsIgnoreCase(colInfo.getType()) || DataType.DATATYPE_BIT_VARYING.equalsIgnoreCase(colInfo.getType())) && newValue.getValue() instanceof String) {
String dataType = DataType.makeType(colInfo.getType(), colInfo.getChildElementType(), colInfo.getPrecision(), colInfo.getScale());
String charset = getDatabaseInfo() != null ? getDatabaseInfo().getCharSet() : null;
FormatDataResult result = DBAttrTypeFormatter.format(dataType, cellValue.getStringValue(), null, false, charset, false);
setSQLBf.append(QuerySyntax.escapeKeyword(colName));
setSQLBf.append(" = ").append(result.getFormatedString());
} else {
setSQLBf.append(QuerySyntax.escapeKeyword(colName)).append(" = ?");
PstmtParameter pstmtParameter = new PstmtParameter(colInfo.getName(), valueParamIndex++, colInfo.getComleteType(), cellValue.getValue());
pstmtParaList.add(pstmtParameter);
}
}
if (setSQLBf.length() < 1) {
continue;
}
updateSQLBuffer.append(setSQLBf);
updateSQLBuffer.append(" WHERE ");
List<String> pkList = UIQueryUtil.getPkList(getDatabaseInfo(), tableName);
int pkParamIndex = 0;
for (int i = 0; i < newValueMap.size(); i++) {
ColumnInfo colInfo = ((ColumnInfo) getAllColumnList().get(i));
String col = colInfo.getName();
if (!pkList.contains(col)) {
continue;
}
if (queryEditor.isIgnoreType(colInfo.getType())) {
continue;
}
if (pkParamIndex > 0) {
updateSQLBuffer.append(" AND ");
}
updateSQLBuffer.append(QuerySyntax.escapeKeyword(col)).append(" = ?");
CellValue object = oldValueMap.get(colInfo.getIndex());
PstmtParameter pstmtParameter = new PstmtParameter(colInfo.getName(), valueParamIndex++, colInfo.getComleteType(), object.getValue());
pstmtParaList.add(pstmtParameter);
pkParamIndex++;
}
pstmt = conn.prepareStatement(updateSQLBuffer.toString());
for (PstmtParameter pstmtParameter : pstmtParaList) {
paramSetter.handle(pstmt, pstmtParameter);
}
pstmt.executeUpdate();
successedMap.put(key, newValueMap);
if (!connection.isAutoCommit() && queryEditor.getConnection() == connection) {
queryEditor.setHaveActiveTransaction(true);
}
for (ColumnInfo colInfo : updatedColInfoList) {
CellValue newValue = newValueMap.get(colInfo.getIndex());
CellValue oldValue = oldValueMap.get(colInfo.getIndex());
if (newValue != null && oldValue != null) {
oldValue.setValue(newValue.getValue());
}
}
} catch (SQLException e) {
if (successedMap.containsKey(key)) {
successedMap.remove(key);
}
LOGGER.error("", e);
logMessageText.setText(e.getLocalizedMessage());
throw e;
} finally {
QueryUtil.freeQuery(pstmt);
}
}
} finally {
if (connection != null && connection.isAutoClosable()) {
connection.commit();
connection.close();
}
}
return successedMap;
}
use of com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult in project cubrid-manager by CUBRID.
the class QueryExecuter method handleButtonEvent.
/**
* Open detail dialog
*
* @param event MouseEvent
*/
@SuppressWarnings("unchecked")
public void handleButtonEvent(int rowIndex, int columnIndex) {
// Get columnInfo
ColumnInfo columnInfo = (ColumnInfo) tblResult.getColumn(columnIndex).getData();
// Get data
final TableItem item = selectableSupport.getTableCursor().getRow();
Map<String, CellValue> dataMap = (Map<String, CellValue>) item.getData();
Map<String, CellValue> newValueMap = (Map<String, CellValue>) item.getData(LASTEST_DATA_FLAG);
if (newValueMap == null) {
newValueMap = new HashMap<String, CellValue>();
newValueMap.putAll(dataMap);
item.setData(LASTEST_DATA_FLAG, newValueMap);
}
String dataIndex = String.valueOf(columnIndex);
CellValue cellValue = newValueMap.get(dataIndex);
if (cellValue == null) {
cellValue = new CellValue();
newValueMap.put(dataIndex, cellValue);
}
String charset = getDatabaseInfo() != null ? getDatabaseInfo().getCharSet() : null;
String dataType = DataType.makeType(columnInfo.getType(), columnInfo.getChildElementType(), columnInfo.getPrecision(), columnInfo.getScale());
cellValue.setFileCharset(charset);
CellViewer cellViewer = new CellViewer(columnInfo, editMode, charset);
if (IDialogConstants.OK_ID == cellViewer.openCellViewer(tblResult.getShell(), cellValue)) {
CellValue newValue = cellViewer.getValue();
if (!CellViewer.isCellValueEqual(cellValue, newValue)) {
String showValue = null;
if (newValue.getValue() == null) {
showValue = DataType.NULL_EXPORT_FORMAT;
item.setText(columnIndex, showValue);
newValueMap.put(dataIndex, newValue);
updateValue(item, dataMap, newValueMap);
} else if (newValue.getValue() instanceof String) {
String strValue = newValue.getValue().toString();
FormatDataResult result = DBAttrTypeFormatter.format(dataType, strValue, null, false, charset, false);
if (result.isSuccess()) {
// Update the data
showValue = newValue.getShowValue();
item.setText(columnIndex, showValue);
newValueMap.put(dataIndex, newValue);
updateValue(item, dataMap, newValueMap);
} else {
CommonUITool.openErrorBox(Messages.bind(Messages.errTextTypeNotMatch, dataType));
return;
}
} else if (newValue.getValue() instanceof byte[]) {
if (DataType.DATATYPE_BIT.equalsIgnoreCase(columnInfo.getType()) || DataType.DATATYPE_BIT_VARYING.equalsIgnoreCase(columnInfo.getType())) {
byte[] bValues = (byte[]) newValue.getValue();
if (bValues.length * 8 > columnInfo.getPrecision() + 7) {
String msg = Messages.bind(Messages.errTextTypeNotMatch, dataType);
CommonUITool.openErrorBox(msg);
return;
}
}
showValue = newValue.getShowValue();
item.setText(columnIndex, showValue);
newValueMap.put(dataIndex, newValue);
updateValue(item, dataMap, newValueMap);
} else {
showValue = newValue.getShowValue();
item.setText(columnIndex, showValue);
newValueMap.put(dataIndex, newValue);
updateValue(item, dataMap, newValueMap);
}
selectableSupport.getTableCursor().redraw();
}
}
}
use of com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult in project cubrid-manager by CUBRID.
the class TableEditorPart method okPressed.
protected void okPressed() {
if (!verifyTableName()) {
return;
}
if (columnsTable.getItemCount() == 0) {
CommonUITool.openErrorBox(Messages.noAttributes);
return;
}
String message = (oldSchemaInfo == null) ? Messages.msgCreateTableConfirm : Messages.msgAlterTableConfirm;
if (!CommonUITool.openConfirmBox(message)) {
return;
}
tableName = tableNameText.getText();
owner = ownerCombo.getText();
String tableDesc = tableDescText.getText();
newSchemaInfo.setClassname(tableName);
newSchemaInfo.setOwner(owner);
newSchemaInfo.setDescription(tableDesc);
if (reuseOIDBtn != null) {
newSchemaInfo.setReuseOid(reuseOIDBtn.getSelection());
}
DatabaseInfo dbInfo = database.getDatabaseInfo();
CommonSQLExcuterTask commonSqlTask = new CommonSQLExcuterTask(dbInfo);
schemaDDL.setEndLineChar("$$$$");
String ddlStr = null;
if (isNewTableFlag) {
ddlStr = schemaDDL.getSchemaDDL(newSchemaInfo);
} else {
ddlStr = schemaDDL.getSchemaDDL(oldSchemaInfo, newSchemaInfo);
}
boolean isExecuteCommonSqlTask = false;
String[] sqlStr = ddlStr.split("\\$\\$\\$\\$");
for (String sql : sqlStr) {
String trimSql = sql.trim();
if (trimSql.length() > 0 && !trimSql.startsWith("--")) {
if (dbInfo.isShard()) {
sql = dbInfo.wrapShardQuery(sql);
}
commonSqlTask.addSqls(sql);
isExecuteCommonSqlTask = true;
}
}
// do with table user change
String changeOwnerDDL = getChangeOwnerDDL();
if (StringUtil.isNotEmpty(changeOwnerDDL)) {
changeOwnerDDL = dbInfo.wrapShardQuery(changeOwnerDDL);
commonSqlTask.addCallSqls(changeOwnerDDL);
isExecuteCommonSqlTask = true;
}
schemaDDL.setEndLineChar(";");
// do with column null attribute change
List<String[]> nullAttrChangedColumnList = getNotNullChangedColumn();
// if the column is null value, when set this column for not null,need
// change these null value for default value
List<String> nullToDefaultChangedColumnList = new ArrayList<String>();
List<String> defaultValList = new ArrayList<String>();
if (ApplicationType.CUBRID_MANAGER.equals(PerspectiveManager.getInstance().getCurrentMode())) {
for (Iterator<String[]> it = nullAttrChangedColumnList.iterator(); it.hasNext(); ) {
String[] column = it.next();
if (!Boolean.parseBoolean(column[1])) {
continue;
}
nullToDefaultChangedColumnList.add(column[0]);
}
// if the column is null value, when set this column for not null,do
// not need change these null value for default value
List<String> keepNullValueColList = new ArrayList<String>();
for (Iterator<String> it = nullToDefaultChangedColumnList.iterator(); it.hasNext(); ) {
String nullColumn = it.next();
DBAttribute dBAttribute = newSchemaInfo.getDBAttributeByName(nullColumn, false);
if (dBAttribute == null) {
continue;
}
String defaultVal = dBAttribute.getDefault();
boolean isUnique = dBAttribute.isUnique();
if (isUnique) {
keepNullValueColList.add(nullColumn);
it.remove();
} else {
if (defaultVal == null) {
keepNullValueColList.add(nullColumn);
it.remove();
continue;
} else {
FormatDataResult result = DBAttrTypeFormatter.formatForInput(dBAttribute.getType(), defaultVal, false);
if (result.isSuccess()) {
defaultValList.add(result.getFormatResult());
}
}
}
}
String msg = Messages.bind(Messages.confirmSetDef, nullToDefaultChangedColumnList);
if (!nullToDefaultChangedColumnList.isEmpty() && (!CommonUITool.openConfirmBox(msg))) {
return;
}
msg = Messages.bind(Messages.confirmKeepNull, keepNullValueColList);
if (!keepNullValueColList.isEmpty() && (!CommonUITool.openConfirmBox(msg))) {
return;
}
}
TaskJobExecutor taskJobExec = new CommonTaskJobExec(this);
boolean hasChanges = isExecuteCommonSqlTask || !nullAttrChangedColumnList.isEmpty() || !nullToDefaultChangedColumnList.isEmpty();
if (hasChanges) {
if (isExecuteCommonSqlTask) {
taskJobExec.addTask(commonSqlTask);
}
if (database == null || newSchemaInfo == null) {
return;
}
// change all table data from null value to default value
int nullColSize = nullToDefaultChangedColumnList.size();
for (int colIndex = 0; colIndex < nullColSize; colIndex++) {
UpdateNullToDefault updateNullToDefault = new UpdateNullToDefault(dbInfo);
updateNullToDefault.setTable(tableName);
updateNullToDefault.setColumn(nullToDefaultChangedColumnList.get(colIndex));
updateNullToDefault.setDefaultValue(defaultValList.get(colIndex));
taskJobExec.addTask(updateNullToDefault);
}
}
List<UpdateDescriptionTask> updateDescriptionTaskList = getUpdateDescriptionTaskList(dbInfo);
for (UpdateDescriptionTask task : updateDescriptionTaskList) {
taskJobExec.addTask(task);
}
if (taskJobExec.getTaskCount() > 0) {
String serverName = database.getServer().getName();
String dbName = database.getDatabaseInfo().getDbName();
String title = getSite().getShell().getText();
jobName = title + " - " + tableName + "@" + dbName;
JobFamily jobFamily = new JobFamily();
jobFamily.setServerName(serverName);
jobFamily.setDbName(dbName);
taskJobExec.schedule(jobName, jobFamily, true, Job.SHORT);
} else {
getSite().getWorkbenchWindow().getActivePage().closeEditor(editor, false);
}
}
use of com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult in project cubrid-manager by CUBRID.
the class ERTable method checkModifyColumn.
private String checkModifyColumn(ERTableColumn oldColumn, ERTableColumn newColumn) {
if (oldColumn == null || this.getColumn(oldColumn.getName()) == null || newColumn == null || newColumn.getName() == null) {
return null;
}
boolean isNameChanged = !StringUtil.isEqualNotIgnoreNull(oldColumn.getName(), newColumn.getName());
boolean isDataTypeChanged = !StringUtil.isEqualNotIgnoreNull(oldColumn.getShowType(), newColumn.getShowType());
boolean isPK2NotPK = oldColumn.isPrimaryKey() && !newColumn.isPrimaryKey();
boolean isNotPK2PK = !oldColumn.isPrimaryKey() && newColumn.isPrimaryKey();
if (isNameChanged && getColumn(newColumn.getName()) != null) {
//duplicated name
return Messages.errExistColumnName;
}
if (isOneRefColumn(oldColumn.getName())) {
if (isNameChanged) {
return Messages.errChangeColNameInFK;
}
if (isDataTypeChanged) {
return Messages.errChangeColTypeInFK;
}
} else if (isOneRefedColumn(oldColumn.getName())) {
if (isNameChanged) {
return Messages.errChangeColNameInFK;
}
if (isDataTypeChanged) {
return Messages.errChangeColTypeInFK;
}
if (isPK2NotPK) {
return Messages.errCancelExistedPK;
}
if (isNotPK2PK && getTargetedRelationships() != null && getTargetedRelationships().size() > 0) {
return Messages.errAddNewPK;
}
}
String defaultValue = newColumn.getAttr().getDefault();
if (!StringUtil.isEmpty(defaultValue)) {
FormatDataResult formatDataResult = DBAttrTypeFormatter.format(newColumn.getShowType(), defaultValue, true, getCubridDatabase().getDatabaseInfo().getCharSet(), false);
if (!formatDataResult.isSuccess()) {
return Messages.bind(Messages.errMatchDefaultValue, defaultValue, newColumn.getShowType());
}
}
return ERTableColumn.checkDataShowType(newColumn.getShowType());
}
use of com.cubrid.cubridmanager.core.cubrid.table.model.FormatDataResult in project cubrid-manager by CUBRID.
the class FieldHandlerUtils method setPreparedStatementValue.
// /**
// * validate Increment Field
// *
// * @param dataType String
// * @param numberStr String
// * @param digitalNum int
// * @return error messages.if it has no errors,returns null.
// */
// public static String validateIncrementField(String dataType,
// String numberStr, int digitalNum) {
// boolean validFormat = ValidateUtil.isInteger(numberStr);
// if (!validFormat) {
// return Messages.bind(Messages.errNumber, numberStr);
// }
// BigInteger minValue = BigInteger.ONE;
// BigInteger maxValue = BigInteger.ZERO;
// if (DataType.DATATYPE_SMALLINT.equals(dataType)) {
// maxValue = new BigInteger(Short.MAX_VALUE + "");
// } else if (DataType.DATATYPE_INTEGER.equals(dataType)) {
// maxValue = new BigInteger(Integer.MAX_VALUE + "");
// } else if (DataType.DATATYPE_NUMERIC.equals(dataType)) {
// maxValue = new BigInteger(DataType.getNumericMaxValue(digitalNum));
// } else if (DataType.DATATYPE_BIGINT.equals(dataType)) {
// maxValue = new BigInteger(Long.MAX_VALUE + "");
// }
// BigInteger value = new BigInteger(numberStr);
// if (value.compareTo(BigInteger.ZERO) <= 0) {
// return Messages.bind(Messages.errIncrement, numberStr);
// }
// if (value.compareTo(maxValue) > 0 || value.compareTo(minValue) < 0) {
// String[] strs = new String[]{numberStr, minValue + "",
// maxValue + "" };
// return Messages.bind(Messages.errRange, strs);
// }
// return null;
// }
// /**
// * Validate Current value of auto increments.
// *
// * @param dataType String
// * @param numberStr String
// * @param seed String
// * @param digitalNum int
// * @return true:is valid;false:is not valid.
// */
// public static String validateCurVal(String dataType, String numberStr,
// String seed, int digitalNum) {
// boolean validFormat = ValidateUtil.isInteger(numberStr);
// if (!validFormat) {
// return Messages.bind(Messages.errNumber, numberStr);
// }
// BigInteger minValue = null;
// BigInteger maxValue = null;
// boolean seedIsEmpty = seed == null || seed.equals("");
// if (DataType.DATATYPE_SMALLINT.equals(dataType)) {
// short minV = 0;
// if (seedIsEmpty) {
// minV = Short.MIN_VALUE;
// } else {
// minV = Short.valueOf(seed);
// }
// minValue = new BigInteger(minV + "");
// maxValue = new BigInteger(Short.MAX_VALUE + "");
// } else if (DataType.DATATYPE_INTEGER.equals(dataType)) {
// int minV = 0;
// if (seedIsEmpty) {
// minV = Integer.MIN_VALUE;
// } else {
// minV = Integer.valueOf(seed);
// }
// minValue = new BigInteger(minV + "");
// maxValue = new BigInteger(Integer.MAX_VALUE + "");
// } else if (DataType.DATATYPE_NUMERIC.equals(dataType)) {
// minValue = new BigInteger(DataType.getNumericMinValue(digitalNum));
// maxValue = new BigInteger(DataType.getNumericMaxValue(digitalNum));
// if (!seedIsEmpty) {
// BigInteger bigSeed = new BigInteger(seed.toString());
// minValue = minValue.compareTo(bigSeed) >= 0 ? minValue
// : bigSeed;
// }
// } else if (DataType.DATATYPE_BIGINT.equals(dataType)) {
// long minV = 0;
// if (seedIsEmpty) {
// minV = Long.MIN_VALUE;
// } else {
// minV = Long.valueOf(seed);
// }
// minValue = new BigInteger(minV + "");
// maxValue = new BigInteger(Long.MAX_VALUE + "");
// }
//
// BigInteger value = new BigInteger(numberStr);
//
// if (minValue == null || maxValue == null) {
// String[] strs = new String[]{numberStr, " ", " " };
// return Messages.bind(Messages.errRange, strs);
// } else if (value.compareTo(maxValue) > 0
// || value.compareTo(minValue) < 0) {
// String[] strs = new String[]{numberStr, minValue + "",
// maxValue + "" };
// return Messages.bind(Messages.errRange, strs);
// }
// return null;
// }
/**
*
* Fill in PreparedStatement parameter value
*
* @param parameter PstmtParameter
* @param pstmt PreparedStatement
* @param dbCharSet String
* @throws SQLException The exception
*/
public static void setPreparedStatementValue(PstmtParameter parameter, PreparedStatement pstmt, String dbCharSet) throws SQLException {
String newDbCharSet = dbCharSet;
String fileCharSet = parameter.getCharSet();
if (dbCharSet == null) {
newDbCharSet = StringUtil.getDefaultCharset();
}
Object realObj = null;
String type = DataType.getRealType(parameter.getDataType());
boolean isMuchValue = DBAttrTypeFormatter.isMuchValueType(type);
FormatDataResult formatDataResult = DBAttrTypeFormatter.format(type, parameter.getStringParamValue(), false, newDbCharSet, true);
String errorMsg = null;
if (formatDataResult.isSuccess()) {
Object obj = formatDataResult.getFormatedJavaObj();
if (isMuchValue && obj instanceof String) {
realObj = DBAttrTypeFormatter.formatMuchValue((String) obj, type, pstmt.getConnection(), newDbCharSet, fileCharSet, true);
} else {
realObj = obj;
}
if (realObj instanceof Exception) {
errorMsg = ((Exception) realObj).getMessage();
} else {
if (realObj instanceof Object[]) {
Object[] objs = DataType.getCollectionValues(type, (Object[]) realObj, true);
((CUBRIDPreparedStatementProxy) pstmt).setCollection(parameter.getParamIndex(), objs);
} else {
pstmt.setObject(parameter.getParamIndex(), realObj);
}
}
} else {
errorMsg = Messages.bind(Messages.errParaTypeValueMapping, new String[] { parameter.getStringParamValue(), type });
}
if (errorMsg != null) {
throw new SQLException(errorMsg, "", -10000);
}
}
Aggregations