Search in sources :

Example 36 with RepositoryException

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

the class RowManager method deleteRow.

void deleteRow(IRowListener src, Row r, boolean tracking, boolean partOfBiggerDelete) throws ServoyException {
    // $NON-NLS-1$
    if (r.getRowManager() != this)
        throw new IllegalArgumentException("I'm not the row manager from row");
    // prevent it processed by any update, changed is false now
    r.flagExistInDB();
    if (!partOfBiggerDelete) {
        QueryDelete sqlDelete = AbstractBaseQuery.deepClone((QueryDelete) sheet.getSQLDescription(SQLSheet.DELETE).getSQLQuery());
        Object[] pk = r.getPK();
        if (!sqlDelete.setPlaceholderValue(new TablePlaceholderKey(sqlDelete.getTable(), SQLGenerator.PLACEHOLDER_PRIMARY_KEY), pk)) {
            Debug.error(new RuntimeException(// $NON-NLS-1$
            "Could not set placeholder " + new TablePlaceholderKey(sqlDelete.getTable(), SQLGenerator.PLACEHOLDER_PRIMARY_KEY) + " in query " + sqlDelete + // $NON-NLS-1$ //$NON-NLS-2$
            "-- continuing"));
        }
        IDataSet pks = new BufferedDataSet();
        pks.addRow(pk);
        ISQLStatement[] stats_a = new ISQLStatement[1];
        String tid = null;
        GlobalTransaction gt = fsm.getGlobalTransaction();
        if (gt != null) {
            tid = gt.getTransactionID(sheet.getServerName());
        }
        SQLStatement statement = new SQLStatement(ISQLActionTypes.DELETE_ACTION, sheet.getServerName(), sheet.getTable().getName(), pks, tid, sqlDelete, fsm.getTableFilterParams(sheet.getServerName(), sqlDelete));
        // check that 1 record is deleted
        statement.setExpectedUpdateCount(1);
        stats_a[0] = statement;
        if (tracking) {
            statement.setTrackingData(sheet.getColumnNames(), r.getRawColumnData() != null ? new Object[][] { r.getRawColumnData() } : null, null, fsm.getApplication().getUserUID(), fsm.getTrackingInfo(), fsm.getApplication().getClientID());
        }
        try {
            Object[] results = fsm.getDataServer().performUpdates(fsm.getApplication().getClientID(), stats_a);
            for (int i = 0; results != null && i < results.length; i++) {
                if (results[i] instanceof ServoyException) {
                    throw (ServoyException) results[i];
                }
            }
        } catch (RemoteException e) {
            throw new RepositoryException(e);
        }
        SoftReferenceWithData<Row, Pair<Map<String, List<CalculationDependency>>, CalculationDependencyData>> removed;
        synchronized (this) {
            removed = pkRowMap.remove(r.getPKHashKey());
        }
        fireDependingCalcs(removed, null, null);
    } else {
        synchronized (this) {
            pkRowMap.remove(r.getPKHashKey());
        }
    }
    fireNotifyChange(src, r, r.getPKHashKey(), null, RowEvent.DELETE);
}
Also used : QueryDelete(com.servoy.j2db.query.QueryDelete) TablePlaceholderKey(com.servoy.j2db.query.TablePlaceholderKey) RepositoryException(com.servoy.j2db.persistence.RepositoryException) ServoyException(com.servoy.j2db.util.ServoyException) List(java.util.List) ArrayList(java.util.ArrayList) SafeArrayList(com.servoy.j2db.util.SafeArrayList) Collectors.toList(java.util.stream.Collectors.toList) RemoteException(java.rmi.RemoteException) Pair(com.servoy.j2db.util.Pair)

Example 37 with RepositoryException

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

the class JSTableObject method js_createNewColumn.

/**
 * Creates a new column in this table. The name, type and length of the new column must be specified. For specifying the
 * type of the column, use the JSColumn constants. The column is not actually created in the database until this
 * table is synchronized with the database using the JSServer.synchronizeWithDB method.
 *
 * The method returns a JSColumn instance that corresponds to the newly created column. If any error occurs and the column cannot be created, then the method
 * returns null.
 * @see JSColumnObject
 *
 * @sample
 * var server = plugins.maintenance.getServer("example_data");
 * if (server)
 * {
 * 	var table = server.createNewTable("users");
 * 	if (table)
 * 	{
 * 		var pk = table.createNewColumn("id", JSColumn.MEDIA, 16); // can also use (JSColumn.TEXT, 36) for UUIDs
 * 		pk.rowIdentifierType = JSColumn.PK_COLUMN;
 * 		pk.setFlag(JSColumn.UUID_COLUMN, true)
 * 		pk.sequenceType = JSColumn.UUID_GENERATOR
 * 		var c = table.createNewColumn("name", JSColumn.TEXT, 100);
 * 		c.allowNull = false
 * 		table.createNewColumn("age", JSColumn.INTEGER, 0);
 * 		table.createNewColumn("last_login", JSColumn.DATETIME, 0);
 * 		var result = server.synchronizeWithDB(table);
 * 		if (result) application.output("Table successfully created.");
 * 		else application.output("Table not created.");
 * 	}
 * }
 *
 * @param columnName
 * @param type
 * @param length
 * @param allowNull
 * @param pkColumn
 */
