use of com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy in project cubrid-manager by CUBRID.
the class ExportToXlsHandler method exportByQuerying.
public void exportByQuerying(String tableName) throws IOException, SQLException {
if (StringUtil.isEmpty(tableName)) {
// FIXME move this logic to core module
return;
}
long totalRecord = exportConfig.getTotalCount(tableName);
if (totalRecord == 0) {
return;
}
Connection conn = null;
CUBRIDPreparedStatementProxy pStmt = null;
CUBRIDResultSetProxy rs = null;
WritableWorkbook workbook = null;
int workbookNum = 0;
String whereCondition = exportConfig.getWhereCondition(tableName);
boolean hasNextPage = true;
long beginIndex = 1;
int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
// 65536: limit xls row number.
int rowLimit = ImportFileConstants.XLS_ROW_LIMIT;
boolean isInitedColumnTitles = false;
List<String> columnTitles = new ArrayList<String>();
try {
conn = getConnection();
int sheetNum = 0;
int xlsRecordNum = 0;
workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
WritableSheet sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
sheetNum++;
int exportedCount = 0;
String sql = QueryUtil.getSelectSQL(conn, tableName);
isPaginating = isPagination(whereCondition, sql, whereCondition);
while (hasNextPage) {
try {
String executeSQL = null;
if (isPaginating) {
long endIndex = beginIndex + RSPAGESIZE;
executeSQL = getExecuteSQL(sql, beginIndex, endIndex, whereCondition);
executeSQL = dbInfo.wrapShardQuery(executeSQL);
beginIndex = endIndex + 1;
} else {
executeSQL = getExecuteSQL(sql, whereCondition);
executeSQL = dbInfo.wrapShardQuery(sql);
beginIndex = totalRecord + 1;
}
pStmt = getStatement(conn, executeSQL, tableName);
rs = (CUBRIDResultSetProxy) pStmt.executeQuery();
CUBRIDResultSetMetaDataProxy rsmt = (CUBRIDResultSetMetaDataProxy) rs.getMetaData();
int colCount = rsmt.getColumnCount();
if (!isInitedColumnTitles) {
isInitedColumnTitles = true;
columnTitles = getColumnTitleList(rsmt);
if (isExit) {
return;
}
// first line add column name
if (exportConfig.isFirstRowAsColumnName()) {
writeHeader(sheet, columnTitles);
xlsRecordNum++;
}
}
while (rs.next()) {
//Check memory
if (!CommonUITool.isAvailableMemory(REMAINING_MEMORY_SIZE)) {
closeWorkbook(workbook);
workbook = null;
System.gc();
workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
sheetNum = 0;
sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
sheetNum++;
xlsRecordNum = 0;
// first line add column name
if (exportConfig.isFirstRowAsColumnName()) {
writeHeader(sheet, columnTitles);
xlsRecordNum++;
}
}
for (int j = 1; j <= colCount; j++) {
String colType = rsmt.getColumnTypeName(j);
colType = FieldHandlerUtils.amendDataTypeByResult(rs, j, colType);
int precision = rsmt.getPrecision(j);
setIsHasBigValue(colType, precision);
Object cellValue = FieldHandlerUtils.getRsValueForExport(colType, rs, j, exportConfig.getNULLValueTranslation());
// We need judge the CLOB/BLOD data by column type
if (DataType.DATATYPE_BLOB.equals(colType) || DataType.DATATYPE_CLOB.equals(colType)) {
if (DataType.DATATYPE_BLOB.equals(colType)) {
String fileName = exportBlobData(tableName, rs, j);
String dataCellValue = DataType.NULL_EXPORT_FORMAT;
if (StringUtil.isNotEmpty(fileName)) {
dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + BLOB_FOLDER_POSTFIX + File.separator + fileName;
}
sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
} else {
String fileName = exportClobData(tableName, rs, j);
String dataCellValue = DataType.NULL_EXPORT_FORMAT;
if (StringUtil.isNotEmpty(fileName)) {
dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + CLOB_FOLDER_POSTFIX + File.separator + fileName;
}
sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
}
} else if (cellValue instanceof Long) {
sheet.addCell(new Number(j - 1, xlsRecordNum, (Long) cellValue));
} else if (cellValue instanceof Double) {
sheet.addCell(new Number(j - 1, xlsRecordNum, (Double) cellValue));
} else if (cellValue instanceof Timestamp) {
String dataCellValue = FieldHandlerUtils.formatDateTime((Timestamp) cellValue);
sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
} else if (cellValue instanceof java.sql.Time) {
String dataCellValue = DateUtil.getDatetimeString(((java.sql.Time) cellValue).getTime(), FieldHandlerUtils.FORMAT_TIME);
sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
} else if (cellValue instanceof java.sql.Date) {
String dataCellValue = DateUtil.getDatetimeString(((java.sql.Date) cellValue).getTime(), FieldHandlerUtils.FORMAT_DATE);
sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
} else {
sheet.addCell(new Label(j - 1, xlsRecordNum, cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString()));
}
}
xlsRecordNum++;
if ((xlsRecordNum + 1) % rowLimit == 0) {
xlsRecordNum = 0;
sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
sheetNum++;
// first line add column name
if (exportConfig.isFirstRowAsColumnName()) {
writeHeader(sheet, columnTitles);
xlsRecordNum++;
}
}
exportedCount++;
if (exportedCount >= COMMIT_LINES) {
exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
exportedCount = 0;
}
if (stop) {
break;
}
}
exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
exportedCount = 0;
} catch (Exception e) {
LOGGER.error("", e);
exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
} finally {
QueryUtil.freeQuery(pStmt, rs);
}
if (hasNextPage(beginIndex, totalRecord)) {
hasNextPage = true;
} else {
hasNextPage = false;
}
System.gc();
}
} catch (Exception e) {
LOGGER.error("", e);
} finally {
QueryUtil.freeQuery(conn);
closeWorkbook(workbook);
}
}
use of com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy in project cubrid-manager by CUBRID.
the class QueryExecuter method makeUpdateQueryWithSelectedRecords.
public String makeUpdateQueryWithSelectedRecords() {
TableItem[] items = selectableSupport.getSelectedTableItems();
if (items == null || items.length == 0) {
return "";
}
if (items.length > 100) {
CommonUITool.openErrorBox(Messages.makeQueryFromSelectedRecordError);
return "";
}
boolean matched = true;
String tableName = null;
try {
CUBRIDPreparedStatementProxy pstmt = QueryExecuter.getStatement(connection.checkAndConnectQuietly(), query, false, false);
ResultSetMetaData rsMetaData = pstmt.getMetaData();
tableName = rsMetaData.getTableName(1);
for (int i = 2; i <= rsMetaData.getColumnCount(); i++) {
if (!tableName.equals(rsMetaData.getTableName(i))) {
matched = false;
break;
}
}
} catch (Exception e) {
matched = false;
}
if (!matched) {
tableName = "{table}";
}
List<String> pkList = UIQueryUtil.getPkList(getDatabaseInfo(), tableName);
List<ColumnInfo> cols = getAllColumnList();
int colCount = cols.size();
StringBuilder notSupportedColumns = new StringBuilder();
for (int i = 0; i < colCount; i++) {
ColumnInfo colInfo = cols.get(i);
if (colInfo == null || colInfo.getName() == null || colInfo.getType() == null) {
continue;
}
if (!isSupportOnMakeQueryWithRecords(colInfo.getType().toUpperCase())) {
if (notSupportedColumns.length() > 0) {
notSupportedColumns.append(", ");
}
notSupportedColumns.append(colInfo.getName());
notSupportedColumns.append(" ");
notSupportedColumns.append(colInfo.getType().toLowerCase());
}
}
StringBuilder sql = new StringBuilder();
if (notSupportedColumns.length() > 0) {
sql.append("-- ");
sql.append(Messages.makeQueryFromSelectedRecordNotSupported).append(" ");
sql.append(notSupportedColumns).append(StringUtil.NEWLINE);
}
if (pkList.size() == 0) {
sql.append("-- ");
sql.append(Messages.makeQueryFromSelectedRecordNoPK);
sql.append(StringUtil.NEWLINE);
}
if (!matched) {
sql.append("-- ");
sql.append(Messages.makeQueryFromSelectedRecordHasMultipleTableNames);
sql.append(StringUtil.NEWLINE);
}
for (TableItem item : items) {
sql.append("UPDATE ").append(QuerySyntax.escapeKeyword(tableName)).append(" SET ");
for (int i = 0; i < colCount; i++) {
ColumnInfo colInfo = cols.get(i);
if (colInfo == null) {
continue;
}
String colName = QuerySyntax.escapeKeyword(colInfo.getName());
String data = item.getText(i + 1);
if (i > 0) {
sql.append(", ");
}
sql.append(colName).append("=");
if (QueryUtil.isStringDataType(colInfo.getType())) {
sql.append(StringUtil.escapeQuotes(getFormatedValue(colInfo, data)));
} else {
sql.append(getFormatedValue(colInfo, data));
}
}
int count = 0;
for (int i = 0; i < colCount; i++) {
ColumnInfo colInfo = cols.get(i);
String colName = QuerySyntax.escapeKeyword(colInfo.getName());
String data = item.getText(i + 1);
if (!pkList.contains(colName)) {
continue;
}
if (i == 0) {
sql.append(" WHERE ");
}
if (count > 0) {
sql.append(" AND ");
}
count++;
sql.append(colName);
if (QueryEditorPart.isNullEmpty(colInfo.getType(), data)) {
sql.append(" IS NULL");
} else if ("(NULL)".equals(data)) {
sql.append(" IS NULL");
} else if (QueryEditorPart.isNotNeedQuote(colInfo.getType())) {
sql.append("=").append(data);
} else {
sql.append("='").append(data.replaceAll("'", "''")).append("'");
}
}
sql.append(";").append(StringUtil.NEWLINE);
}
return sql.toString();
}
use of com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy 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);
}
}
use of com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy in project cubrid-manager by CUBRID.
the class TableUtil method getParameterMetaData.
/**
* Get parameter meta
*
* @param database CubridDatabase
* @param sql String
* @return ParameterMetaData
*/
public static ParameterMetaData getParameterMetaData(CubridDatabase database, String sql) {
Connection conn = null;
CUBRIDPreparedStatementProxy pStmt = null;
try {
conn = JDBCConnectionManager.getConnection(database.getDatabaseInfo(), false);
pStmt = (CUBRIDPreparedStatementProxy) conn.prepareStatement(sql);
// because this method can not be supported by CUBRID JDBC driver
//return pStmt.getParameterMetaData();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
QueryUtil.freeQuery(conn, pStmt);
}
return null;
}
use of com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy in project cubrid-manager by CUBRID.
the class LoadTableRecordCountsProgress method getRecordsCount.
protected int getRecordsCount(Connection conn, String tableName) {
int recordsCount = 0;
try {
if (conn == null || conn.isClosed()) {
return recordsCount;
}
} catch (SQLException e) {
LOGGER.error("", e);
}
String sql = "SELECT COUNT(*) FROM " + QuerySyntax.escapeKeyword(tableName);
// [TOOLS-2425]Support shard broker
if (CubridDatabase.hasValidDatabaseInfo(database)) {
sql = database.getDatabaseInfo().wrapShardQuery(sql);
}
CUBRIDPreparedStatementProxy stmt = null;
ResultSet rs = null;
try {
stmt = QueryExecuter.getStatement(conn, sql, false, false);
rs = stmt.executeQuery();
if (rs.next()) {
recordsCount = rs.getInt(1);
}
} catch (SQLException e) {
LOGGER.error("", e);
e.printStackTrace();
} finally {
QueryUtil.freeQuery(stmt, rs);
}
return recordsCount;
}
Aggregations