Search in sources :

Example 6 with TableNode

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

the class ScriptEngine method compileFunction.

@SuppressWarnings("nls")
public Function compileFunction(IScriptProvider sp, Scriptable scope) throws Exception {
    Context cx = Context.enter();
    int iOp = cx.getOptimizationLevel();
    String sourceName = sp.getDataProviderID();
    if (sp.getScopeName() != null) {
        Solution sol = (Solution) sp.getAncestor(IRepository.SOLUTIONS);
        sourceName = sol.getName() + "/scopes/" + sp.getScopeName() + '/' + sourceName;
    } else if (sp.getParent() instanceof Form) {
        Solution sol = (Solution) sp.getAncestor(IRepository.SOLUTIONS);
        sourceName = sol.getName() + "/forms/" + ((Form) sp.getParent()).getName() + '/' + sourceName;
    } else if (sp.getParent() instanceof TableNode) {
        Solution sol = (Solution) sp.getAncestor(IRepository.SOLUTIONS);
        sourceName = sol.getName() + '/' + ((TableNode) sp.getParent()).getDataSource() + '/' + sourceName;
        if (sp instanceof ScriptCalculation) {
            sourceName = sourceName.replace("db:", "calculations");
        } else {
            sourceName = sourceName.replace("db:", "entities");
        }
    }
    try {
        if (// flag should only be used in rich client
        Utils.getAsBoolean(System.getProperty(SERVOY_DISABLE_SCRIPT_COMPILE_PROPERTY, "false"))) {
            cx.setOptimizationLevel(-1);
        } else {
            cx.setOptimizationLevel(9);
        }
        cx.setGeneratingSource(Boolean.getBoolean("servoy.generateJavascriptSource"));
        return compileScriptProvider(sp, scope, cx, sourceName);
    } catch (Exception e) {
        Debug.error("Compilation failed for method: " + sourceName);
        throw e;
    } finally {
        cx.setOptimizationLevel(iOp);
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) ScriptCalculation(com.servoy.j2db.persistence.ScriptCalculation) Form(com.servoy.j2db.persistence.Form) TableNode(com.servoy.j2db.persistence.TableNode) Solution(com.servoy.j2db.persistence.Solution) ApplicationException(com.servoy.j2db.ApplicationException) ExitScriptException(com.servoy.j2db.ExitScriptException) DataException(com.servoy.j2db.dataprocessing.DataException) ServoyException(com.servoy.j2db.util.ServoyException) JavaScriptException(org.mozilla.javascript.JavaScriptException) RepositoryException(com.servoy.j2db.persistence.RepositoryException)

Example 7 with TableNode

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

the class FoundSet method getPrototype.

public Scriptable getPrototype() {
    if (prototypeScope == null) {
        LazyCompilationScope scope = new LazyCompilationScope(this, fsm.getApplication().getScriptEngine(), new ISupportScriptProviders() {

            public Iterator<? extends IScriptProvider> getScriptMethods(boolean sort) {
                List<ScriptMethod> methods = null;
                Iterator<TableNode> tableNodes = fsm.getApplication().getFlattenedSolution().getTableNodes(getTable());
                while (tableNodes.hasNext()) {
                    TableNode tn = tableNodes.next();
                    Iterator<ScriptMethod> fsMethods = tn.getFoundsetMethods(sort);
                    if (methods == null) {
                        if (!tableNodes.hasNext()) {
                            // just 1
                            return fsMethods;
                        }
                        methods = new ArrayList<ScriptMethod>();
                    }
                    while (fsMethods.hasNext()) {
                        methods.add(fsMethods.next());
                    }
                }
                return methods == null ? Collections.<ScriptMethod>emptyList().iterator() : methods.iterator();
            }

            public Iterator<ScriptVariable> getScriptVariables(boolean b) {
                return Collections.<ScriptVariable>emptyList().iterator();
            }

            public ScriptMethod getScriptMethod(int methodId) {
                // not called by LCS
                return null;
            }
        }) {

            @Override
            public String getClassName() {
                // $NON-NLS-1$
                return "FoundSetScope";
            }

            @Override
            public String getScopeName() {
                return getDataSource();
            }
        };
        // make sure functions like getSize cannot be overridden
        scope.setFunctionParentScriptable(this);
        prototypeScope = scope;
    }
    return prototypeScope;
}
Also used : ISupportScriptProviders(com.servoy.j2db.persistence.ISupportScriptProviders) IScriptProvider(com.servoy.j2db.persistence.IScriptProvider) Iterator(java.util.Iterator) TableNode(com.servoy.j2db.persistence.TableNode) ArrayList(java.util.ArrayList) SafeArrayList(com.servoy.j2db.util.SafeArrayList) ScriptVariable(com.servoy.j2db.persistence.ScriptVariable) LazyCompilationScope(com.servoy.j2db.scripting.LazyCompilationScope) Arrays.asList(java.util.Arrays.asList) ArrayList(java.util.ArrayList) List(java.util.List) SafeArrayList(com.servoy.j2db.util.SafeArrayList) Collectors.toList(java.util.stream.Collectors.toList) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod)

