Using ActiveGrid APIs

Using ActiveGrid APIs
This appendix documents ActiveGrid APIs that are available for your use:
API to the Data Layer: The DataService Class
The API to the data layer is comprised of one principle class, DataService, that you can use to get and manipulate data. Deleting objects, inserting new objects, or retrieving additional objects requires use of the DataService APIs directly.
A DataService instance is available through the function getDataService() in the activegrid.runtime module. Modifications to data objects defined by a schema will be persisted transparently when the transaction in which they are being changed is committed.
The DataService APIs can be accessed:
DataService Properties
The following properties or attributes are present on a DataService instance:
 
Read/write property controlling whether references to attributes of data objects will be resolved by fetching the data from the data source. If lazyLoading is True data is fetched as referenced. If lazyLoading if False references to non-existent data will produce a DataServiceUnselectedAttributeException exception.
Read/write property to describe what type of transactions are run. Currently the only value supported is TX_OPTIMISTIC_VERIFY_ALL. The transactionType cannot be set if a transaction is currently in progress.
Read only property describing the current transactional state. It will either have a value of TX_NONE indicating no transaction is in progress, or the value of the transactionType property.
A reference to the DataServiceMgr instance controlling this DataService instance.
A reference to the DataSourceMgr instance providing data for this DataService instance.
A reference to the SchemaMgr instance managing the Schema instances describing the data accessible by this DataService instance.
DataService Methods for Data Manipulation
The DataService methods defined in this section are useful for manipulating data. The APIs for these operations are: deleteObjects, insertObjects, and getObjects respectively. Normally these will be the only DataService APIs you should use in a method implementing a stateful service operation; however all the DataService APIs are documented here for completeness.
Note that the DataService instance is acquired using the getDataService method, defined in the activegrid.runtime module.
The following table defines the parameters used by the DataService methods in this section.
 
