Search in sources :

Example 21 with RepositoryException

use of com.servoy.j2db.persistence.RepositoryException in project servoy-client by Servoy.

the class ColumnSortListener method mouseClicked.

/*
	 * (non-Javadoc)
	 * 
	 * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
	 */
@Override
public void mouseClicked(final MouseEvent e) {
    if (!table.isEnabled())
        return;
    if (e.getButton() == MouseEvent.BUTTON1) {
        if (fc != null)
            fc.setLastKeyModifiers(e.getModifiers());
        TableColumnModel colModel = table.getColumnModel();
        if (colModel == null) {
            return;
        }
        int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
        if (columnModelIndex < 0) {
            return;
        }
        final TableColumn column = colModel.getColumn(columnModelIndex);
        if (column == null) {
            return;
        }
        int modelIndex = column.getModelIndex();
        if (modelIndex < 0) {
            return;
        }
        if (table.getModel() instanceof IFoundSetInternal && application.getFoundSetManager().getEditRecordList().stopIfEditing((IFoundSetInternal) table.getModel()) != ISaveConstants.STOPPED) {
            return;
        }
        Integer columnIndex = Integer.valueOf(columnModelIndex);
        if (lastColumnIndex.containsKey(columnIndex)) {
            lastSortAsc = !lastColumnIndex.get(columnIndex).booleanValue();
        } else {
            lastSortAsc = true;
            if (fc != null && column instanceof CellAdapter && ((CellAdapter) column).getDataProviderID() != null && e.getClickCount() <= 1 && table.getModel() instanceof IFoundSetInternal) {
                IFoundSetInternal foundset = (IFoundSetInternal) table.getModel();
                List<SortColumn> sortCols = foundset.getSortColumns();
                if (sortCols != null && sortCols.size() > 0) {
                    CellAdapter ca = (CellAdapter) column;
                    List<String> sortingProviders = null;
                    Component renderer = ca.getRenderer();
                    if (renderer instanceof ISupportValueList && ((ISupportValueList) renderer).getValueList() != null) {
                        try {
                            sortingProviders = DBValueList.getShowDataproviders(((ISupportValueList) renderer).getValueList().getValueList(), (Table) foundset.getTable(), ca.getDataProviderID(), application.getFoundSetManager());
                        } catch (RepositoryException ex) {
                            Debug.error(ex);
                        }
                    }
                    if (sortingProviders == null) {
                        // no related sort, use sort on dataProviderID instead
                        sortingProviders = Collections.singletonList(ca.getDataProviderID());
                    }
                    for (String sortingProvider : sortingProviders) {
                        SortColumn existingSc;
                        try {
                            FoundSetManager fsm = (FoundSetManager) foundset.getFoundSetManager();
                            existingSc = fsm.getSortColumn(foundset.getTable(), sortingProvider, false);
                        } catch (Exception ex) {
                            Debug.error(ex);
                            continue;
                        }
                        for (SortColumn sc : sortCols) {
                            if (sc.equalsIgnoreSortorder(existingSc)) {
                                lastSortAsc = sc.getSortOrder() == SortColumn.DESCENDING;
                            }
                        }
                    }
                }
            }
        }
        if (!e.isShiftDown()) {
            // clear previous data
            lastColumnIndex.clear();
        }
        lastColumnIndex.put(columnIndex, Boolean.valueOf(lastSortAsc));
        if (column instanceof CellAdapter && table.getModel() instanceof IFoundSetInternal) {
            try {
                if (sortTimer != null) {
                    sortTimer.stop();
                }
                sortTimer = new Timer(300, new AbstractAction() {

                    public void actionPerformed(ActionEvent event) {
                        try {
                            String dataProviderID = ((CellAdapter) column).getDataProviderID();
                            int labelForOnActionMethodId = 0;
                            if (((CellAdapter) column).getHeaderRenderer() instanceof LFAwareSortableHeaderRenderer) {
                                labelForOnActionMethodId = ((LFAwareSortableHeaderRenderer) ((CellAdapter) column).getHeaderRenderer()).getOnActionMethodID();
                            }
                            if (fc != null && labelForOnActionMethodId > 0) {
                                LFAwareSortableHeaderRenderer renderer = (LFAwareSortableHeaderRenderer) (((CellAdapter) column).getHeaderRenderer());
                                fc.executeFunction(String.valueOf(labelForOnActionMethodId), Utils.arrayMerge((new Object[] { getJavaScriptEvent(e, JSEvent.EventType.action, renderer.getName()) }), Utils.parseJSExpressions(renderer.getFlattenedMethodArguments("onActionMethodID"))), true, null, false, // $NON-NLS-1$//$NON-NLS-2$
                                "onActionMethodID");
                            } else if (fc != null && fc.getForm().getOnSortCmdMethodID() > 0) {
                                // Also execute the on sort command on none data providers (like a label) then they can do there own sort.
                                fc.executeFunction(String.valueOf(fc.getForm().getOnSortCmdMethodID()), Utils.arrayMerge((new Object[] { dataProviderID, Boolean.valueOf(lastSortAsc), getJavaScriptEvent(e, JSEvent.EventType.none, null) }), Utils.parseJSExpressions(fc.getForm().getFlattenedMethodArguments("onSortCmdMethodID"))), true, null, false, // $NON-NLS-1$//$NON-NLS-2$
                                "onSortCmdMethodID");
                            } else if (dataProviderID != null && fc.getForm().getOnSortCmdMethodID() != -1) {
                                List<String> sortingProviders = null;
                                IFoundSetInternal model = (IFoundSetInternal) table.getModel();
                                Component renderer = ((CellAdapter) column).getRenderer();
                                if (renderer instanceof ISupportValueList && ((ISupportValueList) renderer).getValueList() != null) {
                                    try {
                                        sortingProviders = DBValueList.getShowDataproviders(((ISupportValueList) renderer).getValueList().getValueList(), (Table) model.getTable(), dataProviderID, application.getFoundSetManager());
                                    } catch (RepositoryException ex) {
                                        Debug.error(ex);
                                    }
                                }
                                if (sortingProviders == null) {
                                    // no related sort, use sort on dataProviderID instead
                                    sortingProviders = Collections.singletonList(dataProviderID);
                                }
                                try {
                                    List<SortColumn> list = e.isShiftDown() ? model.getSortColumns() : new ArrayList<SortColumn>();
                                    for (String sortingProvider : sortingProviders) {
                                        FoundSetManager fsm = ((FoundSetManager) model.getFoundSetManager());
                                        SortColumn sc = fsm.getSortColumn(model.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(lastSortAsc ? SortColumn.ASCENDING : SortColumn.DESCENDING);
                                        }
                                        model.sort(list, false);
                                    }
                                } catch (Exception ex) {
                                    Debug.error(ex);
                                }
                            }
                        } finally {
                            sortTimer.stop();
                        }
                    }
                });
                sortTimer.start();
            } catch (Exception ex) {
                Debug.error(ex);
            }
        }
    }
}
Also used : LFAwareSortableHeaderRenderer(com.servoy.j2db.gui.LFAwareSortableHeaderRenderer) FoundSetManager(com.servoy.j2db.dataprocessing.FoundSetManager) Table(com.servoy.j2db.persistence.Table) IFoundSetInternal(com.servoy.j2db.dataprocessing.IFoundSetInternal) ActionEvent(java.awt.event.ActionEvent) ISupportValueList(com.servoy.j2db.ui.ISupportValueList) TableColumnModel(javax.swing.table.TableColumnModel) RepositoryException(com.servoy.j2db.persistence.RepositoryException) SortColumn(com.servoy.j2db.dataprocessing.SortColumn) TableColumn(javax.swing.table.TableColumn) RepositoryException(com.servoy.j2db.persistence.RepositoryException) Timer(javax.swing.Timer) Component(java.awt.Component) AbstractAction(javax.swing.AbstractAction)