Example 8 with TableNode

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

the class FoundSetManager method insertToDataSource.

public Object[] insertToDataSource(String name, IDataSet dataSet, ColumnType[] columnTypes, WrappedObjectReference<String[]> pkNames, boolean create, boolean skipOnLoad, String server) throws ServoyException {
    if (name == null) {
        return null;
    }
    WrappedObjectReference<String[]> actualPkNames = pkNames;
    if (actualPkNames == null)
        actualPkNames = new WrappedObjectReference<String[]>(null);
    String dataSource = IServer.VIEW_SERVER.equals(server) ? DataSourceUtils.createViewDataSource(name) : DataSourceUtils.createInmemDataSource(name);
    // initial dataset to use, but can also be set later to a 0 row dataset that is created to match columnNames and columnTypes with an in-mem
    // table definition, if that is available and columns do not match with the initial dataset
    IDataSet fixedDataSet = dataSet;
    List<ColumnType> fixedColumnTypes;
    if (columnTypes == null) {
        ColumnType[] dataSetTypes = BufferedDataSetInternal.getColumnTypeInfo(dataSet);
        fixedColumnTypes = dataSetTypes == null ? null : asList(dataSetTypes);
    } else {
        fixedColumnTypes = asList(columnTypes);
    }
    // get column def from the first in-mem datasource found
    ServoyJSONObject columnsDef = null;
    Iterator<TableNode> tblIte = application.getFlattenedSolution().getTableNodes(dataSource);
    int onLoadMethodId = -1;
    while (tblIte.hasNext()) {
        TableNode tn = tblIte.next();
        if (columnsDef == null)
            columnsDef = tn.getColumns();
        if (onLoadMethodId == -1)
            onLoadMethodId = tn.getOnFoundSetLoadMethodID();
    }
    HashMap<String, ColumnInfoDef> columnInfoDefinitions = null;
    Set<Integer> columnsThatNeedToStringSerialize = null;
    if (columnsDef == null) {
        // if we have array columns, convert values using StringSerializer
        if (containsArrayType(fixedColumnTypes)) {
            columnsThatNeedToStringSerialize = new HashSet<>();
            for (int i = 0; i < fixedColumnTypes.size(); i++) {
                ColumnType columnType = fixedColumnTypes.get(i);
                if (columnType.getSqlType() == Types.ARRAY) {
                    fixedColumnTypes.set(i, ColumnType.getColumnType(IColumnTypes.TEXT));
                    columnsThatNeedToStringSerialize.add(Integer.valueOf(i));
                }
            }
        }
    } else {
        TableDef tableInfo = DatabaseUtils.deserializeTableInfo(columnsDef);
        // column names that are not SEQUENCE_AUTO_ENTER/DATABASE_IDENTITY from table node (columnsDef)
        List<String> inmemColumnNamesThatCanSetData = new ArrayList<>();
        // column types of columns that are not SEQUENCE_AUTO_ENTER/DATABASE_IDENTITY from table node (columnsDef)
        List<ColumnType> inmemColumnTypesForColumnsThatCanSetData = new ArrayList<>();
        // ALL column defs from design time table node (columnsDef)
        columnInfoDefinitions = new HashMap<String, ColumnInfoDef>();
        // pk/rowid column names from design time table node (columnsDef)
        List<String> inmemPKs = new ArrayList<>();
        for (int j = 0; j < tableInfo.columnInfoDefSet.size(); j++) {
            ColumnInfoDef cid = tableInfo.columnInfoDefSet.get(j);
            if (cid.autoEnterType != ColumnInfo.SEQUENCE_AUTO_ENTER || cid.autoEnterSubType != ColumnInfo.DATABASE_IDENTITY) {
                // we only support auto-enter for in-mem tables based on dbident (that is then handled by hsql)
                // that is why we only check for that here; for example, if one would define at design time a
                // uuid generator pk column on an in-mem table, that would not work; it would try to insert null into a non-nullable column
                inmemColumnNamesThatCanSetData.add(cid.name);
                inmemColumnTypesForColumnsThatCanSetData.add(cid.columnType);
            }
            if ((cid.flags & IBaseColumn.IDENT_COLUMNS) != 0) {
                inmemPKs.add(cid.name);
            }
            columnInfoDefinitions.put(cid.name, cid);
            // apply stringserializer on designed datasources
            if (JSONSerializerWrapper.STRING_SERIALIZER_NAME.equals(cid.converterName)) {
                if (columnsThatNeedToStringSerialize == null) {
                    columnsThatNeedToStringSerialize = new HashSet<>();
                }
                columnsThatNeedToStringSerialize.add(Integer.valueOf(j));
            }
        }
        if (actualPkNames.o == null && inmemPKs.size() > 0) {
            actualPkNames.o = inmemPKs.toArray(new String[inmemPKs.size()]);
        }
        if (!asList(dataSet.getColumnNames()).equals(inmemColumnNamesThatCanSetData) || !compareColumnTypes(fixedColumnTypes, inmemColumnTypesForColumnsThatCanSetData)) {
            if (dataSet.getColumnCount() > 0 && /*
													 * do not generate warning if this is just the initial load of a design time inmem table that adds 0 rows
													 * and doesn't care about columns
													 */
            !asList(dataSet.getColumnNames()).equals(inmemColumnNamesThatCanSetData)) {
                Debug.warn("Dataset column names definition does not match inmem table definition for datasource : " + dataSource + " columns of dataset: " + Arrays.toString(dataSet.getColumnNames()) + ", columns of in mem definition: " + inmemColumnNamesThatCanSetData);
            }
            if (fixedColumnTypes != null && !compareColumnTypes(fixedColumnTypes, inmemColumnTypesForColumnsThatCanSetData)) {
                Debug.warn("Dataset column types definition does not match inmem table definition for datasource : " + dataSource + " types of dataset: " + fixedColumnTypes + ", types of in mem definition: " + inmemColumnTypesForColumnsThatCanSetData);
            }
            fixedColumnTypes = inmemColumnTypesForColumnsThatCanSetData;
            fixedDataSet = BufferedDataSetInternal.createBufferedDataSet(inmemColumnNamesThatCanSetData.toArray(new String[inmemColumnNamesThatCanSetData.size()]), fixedColumnTypes.toArray(new ColumnType[fixedColumnTypes.size()]), new ArrayList<Object[]>(), false);
        }
    }
    // - in the else branch above (already defined at design time), columns that are not auto sequences or dbidents; see inmemColumnNames/inmemColumnTypes(which is at this point the same as fixedColumnTypes)
    if (fixedColumnTypes != null && dataSet.getRowCount() > 0 && dataSet.getRow(0).length != fixedColumnTypes.size()) {
        // $NON-NLS-1$
        throw new RepositoryException("Data set rows do not match column count");
    }
    if (columnsThatNeedToStringSerialize != null) {
        replaceValuesWithSerializedString(dataSet, columnsThatNeedToStringSerialize);
    }
    try {
        ITable table = IServer.VIEW_SERVER.equals(server) ? viewDataSources.get(dataSource) : inMemDataSources.get(dataSource);
        if (table == null && !create) {
            throw new RepositoryException("Appending to non-existing datasource: " + dataSource);
        }
        GlobalTransaction gt = getGlobalTransaction();
        String tid = null;
        String serverName = server == null ? (table == null ? IServer.INMEM_SERVER : table.getServerName()) : server;
        if (gt != null) {
            tid = gt.getTransactionID(serverName);
        }
        if (create && table != null) {
            // temp table was used before, delete all data in it
            FoundSet foundSet = (FoundSet) getSharedFoundSet(dataSource);
            foundSet.removeLastFound();
            try {
                QueryDelete delete = new QueryDelete(new QueryTable(table.getSQLName(), table.getDataSource(), table.getCatalog(), table.getSchema(), true));
                SQLStatement deleteStatement = new SQLStatement(ISQLActionTypes.DELETE_ACTION, table.getServerName(), table.getName(), null, tid, delete, null);
                application.getDataServer().performUpdates(application.getClientID(), new ISQLStatement[] { deleteStatement });
            } catch (Exception e) {
                Debug.log(e);
                table = null;
            }
            RowManager element = rowManagers.get(dataSource);
            if (element != null) {
                element.flushAllCachedRows();
            }
        }
        InsertResult insertResult = application.getDataServer().insertDataSet(application.getClientID(), fixedDataSet, dataSource, table == null ? IServer.INMEM_SERVER : table.getServerName(), table == null ? null : table.getName(), /* create temp table when null */
        tid, fixedColumnTypes == null ? null : fixedColumnTypes.toArray(new ColumnType[fixedColumnTypes.size()]), /* inferred from dataset when null */
        actualPkNames.o, columnInfoDefinitions);
        if (insertResult != null) {
            table = insertResult.getTable();
            // do we want to fix that somehow or the caller should just make sure it calls it with the correct column order?
            if (dataSet != fixedDataSet && dataSet.getRowCount() > 0) {
                insertResult = application.getDataServer().insertDataSet(application.getClientID(), dataSet, dataSource, table.getServerName(), table.getName(), tid, columnTypes, /* will be inferred by called method from dataset if null */
                actualPkNames.o, columnInfoDefinitions);
            }
            if (IServer.INMEM_SERVER.equals(serverName)) {
                inMemDataSources.put(dataSource, table);
            } else {
                viewDataSources.put(dataSource, table);
            }
            fireTableEvent(table);
            if (!skipOnLoad && dataSet.getRowCount() == 0 && onLoadMethodId > 0) {
                IFoundSetInternal sharedFoundSet = getSharedFoundSet(dataSource);
                executeFoundsetTriggerReturnFirst(sharedFoundSet.getTable(), new Object[] { DataSourceUtils.getInmemDataSourceName(dataSource) }, StaticContentSpecLoader.PROPERTY_ONFOUNDSETLOADMETHODID, false, (Scriptable) sharedFoundSet);
            }
            if (create) {
                // only refresh when it is a new full load, when adding data to an existing table, it is only applicable to the (shared) foundset
                refreshFoundSetsFromDB(dataSource, null, false);
            }
            return insertResult.getGeneratedPks();
        }
    } catch (RemoteException e) {
        throw new RepositoryException(e);
    }
    return null;
}
Also used : ColumnType(com.servoy.j2db.query.ColumnType) BaseColumnType(com.servoy.base.query.BaseColumnType) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) TableDef(com.servoy.j2db.util.xmlxport.TableDef) ColumnInfoDef(com.servoy.j2db.util.xmlxport.ColumnInfoDef) ITable(com.servoy.j2db.persistence.ITable) WrappedObjectReference(com.servoy.j2db.util.WrappedObjectReference) InsertResult(com.servoy.j2db.dataprocessing.IDataServer.InsertResult) QueryDelete(com.servoy.j2db.query.QueryDelete) RepositoryException(com.servoy.j2db.persistence.RepositoryException) 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) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) TableNode(com.servoy.j2db.persistence.TableNode) ServoyJSONObject(com.servoy.j2db.util.ServoyJSONObject) RemoteException(java.rmi.RemoteException)