The limit parameter is an integer specifying the maximum number of objects which should be returned. For example “offset=10, limit=5” will return rows 11 through 16.
The offset parameter is an integer specifying the number of result set objects which should be skipped.
The options parameter can be any combination of (i.e. these values may be bitwise OR’d together):
QUERY_OPT_NO_JOIN to prevent the query processor from using joins to process 1-1 associations
QUERY_OPT_NO_OUTER_JOIN to prevent the query processor from using outer joins to process optional associations
The orderings parameter is an XPath expression or list of XPath expressions naming the attributes on which the result set should be ordered. By default the ordering is ascending. Optionally the keyword “descending” or “desc” can follow the XPath expression.
primaryRef Parameter
The primaryRef parameter is the name of a complex type or a reference to a complex type object (as returned by getComplexType, for example). The objects returned will be of this type.
The qualifications parameter is an XPath expression or list of XPath expressions describing which objects should be returned. In database terms this expresses the selection. Placeholders may be present in these expressions. Values from the values parameter will be substituted for any placeholders. The syntax for placeholders in PHP is “:pN”, where N > 0 (e.g. :p1, :p2, :p3, etc.) The syntax for placeholders in Python is:
The refs parameter is an XPath expression or list of XPath expressions describing what attributes and relationships in the result object should be populated with data. In database terms this expresses the projection.
The values parameter is a scalar value or list of scalar values that provide the values for any placeholders specified in the qualifications.
getObjects
getObjects(primaryRef, refs, qualifications=None, values=None, orderings=None, offset=0, limit=None, options=None)
Returns a list of objects from the database. If a transactional object context exists, any objects in it that have the same id will be used in preference to the objects selected. If the selected object has more data it will either be “glued in” or an exception is raised depending on concurrency mode. All objects returned are saved in the transactional object context if it exists.
Example:
getObjects("product", ["name", "category_ref/descn], "category_ref[name=%s]", "Fish", "name desc", 0, 5)
This will return product objects with the name attribute populated and the category_ref relationship populated with category objects. These category objects will have their descn attribute populated. It will only return “Fish” products”. It will be sorted last name first. Only the first 5 matches will be returned – but since we’re ordering by name descending it will actually be the last 5.
getObject
getObject(primaryRef, refs, qualifications=None, values=None, orderings=None, offset=0, limit=None, options=None)
Like getObjects but returns only a single object. Raises an exception if the query returns more than one object.
getObjectsByExample
getObjects(object, refs, qualifications=None, values=None, orderings=None, offset=0, limit=None, options=None, expressionRefs=None)
Similar to getObjects. Gets a list of objects from the database when the qualification (the database selection) is not known at application design time. Results match the type of the object instance passed in as the first parameter. Qualifications are built from the object attributes, if they are set. Additional qualifications may be passed using the qualifications parameter (this can be used to restrict the results returned). The expressionRefs parameter is a list of XPath expressions that identifies which attributes of the object parameter should be treated as expressions (rather than just as values).
getObjectsByExample is typically used in a SearchAction, where the object instance (the first parameter) is populated with search criteria by the SearchPage.
Example 1:
qbe = dataService.newObject("Product", search=True)
qbe.category_ref = dataService.newObject("Category", search=True)
qbe.category_ref.name = "Fish"
getObjectsByExample(qbe)
Returns all products that have a category with name “Fish”.
Example 2:
qbe = dataService.newObject("Product", search=True)
qbe.name = “like %fish and not like gold%”
getObjectsByExample(qbe, expressionRefs=”name”)
Returns all products that have a name ending with “fish” and not starting with “gold”. Note that expression handling has to be enabled explicitly for the name attribute, using the expressionRefs parameter.
Search Modification Example:
When the user searches for a product with some name, “some-name”, we want the search to use the following expression:
“name like %some-name%”
We don’t want the user to have to explicitly type the expression “like %some-name%” into the search form, so we use the “Field Value Override” in the Page Layout to add information to the user input. To see how this works, follow these steps:
1.
2.
3.
From the File Menu select the New... option. The New dialog appears. Leave the New Project button selected and, under Type select From a Data Source.
4.
Click OK. The Choose a Data Source screen appears.
5.
Choose the petstore-SQLite data source and click Next. The Choose Tables screen appears.
6.
Click the Deselect All button and then check only the Product check box.
7.
Name the project whatever you like and accept all defaults. Click Finish. TheActiveGrid Studio generates the application.
8.
Open the ProductSearchPage, double-click on the Text Input that has “name” as MessageRef. In Field Value Override, add:
“like %${input}%”
9.
10.
Open the Page Flow (.bpel) file and open the ProductSearch Action in the Custom Action Editor (Customize Action...). Open the variable Set and add “name” to the end of the getObjectsByExample call:
dataservice:getObjectsByExample(message/product, "*", "", 50, "name")
This allows expressions for the name attribute. Run the application. Searching on product name will now use “like %<name>%”.
loadAttributes
loadAttributes(objects, refs)
Ensures that all attributes specified are present in each object in the list "objects". If necessary it will run the minimum number of queries to populate the object graph as required by the refs parameter. This will usually be one but can be more if the refs parameter specifies any to-many type relationships. If all the attributes specified by the refs parameter are already present no queries are run. This allows you to do lazy loading the “smart” way.
newObject
newObject(complexTypeName, search=False)
Creates and returns a new instance of an object of the specified type with default values filled in. Populated it with data and then call insertObjects should be called. Finally, write it to the database with a commit or synchronizeObjects. If the search parameter is set to True, returns a new object instance to be used as “query” object with getObjectsByExample.
insertObject
insertObjects(objects)
Mark the objects for insert into the data source. The object is inserted into the data source when commit or synchronizeObjects is called.
deleteObjects
deleteObjects(objects)
Mark the object as deleted. The object is deleted from the database when commit or synchronizeObjects is called.
registerObjects
resgisterObjects(objects)
Add the objects to the DataService’s list of managed objects. Works only if the objects were created using SchemaManager.newObject. The objects must match the underlying data in the database. After registerObjects has been called, the objects are transparently persisted, and handled by the DataService, like any other DataService managed objects.
To access the SchemaManager, use : runtime.getDataService().schemaMgr.
synchronizeObjects
synchronizeObjects(objects, clear=False, sessionData=False, failFast=False)
Changes to the objects (insert, update, or delete) are immediately written to the database. This does not end or abort a transactional object context if one exists. synchronizeObjects is primary intended to persist changes outside of a transactional object context (in fact outside a transactional object context, this is the only way to persist the changes made to objects).
You can also use synchronizeObjects to immediately update selected objects within a transactional object context.
The objects parameter holds a list of objects which should be synchronized with the data source.
Normally the objects synchronized are refreshed so that they look like they are unmodified and newly fetched from the data source. If the clear parameter is set to True they are cleared of state.
Normally objects from the session schema are saved. If sessionData is False objects from the session schema are excluded.
Normally an attempt is made to store all objects even if no rows are modified for some objects. If failFast is True then a DataServiceConcurrencyException is thrown the first time the row count is 0 on an update.
The return value is a list of integers as long as the list of objects indicating how many rows in the database were affected for each object. A value of -1 indicates that no updates where required for that object. A value of 0 indicates that updates where required and attempted but did not succeed usually do to a concurrency check failure.
Other Data Layer APIs
getComplexType
getComplexType(complexTypeName)
Convenience method to get a complex type from the schemas associated with the DataService. Equivalent to:
DataService.schemaMgr.getComplexType(complexTypeName)
getDDL
getDDL(complexTypeNames, reorderForDependencies=True)
Return a list of DDL statements (i.e. "CREATE TABLE foo ...") for all complex types named by the complexTypeNames parameter. If the reorderForDependencies parameter is true the DDL statements are reordered so that dependee tables are created before their dependent tables.
getEvolutionDDL
getEvolutionDDL(sourceSchema, targetSchema, excludes=None)
Returns a list of DDL statements necessary to make the source schema like the target schema. This may include create table, drop table, add column, or drop column statements. The excludes parameter holds a list of complex type names to ignore.
createTables
createTables(complexTypeNames)
Runs the statements returned by getDDL to create the tables in the database.
getSchema
getSchema(tableNames, schemaOptions=None)
Returns a schema containing complexTypes describing each table in the database named by the tableNames parameter. If the schemaOptions parameter is specified it is used as the schemaOptions object for the schema.
getTablesNames
getTablesNames(dataSourceName=None)
Return a list of the names of all tables in the database. If the dataSourceName parameter is specified the SQL is run against the named data source otherwise the default data source is used.
executeSql
executeSql(sql, dataSourceName=None)
Executes the SQL specified in the sql parameter. If the dataSourceName parameter is specified the SQL is run against the named data source otherwise the default data source is used.
getMemoryObjects
getMemoryObjects(objectType=MEMORY_OBJ_ALL)
Returns objects contained in the transaction object space. Does not fetch them from the database. The objectType parameter can be any of the following:
 
begin
begin()
Begin a transactional object context. Any objects selected after this will be remembered. Changes to them will be tracked. After an object is changed the changes will be seen in any result set that includes it. The context ends when commit or rollback is called.
commit
commit(restart=False)
End a transactional object context after flushing any changes (insert/update/delete) to the database. If the optional restart parameter is set to true a new transaction is immediately restarted and any objects in the previous transaction are automatically included.
save
save()
Save the DataProxy instance persistently (including any objects selected if a transactional object context exists, and all objects in the "session") so that it could be retrieved by another server on another node. It cannot be used if a database transaction is in progress
rollback
rollback(objects)
Takes an object, or a list of objects, and resets all modified fields to their original values (the values read most recently from the database).
refresh
refreshObjects(objects)
Takes an object, or a list of objects, and re-reads all unmodified fields from the database.
APIs for Application Information
All of these functions are in a class AppInfo, in the activegrid.runtime module:
 
Returns the path of the static files in the ActiveGrid software installation; these include the layout skin and JavaScript files.
Other activegrid.runtime Module APIs
The following APIs are also in the activegrid.runtime but in no particular class within that module.
 
Returns the RequestContext associated with the current request context. This object (defined in runtime.py) contains references to the current session object, as well as a SysProxy object (containing information about the current user and their authentication status) and the currently selected data object (see following entries.)
Returns the object that was implicitly selected by the user when they clicked on an action.
Returns the DataService object associated with the current request. The DataService object includes both access and statistics methods to the backing stores currently in use.
Returns the WebService object in the current request context. This can be used to access the WebService interface directly.
Returns the security (authentication and authorization) module. This is a global construct, not associated with any specific requests.
Returns the ServiceRef object associated with the current request. ServiceRef contains information about the current Web services request, including document type, base URLs, schemas, and more.
Returns an object in the correct type for the response. The type is taken from the schema information available from the ServiceRef object (see getServiceParameters()); the data is left un-initialized.
-
Using getObjects
The DataService getObjects method is used to fetch objects from the database. This section discusses this method in more depth, and gives examples of how it can be used. All examples run in an application generated by the ApplicationWizard, based on the “product” table and the “category” table of the petstore-SQLite data source.
getObjects is exposed at two different levels of abstractions: local code and XPath in Custom Actions and Pages. The method always returns a list containing the results of the SQL query it was translated into by the DataService. The list is empty if the query did not return any results.
Local Code
In order to call this method from local code, you first need to acquire the DataService instance to call it on. To do this, use the getDataService method in the activegrid.runtime module. This example gets all “product” objects, and for each, updates the product’s image file path. It then calls commit so that the modified objects are updated in the database.
import os
import os.path
import activegrid.runtime as runtime
def updatePath():
dataService = runtime.getDataService()
products = dataService.getObjects("product", "image")
for product in products:
product.image = "/home/ag/images/" + os.path.basename(product.image)
dataService.commit()
 
In the above example, we passed two parameters to getObjects:
The type of object to retrieve (which maps to the table name to select from). The type is that name of a complex type that has to exist in one of the application’s Data Models. If more than one complex type with the same name exists, then the type name must be prefixed with the namespace of the schema the complex type is defined in.
Enumerates which attributes of the result object to populate (default is all). Here we’re only interested in the “image” attribute.
Custom Action
This example shows how to call getObjects in a Custom Action to get all products from the database that are “dogs”. The results are then passed to the ProductList xform.
Assuming you have an application generated from petstore-SQLite’s “product” and “category” tables:
1.
In the Page Flow Editor editor, right-click on the HomePage and select Insert Action > Custom... from the resulting pop-up menu.
2.
Set destination Page to ProductList, and call the Action “GetAllDogs”, then click Next.
3.
4.
Double-click on the new GetAllDogs Action. The Custom Action Editor appears
5.
In the Custom Action Editor, right-click on the Variables box and select Add Variable... from the resulting pop-up menu. The Variable Details screen appears.
6.
In the Name: field, type:
dogs
7.
From the Type: list, select yourProject:ProductListMsg.
8.
Click Finish. The dogs variable appears in the Varaibles box.
The next step is to invoke getObjects to populate the Message Part of the “dogs” variable. The Message Part is called “product”.
9.
Right-click on the Variables box and select Add Set... from the resulting pop-up menu. The BPEL Set screen appears.
10.
At the top right of the BPEL Set screen, click the XPath Ref... button. The Select an XPath dialog appears.
11.
Select dogs/product and click OK.
12.
Click the Database Query radio button.
13.
To build the getObjects call, first click the Column... button. The Select a Column screen appears. Select category_ref/name.
14.
From the Operator pull-down menu, select the equals sign (=).
15.
’Dogs’
(note the single quotes)
16.
17.
Back in the Custom Action Editor, double-click the ProductList invoke. The Invoke Details screen appears.
18.
Set the Input Variable to dogs and click Finish.
Run the application and click the GetAllDogs button. You will see a list of all dogs in the database.
Note the two parameters passed to getObjects (in the Set):
This is again the type we want to retrieve; the type name is fully qualified (with namespace).
The second argument is a list of qualifications (getObjects in xpath does not have the “refs” argument). This is the database selection: category_ref/name = ‘Dogs’.
 

ActiveGrid
Application Developer's Guide
Version 2.0