python_test.py

This is a simple example that demonstrate how to use the Zorba XQuery Engine to create, compile, and execute queries.

# Copyright 2006-2008 The FLWOR Foundation.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
sys.path.append('/Users/mbrantner/misc/code/vanilla/head/build/swig/python')
import zorba-api

def example1(zorba):
  xquery = zorba.compileQuery("1+2")
  print xquery.execute()
  return

def example2(zorba):
  xquery = zorba.compileQuery("(1,2,3,4,5)")
  iter = xquery.iterator()
  iter.open()
  item = zorba_api.Item_createEmptyItem()
  while iter.next(item):
    print item.getStringValue()
  iter.close()
  iter.destroy()
  return

def example3(zorba):
  try:
    xquery = zorba.compileQuery("1 div 0")
    print xquery.execute()
  except RuntimeError, e:
    print e
  return

def example4(zorba):
  try:
    xquery = zorba.compileQuery("for $i in (1,2,")
    print xquery.execute()
  except RuntimeError, e:
    print e 
  return

def example5(zorba):
  dataManager = zorba.getXmlDataManager()
  dataManager.loadDocument("books.xml", "<books><book>Book 1</book><book>Book 2</book></books>")
  xquery = zorba.compileQuery("doc('books.xml')//book")
  print xquery.execute()
  return

def example6(zorba):
  dataManager = zorba.getXmlDataManager()
  dataManager.loadDocument("books.xml", "<books><book>Book 1</book><book>Book 2</book></books>")
  xquery1 = zorba.compileQuery("insert node <book>Book 3</book> into doc('books.xml')/books")
  if xquery1.isUpdateQuery():
    xquery1.applyUpdates()
  xquery2 = zorba.compileQuery("doc('books.xml')//book")
  print xquery2.execute()
  return

store = zorba_api.InMemoryStore_getInstance()
zorba = zorba_api.Zorba_getInstance(store)

print "Example1:"
example1(zorba)
print ""

print "Example2:"
example2(zorba)
print ""

print "Example3:"
example3(zorba)
print ""

print "Example4:"
example4(zorba)
print ""

print "Example5:"
example5(zorba)
print ""

print "Example6:"
example6(zorba)
print ""

zorba.shutdown()
zorba_api.InMemoryStore_shutdown(store)