Example 9 with TableNode

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

the class JSForm method getEventHandler.

public static <T extends AbstractBase> JSMethod getEventHandler(IApplication application, T persist, int methodid, IJSParent<?> parent, String propertyName) {
    if (methodid > 0) {
        IJSScriptParent<?> scriptParent = null;
        ScriptMethod scriptMethod = null;
        if (parent instanceof JSForm) {
            // form method
            scriptMethod = ((JSForm) parent).getSupportChild().getScriptMethod(methodid);
            if (scriptMethod == null) {
                Form f = ((JSForm) parent).getSupportChild();
                while (f != null && f.getExtendsID() > 0 && scriptMethod == null) {
                    f = application.getFlattenedSolution().getForm(f.getExtendsID());
                    if (f != null)
                        scriptMethod = f.getScriptMethod(methodid);
                }
                if (scriptMethod != null) {
                    scriptParent = application.getScriptEngine().getSolutionModifier().instantiateForm(f, false);
                }
            }
        }
        if (scriptMethod == null) {
            // foundset method
            if (parent instanceof JSDataSourceNode) {
                scriptMethod = ((JSDataSourceNode) parent).getSupportChild().getFoundsetMethod(methodid);
            } else if (parent instanceof JSForm && ((JSForm) parent).getForm().getDataSource() != null) {
                Iterator<ScriptMethod> foundsetMethods = application.getFlattenedSolution().getFoundsetMethods(((JSForm) parent).getForm().getDataSource(), false);
                scriptMethod = AbstractBase.selectById(foundsetMethods, methodid);
                if (scriptMethod != null) {
                    scriptParent = new JSDataSourceNode(application, ((JSForm) parent).getForm().getDataSource());
                }
            }
        }
        if (scriptMethod == null) {
            // global method
            scriptMethod = application.getFlattenedSolution().getScriptMethod(methodid);
        }
        if (scriptMethod != null) {
            if (scriptParent == null) {
                if (scriptMethod.getParent() instanceof TableNode && parent instanceof JSDataSourceNode) {
                    scriptParent = (JSDataSourceNode) parent;
                } else if (scriptMethod.getParent() instanceof Solution) {
                    // global
                    scriptParent = null;
                } else {
                    // form method
                    scriptParent = getJSFormParent(parent);
                }
            }
            List<Object> arguments = persist.getFlattenedMethodArguments(propertyName);
            if (arguments == null || arguments.size() == 0) {
                return new JSMethod(scriptParent, scriptMethod, application, false);
            } else {
                return new JSMethodWithArguments(application, scriptParent, scriptMethod, false, arguments.toArray());
            }
        }
    } else if (methodid == 0 && BaseComponent.isCommandProperty(propertyName)) {
        return (JSMethod) ISMDefaults.COMMAND_DEFAULT;
    }
    return null;
}
Also used : Form(com.servoy.j2db.persistence.Form) ISMForm(com.servoy.j2db.solutionmodel.ISMForm) IMobileSMForm(com.servoy.base.solutionmodel.mobile.IMobileSMForm) Iterator(java.util.Iterator) TableNode(com.servoy.j2db.persistence.TableNode) IConstantsObject(com.servoy.j2db.scripting.IConstantsObject) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod) FlattenedSolution(com.servoy.j2db.FlattenedSolution) Solution(com.servoy.j2db.persistence.Solution)

