Search in sources :

Example 26 with Column

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

the class SQLSheet method getIdentIndex.

/**
 * Find the index of an identity column. This may be a non-pk column.
 *
 * @return identity column index, -1 if not found
 */
int getIdentIndex() {
    if (sheetIdentIndex == null) {
        SQLSheet.SQLDescription desc = getSQLDescription(SQLSheet.UPDATE);
        List<?> list = desc.getRequiredDataProviderIDs();
        for (int i = 0; sheetIdentIndex == null && i < list.size(); i++) {
            String dataProviderID = (String) list.get(i);
            Column c = table.getColumn(dataProviderID);
            if (c.isDBIdentity()) {
                sheetIdentIndex = new Integer(i);
            }
        }
        if (sheetIdentIndex == null) {
            sheetIdentIndex = new Integer(-1);
        }
    }
    return sheetIdentIndex.intValue();
}
Also used : IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column)

Example 27 with Column

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

the class SQLSheet method getCalculationOrColumnVariableInfo.

VariableInfo getCalculationOrColumnVariableInfo(String dataProviderID, int columnIndex) {
    if (columnIndex != -1) {
        Column c = table.getColumn(dataProviderID);
        if (c == null)
            Debug.error("getCalculationOrColumnVariableInfo: Cannot get column with DP " + dataProviderID + " and columnIndex " + columnIndex + " for table " + table.getDataSource());
        return new VariableInfo(c.getType(), c.getLength(), c.getFlags());
    }
    Integer retVal = null;
    ScriptCalculation sc = application.getFlattenedSolution().getScriptCalculation(dataProviderID, table);
    if (sc != null) {
        retVal = new Integer(sc.getDataProviderType());
    }
    return new VariableInfo((retVal != null ? retVal.intValue() : 0), Integer.MAX_VALUE, /* allow unlimited value for unstored calcs */
    IBaseColumn.NORMAL_COLUMN);
}
Also used : ScriptCalculation(com.servoy.j2db.persistence.ScriptCalculation) IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column)

Example 28 with Column

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

the class RelatedFoundSet method getWhereArgs.

