use of com.servoy.j2db.persistence.Table in project servoy-client by Servoy.
the class SortableCellViewHeaderGroup method sort.
protected final void sort(final String name, final WebCellBasedView view, int modifiers) {
direction = Utils.getAsBoolean(sorted.get(name));
direction = !direction;
FormController fc = null;
try {
Iterator<IPersist> it = cellview.getAllObjects();
while (it.hasNext()) {
IPersist element = it.next();
if (element instanceof ISupportName && element instanceof ISupportDataProviderID) {
if (name.equals(ComponentFactory.getWebID(form, element))) {
IFoundSetInternal fs = ((FoundSetListWrapper) listView.getList()).getFoundSet();
if (fs != null) {
WebForm wf = listView.findParent(WebForm.class);
if (wf != null)
fc = wf.getController();
GraphicalComponent gc = (GraphicalComponent) view.labelsFor.get(((ISupportName) element).getName());
int labelForOnActionMethodId = 0;
if (gc != null) {
labelForOnActionMethodId = gc.getOnActionMethodID();
}
if (fc != null && labelForOnActionMethodId > 0) {
// execute on action
JSEvent event = new JSEvent();
event.setType(JSEvent.EventType.action);
event.setName(RepositoryHelper.getDisplayName(StaticContentSpecLoader.PROPERTY_ONSORTCMDMETHODID.getPropertyName(), Form.class));
event.setFormName(view.getDataAdapterList().getFormController().getName());
event.setModifiers(modifiers);
event.setElementName(gc.getName());
fc.executeFunction(String.valueOf(labelForOnActionMethodId), // $NON-NLS-1$
Utils.arrayMerge((new Object[] { event }), Utils.parseJSExpressions(gc.getFlattenedMethodArguments("onActionMethodID"))), true, null, false, // $NON-NLS-1$
"onActionMethodID");
}
String id = ((ISupportDataProviderID) element).getDataProviderID();
if (id != null) {
if (cellview instanceof Portal && !ScopesUtils.isVariableScope(id)) {
int idx = id.lastIndexOf('.');
if (idx > 0) {
id = id.substring(idx + 1);
}
}
IDataProvider dataProvider = null;
if (fc != null) {
dataProvider = fs.getFoundSetManager().getApplication().getFlattenedSolution().getDataproviderLookup(fs.getFoundSetManager(), fc.getForm()).getDataProvider(id);
}
if (!(fc != null && labelForOnActionMethodId > 0)) {
// in case there is no onAction definned
if (cellview instanceof Portal || fc == null || fc.getForm().getOnSortCmdMethodID() == 0) {
List<String> sortingProviders = null;
try {
sortingProviders = DBValueList.getShowDataproviders(fs.getFoundSetManager().getApplication().getFlattenedSolution().getValueList(((ISupportDataProviderID) element).getValuelistID()), (Table) fs.getTable(), dataProvider == null ? id : dataProvider.getDataProviderID(), fs.getFoundSetManager());
} catch (RepositoryException ex) {
Debug.error(ex);
}
if (sortingProviders == null) {
// no related sort, use sort on dataProviderID instead
sortingProviders = Collections.singletonList(dataProvider == null ? id : dataProvider.getDataProviderID());
}
List<SortColumn> list = (modifiers & Event.SHIFT_MASK) != 0 ? fs.getSortColumns() : new ArrayList<SortColumn>();
for (String sortingProvider : sortingProviders) {
FoundSetManager fsm = (FoundSetManager) fs.getFoundSetManager();
SortColumn sc = fsm.getSortColumn(fs.getTable(), sortingProvider, false);
if (sc != null && sc.getColumn().getDataProviderType() != IColumnTypes.MEDIA) {
for (SortColumn oldColumn : list) {
if (oldColumn.equalsIgnoreSortorder(sc)) {
sc = oldColumn;
break;
}
}
if (!list.contains(sc))
list.add(sc);
sc.setSortOrder(direction ? SortColumn.ASCENDING : SortColumn.DESCENDING);
}
fs.sort(list, false);
}
} else if (fc != null && fc.getForm().getOnSortCmdMethodID() != -1) {
JSEvent event = new JSEvent();
event.setType(JSEvent.EventType.none);
event.setName(RepositoryHelper.getDisplayName(StaticContentSpecLoader.PROPERTY_ONSORTCMDMETHODID.getPropertyName(), Form.class));
event.setFormName(view.getDataAdapterList().getFormController().getName());
event.setModifiers(modifiers);
fc.executeFunction(String.valueOf(fc.getForm().getOnSortCmdMethodID()), Utils.arrayMerge((new Object[] { dataProvider == null ? id : dataProvider.getDataProviderID(), Boolean.valueOf(direction), event }), // $NON-NLS-1$
Utils.parseJSExpressions(fc.getForm().getFlattenedMethodArguments("onSortCmdMethodID"))), true, null, false, // $NON-NLS-1$
"onSortCmdMethodID");
}
}
if ((modifiers & Event.SHIFT_MASK) == 0) {
sorted.clear();
}
sorted.put(name, new Boolean(direction));
listView.setCurrentPage(0);
}
}
break;
}
}
}
listView.modelChanged();
} catch (Exception e) {
if (fc != null) {
if (e instanceof ServoyException) {
((ServoyException) e).setContext(fc.toString());
} else {
ServoyException se = new ServoyException();
se.initCause(e);
se.setContext(fc.toString());
e = se;
}
}
Debug.error("error sorting foundset: " + sorted, e);
}
}
use of com.servoy.j2db.persistence.Table in project servoy-client by Servoy.
the class FoundSet method deleteAllInternal.
public void deleteAllInternal() throws ServoyException {
Table table = sheet.getTable();
if (table == null) {
return;
}
fireSelectionAdjusting();
boolean partOfBiggerDelete = false;
// does have access, does not have join to other table and doesn't have a on delete method
QuerySelect sqlSelect;
IDataSet currentPKs;
synchronized (pksAndRecords) {
sqlSelect = pksAndRecords.getQuerySelectForReading();
currentPKs = pksAndRecords.getPks();
}
if (!hasAccess(IRepository.TRACKING) && sqlSelect.getJoins() == null && !tableHasOnDeleteMethods()) {
if (!hasAccess(IRepository.DELETE)) {
throw new ApplicationException(ServoyException.NO_DELETE_ACCESS, new Object[] { table.getName() });
}
boolean hasRelationsWithDelete = false;
Iterator<Relation> it = fsm.getApplication().getFlattenedSolution().getRelations(table, true, false);
while (it.hasNext()) {
Relation element = it.next();
if ((element.getDeleteRelatedRecords() || !element.getAllowParentDeleteWhenHavingRelatedRecords()) && !element.isGlobal()) {
// $NON-NLS-1$ //$NON-NLS-2$
Debug.trace("Foundset deleted per-record because relation '" + element.getName() + "' requires some checks");
hasRelationsWithDelete = true;
break;
}
}
if (!hasRelationsWithDelete) {
getFoundSetManager().getEditRecordList().removeEditedRecords(this);
// do sql delete all at once
QueryDelete delete_sql = new QueryDelete(sqlSelect.getTable());
delete_sql.setCondition(sqlSelect.getWhereClone());
IDataSet deletePKs;
boolean allFoundsetRecordsLoaded = currentPKs != null && pksAndRecords.getCachedRecords().size() == getSize() && !hadMoreRows();
if (allFoundsetRecordsLoaded) {
// clone because this will be used in a separate thread by performUpdates while it will be altered in this one (deletes all records at the end of the method)
deletePKs = currentPKs.clone();
} else {
deletePKs = new BufferedDataSet();
deletePKs.addRow(new Object[] { ValueFactory.createTableFlushValue() });
}
String tid = fsm.getTransactionID(table.getServerName());
SQLStatement statement = new SQLStatement(ISQLActionTypes.DELETE_ACTION, table.getServerName(), table.getName(), deletePKs, tid, delete_sql, fsm.getTableFilterParams(table.getServerName(), delete_sql));
try {
Object[] results = fsm.getDataServer().performUpdates(fsm.getApplication().getClientID(), new ISQLStatement[] { statement });
for (int i = 0; results != null && i < results.length; i++) {
if (results[i] instanceof ServoyException) {
throw (ServoyException) results[i];
}
}
if (!allFoundsetRecordsLoaded) {
fsm.flushCachedDatabaseData(fsm.getDataSource(table));
}
partOfBiggerDelete = true;
} catch (ApplicationException aex) {
if (allFoundsetRecordsLoaded || aex.getErrorCode() != ServoyException.RECORD_LOCKED) {
throw aex;
}
// a record was locked by another client, try per-record
// $NON-NLS-1$
Debug.log("Could not delete all records in 1 statement (a record may be locked), trying per-record");
} catch (RemoteException e) {
throw new RepositoryException(e);
}
}
}
// Need to get all the PKs, recursive delete may not actually remove the PK from the list because it is already being deleted.
if (!partOfBiggerDelete) {
PksAndRecordsHolder pksAndRecordsCopy;
int rowCount;
synchronized (pksAndRecords) {
pksAndRecordsCopy = pksAndRecords.shallowCopy();
IDataSet pks = pksAndRecordsCopy.getPks();
rowCount = pks == null ? 0 : pks.getRowCount();
}
queryForMorePKs(pksAndRecordsCopy, rowCount, -1, false);
}
try {
for (int i = getSize() - 1; i >= 0; i--) {
deleteRecord(i, partOfBiggerDelete);
}
} finally {
int correctedSize = getCorrectedSizeForFires();
if (correctedSize > -1)
fireFoundSetEvent(0, correctedSize, FoundSetEvent.CHANGE_DELETE);
}
}
use of com.servoy.j2db.persistence.Table in project servoy-client by Servoy.
the class FoundSetManager method createDataproviderTableFilterdefinition.
public DataproviderTableFilterdefinition createDataproviderTableFilterdefinition(ITable table, String dataprovider, String operator, Object val) throws ServoyException {
if (dataprovider == null || operator == null) {
return null;
}
int op = RelationItem.getValidOperator(operator.trim(), IBaseSQLCondition.ALL_DEFINED_OPERATORS, IBaseSQLCondition.ALL_MODIFIERS);
if (op == -1) {
return null;
}
Object value = val;
if (value instanceof Wrapper) {
value = ((Wrapper) value).unwrap();
}
if (table != null) {
Column column = ((Table) table).getColumn(dataprovider);
if (column == null) {
return null;
}
value = convertFilterValue(table, column, value);
}
return new DataproviderTableFilterdefinition(dataprovider, op, value);
}
use of com.servoy.j2db.persistence.Table in project servoy-client by Servoy.
the class FoundSetManager method getTableFilterParams.
/**
* Get the table filters that are applicable on the sql for the server. Returns an array of table filters, the resulting array may be modified by the
* caller.
*
* @param serverName
* @param sql
* @return
*/
public ArrayList<TableFilter> getTableFilterParams(String serverName, IQueryElement sql) {
final List<TableFilter> serverFilters = tableFilterParams.get(serverName);
Object[] tenantValue = application.getTenantValue();
if (serverFilters == null && tenantValue == null) {
return null;
}
// get the sql table names in the query
final Set<String> tableSqlNames = new HashSet<String>();
// find the filters for the tables found in the query
final ArrayList<TableFilter>[] filters = new ArrayList[] { null };
sql.acceptVisitor(o -> {
try {
if (o instanceof QueryTable && ((QueryTable) o).getDataSource() != null && ((QueryTable) o).getName() != null && tableSqlNames.add(((QueryTable) o).getName())) {
QueryTable qTable = (QueryTable) o;
Table table = (Table) getTable(qTable.getDataSource());
if (table == null) {
// should never happen
throw new RuntimeException("Could not find table '" + qTable.getDataSource() + "' for table filters");
}
if (tenantValue != null) {
for (Column tenantColumn : table.getTenantColumns()) {
addFilter(filters, createTenantFilter(table, tenantColumn, tenantValue));
}
}
for (TableFilter filter : iterate(serverFilters)) {
TableFilterdefinition tableFilterdefinition = filter.getTableFilterdefinition();
if (filter.getTableName() == null && tableFilterdefinition instanceof DataproviderTableFilterdefinition) {
DataproviderTableFilterdefinition dataproviderTableFilterdefinition = (DataproviderTableFilterdefinition) tableFilterdefinition;
// filter is on all tables with specified dataProvider as column
Column column = table.getColumn(dataproviderTableFilterdefinition.getDataprovider());
if (column != null) {
// Use filter with table name filled in.
// When table was null value was not yet converted, convert now.
Object value = convertFilterValue(table, column, dataproviderTableFilterdefinition.getValue());
TableFilter useFilter = new TableFilter(filter.getName(), filter.getServerName(), table.getName(), table.getSQLName(), dataproviderTableFilterdefinition.getDataprovider(), dataproviderTableFilterdefinition.getOperator(), value);
addFilter(filters, useFilter);
}
} else if (filter.getTableSQLName().equals(qTable.getName())) {
addFilter(filters, filter);
}
}
}
} catch (Exception e) {
// big trouble, this is security filtering, so bail out on error
throw new RuntimeException(e);
}
return o;
});
return filters[0];
}
use of com.servoy.j2db.persistence.Table in project servoy-client by Servoy.
the class FoundSetManager method getSortColumn.
public SortColumn getSortColumn(ITable table, String dataProviderID, boolean logIfCannotBeResolved) throws RepositoryException {
if (table == null || dataProviderID == null)
return null;
Table lastTable = (Table) table;
List<Relation> relations = new ArrayList<Relation>();
// $NON-NLS-1$
String[] split = dataProviderID.split("\\.");
for (int i = 0; i < split.length - 1; i++) {
Relation r = application.getFlattenedSolution().getRelation(split[i]);
String reason = null;
if (r == null) {
reason = "relation '" + split[i] + "' not found";
} else if (!Relation.isValid(r, application.getFlattenedSolution()) || !r.isUsableInSort()) {
if (!Relation.isValid(r, application.getFlattenedSolution()))
reason = "relation '" + split[i] + "' not valid";
else if (r.isMultiServer())
reason = "relation '" + split[i] + "' is cross server, sorting is not supported";
else if (r.isGlobal())
reason = "relation '" + split[i] + "' is global, sorting is not supported";
else
reason = "relation '" + split[i] + "' is outer join with or null modifier, sorting is not supported";
} else if (!lastTable.equals(getTable(r.getPrimaryDataSource()))) {
reason = "table '" + lastTable.getName() + "' does not match with relation '" + split[i] + "'primary table";
}
if (reason != null) {
if (logIfCannotBeResolved)
Debug.log("Cannot sort on dataprovider " + dataProviderID + ", " + reason, new Exception(split[i]));
return null;
}
relations.add(r);
lastTable = (Table) getTable(r.getForeignDataSource());
}
String colName = split[split.length - 1];
IColumn c = lastTable.getColumn(colName);
if (c == null) {
// check for aggregate
c = AbstractBase.selectByName(application.getFlattenedSolution().getAggregateVariables(lastTable, false), colName);
}
if (c != null) {
return new SortColumn(c, relations.size() == 0 ? null : relations.toArray(new Relation[relations.size()]));
}
return null;
}
Aggregations