Example 10 with TableNode

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

the class JSForm method getEventHandler.

public static <T extends AbstractBase> JSMethod getEventHandler(IApplication application, T persist, String uuidOrName, IJSParent<?> parent, String propertyName) {
    if (uuidOrName != null) {
        IJSScriptParent<?> scriptParent = null;
        ScriptMethod scriptMethod = application.getFlattenedSolution().getScriptMethod(uuidOrName);
        ;
        if (scriptMethod != null) {
            if (scriptMethod.getParent() instanceof TableNode && parent instanceof JSDataSourceNode) {
                scriptParent = (JSDataSourceNode) parent;
            } else if (scriptMethod.getParent() instanceof Solution) {
                // global
                scriptParent = null;
            } else {
                // form method
                scriptParent = getJSFormParent(parent);
                if (scriptMethod.getParent() != scriptParent.getSupportChild() && scriptParent.getSupportChild() instanceof Form) {
                    scriptParent = application.getScriptEngine().getSolutionModifier().instantiateForm((Form) scriptParent.getSupportChild(), false);
                }
            }
            List<Object> arguments = persist.getFlattenedMethodArguments(propertyName);
            if (arguments == null || arguments.size() == 0) {
                return new JSMethod(scriptParent, scriptMethod, application, false);
            } else {
                return new JSMethodWithArguments(application, scriptParent, scriptMethod, false, arguments.toArray());
            }
        }
    }
    return null;
}
Also used : Form(com.servoy.j2db.persistence.Form) ISMForm(com.servoy.j2db.solutionmodel.ISMForm) IMobileSMForm(com.servoy.base.solutionmodel.mobile.IMobileSMForm) TableNode(com.servoy.j2db.persistence.TableNode) IConstantsObject(com.servoy.j2db.scripting.IConstantsObject) ScriptMethod(com.servoy.j2db.persistence.ScriptMethod) FlattenedSolution(com.servoy.j2db.FlattenedSolution) Solution(com.servoy.j2db.persistence.Solution)