Example 22 with RepositoryException

use of com.servoy.j2db.persistence.RepositoryException in project servoy-client by Servoy.

the class FoundSet method browseAll.

public // ONLY used by printing
void browseAll(// ONLY used by printing
QuerySelect otherSQLSelect) throws // ONLY used by printing
ServoyException {
    if (sheet == null || sheet.getTable() == null)
        return;
    int oldSize = getSize();
    if (oldSize > 0) {
        fireSelectionAdjusting();
    }
    lastSortColumns = defaultSort;
    QuerySelect sqlSelect = fsm.getSQLGenerator().getPKSelectSqlSelect(this, sheet.getTable(), otherSQLSelect, null, true, null, lastSortColumns, true);
    if (!initialized) {
        creationSqlSelect = AbstractBaseQuery.deepClone(sqlSelect);
    }
    IFoundSetChanges changes = null;
    // cache pks
    String transaction_id = fsm.getTransactionID(sheet);
    long time = System.currentTimeMillis();
    try {
        IDataSet pks = performQuery(transaction_id, sqlSelect, getRowIdentColumnTypes(), 0, fsm.config.pkChunkSize(), IDataServer.FOUNDSET_LOAD_QUERY);
        changes = pksAndRecords.setPksAndQuery(pks, pks.getRowCount(), sqlSelect);
    } catch (RemoteException e) {
        throw new RepositoryException(e);
    }
    if (Debug.tracing()) {
        Debug.trace(// $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        "BrowseAll time: " + (System.currentTimeMillis() - time) + " thread: " + Thread.currentThread().getName() + ", SQL: " + sqlSelect.toString());
    }
    initialized = true;
    omittedPKs = null;
    clearInternalState(true);
    // let the List know the model changed
    fireDifference(oldSize, getSize(), changes);
}
Also used : RepositoryException(com.servoy.j2db.persistence.RepositoryException) RemoteException(java.rmi.RemoteException) QuerySelect(com.servoy.j2db.query.QuerySelect)

Example 23 with RepositoryException

use of com.servoy.j2db.persistence.RepositoryException in project servoy-client by Servoy.

the class FoundSet method refreshFromDBInternal.

/**
 * browse all part which can be used by subclasses this also acts as refresh and performs the pk query (again) can be called on any thread
 *
 * @param querySelect will not be modified, null for the current active query
 * @param flushRelatedFS
 * @param skipStopEdit
 */
protected void refreshFromDBInternal(QuerySelect sqlSelect, boolean dropSort, int rowsToRetrieve, boolean keepPkOrder, boolean skipStopEdit) throws ServoyException {
    if (fsm.getDataServer() == null) {
        // no data access yet
        return;
    }
    SafeArrayList<IRecordInternal> cachedRecords;
    IDataSet pks;
    Object[] selectedPK;
    synchronized (pksAndRecords) {
        cachedRecords = pksAndRecords.getCachedRecords();
        pks = pksAndRecords.getPks();
        selectedPK = (pks != null && getSelectedIndex() >= 0 && getSelectedIndex() < pks.getRowCount()) ? pks.getRow(getSelectedIndex()) : null;
    }
    Map<Integer, IRecordInternal> newRecords = new HashMap<Integer, IRecordInternal>();
    EditRecordList editRecordList = getFoundSetManager().getEditRecordList();
    IRecordInternal[] array = editRecordList.getEditedRecords(this);
    for (IRecordInternal editingRecord : array) {
        if (!editingRecord.existInDataSource()) {
            synchronized (pksAndRecords) {
                int newRecordIndex = cachedRecords.indexOf(editingRecord);
                // incase some has called startEdit before new/duplicateRecords was completed.
                if (newRecordIndex == -1)
                    newRecordIndex = 0;
                newRecords.put(Integer.valueOf(newRecordIndex), editingRecord);
                cachedRecords.set(newRecordIndex, null);
            }
        } else {
            // TODO check.. call stop edit? Records will be only referenced in the foundset manager:
            if (!skipStopEdit)
                editingRecord.stopEditing();
        }
    }
    int oldSize = getSize();
    if (oldSize > 1) {
        fireSelectionAdjusting();
    }
    IDataSet oldPKs = pks;
    IFoundSetChanges changes = null;
    // cache pks
    String transaction_id = fsm.getTransactionID(sheet);
    long time = System.currentTimeMillis();
    try {
        QuerySelect theQuery = (sqlSelect == null) ? pksAndRecords.getQuerySelectForReading() : sqlSelect;
        if (theQuery == null) {
            // query has been cleared
            pks = new BufferedDataSet();
        } else {
            pks = performQuery(transaction_id, theQuery, getRowIdentColumnTypes(), 0, rowsToRetrieve, IDataServer.FOUNDSET_LOAD_QUERY);
        }
        synchronized (pksAndRecords) {
            // optimistic locking, if the query has been changed in the mean time forget about the refresh
            if (sqlSelect != null || theQuery == null || theQuery == pksAndRecords.getQuerySelectForReading()) {
                changes = pksAndRecords.setPksAndQuery(pks, pks.getRowCount(), theQuery);
                cachedRecords = pksAndRecords.getCachedRecords();
            } else {
                // $NON-NLS-1$
                Debug.log("refreshFromDBInternal: query was changed during refresh, not resetting old query");
            }
        }
        if (Debug.tracing()) {
            Debug.trace(// $NON-NLS-1$//$NON-NLS-2$
            Thread.currentThread().getName() + ": RefreshFrom DB time: " + (System.currentTimeMillis() - time) + " pks: " + pks.getRowCount() + ", SQL: " + // $NON-NLS-1$
            theQuery);
        }
    } catch (RemoteException e) {
        throw new RepositoryException(e);
    }
    initialized = true;
    clearInternalState(true);
    if (dropSort)
        lastSortColumns = defaultSort;
    int selectedIndex = -1;
    synchronized (pksAndRecords) {
        if (cachedRecords == pksAndRecords.getCachedRecords()) {
            pks = pksAndRecords.getPks();
            Iterator<Map.Entry<Integer, IRecordInternal>> it = newRecords.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Integer, IRecordInternal> entry = it.next();
                int newRecordIndex = entry.getKey().intValue();
                IRecordInternal newRecord = entry.getValue();
                if (newRecordIndex == 0) {
                    cachedRecords.add(0, newRecord);
                    pks.addRow(0, newRecord.getPK());
                    selectedIndex = 0;
                    changes = null;
                } else if (newRecordIndex > 0) {
                    newRecordIndex = pks.getRowCount();
                    cachedRecords.add(newRecordIndex, newRecord);
                    pks.addRow(newRecordIndex, newRecord.getPK());
                    selectedIndex = newRecordIndex;
                    changes = null;
                }
            }
            if (keepPkOrder) {
                pksAndRecords.reorder(oldPKs);
                changes = null;
            }
        } else {
            // $NON-NLS-1$
            Debug.log("refreshFromDBInternal: cached records were changed during refresh, not reading editing records (would be duplicated)");
        }
        IRecordInternal[] currentEditedRecords = editRecordList.getEditedRecords(this);
        outer: for (IRecordInternal record : currentEditedRecords) {
            Object[] pk = record.getPK();
            pks = pksAndRecords.getPks();
            int i = 0;
            while (true) {
                for (; i < pks.getRowCount(); i++) {
                    if (Utils.equalObjects(pks.getRow(i), pk)) {
                        pksAndRecords.getCachedRecords().set(i, record);
                        continue outer;
                    }
                }
                if (getSize() < oldSize && pks.hadMoreRows()) {
                    int hint = ((getSize() / fsm.config.pkChunkSize()) + 2) * fsm.config.pkChunkSize();
                    queryForMorePKs(pksAndRecords, pks.getRowCount(), hint, true);
                    changes = null;
                } else {
                    break;
                }
            }
        }
    }
    // let the List know the model changed
    fireDifference(oldSize, getSize(), changes);
    // move to correct position if we know
    if (selectedIndex != -1 || !selectRecord(selectedPK)) {
        if (pks != null && pks.getRowCount() > 0 && selectedIndex == -1) {
            if (!(getSelectedIndex() >= 0 && getSelectedIndex() < pks.getRowCount())) {
                setSelectedIndex(0);
            }
        } else {
            setSelectedIndex(selectedIndex);
        }
    }
}
Also used : HashMap(java.util.HashMap) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QuerySelect(com.servoy.j2db.query.QuerySelect) RemoteException(java.rmi.RemoteException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 24 with RepositoryException

use of com.servoy.j2db.persistence.RepositoryException in project servoy-client by Servoy.

the class FoundSet method loadByQuery.

private boolean loadByQuery(QuerySelect sqlSelect) throws ServoyException {
    if (initialized && (getFoundSetManager().getEditRecordList().stopIfEditing(this) != ISaveConstants.STOPPED)) {
        fsm.getApplication().reportJSError(// $NON-NLS-1$
        "couldn't load dataset because foundset had edited records but couldn't save it: " + this + ", edited record(s): " + Utils.stringJoin(getFoundSetManager().getEditRecordList().getEditedRecords(this), '.') + ", failed record(s): " + Utils.stringJoin(getFoundSetManager().getEditRecordList().getFailedRecords(this), '.'), null);
        return false;
    }
    IDataSet pks = pksAndRecords.getPks();
    Object[] selectedPK = (pks != null && getSelectedIndex() >= 0 && getSelectedIndex() < pks.getRowCount()) ? pks.getRow(getSelectedIndex()) : null;
    int sizeBefore = getSize();
    if (sizeBefore > 1) {
        fireSelectionAdjusting();
    }
    clearOmit(sqlSelect);
    if (relationName != null) {
        AndCondition fsRelatedCondition = pksAndRecords.getQuerySelectForReading().getCondition(SQLGenerator.CONDITION_RELATION);
        AndCondition selectRelatedCondition = sqlSelect.getCondition(SQLGenerator.CONDITION_RELATION);
        if (selectRelatedCondition != null && !selectRelatedCondition.equals(fsRelatedCondition)) {
            // add the different relation condition as search
            sqlSelect.addCondition(SQLGenerator.CONDITION_SEARCH, selectRelatedCondition);
        }
        // Make sure the relation condition of this related foundset is left untouched
        sqlSelect.setCondition(SQLGenerator.CONDITION_RELATION, AbstractBaseQuery.relinkTable(pksAndRecords.getQuerySelectForReading().getTable(), sqlSelect.getTable(), fsRelatedCondition));
    }
    initialized = true;
    // do query with sqlSelect
    String transaction_id = fsm.getTransactionID(sheet);
    IDataSet pk_data;
    try {
        pk_data = performQuery(transaction_id, sqlSelect, getRowIdentColumnTypes(), 0, fsm.config.pkChunkSize(), IDataServer.CUSTOM_QUERY);
    } catch (RemoteException e) {
        clear();
        throw new RepositoryException(e);
    }
    if (pk_data.getRowCount() > 0 && pk_data.getColumnCount() != sheet.getPKIndexes().length)
        // $NON-NLS-1$
        throw new IllegalArgumentException(fsm.getApplication().getI18NMessage("servoy.foundSet.query.error.incorrectNumberOfPKS"));
    IFoundSetChanges changes = pksAndRecords.setPksAndQuery(pk_data, pk_data.getRowCount(), sqlSelect);
    clearInternalState(true);
    fireDifference(sizeBefore, getSize(), changes);
    // try to preserve selection after load by query; if not possible select first record
    if (selectedPK != null) {
        if (!selectRecord(selectedPK)) {
            setSelectedIndex(getSize() > 0 ? 0 : -1);
        }
    }
    return true;
}
Also used : RepositoryException(com.servoy.j2db.persistence.RepositoryException) RemoteException(java.rmi.RemoteException) AndCondition(com.servoy.j2db.query.AndCondition)

Example 25 with RepositoryException

use of com.servoy.j2db.persistence.RepositoryException in project servoy-client by Servoy.

the class FoundSet method loadByQuery.

public boolean loadByQuery(String query, Object[] args) throws ServoyException {
    if (query == null || sheet.getTable() == null)
        return false;
    int from_index = -1;
    int order_by_index;
    // check requirements
    if (!SQLGenerator.isSelectQuery(query)) {
        throw new IllegalArgumentException(SQLGenerator.SQL_QUERY_VALIDATION_MESSAGE + ':' + query);
    }
    String sql_lowercase = Utils.toEnglishLocaleLowerCase(query);
    // $NON-NLS-1$
    order_by_index = sql_lowercase.lastIndexOf("order by");
    boolean analyse_query_parts = (order_by_index != -1);
    if (analyse_query_parts) {
        // subquery. NOTE: this means that the ordering defined in the order-by part is lost.
        if (// $NON-NLS-1$
        ((from_index = sql_lowercase.indexOf("from")) == -1) || (sql_lowercase.indexOf(Utils.toEnglishLocaleLowerCase(sheet.getTable().getSQLName())) == -1) || // $NON-NLS-1$
        (sql_lowercase.indexOf("group by") != -1) || // $NON-NLS-1$
        (sql_lowercase.indexOf("having") != -1) || // $NON-NLS-1$
        (sql_lowercase.indexOf("union") != -1) || // $NON-NLS-1$
        (sql_lowercase.indexOf("join") != -1) || // $NON-NLS-1$
        (sql_lowercase.indexOf(".") == -1)) {
            analyse_query_parts = false;
        }
    }
    if (initialized && (getFoundSetManager().getEditRecordList().stopIfEditing(this) != ISaveConstants.STOPPED)) {
        fsm.getApplication().reportJSError(// $NON-NLS-1$
        "couldn't load dataset because foundset had edited records but couldn't save it: " + this + ", edited record(s): " + Utils.stringJoin(getFoundSetManager().getEditRecordList().getEditedRecords(this), '.') + ", failed record(s): " + Utils.stringJoin(getFoundSetManager().getEditRecordList().getFailedRecords(this), '.'), null);
        return false;
    }
    QuerySelect originalQuery = pksAndRecords.getQuerySelectForReading();
    QuerySelect sqlSelect = AbstractBaseQuery.deepClone(creationSqlSelect);
    sqlSelect.clearCondition(SQLGenerator.CONDITION_RELATION);
    sqlSelect.clearCondition(SQLGenerator.CONDITION_OMIT);
    if (rowManager != null)
        rowManager.clearAndCheckCache();
    initialized = true;
    Object[] whereArgs = null;
    if (args != null) {
        whereArgs = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            Object o = args[i];
            if (o != null && o.getClass().equals(Date.class)) {
                o = new Timestamp(((Date) o).getTime());
            }
            whereArgs[i] = o;
        }
    }
    // for instance, loadRecords(SQL) followed by extended search (S) and invertrecords executes query 'NOT(SQL OR S)'
    if (!analyse_query_parts) {
        // do not analyze the parts of the query, just create a set-condition that compares the pk columns with the result of the subquery
        Iterator<Column> pkIt = ((Table) getTable()).getRowIdentColumns().iterator();
        if (!pkIt.hasNext()) {
            throw new RepositoryException(ServoyException.InternalCodes.PRIMARY_KEY_NOT_FOUND, new Object[] { getTable().getName() }).setContext(this.toString());
        }
        List<QueryColumn> pkQueryColumns = new ArrayList<QueryColumn>();
        while (pkIt.hasNext()) {
            Column c = pkIt.next();
            pkQueryColumns.add(c.queryColumn(sqlSelect.getTable()));
        }
        // must strip of the order-by part because not all databases (Oracle, who else) like order-by in subselect
        String customQuery = query;
        if (order_by_index > 0) {
            // query contains order-by clause, find the next a closing bracket if it exists.
            // order-by has to be removed because some dbs do not allow that inside subselect.
            char[] chars = query.toCharArray();
            int level = 1;
            int i;
            for (i = order_by_index; level > 0 && i < chars.length; i++) {
                switch(chars[i]) {
                    case ')':
                        level--;
                        break;
                    case '(':
                        level++;
                        break;
                }
            }
            // in that case we can leave the ordering in place because it it not the sorting of the top-level query.
            if (level == 1) {
                // order-by clause was at the end
                customQuery = query.substring(0, order_by_index);
            }
        }
        sqlSelect.setCondition(SQLGenerator.CONDITION_SEARCH, new SetCondition(IBaseSQLCondition.IN_OPERATOR, pkQueryColumns.toArray(new QueryColumn[pkQueryColumns.size()]), new QueryCustomSelect(customQuery, whereArgs), true));
        // set the previous sort, add all joins that are needed for this sort
        List<IQuerySort> origSorts = originalQuery.getSorts();
        if (origSorts != null) {
            ArrayList<IQuerySort> sorts = new ArrayList<IQuerySort>();
            // find which sorts we will use and which tables are needed for that
            Set<BaseQueryTable> sortTables = new HashSet<BaseQueryTable>();
            for (IQuerySort isort : origSorts) {
                if (isort instanceof QuerySort) {
                    QuerySort sort = (QuerySort) isort;
                    IQuerySelectValue icolumn = sort.getColumn();
                    if (icolumn instanceof QueryColumn) {
                        QueryColumn column = (QueryColumn) icolumn;
                        sortTables.add(column.getTable());
                        sorts.add(sort);
                    }
                }
            // ignore custom sorts and sorts on other things than columns
            }
            // try to find the joins that are needed to satisfy tablesToResolve
            List<BaseQueryTable> tablesToResolve = new ArrayList<BaseQueryTable>();
            tablesToResolve.addAll(sortTables);
            List<BaseQueryTable> resolvedTables = new ArrayList<BaseQueryTable>();
            resolvedTables.add(sqlSelect.getTable());
            ArrayList<ISQLJoin> requiredJoins = new ArrayList<ISQLJoin>();
            boolean found = true;
            while (found && tablesToResolve.size() > 0) {
                BaseQueryTable table = tablesToResolve.remove(0);
                if (resolvedTables.contains(table)) {
                    continue;
                }
                found = false;
                ArrayList<ISQLJoin> joins = originalQuery.getJoins();
                if (joins != null) {
                    for (ISQLJoin ijoin : joins) {
                        if (!found && ijoin instanceof ISQLTableJoin) {
                            ISQLTableJoin join = (ISQLTableJoin) ijoin;
                            if (table.equals(join.getForeignTable())) {
                                // have to add this join
                                tablesToResolve.add(join.getPrimaryTable());
                                resolvedTables.add(table);
                                requiredJoins.add(join);
                                found = true;
                            }
                        }
                    }
                }
            }
            if (found) {
                sqlSelect.setJoins(requiredJoins);
                sqlSelect.setSorts(sorts);
            } else {
                // $NON-NLS-1$
                Debug.log("Could not restore order by in loadRecords(): couild not find all tables for sorting in " + originalQuery);
            }
        }
    } else {
        // create a query with the different parts as custom elements
        sqlSelect.clearJoins();
        // not needed when you have no joins and may conflict with order by
        sqlSelect.setDistinct(false);
        String tables;
        // $NON-NLS-1$
        int where_index = sql_lowercase.indexOf("where");
        if (where_index == -1) {
            tables = query.substring(from_index + 4, order_by_index);
            // no where-clause, remove the search condition (was set to FALSE in clear()
            sqlSelect.clearCondition(SQLGenerator.CONDITION_SEARCH);
        } else {
            tables = query.substring(from_index + 4, where_index);
            sqlSelect.setCondition(SQLGenerator.CONDITION_SEARCH, new CustomCondition(query.substring(where_index + 5, order_by_index).trim(), whereArgs));
        }
        // pick the foundset main table from the tables in the query (does not have to be the first one, we generate sql ourselves
        // that puts the main table at the end, see QueryGenerator)
        boolean foundTable = false;
        String mainTable = sheet.getTable().getName();
        StringBuilder otherTables = new StringBuilder();
        // $NON-NLS-1$
        StringTokenizer tok = new StringTokenizer(tables, ",");
        // default alias to table name
        String mainTableAlias = mainTable;
        // $NON-NLS-1$
        String whitespace = "\\s+";
        while (tok.hasMoreElements()) {
            String tableName = tok.nextToken().trim();
            String[] lcTableName = tableName.toLowerCase().split(whitespace);
            if (matchesMainTablename(lcTableName[0])) {
                foundTable = true;
                // either 'tabname', 'tabname aliasname' or 'tabname AS aliasname', when no alias is given, use table name as alias
                mainTableAlias = tableName.split(whitespace)[lcTableName.length - 1];
            } else {
                if (otherTables.length() > 0) {
                    // $NON-NLS-1$
                    otherTables.append(", ");
                }
                otherTables.append(tableName);
            }
        }
        // set table alias or unalias table when no alias was used
        BaseQueryTable qTable = sqlSelect.getTable();
        sqlSelect.relinkTable(sqlSelect.getTable(), new QueryTable(qTable.getName(), qTable.getDataSource(), qTable.getCatalogName(), qTable.getSchemaName(), mainTableAlias));
        if (otherTables.length() > 0) {
            // $NON-NLS-1$
            if (!foundTable)
                throw new IllegalArgumentException(fsm.getApplication().getI18NMessage("servoy.foundSet.query.error.firstTable"));
            // $NON-NLS-1$
            sqlSelect.addJoin(new QueryCustomJoin("foundset.loadbyquery", sqlSelect.getTable(), otherTables.toString()));
        }
        ArrayList<IQuerySort> sorts = new ArrayList<IQuerySort>();
        // $NON-NLS-1$
        Enumeration<Object> sortParts = new StringTokenizer(query.substring(order_by_index + 8), ",");
        while (sortParts.hasMoreElements()) {
            sorts.add(new QueryCustomSort(((String) sortParts.nextElement()).trim()));
        }
        sqlSelect.setSorts(sorts);
    }
    return loadByQuery(sqlSelect);
}
Also used : ArrayList(java.util.ArrayList) SafeArrayList(com.servoy.j2db.util.SafeArrayList) SetCondition(com.servoy.j2db.query.SetCondition) Timestamp(java.sql.Timestamp) IQuerySort(com.servoy.j2db.query.IQuerySort) QueryCustomSort(com.servoy.j2db.query.QueryCustomSort) QueryColumn(com.servoy.j2db.query.QueryColumn) Column(com.servoy.j2db.persistence.Column) IColumn(com.servoy.j2db.persistence.IColumn) ISQLTableJoin(com.servoy.j2db.query.ISQLTableJoin) IQuerySort(com.servoy.j2db.query.IQuerySort) QuerySort(com.servoy.j2db.query.QuerySort) HashSet(java.util.HashSet) CustomCondition(com.servoy.j2db.query.CustomCondition) RepositoryException(com.servoy.j2db.persistence.RepositoryException) ISQLJoin(com.servoy.j2db.query.ISQLJoin) QueryCustomSelect(com.servoy.j2db.query.QueryCustomSelect) QuerySelect(com.servoy.j2db.query.QuerySelect) Date(java.util.Date) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) StringTokenizer(java.util.StringTokenizer) BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryCustomJoin(com.servoy.j2db.query.QueryCustomJoin) QueryColumn(com.servoy.j2db.query.QueryColumn) IQuerySelectValue(com.servoy.j2db.query.IQuerySelectValue)