public Object[] getWhereArgs(boolean onlyEqualsConditions) {
    Placeholder ph = creationSqlSelect.getPlaceholder(SQLGenerator.createRelationKeyPlaceholderKey(creationSqlSelect.getTable(), getRelationName()));
    if (ph == null || !ph.isSet()) {
        if (!findMode) {
            Debug.error(// $NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            "RelatedFoundset, creation args not found\nplaceholder=" + ph + "\nrelation=" + getRelationName() + "\ncreationSqlSelect=" + creationSqlSelect, new RuntimeException("RelatedFoundset, creation args not found!!"));
        }
        // how can this happen (other then in find mode) ??
        return null;
    }
    Relation relation = fsm.getApplication().getFlattenedSolution().getRelation(relationName);
    if (relation == null) {
        // $NON-NLS-1$
        throw new IllegalStateException("Relation not found for related foundset: " + relationName);
    }
    Object[][] foreignData = (Object[][]) ph.getValue();
    Column[] columns;
    try {
        columns = relation.getForeignColumns(fsm.getApplication().getFlattenedSolution());
    } catch (RepositoryException e) {
        Debug.error(e);
        // $NON-NLS-1$
        throw new IllegalStateException("Relation columns not found for related foundset: " + relationName);
    }
    if (columns.length != foreignData.length) {
        // $NON-NLS-1$
        throw new IllegalStateException("Relation where-args inconsistent with columns for relation" + relationName);
    }
    IntStream columnIndexesStream;
    if (onlyEqualsConditions) {
        int[] columnIndexes = getIndexesEqualsEntries();
        if (columnIndexes.length == 0) {
            return null;
        }
        columnIndexesStream = IntStream.of(columnIndexes);
    } else {
        columnIndexesStream = IntStream.range(0, columns.length);
    }
    return columnIndexesStream.mapToObj(i -> {
        // Use converted value for hash
        int colindex = getSQLSheet().getColumnIndex(columns[i].getDataProviderID());
        return getSQLSheet().convertValueToObject(foreignData[i][0], colindex, fsm.getColumnConverterManager());
    }).toArray();
}
Also used : IntStream(java.util.stream.IntStream) DbIdentValue(com.servoy.j2db.dataprocessing.ValueFactory.DbIdentValue) Builder(java.util.stream.IntStream.Builder) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Placeholder(com.servoy.j2db.query.Placeholder) Debug(com.servoy.j2db.util.Debug) IQuerySelectValue(com.servoy.j2db.query.IQuerySelectValue) HashMap(java.util.HashMap) NativeJavaMethod(org.mozilla.javascript.NativeJavaMethod) ArrayList(java.util.ArrayList) Utils(com.servoy.j2db.util.Utils) StringTokenizer(java.util.StringTokenizer) SafeArrayList(com.servoy.j2db.util.SafeArrayList) Map(java.util.Map) ISQLSelect(com.servoy.j2db.query.ISQLSelect) Relation(com.servoy.j2db.persistence.Relation) ObjectOutputStream(java.io.ObjectOutputStream) QBSelect(com.servoy.j2db.querybuilder.impl.QBSelect) ServoyException(com.servoy.j2db.util.ServoyException) IBaseSQLCondition(com.servoy.base.query.IBaseSQLCondition) AbstractBaseQuery(com.servoy.j2db.query.AbstractBaseQuery) Iterator(java.util.Iterator) IRepository(com.servoy.j2db.persistence.IRepository) ServoyClientSupport(com.servoy.base.scripting.annotations.ServoyClientSupport) QuerySelect(com.servoy.j2db.query.QuerySelect) RemoteException(java.rmi.RemoteException) List(java.util.List) Scriptable(org.mozilla.javascript.Scriptable) Column(com.servoy.j2db.persistence.Column) RepositoryException(com.servoy.j2db.persistence.RepositoryException) PackVisitor(com.servoy.j2db.util.visitor.PackVisitor) AndOrCondition(com.servoy.j2db.query.AndOrCondition) TablePlaceholderKey(com.servoy.j2db.query.TablePlaceholderKey) Placeholder(com.servoy.j2db.query.Placeholder) Relation(com.servoy.j2db.persistence.Relation) Column(com.servoy.j2db.persistence.Column) RepositoryException(com.servoy.j2db.persistence.RepositoryException) IntStream(java.util.stream.IntStream)

Example 29 with Column

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

the class RowManager method rowUpdated.

void rowUpdated(final Row row, final String oldKeyHash, final IRowListener src, List<Runnable> runnables, String[] changedColumnNames) {
    final boolean doesExistInDB = row.existInDB();
    // always needed flushes stuff
    row.flagExistInDB();
    String newKeyHash = row.recalcPKHashKey();
    if (!oldKeyHash.equals(newKeyHash)) {
        // fire pk updated to IRowListeners
        runnables.add(new Runnable() {

            public void run() {
                firePKUpdated(row, oldKeyHash);
            }
        });
    }
    if (changedColumnNames != null) {
        List<String> autoEnterColumns = new ArrayList<String>();
        for (String column : changedColumnNames) {
            Column c = sheet.getTable().getColumn(column);
            if (c != null && c.getColumnInfo() != null && c.getColumnInfo().getAutoEnterType() == ColumnInfo.SYSTEM_VALUE_AUTO_ENTER) {
                int subType = c.getColumnInfo().getAutoEnterSubType();
                if (subType == ColumnInfo.SYSTEM_VALUE_MODIFICATION_DATETIME || subType == ColumnInfo.SYSTEM_VALUE_MODIFICATION_SERVER_DATETIME || subType == ColumnInfo.SYSTEM_VALUE_MODIFICATION_USERNAME || subType == ColumnInfo.SYSTEM_VALUE_MODIFICATION_USERUID) {
                    autoEnterColumns.add(column);
                }
            }
        }
        if (autoEnterColumns.size() > 0) {
            runnables.add(new Runnable() {

                public void run() {
                    FireCollector collector = FireCollector.getFireCollector();
                    try {
                        for (String name : autoEnterColumns) {
                            row.fireNotifyChange(name, row.getValue(name), collector);
                        }
                    } catch (Exception e) {
                        Debug.error("error notifying the system of a autoenter column value change of row: " + row, e);
                    } finally {
                        collector.done();
                    }
                }
            });
        }
    }
    // run fires later (add this runnable here first because the runnables in EditRecordList are processed in reverse order)
    runnables.add(new Runnable() {

        public void run() {
            fireNotifyChange(src, row, row.getPKHashKey(), changedColumnNames, doesExistInDB ? RowEvent.UPDATE : RowEvent.INSERT, false, true);
        }
    });
    if (fsmNotifier == null) {
        fsmNotifier = new FSMTableNotifier();
        runnables.add(fsmNotifier);
    }
    // may add fires for depending calcs
    fireDependingCalcsForPKUpdate(row, oldKeyHash, runnables);
}
Also used : QueryColumn(com.servoy.j2db.query.QueryColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column) ArrayList(java.util.ArrayList) SafeArrayList(com.servoy.j2db.util.SafeArrayList) RemoteException(java.rmi.RemoteException) ServoyException(com.servoy.j2db.util.ServoyException) RepositoryException(com.servoy.j2db.persistence.RepositoryException)

Example 30 with Column

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

the class JSFoundSetUpdater method js_performUpdate.

/**
 * Do the actual update in the database, returns true if successful. It will first try to save all editing records (from all foundsets), if cannot save will return false before doing the update.
 * There are 3 types of possible use with the foundset updater
 * 1) update entire foundset by a single sql statement; that is not possible when the table of the foundset has tracking enabled then it will loop over the whole foundset.
 *    When a single sql statement is done, modification columns will not be updated and associated Table Events won't be triggered, because it does the update directly in the database, without getting the records.
 *   NOTE: this mode will refresh all foundsets based on same datasource
 * 2) update part of foundset, for example the first 4 row (starts with selected row)
 * 3) safely loop through foundset (starts with selected row)
 *
 * after the perform update call there are no records in edit mode, that where not already in edit mode, because all of them are saved directly to the database,
 * or in mode 1 the records are not touched at all and the database is updated directly.
 *
 * @sample
 * //1) update entire foundset
 * var fsUpdater = databaseManager.getFoundSetUpdater(foundset)
 * fsUpdater.setColumn('customer_type',1)
 * fsUpdater.setColumn('my_flag',0)
 * fsUpdater.performUpdate()
 *
 * //2) update part of foundset, for example the first 4 row (starts with selected row)
 * var fsUpdater = databaseManager.getFoundSetUpdater(foundset)
 * fsUpdater.setColumn('customer_type',new Array(1,2,3,4))
 * fsUpdater.setColumn('my_flag',new Array(1,0,1,0))
 * fsUpdater.performUpdate()
 *
 * //3) safely loop through foundset (starts with selected row)
 * controller.setSelectedIndex(1)
 * var count = 0
 * var fsUpdater = databaseManager.getFoundSetUpdater(foundset)
 * while(fsUpdater.next())
 * {
 * 	fsUpdater.setColumn('my_flag',count++)
 * }
 *
 * @return true if succeeded, false if failed.
 */
public boolean js_performUpdate() throws ServoyException {
    if (list.size() == 0 || foundset.getTable() == null) {
        return false;
    }
    if (!foundset.hasAccess(IRepository.UPDATE)) {
        throw new ApplicationException(ServoyException.NO_MODIFY_ACCESS, new Object[] { foundset.getTable().getName() });
    }
    // first stop all edits, 'force' stop the edit by saying that it is a javascript stop
    if (application.getFoundSetManager().getEditRecordList().stopEditing(true) != ISaveConstants.STOPPED)
        return false;
    try {
        QuerySelect sqlParts;
        IDataSet currentPKs;
        synchronized (foundset.getPksAndRecords()) {
            sqlParts = foundset.getPksAndRecords().getQuerySelectForReading();
            currentPKs = foundset.getPksAndRecords().getPks();
        }
        FoundSetManager fsm = (FoundSetManager) application.getFoundSetManager();
        if (rowsToUpdate == -1 && !foundset.hasAccess(IRepository.TRACKING) && sqlParts.getJoins() == null && // does not have join to other table
        !fsm.hasTableFiltersWithJoins(foundset.getTable().getServerName(), sqlParts)) {
            // all rows at once, via sql
            Table table = (Table) foundset.getTable();
            SQLSheet sheet = foundset.getSQLSheet();
            QueryUpdate sqlUpdate = new QueryUpdate(sqlParts.getTable());
            for (Pair<String, Object> p : list) {
                String name = p.getLeft();
                Object val = p.getRight();
                int columnIndex = sheet.getColumnIndex(name);
                VariableInfo variableInfo = sheet.getCalculationOrColumnVariableInfo(name, columnIndex);
                if (// do not convert null to 0 incase of numbers, this means the calcs the value whould change each time //$NON-NLS-1$
                val != null && !("".equals(val) && Column.mapToDefaultType(variableInfo.type) == IColumnTypes.TEXT)) {
                    val = sheet.convertObjectToValue(name, val, foundset.getFoundSetManager().getColumnConverterManager(), foundset.getFoundSetManager().getColumnValidatorManager(), null);
                }
                Column c = table.getColumn(name);
                if (val == null) {
                    val = ValueFactory.createNullValue(c.getType());
                }
                sqlUpdate.addValue(c.queryColumn(sqlParts.getTable()), val);
            }
            sqlUpdate.setCondition(sqlParts.getWhereClone());
            IDataSet pks;
            boolean allFoundsetRecordsLoaded = currentPKs != null && currentPKs.getRowCount() <= fsm.config.pkChunkSize() && !currentPKs.hadMoreRows();
            if (allFoundsetRecordsLoaded) {
                pks = currentPKs;
            } else {
                pks = new BufferedDataSet();
                pks.addRow(new Object[] { ValueFactory.createTableFlushValue() });
            }
            String transaction_id = fsm.getTransactionID(foundset.getSQLSheet());
            try {
                SQLStatement statement = new SQLStatement(ISQLActionTypes.UPDATE_ACTION, table.getServerName(), table.getName(), pks, transaction_id, sqlUpdate, fsm.getTableFilterParams(table.getServerName(), sqlUpdate));
                if (allFoundsetRecordsLoaded) {
                    statement.setExpectedUpdateCount(pks.getRowCount());
                }
                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) {
                        if (((ServoyException) results[i]).getErrorCode() == ServoyException.UNEXPECTED_UPDATE_COUNT) {
                            performLoopUpdate();
                            clear();
                            return true;
                        }
                        fsm.flushCachedDatabaseData(fsm.getDataSource(table));
                        throw (ServoyException) results[i];
                    }
                }
                fsm.flushCachedDatabaseData(fsm.getDataSource(table));
                clear();
                return true;
            } catch (ApplicationException aex) {
                if (allFoundsetRecordsLoaded || aex.getErrorCode() != ServoyException.RECORD_LOCKED) {
                    throw aex;
                }
                // a record was locked by another client, try per-record
                Debug.log("foundsetUpdater could not update all records in 1 statement (a record may be locked), trying per-record");
            }
        }
        performLoopUpdate();
    } catch (Exception ex) {
        // $NON-NLS-1$
        application.handleException(// $NON-NLS-1$
        application.getI18NMessage("servoy.foundsetupdater.updateFailed"), new ApplicationException(ServoyException.SAVE_FAILED, ex));
        return false;
    }
    clear();
    return true;
}
Also used : Table(com.servoy.j2db.persistence.Table) VariableInfo(com.servoy.j2db.dataprocessing.SQLSheet.VariableInfo) QuerySelect(com.servoy.j2db.query.QuerySelect) ServoyException(com.servoy.j2db.util.ServoyException) ServoyException(com.servoy.j2db.util.ServoyException) ApplicationException(com.servoy.j2db.ApplicationException) ApplicationException(com.servoy.j2db.ApplicationException) Column(com.servoy.j2db.persistence.Column) QueryUpdate(com.servoy.j2db.query.QueryUpdate)

