changeset 276:55bc9972fb1b

Merge with d1b43624cc63b829f64cc952540748e15272e389
author casties
date Thu, 23 Feb 2012 21:29:06 +0100
parents eb8a18f94d2d (diff) d1b43624cc63 (current diff)
children 9bfa7a6858f1
files RestDbGisApi.py
diffstat 2 files changed, 106 insertions(+), 18 deletions(-) [+]
line wrap: on
line diff
--- a/RestDbGisApi.py	Thu Feb 23 11:44:38 2012 +0100
+++ b/RestDbGisApi.py	Thu Feb 23 21:29:06 2012 +0100
@@ -13,7 +13,7 @@
 import datetime
 import urlFunctions
 
-from RestDbInterface import *
+from Products.ZDBInterface.WritableRestDbInterface import *
 
 
 def kmlEncode(s):
@@ -25,7 +25,7 @@
     return res
 
 
-class RestDbGisApi(RestDbInterface):
+class RestDbGisApi(WritableRestDbInterface):
     """Object for RESTful GIS database queries
     path schema: /db/{schema}/{table}/
     omitting table gives a list of schemas
@@ -34,6 +34,10 @@
     
     meta_type="RESTgis"
 
+    # data templates
+    GIS_schema_table = PageTemplateFile('zpt/GIS_schema_table', globals())
+    KML_schema_table = PageTemplateFile('zpt/KML_schema_table', globals())
+    HTML_schema_usertables = PageTemplateFile('zpt/HTML_schema_usertables', globals())
     
     # and scripts
     def KML_URL_schema_table(self,schema,table, useTimestamp=True, args=None):
@@ -138,26 +142,110 @@
     def createEmptyTable(self,schema,table,fields):
         """create a table with the given fields
            returns list of created fields"""
-        sqlFields = RestDbInterface.createEmptyTable(self,schema,table,fields)
+        sqlFields = WritableRestDbInterface.createEmptyTable(self,schema,table,fields)
         if sqlFields is not None:
             self.setTableMetaTypes(schema,table,sqlFields)
 
         return sqlFields
     
+    # TODO: move this
+    def getAttributeNames(self,schema='public',table=None):   
+        return self.executeSQL("SELECT attname FROM pg_attribute, pg_class WHERE pg_class.oid = attrelid AND attnum>0 AND relname = %s", (table))
+
+    # TODO: move this
+    def getAttributeTypes(self,schema='public',table=None):   
+        return self.executeSQL("SELECT field_name, gis_type FROM public.gis_table_meta_rows WHERE table_name = %s", (table))
+         
+    # TODO: move back to inherited version
+    def showTable(self,format='XML',schema='public',table=None,REQUEST=None,RESPONSE=None):
+        """returns PageTemplate with tables"""
+        logging.debug("showtable")
+        if REQUEST is None:
+            REQUEST = self.REQUEST
+        queryArgs={'doc':None,'id':None}
+        queryArgs['doc'] = REQUEST.get('doc')
+        queryArgs['id'] = REQUEST.get('id')
+    
+        # should be cross-site accessible 
+        if RESPONSE is None:
+            RESPONSE = self.REQUEST.RESPONSE
+            
+        RESPONSE.setHeader('Access-Control-Allow-Origin', '*')
+        
+        # everything else has its own template
+        pt = getattr(self.template, '%s_schema_table'%format, REQUEST)
+        if pt is None:
+            return "ERROR!! template %s_schema_table not found at %s"%(format, self.template )
+        #data = self.getTable(schema,table)
+        return pt(schema=schema,table=table,args=queryArgs)
+
+    #TODO: move to parent class
+    def getLiveUrl(self,schema,table,useTimestamp=True,REQUEST=None):
+        if REQUEST is None:
+            REQUEST = self.REQUEST
+        logging.debug("getLiveUrl")
+        baseUrl = self.absolute_url()
+        timestamp = time.time()
+        # filter parameters in URL and add to new URL
+        params = [p for p in REQUEST.form.items() if p[0] not in ('format','timestamp')]
+        params.append(('format','KML'))
+        if useTimestamp:
+            # add timestamp so URL changes every time
+            params.append(('timestamp',timestamp))
+        paramstr = urllib.urlencode(params)
+        return "%s/db/%s/%s?%s"%(baseUrl,schema,table,paramstr)
+
+
+    # TODO: remove changes from parent version
+    def getTable(self,schema='public',table=None,sortBy=1,username='guest'):
+        """return table data"""
+        logging.debug("gettable")
+        attrNames=self.getAttributeNames(schema,table)
+        attrTypes=self.getAttributeTypes(schema,table)
+        attrString=""
+ #        try:
+        for name in attrNames['rows']:
+              logging.debug("name: %s"%name[0])
+              not_added=True
+              if name[0] == "the_geom":                        #FJK: the table column is "the_geom"
+                     attrString=attrString+"ST_AsText("+name[0]+"),"
+                     not_added=False
+                     break
+              for a_iter in attrTypes['rows']:
+                 not_added = True
+                 logging.debug("attrTypes.field_name: %s"%a_iter[0])
+                 if a_iter[0]==name[0]:            
+                     logging.debug("attrTypes.gis_type: %s"%a_iter[1])            
+                     if a_iter[1] == "the_geom":                        #FJK: the table column is registered in gis_table_meta_rows as type "the_geom"
+                         attrString=attrString+"ST_AsText("+name[0]+"),"
+                         not_added=False
+              if not_added:
+                  if name[0].find('pg.dropped')==-1:
+                      attrString=attrString+name[0]+","
+        attrString=str(attrString).rsplit(",",1)[0] #to remove last ","
+        if sortBy:
+            data = self.executeSQL('select %s from "%s"."%s" order by %%s'%(attrString,sqlName(schema),sqlName(table)),(sortBy,))
+        else:
+            data = self.executeSQL('select %s from "%s"."%s"'%(attrString,sqlName(schema),sqlName(table)))
+ #       except:
+ #           """ table does not exist """
+ #           fields=self.get
+  #          self.createEmptyTable(schema, table, fields)
+        return data
+
     
     def getLiveKmlUrl(self,schema,table,useTimestamp=True,REQUEST=None):
         return self.getLiveUrl(schema,table,useTimestamp,REQUEST)
 
     def getKmlData(self, schema, table, ids=None, sortBy=1, gisIdField=None, latField=None, lonField=None, geomField="point", colorField="red_big",from_year_name='from_year',until_year_name=''):
         """returns data structure for KML template"""
-        logging.debug("getKMLDATA")
         logging.debug("getKMLdata gid=%s lat=%s lon=%s sortBy=%s geom=%s color=%s"%(gisIdField,latField,lonField,sortBy,geomField,colorField))
         if geomField is None:
             geomField="point"
         if colorField is None:
             colorField="red"
         # Mapping a set of points from table-based SQL-query:
-        qstr='SELECT * FROM "%s"."%s"'%(schema,table)
+        qstr='SELECT * FROM "%s"."%s"'%(sqlName(schema),sqlName(table))
         idList = None
         if ids is not None:
             qstr += ' WHERE '
@@ -203,16 +291,16 @@
             if len(geocolumn_res['rows'])>0:
                 geocolumn=geocolumn_res['rows'][0][0]
                 try:
-                    geomstr="select astext(st_simplify(transform(%s,4326),0.05)) from %s.%s"%(geocolumn,schema,table) # the string variables have to be added here and not in executeSQL!
+                    geomstr="select astext(st_simplify(transform(%s,4326),0.05)) from %s.%s"%(geocolumn,sqlName(schema),sqlName(table)) # the string variables have to be added here and not in executeSQL!
                     geomdata=self.executeSQL(geomstr)
                     teststr=geomdata.values()[1][0]
                     if (teststr == (u'MULTIPOLYGON EMPTY',)):
-                        geomstr="select astext(st_simplify(transform(%s,4326),0.05)) from %s.%s"%(geocolumn,schema,table) # the string variables have to be added here and not in executeSQL!
+                        geomstr="select astext(st_simplify(transform(%s,4326),0.05)) from %s.%s"%(geocolumn,sqlName(schema),sqlName(table)) # the string variables have to be added here and not in executeSQL!
                         geomdata=self.executeSQL(geomstr)
     
                 except:
                     try:
-                        geomstr="select chgis.astext(chgis.st_simplify(chgis.transform(%s,4326),0.05)) from %s.%s"%(geocolumn,schema,table) # the string variables have to be added here and not in executeSQL!
+                        geomstr="select chgis.astext(chgis.st_simplify(chgis.transform(%s,4326),0.05)) from %s.%s"%(geocolumn,sqlName(schema),sqlName(table)) # the string variables have to be added here and not in executeSQL!
                         geomdata=self.executeSQL(geomstr)                
                     except:
                         geomdata=None
@@ -334,11 +422,11 @@
                     until_year = res['rows'][0][0]
             except:
                     until_year = "until_year_dummy"
-                    
+                          
             #DW added for testing E4D with names        
             from_year=from_year_name
             until_year=until_year_name
-            
+      
             logging.debug("from_year:"+from_year)
             logging.debug("until_year:"+until_year)
             for i in range (len(dataset)):
--- a/__init__.py	Thu Feb 23 11:44:38 2012 +0100
+++ b/__init__.py	Thu Feb 23 21:29:06 2012 +0100
@@ -1,17 +1,17 @@
 
-import RestDbInterface
+#import RestDbInterface
 import RestDbJsonStore
 import RestDbGisApi
 
 def initialize(context):
 
-    context.registerClass(
-         RestDbInterface.RestDbInterface,
-        constructors = (
-          RestDbInterface.manage_addRestDbInterfaceForm,
-          RestDbInterface.manage_addRestDbInterface
-          )
-        )
+#    context.registerClass(
+#         RestDbInterface.RestDbInterface,
+#        constructors = (
+#          RestDbInterface.manage_addRestDbInterfaceForm,
+#          RestDbInterface.manage_addRestDbInterface
+#          )
+#        )
 
     context.registerClass(
          RestDbJsonStore.RestDbJsonStore,