Aggregations

RepositoryException (com.servoy.j2db.persistence.RepositoryException)116 RemoteException (java.rmi.RemoteException)45 QuerySelect (com.servoy.j2db.query.QuerySelect)25 ITable (com.servoy.j2db.persistence.ITable)22 JSFunction (org.mozilla.javascript.annotations.JSFunction)22 ServoyException (com.servoy.j2db.util.ServoyException)21 Column (com.servoy.j2db.persistence.Column)19 ArrayList (java.util.ArrayList)19 BaseQueryTable (com.servoy.base.query.BaseQueryTable)16 Table (com.servoy.j2db.persistence.Table)16 QueryTable (com.servoy.j2db.query.QueryTable)16 FlattenedSolution (com.servoy.j2db.FlattenedSolution)14 Point (java.awt.Point)14 IDataProvider (com.servoy.j2db.persistence.IDataProvider)13 QueryColumn (com.servoy.j2db.query.QueryColumn)13 IColumn (com.servoy.j2db.persistence.IColumn)12 ApplicationException (com.servoy.j2db.ApplicationException)11 ScriptNameValidator (com.servoy.j2db.persistence.ScriptNameValidator)10 SafeArrayList (com.servoy.j2db.util.SafeArrayList)10 FoundSetManager (com.servoy.j2db.dataprocessing.FoundSetManager)8