public JSColumnObject js_createNewColumn(String columnName, Number type, Number length, Boolean allowNull, Boolean pkColumn) {
    int _type = Utils.getAsInteger(type);
    int _length = Utils.getAsInteger(length);
    boolean _allowNull = Utils.getAsBoolean(allowNull);
    boolean _pkColumn = Utils.getAsBoolean(pkColumn);
    try {
        Column c = ((Table) getTable()).createNewColumn(DummyValidator.INSTANCE, columnName, _type, _length, _allowNull, _pkColumn);
        return new JSColumnObject(c, getServer(), getTable());
    } catch (RepositoryException e) {
        // $NON-NLS-1$
        Debug.error("Exception while creating new column.", e);
        return null;
    }
}
Also used : ITable(com.servoy.j2db.persistence.ITable) Table(com.servoy.j2db.persistence.Table) Column(com.servoy.j2db.persistence.Column) RepositoryException(com.servoy.j2db.persistence.RepositoryException)

Example 38 with RepositoryException

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

the class MetaDataUtils method loadMetadataInTable.

public static int loadMetadataInTable(ITable table, String json) throws IOException, ServoyException, JSONException {
    // parse dataset
    BufferedDataSet dataSet = MetaDataUtils.deserializeTableMetaDataContents(json);
    // check if all columns exist
    List<String> missingColumns = null;
    for (String colname : dataSet.getColumnNames()) {
        if (table.getColumn(colname) == null) {
            if (missingColumns == null) {
                missingColumns = new ArrayList<String>();
            }
            missingColumns.add(colname);
        }
    }
    if (missingColumns != null) {
        StringBuilder message = new StringBuilder("Missing columns from meta data for table '").append(table.getName()).append("'").append(" in server '").append(table.getServerName()).append("' : ");
        for (String name : missingColumns) {
            message.append('\'').append(name).append("' ");
        }
        throw new RepositoryException(message.toString());
    }
    // delete existing data
    ApplicationServerRegistry.get().getDataServer().performUpdates(ApplicationServerRegistry.get().getClientId(), new ISQLStatement[] { new // 
    SQLStatement(// 
    IDataServer.META_DATA_QUERY, // 
    table.getServerName(), // 
    table.getName(), // 
    null, // delete entire table
    new QueryDelete(new QueryTable(table.getSQLName(), table.getDataSource(), table.getCatalog(), table.getSchema()))) });
    // insert the data
    ApplicationServerRegistry.get().getDataServer().insertDataSet(ApplicationServerRegistry.get().getClientId(), dataSet, table.getDataSource(), table.getServerName(), table.getName(), null, null, null, null);
    return dataSet.getRowCount();
}
Also used : QueryDelete(com.servoy.j2db.query.QueryDelete) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QueryTable(com.servoy.j2db.query.QueryTable)

Example 39 with RepositoryException

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

the class FoundSetManager method getTable.

@SuppressWarnings("nls")
public ITable getTable(String dataSource) throws RepositoryException {
    if (dataSource == null) {
        return null;
    }
    if (application.getSolution() == null) {
        if (Debug.tracing()) {
            Debug.trace("Trying to get a table for a datasource: " + dataSource + " on an already closed solution", new RuntimeException());
        }
        return null;
    }
    ITable table = dataSource.startsWith(DataSourceUtils.VIEW_DATASOURCE_SCHEME_COLON) ? viewDataSources.get(dataSource) : inMemDataSources.get(dataSource);
    if (table == null) {
        // when it is a db:/server/table data source
        String[] servernameTablename = DataSourceUtilsBase.getDBServernameTablename(dataSource);
        if (servernameTablename != null && servernameTablename[0] != null) {
            try {
                IServer server = application.getSolution().getServer(servernameTablename[0]);
                if (server == null) {
                    // $NON-NLS-1$
                    throw new RepositoryException(Messages.getString("servoy.exception.serverNotFound", new Object[] { servernameTablename[0] }));
                }
                table = server.getTable(servernameTablename[1]);
            } catch (RemoteException e) {
                throw new RepositoryException(e);
            }
        } else if (getDataSourceServerName(dataSource) == IServer.INMEM_SERVER) {
            if (!inMemDataSources.containsKey(dataSource) && dataSourceExists(dataSource)) {
                try {
                    insertToDataSource(DataSourceUtils.getDataSourceTableName(dataSource), new BufferedDataSet(), null, null, true, false, IServer.INMEM_SERVER);
                } catch (Exception e) {
                    Debug.error(e);
                }
            }
            return inMemDataSources.get(dataSource);
        } else if (getDataSourceServerName(dataSource) == IServer.VIEW_SERVER) {
            Optional<ServoyJSONObject> columnDefintion;
            if (!viewDataSources.containsKey(dataSource) && (columnDefintion = getColumnDefintion(dataSource)).isPresent()) {
                Table tbl = new Table(IServer.VIEW_SERVER, DataSourceUtils.getViewDataSourceName(dataSource), true, ITable.VIEW, null, null);
                tbl.setDataSource(dataSource);
                DatabaseUtils.deserializeInMemoryTable(application.getFlattenedSolution().getPersistFactory(), tbl, columnDefintion.get());
                tbl.setExistInDB(true);
                tbl.setInitialized(true);
                viewDataSources.put(dataSource, tbl);
                try {
                    executeFoundsetTriggerReturnFirst(tbl, new Object[] { DataSourceUtils.getViewDataSourceName(dataSource) }, StaticContentSpecLoader.PROPERTY_ONFOUNDSETLOADMETHODID, false, // can't entity methods, not supported on view foundsets
                    null);
                } catch (ServoyException e) {
                    Debug.error("Error executing foundset method for datasource:  " + dataSource, e);
                }
            }
            return viewDataSources.get(dataSource);
        }
    }
    return table;
}
Also used : IServer(com.servoy.j2db.persistence.IServer) BaseQueryTable(com.servoy.base.query.BaseQueryTable) Table(com.servoy.j2db.persistence.Table) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) RepositoryException(com.servoy.j2db.persistence.RepositoryException) 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) ServoyException(com.servoy.j2db.util.ServoyException) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) ITable(com.servoy.j2db.persistence.ITable) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) RemoteException(java.rmi.RemoteException)