Aggregations

TableNode (com.servoy.j2db.persistence.TableNode)20 RepositoryException (com.servoy.j2db.persistence.RepositoryException)9 ScriptMethod (com.servoy.j2db.persistence.ScriptMethod)9 FlattenedSolution (com.servoy.j2db.FlattenedSolution)8 ScriptCalculation (com.servoy.j2db.persistence.ScriptCalculation)6 Solution (com.servoy.j2db.persistence.Solution)6 Form (com.servoy.j2db.persistence.Form)5 BaseColumnType (com.servoy.base.query.BaseColumnType)4 IPersist (com.servoy.j2db.persistence.IPersist)4 ServoyException (com.servoy.j2db.util.ServoyException)4 ServoyJSONObject (com.servoy.j2db.util.ServoyJSONObject)4 ColumnInfoDef (com.servoy.j2db.util.xmlxport.ColumnInfoDef)4 TableDef (com.servoy.j2db.util.xmlxport.TableDef)4 ArrayList (java.util.ArrayList)4 ApplicationException (com.servoy.j2db.ApplicationException)3 FoundSetManager (com.servoy.j2db.dataprocessing.FoundSetManager)3 ITable (com.servoy.j2db.persistence.ITable)3 JavaScriptException (org.mozilla.javascript.JavaScriptException)3 JSFunction (org.mozilla.javascript.annotations.JSFunction)3 BaseQueryTable (com.servoy.base.query.BaseQueryTable)2