Search in sources :

Example 31 with Table

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);
    }
}
Also used : Form(com.servoy.j2db.persistence.Form) WebForm(com.servoy.j2db.server.headlessclient.WebForm) IFoundSetInternal(com.servoy.j2db.dataprocessing.IFoundSetInternal) WebForm(com.servoy.j2db.server.headlessclient.WebForm) ISupportName(com.servoy.j2db.persistence.ISupportName) FoundSetListWrapper(com.servoy.j2db.dataprocessing.FoundSetListWrapper) GraphicalComponent(com.servoy.j2db.persistence.GraphicalComponent) IDataProvider(com.servoy.j2db.persistence.IDataProvider) SortColumn(com.servoy.j2db.dataprocessing.SortColumn) ServoyException(com.servoy.j2db.util.ServoyException) Portal(com.servoy.j2db.persistence.Portal) FormController(com.servoy.j2db.FormController) FoundSetManager(com.servoy.j2db.dataprocessing.FoundSetManager) JSEvent(com.servoy.j2db.scripting.JSEvent) Table(com.servoy.j2db.persistence.Table) ISupportDataProviderID(com.servoy.j2db.persistence.ISupportDataProviderID) RepositoryException(com.servoy.j2db.persistence.RepositoryException) ServoyException(com.servoy.j2db.util.ServoyException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) IPersist(com.servoy.j2db.persistence.IPersist)

Example 32 with Table

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);
    }
}
Also used : BaseQueryTable(com.servoy.base.query.BaseQueryTable) Table(com.servoy.j2db.persistence.Table) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) QueryDelete(com.servoy.j2db.query.QueryDelete) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QuerySelect(com.servoy.j2db.query.QuerySelect) ServoyException(com.servoy.j2db.util.ServoyException) Relation(com.servoy.j2db.persistence.Relation) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException)

Example 33 with Table

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);
}
Also used : Wrapper(org.mozilla.javascript.Wrapper) JSONSerializerWrapper(com.servoy.j2db.util.serialize.JSONSerializerWrapper) BaseQueryTable(com.servoy.base.query.BaseQueryTable) Table(com.servoy.j2db.persistence.Table) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) Column(com.servoy.j2db.persistence.Column) IColumn(com.servoy.j2db.persistence.IColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject)

Example 34 with Table

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];
}
Also used : BaseQueryTable(com.servoy.base.query.BaseQueryTable) Table(com.servoy.j2db.persistence.Table) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ServoyException(com.servoy.j2db.util.ServoyException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) MarshallException(org.jabsorb.serializer.MarshallException) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) Column(com.servoy.j2db.persistence.Column) IColumn(com.servoy.j2db.persistence.IColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) HashSet(java.util.HashSet)

Example 35 with Table

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;
}
Also used : Relation(com.servoy.j2db.persistence.Relation) BaseQueryTable(com.servoy.base.query.BaseQueryTable) Table(com.servoy.j2db.persistence.Table) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) IColumn(com.servoy.j2db.persistence.IColumn) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) ServoyException(com.servoy.j2db.util.ServoyException) JavaScriptException(org.mozilla.javascript.JavaScriptException) IOException(java.io.IOException) MarshallException(org.jabsorb.serializer.MarshallException) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) RepositoryException(com.servoy.j2db.persistence.RepositoryException)

Aggregations

Table (com.servoy.j2db.persistence.Table)43 ITable (com.servoy.j2db.persistence.ITable)27 QueryTable (com.servoy.j2db.query.QueryTable)26 RepositoryException (com.servoy.j2db.persistence.RepositoryException)23 BaseQueryTable (com.servoy.base.query.BaseQueryTable)22 Column (com.servoy.j2db.persistence.Column)21 ServoyException (com.servoy.j2db.util.ServoyException)17 QueryColumn (com.servoy.j2db.query.QueryColumn)16 QuerySelect (com.servoy.j2db.query.QuerySelect)16 ArrayList (java.util.ArrayList)16 RemoteException (java.rmi.RemoteException)14 ApplicationException (com.servoy.j2db.ApplicationException)13 IColumn (com.servoy.j2db.persistence.IColumn)10 IBaseColumn (com.servoy.base.persistence.IBaseColumn)9 IServer (com.servoy.j2db.persistence.IServer)7 Relation (com.servoy.j2db.persistence.Relation)7 HashMap (java.util.HashMap)7 SortColumn (com.servoy.j2db.dataprocessing.SortColumn)6 SafeArrayList (com.servoy.j2db.util.SafeArrayList)6 ColumnInfo (com.servoy.j2db.persistence.ColumnInfo)5