Example 40 with RepositoryException

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

the class JSDatabaseManager method js_getSQLParameters.

/**
 * Returns the internal SQL parameters, as an array, that are used to define the specified (related)foundset.
 * When the founset is in find mode, the arguments for the find conditions are included in the result.
 *
 * @sample var sqlParameterArray = databaseManager.getSQLParameters(foundset,false)
 *
 * @param foundsetOrQBSelect The JSFoundset or QBSelect to get the sql parameters for.
 * @param includeFilters include the parameters for the filters.
 *
 * @return An Array with the sql parameter values.
 */
public Object[] js_getSQLParameters(Object foundsetOrQBSelect, boolean includeFilters) throws ServoyException {
    checkAuthorized();
    if (foundsetOrQBSelect instanceof IFoundSetInternal && ((IFoundSetInternal) foundsetOrQBSelect).getTable() != null) {
        try {
            // TODO parameters from updates and cleanups
            QuerySet querySet = getQuerySet(((IFoundSetInternal) foundsetOrQBSelect).getCurrentStateQuery(true, false), includeFilters);
            Object[][] qsParams = querySet.getSelect().getParameters();
            if (qsParams == null || qsParams.length == 0) {
                return null;
            }
            return qsParams[0];
        } catch (Exception e) {
            Debug.error(e);
        }
    } else if (foundsetOrQBSelect instanceof QBSelect) {
        try {
            QuerySelect select = ((QBSelect) foundsetOrQBSelect).build();
            if (select.getColumns() == null) {
                // no columns, add pk
                // note that QBSelect.build() already returns a clone
                ITable table = application.getFoundSetManager().getTable(select.getTable().getDataSource());
                Iterator<Column> pkIt = ((Table) table).getRowIdentColumns().iterator();
                if (!pkIt.hasNext()) {
                    throw new RepositoryException(ServoyException.InternalCodes.PRIMARY_KEY_NOT_FOUND, new Object[] { table.getName() });
                }
                while (pkIt.hasNext()) {
                    Column c = pkIt.next();
                    select.addColumn(c.queryColumn(select.getTable()));
                }
            }
            QuerySet querySet = getQuerySet(select, includeFilters);
            Object[][] qsParams = querySet.getSelect().getParameters();
            if (qsParams == null || qsParams.length == 0) {
                return null;
            }
            return qsParams[0];
        } catch (RemoteException e) {
            Debug.error(e);
        }
    }
    return null;
}
Also used : BaseQueryTable(com.servoy.base.query.BaseQueryTable) QueryTable(com.servoy.j2db.query.QueryTable) ITable(com.servoy.j2db.persistence.ITable) Table(com.servoy.j2db.persistence.Table) QuerySet(com.servoy.j2db.persistence.QuerySet) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QuerySelect(com.servoy.j2db.query.QuerySelect) ApplicationException(com.servoy.j2db.ApplicationException) RemoteException(java.rmi.RemoteException) SQLException(java.sql.SQLException) ServoyException(com.servoy.j2db.util.ServoyException) RepositoryException(com.servoy.j2db.persistence.RepositoryException) QBSelect(com.servoy.j2db.querybuilder.impl.QBSelect) QueryColumn(com.servoy.j2db.query.QueryColumn) IBaseColumn(com.servoy.base.persistence.IBaseColumn) Column(com.servoy.j2db.persistence.Column) QBColumn(com.servoy.j2db.querybuilder.impl.QBColumn) Iterator(java.util.Iterator) ITable(com.servoy.j2db.persistence.ITable) NativeObject(org.mozilla.javascript.NativeObject) RemoteException(java.rmi.RemoteException)

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