#
# Note, this file uses a table called gnue_demo:
#
# create table gnue_demo (
#    field1 varchar(40),
#    field2 int,
#    field3 varchar(40)
# )
#
# It also expects a connections.conf entry for [gnue]
# that points to the database containing gnue_demo.
#


# Stuff we'll need
from gnue.common import GClientApp, GDataSource, GLoginHandler, GConditions


class MyApp(GClientApp.GClientApp):

  def run(self):

    # The connections manager (self.connections) is
    # created by GClientApp. It handles prompting for
    # username/password.  We'll provide our own login
    # handler.
    self.connections.setLoginHandler(MyLoginHandler())


    # Create a datasource object
    datasource = GDataSource.GDataSource()


    # Add our parameters and initialize.
    # GParser would normally handle the
    # next 3 steps; however, we aren't
    # using GParser.
    datasource.buildObject(name = 'dtsDemo',
                           table = 'gnue_demo',
                           database = 'gnue')

    # This tells the datasource which connection manager to use
    datasource.setConnectionManager(self.connections)

    # ..and init/connect
    datasource.phaseInit()


    # Now, reference all the fields we'll be accessing.
    for field in ('field1','field2','field3'):
      datasource.referenceField(field)


    #############################################################
    #
    # First, let's wipe out the table.
    # This isn't the most efficient way delete an entire table,
    # but we are demo-ing DataObjects, so we'll only use
    # DataObjects :)
    #

    print "Clearing out the table"

    # Get a resultset with all the rows in the table
    resultSet = datasource.createResultSet()

    # Loop through each record and delete it
    while resultSet.nextRecord():
      resultSet.current.delete()
      print "  .. Deleting existing record"

    # And post/commit our changes
    # The table should be empty now.
    resultSet.post()
    datasource.commit()
    print "Data committed"


    #############################################################
    #
    # Next, let's add some data
    #

    # We will need an empty result set to do this
    resultSet = datasource.createEmptyResultSet()

    # Load our dataset
    for val1, val2, val3 in ( ('Entry 1', 1, 'Bob'),
                              ('Entry 2', 2, 'Jane'),
                              ('Entry 3', 3, 'Jill'),
                              ('Entry 4', 4, 'Jason'),
                              ('Entry 5', 5, 'Derek'),
                              ('Entry 6', 6, 'James') ):

      # Create a new record.  This will return 1 if
      # successful.
      resultSet.insertRecord()

      # Set all the fields
      resultSet.current.setField('field1',val1)
      resultSet.current.setField('field2',val2)
      resultSet.current.setField('field3',val3)


      print "Added record ('%s',%s,'%s')" % \
                    (resultSet.current.getField('field1'),
                     resultSet.current.getField('field2'),
                     resultSet.current.getField('field3') )


    # Post/Commit our changes to the database
    resultSet.post()
    datasource.commit()

    print "Data committed"


    #############################################################
    #
    # Next, let's print out all the data
    #

    print
    print "Looking for all records"

    resultSet = datasource.createResultSet()

    # Print out the entire table
    while resultSet.nextRecord():
      print "%s is %s" % (resultSet.current.getField('field1'),
                          resultSet.current.getField('field3') )

    # Print out the second-to-last record

    print
    print "  Going to the previous record!"

    if resultSet.prevRecord():
      print "  Now I'm at %s" % resultSet.current.getField('field1')


    #############################################################
    #
    # Next, return all records with field2 < 3
    #

    print
    print "Looking for records where field < 3 (newResultSet)"

    #
    # We'll need a conditional tree for that
    #
    # "Less than" operator
    conditions = GConditions.GConditions()
    oper = GConditions.GClt(conditions)
    # Add a field
    GConditions.GCField(oper, 'field2')
    # .. and a constant
    GConditions.GCConst(oper, 3)

    print
    print "  Our Conditional Tree:"
    conditions.showTree(indent=4)
    print

    # Create our result set
    newResultSet = datasource.createResultSet(conditions=conditions)

    # And show off
    while newResultSet.nextRecord():
      print "  %s; %s; %s" % (newResultSet.current.getField('field1'),
                              newResultSet.current.getField('field2'),
                              newResultSet.current.getField('field3') )


    #############################################################
    #

    print
    print "Look, resultSet is still active! %s" % \
              resultSet.current.getField('field1')


class MyLoginHandler(GLoginHandler.LoginHandler):
  # Get username/password for the database connection.
  # In a live app, this would either be read from a
  # settings file, or would actually prompt the user
  # for a username / password.
  def getLogin(self, *arguments):

    return {'_username':'gnue',
            '_password': 'gnue'}



# Run our app
MyApp().run()