Aggregations

Column (com.servoy.j2db.persistence.Column)76 QueryColumn (com.servoy.j2db.query.QueryColumn)44 IColumn (com.servoy.j2db.persistence.IColumn)37 RepositoryException (com.servoy.j2db.persistence.RepositoryException)32 IBaseColumn (com.servoy.base.persistence.IBaseColumn)31 QuerySelect (com.servoy.j2db.query.QuerySelect)29 ArrayList (java.util.ArrayList)29 QueryTable (com.servoy.j2db.query.QueryTable)27 ITable (com.servoy.j2db.persistence.ITable)23 BaseQueryTable (com.servoy.base.query.BaseQueryTable)22 Table (com.servoy.j2db.persistence.Table)22 ServoyException (com.servoy.j2db.util.ServoyException)21 SafeArrayList (com.servoy.j2db.util.SafeArrayList)19 IQuerySelectValue (com.servoy.j2db.query.IQuerySelectValue)18 RemoteException (java.rmi.RemoteException)17 ColumnInfo (com.servoy.j2db.persistence.ColumnInfo)16 BaseQueryColumn (com.servoy.base.query.BaseQueryColumn)14 IDataProvider (com.servoy.j2db.persistence.IDataProvider)12 Relation (com.servoy.j2db.persistence.Relation)12 Placeholder (com.servoy.j2db.query.Placeholder)12