use of com.servoy.j2db.persistence.IServer in project servoy-client by Servoy.
the class RowManager method getRowUpdateInfo.
RowUpdateInfo getRowUpdateInfo(Row row, boolean tracking) throws ServoyException {
try {
if (row.getRowManager() != this) {
// $NON-NLS-1$
throw new IllegalArgumentException("I'm not the row manager from row");
}
if (adjustingForChangeByOtherPKHashKey.get() != null && adjustingForChangeByOtherPKHashKey.get().equals(row.getPKHashKey())) {
row.flagExistInDB();
// we ignore changes here because stored calc with time element are always changed,resulting in endlessloop between clients
return null;
}
if (row.getLastException() instanceof DataException) {
// cannot update an row which is not changed (which clears the dataexception)
return null;
}
if (!row.isChanged())
return null;
boolean mustRequeryRow = false;
List<Column> dbPKReturnValues = new ArrayList<Column>();
SQLSheet.SQLDescription sqlDesc = null;
int statement_action;
ISQLUpdate sqlUpdate = null;
IServer server = fsm.getApplication().getSolution().getServer(sheet.getServerName());
boolean oracleServer = SQLSheet.isOracleServer(server);
boolean usesLobs = false;
Table table = sheet.getTable();
boolean doesExistInDB = row.existInDB();
List<String> aggregatesToRemove = new ArrayList<String>(8);
List<String> changedColumns = null;
if (doesExistInDB) {
statement_action = ISQLActionTypes.UPDATE_ACTION;
sqlDesc = sheet.getSQLDescription(SQLSheet.UPDATE);
sqlUpdate = (QueryUpdate) AbstractBaseQuery.deepClone(sqlDesc.getSQLQuery());
List<String> req = sqlDesc.getRequiredDataProviderIDs();
List<String> old = sqlDesc.getOldRequiredDataProviderIDs();
Object[] olddata = row.getRawOldColumnData();
if (// for safety only, nothing changed
olddata == null) {
return null;
}
Object[] newdata = row.getRawColumnData();
for (int i = 0; i < olddata.length; i++) {
String dataProviderID = req.get(i);
Column c = table.getColumn(dataProviderID);
ColumnInfo ci = c.getColumnInfo();
if (ci != null && ci.isDBManaged()) {
mustRequeryRow = true;
} else {
Object modificationValue = c.getModificationValue(fsm.getApplication());
if (modificationValue != null) {
row.setRawValue(dataProviderID, modificationValue);
}
if (newdata[i] instanceof BlobMarkerValue) {
// because that would be a byte[]
continue;
}
if (!Utils.equalObjects(olddata[i], newdata[i])) {
if (sheet.isUsedByAggregate(dataProviderID)) {
aggregatesToRemove.addAll(sheet.getAggregateName(dataProviderID));
}
Object robj = c.getAsRightType(newdata[i]);
if (robj == null)
robj = ValueFactory.createNullValue(c.getType());
((QueryUpdate) sqlUpdate).addValue(c.queryColumn(((QueryUpdate) sqlUpdate).getTable()), robj);
if (changedColumns == null) {
changedColumns = new ArrayList<String>(olddata.length - i);
}
changedColumns.add(c.getName());
if (oracleServer && !usesLobs) {
int type = c.getType();
if (type == Types.BLOB && robj instanceof byte[] && ((byte[]) robj).length > 4000) {
usesLobs = true;
} else if (type == Types.CLOB && robj instanceof String && ((String) robj).length() > 4000) {
usesLobs = true;
}
}
}
}
}
if (// nothing changed after all
changedColumns == null) {
// clear the old data now else it will be kept and in a changed state.
row.flagExistInDB();
return null;
}
// add PK
Object[] pkValues = new Object[old.size()];
for (int j = 0; j < old.size(); j++) {
String dataProviderID = old.get(j);
pkValues[j] = row.getOldRequiredValue(dataProviderID);
}
// TODO: check for success
AbstractBaseQuery.setPlaceholderValue(sqlUpdate, new TablePlaceholderKey(((QueryUpdate) sqlUpdate).getTable(), SQLGenerator.PLACEHOLDER_PRIMARY_KEY), pkValues);
} else {
List<Object> argsArray = new ArrayList<Object>();
statement_action = ISQLActionTypes.INSERT_ACTION;
sqlDesc = sheet.getSQLDescription(SQLSheet.INSERT);
sqlUpdate = (ISQLUpdate) AbstractBaseQuery.deepClone(sqlDesc.getSQLQuery());
List<String> req = sqlDesc.getRequiredDataProviderIDs();
if (Debug.tracing())
Debug.trace(sqlUpdate.toString());
for (int i = 0; i < req.size(); i++) {
String dataProviderID = req.get(i);
if (sheet.isUsedByAggregate(dataProviderID)) {
aggregatesToRemove.addAll(sheet.getAggregateName(dataProviderID));
}
Column c = table.getColumn(dataProviderID);
QueryColumn queryColumn = c.queryColumn(((QueryInsert) sqlUpdate).getTable());
ColumnInfo ci = c.getColumnInfo();
if (c.isDBIdentity()) {
dbPKReturnValues.add(c);
argsArray.add(row.getDbIdentValue());
} else if (ci != null && ci.isDBManaged()) {
mustRequeryRow = true;
} else {
int columnIndex = getSQLSheet().getColumnIndex(dataProviderID);
// HACK: DIRTY way, should use some kind of identifier preferably
if (c.getDatabaseDefaultValue() != null && row.getRawValue(columnIndex, false) == null && c.getRowIdentType() == IBaseColumn.NORMAL_COLUMN) {
// The database has a default value, and the value is null, and this is an insert...
// Remove the column from the query entirely and make sure the default value is requeried from the db.
mustRequeryRow = true;
((QueryInsert) sqlUpdate).removeColumn(queryColumn);
} else {
Object robj = c.getAsRightType(row.getRawValue(columnIndex, false));
if (robj == null)
robj = ValueFactory.createNullValue(c.getType());
argsArray.add(robj);
if (oracleServer && !usesLobs) {
int type = c.getType();
if (type == Types.BLOB && robj instanceof byte[] && ((byte[]) robj).length > 4000) {
usesLobs = true;
} else if (type == Types.CLOB && robj instanceof String && ((String) robj).length() > 4000) {
usesLobs = true;
}
}
}
}
}
AbstractBaseQuery.setPlaceholderValue(sqlUpdate, new TablePlaceholderKey(((QueryInsert) sqlUpdate).getTable(), SQLGenerator.PLACEHOLDER_INSERT_KEY), argsArray.toArray());
}
Object[] pk = row.getPK();
IDataSet pks = new BufferedDataSet();
pks.addRow(pk);
String tid = null;
GlobalTransaction gt = fsm.getGlobalTransaction();
if (gt != null) {
tid = gt.getTransactionID(sheet.getServerName());
}
QuerySelect requerySelect = null;
if (mustRequeryRow) {
requerySelect = (QuerySelect) AbstractBaseQuery.deepClone(sheet.getSQL(SQLSheet.SELECT));
if (!requerySelect.setPlaceholderValue(new TablePlaceholderKey(requerySelect.getTable(), SQLGenerator.PLACEHOLDER_PRIMARY_KEY), pk)) {
Debug.error(new RuntimeException(// $NON-NLS-1$
"Could not set placeholder " + new TablePlaceholderKey(requerySelect.getTable(), SQLGenerator.PLACEHOLDER_PRIMARY_KEY) + " in query " + requerySelect + // $NON-NLS-1$//$NON-NLS-2$
"-- continuing"));
}
}
SQLStatement statement = new SQLStatement(statement_action, sheet.getServerName(), table.getName(), pks, tid, sqlUpdate, fsm.getTableFilterParams(sheet.getServerName(), sqlUpdate), requerySelect);
// check that the row is updated (skip check for insert)
if (doesExistInDB)
statement.setExpectedUpdateCount(1);
if (changedColumns != null) {
statement.setChangedColumns(changedColumns.toArray(new String[changedColumns.size()]));
}
statement.setOracleFixTrackingData(usesLobs && !tracking);
statement.setIdentityColumn(dbPKReturnValues.size() == 0 ? null : dbPKReturnValues.get(0));
if (tracking || usesLobs) {
statement.setTrackingData(sheet.getColumnNames(), row.getRawOldColumnData() != null ? new Object[][] { row.getRawOldColumnData() } : null, row.getRawColumnData() != null ? new Object[][] { row.getRawColumnData() } : null, fsm.getApplication().getUserUID(), fsm.getTrackingInfo(), fsm.getApplication().getClientID());
}
return new RowUpdateInfo(row, statement, dbPKReturnValues, aggregatesToRemove);
} catch (RemoteException e) {
throw new RepositoryException(e);
}
}
use of com.servoy.j2db.persistence.IServer in project servoy-client by Servoy.
the class JSDatabaseManager method js_mergeRecords.
// strongly recommended to use a transaction
// currently does not support compound pks
/**
* Merge records from the same foundset, updates entire datamodel (via foreign type on columns) with destination
* record pk, deletes source record. Do use a transaction!
*
* This function is very handy in situations where duplicate data exists. It allows you to merge the two records
* and move all related records in one go. Say the source_record is "Ikea" and the combined_destination_record is "IKEA", the
* "Ikea" record is deleted and all records related to it (think of contacts and orders, for instance) will be related
* to the "IKEA" record.
*
* The function takes an optional array of column names. If provided, the data in the named columns will be copied
* from source_record to combined_destination_record.
*
* Note that it is essential for both records to originate from the same foundset, as shown in the sample code.
*
* @sample databaseManager.mergeRecords(foundset.getRecord(1),foundset.getRecord(2));
*
* @param sourceRecord The source JSRecord to copy from.
* @param combinedDestinationRecord The target/destination JSRecord to copy into.
* @param columnNames The column names array that should be copied.
*
* @return true if the records could me merged.
*/
public boolean js_mergeRecords(IRecordInternal sourceRecord, IRecordInternal combinedDestinationRecord, String[] columnNames) throws ServoyException {
checkAuthorized();
if (sourceRecord != null && combinedDestinationRecord != null) {
FoundSetManager fsm = (FoundSetManager) application.getFoundSetManager();
try {
if (sourceRecord.getParentFoundSet() != combinedDestinationRecord.getParentFoundSet()) {
return false;
}
Table mainTable = (Table) combinedDestinationRecord.getParentFoundSet().getTable();
String mainTableForeignType = mainTable.getName();
String transaction_id = fsm.getTransactionID(mainTable.getServerName());
Object sourceRecordPK = null;
Object combinedDestinationRecordPK = null;
Column pkc = null;
Iterator<Column> pk_it = mainTable.getRowIdentColumns().iterator();
if (pk_it.hasNext()) {
pkc = pk_it.next();
sourceRecordPK = sourceRecord.getValue(pkc.getDataProviderID());
if (sourceRecordPK == null)
sourceRecordPK = ValueFactory.createNullValue(pkc.getType());
combinedDestinationRecordPK = combinedDestinationRecord.getValue(pkc.getDataProviderID());
if (combinedDestinationRecordPK == null)
combinedDestinationRecordPK = ValueFactory.createNullValue(pkc.getType());
// multipk not supported
if (pk_it.hasNext())
return false;
}
List<SQLStatement> updates = new ArrayList<SQLStatement>();
IServer server = application.getSolution().getServer(mainTable.getServerName());
if (server != null) {
Iterator<String> it = server.getTableNames(false).iterator();
while (it.hasNext()) {
String tableName = it.next();
Table table = (Table) server.getTable(tableName);
// not supported
if (table.getRowIdentColumnsCount() > 1)
continue;
Iterator<Column> it2 = table.getColumns().iterator();
while (it2.hasNext()) {
Column c = it2.next();
if (c.getColumnInfo() != null) {
if (mainTableForeignType.equalsIgnoreCase(c.getColumnInfo().getForeignType())) {
// update table set foreigntypecolumn = combinedDestinationRecordPK where foreigntypecolumn = sourceRecordPK
QueryTable qTable = new QueryTable(table.getSQLName(), table.getDataSource(), table.getCatalog(), table.getSchema());
QueryUpdate qUpdate = new QueryUpdate(qTable);
QueryColumn qc = c.queryColumn(qTable);
qUpdate.addValue(qc, combinedDestinationRecordPK);
ISQLCondition condition = new CompareCondition(IBaseSQLCondition.EQUALS_OPERATOR, qc, sourceRecordPK);
qUpdate.setCondition(condition);
IDataSet pks = new BufferedDataSet();
// unknown number of records changed
pks.addRow(new Object[] { ValueFactory.createTableFlushValue() });
SQLStatement statement = new SQLStatement(ISQLActionTypes.UPDATE_ACTION, table.getServerName(), table.getName(), pks, transaction_id, qUpdate, fsm.getTableFilterParams(table.getServerName(), qUpdate));
updates.add(statement);
}
}
}
}
}
IDataSet pks = new BufferedDataSet();
pks.addRow(new Object[] { sourceRecordPK });
QueryTable qTable = new QueryTable(mainTable.getSQLName(), mainTable.getDataSource(), mainTable.getCatalog(), mainTable.getSchema());
QueryDelete qDelete = new QueryDelete(qTable);
ISQLCondition condition = new CompareCondition(IBaseSQLCondition.EQUALS_OPERATOR, pkc.queryColumn(qTable), sourceRecordPK);
qDelete.setCondition(condition);
SQLStatement statement = new SQLStatement(ISQLActionTypes.DELETE_ACTION, mainTable.getServerName(), mainTable.getName(), pks, transaction_id, qDelete, fsm.getTableFilterParams(mainTable.getServerName(), qDelete));
// check that the row is really deleted
statement.setExpectedUpdateCount(1);
updates.add(statement);
IFoundSetInternal sfs = sourceRecord.getParentFoundSet();
if (combinedDestinationRecord.startEditing()) {
if (columnNames != null) {
for (String element : columnNames) {
if (element == null)
continue;
if (sfs.getColumnIndex(element) >= 0) {
combinedDestinationRecord.setValue(element, sourceRecord.getValue(element));
}
}
}
fsm.getEditRecordList().stopEditing(true, combinedDestinationRecord);
} else {
return false;
}
Object[] results = fsm.getDataServer().performUpdates(fsm.getApplication().getClientID(), updates.toArray(new ISQLStatement[updates.size()]));
for (int i = 0; results != null && i < results.length; i++) {
if (results[i] instanceof ServoyException) {
throw (ServoyException) results[i];
}
}
// sfs.deleteRecord(sfs.getRecordIndex(sourceRecord), true); not needed, will be flushed from memory in finally
return true;
} catch (Exception ex) {
// $NON-NLS-1$
application.handleException(// $NON-NLS-1$
application.getI18NMessage("servoy.foundsetupdater.updateFailed"), new ApplicationException(ServoyException.SAVE_FAILED, ex));
} finally {
fsm.flushCachedDatabaseData(null);
}
}
return false;
}
use of com.servoy.j2db.persistence.IServer in project servoy-client by Servoy.
the class JSDatabaseManager method js_updateTableFilterParam.
/**
* Updates a filter with a new condition. The server/table name should be unchanged.
*
* @sample
* databaseManager.updateTableFilterParam('database', 'myfilter', 'your_i18n_table', 'message_variant', 'in', [1, 2])
*
* @param serverName The name of the database server connection for the specified table name.
* @param filterName The name of the filter that should be updated.
* @param tableName The name of the specified table.
* @param dataprovider A specified dataprovider column name.
* @param operator One of "=, <, >, >=, <=, !=, LIKE, or IN" optionally augmented with modifiers "#" (ignore case) or "^||" (or-is-null), prefix with "sql:" to allow the value to be interpreted as a custom query.
* @param value The specified filter value.
*
* @return true if the tablefilter could be updated.
*/
public boolean js_updateTableFilterParam(String serverName, String filterName, String tableName, String dataprovider, String operator, Object value) throws ServoyException {
checkAuthorized();
try {
if (value instanceof Wrapper) {
value = ((Wrapper) value).unwrap();
}
IServer server = application.getSolution().getServer(serverName);
if (server == null) {
application.reportJSError("Table filter not applied to unknown server '" + serverName + "', tableName = '" + tableName + "', dataprovider = '" + dataprovider + "', operator = '" + operator + "', value = '" + value + "', filterName = '" + filterName + "'", null);
return false;
}
ITable table = null;
if (tableName != null) {
table = server.getTable(tableName);
if (table == null) {
application.reportJSError("Table filter not applied to unknown table: serverName = '" + serverName + "', tableName = '" + tableName + "', dataprovider = '" + dataprovider + "', operator = '" + operator + "', value = '" + value + "', filterName = '" + filterName + "'", null);
return false;
}
}
// else table remains null: apply to all tables with that column
DataproviderTableFilterdefinition dataproviderTableFilterdefinition = application.getFoundSetManager().createDataproviderTableFilterdefinition(table, dataprovider, operator, value);
if (dataproviderTableFilterdefinition == null) {
application.reportJSError("Table filter not created, column not found in table or operator invalid, filterName = '" + filterName + "', serverName = '" + serverName + "', table = '" + table + "', dataprovider = '" + dataprovider + "', operator = '" + operator + "'", null);
return false;
}
return (((FoundSetManager) application.getFoundSetManager()).updateTableFilterParam(serverName, filterName, table, dataproviderTableFilterdefinition));
} catch (Exception ex) {
Debug.error(ex);
}
return false;
}
use of com.servoy.j2db.persistence.IServer in project servoy-client by Servoy.
the class JSDatabaseManager method js_switchServer.
/**
* Switches a named server to another named server with the same datamodel (recommended to be used in an onOpen method for a solution).
* return true if successful.
* Note that this only works if source and destination server are of the same database type.
*
* @sample
* //dynamically changes a server for the entire solution, destination database server must contain the same tables/columns!
* //will fail if there is a lock, transaction , if repository_server is used or if destination server is invalid
* //in the solution keep using the sourceName every where to reference the server!
* var success = databaseManager.switchServer('crm', 'crm1')
*
* @param sourceName The name of the source database server connection
* @param destinationName The name of the destination database server connection.
*
* @return true if the switch could be done.
*/
public boolean js_switchServer(String sourceName, String destinationName) throws ServoyException {
checkAuthorized();
if (IServer.REPOSITORY_SERVER.equals(sourceName))
return false;
if (IServer.REPOSITORY_SERVER.equals(destinationName))
return false;
if (((FoundSetManager) application.getFoundSetManager()).hasTransaction())
return false;
if (((FoundSetManager) application.getFoundSetManager()).hasLocks(null))
return false;
IServer server = null;
try {
server = application.getSolution().getServer(destinationName);
} catch (Exception ex) {
Debug.error(ex);
}
try {
if (server == null || !server.isValid())
return false;
} catch (RemoteException e) {
Debug.error(e);
return false;
}
DataServerProxy pds = application.getDataServerProxy();
if (pds == null) {
// no dataserver access yet?
return false;
}
pds.switchServer(sourceName, destinationName);
// flush all
((FoundSetManager) application.getFoundSetManager()).flushCachedDatabaseData(null);
// register existing used tables to server
((FoundSetManager) application.getFoundSetManager()).registerClientTables(sourceName);
if (sourceName.equals(application.getSolution().getI18nServerName())) {
((ClientState) application).refreshI18NMessages(true);
}
return true;
}
Aggregations