Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 2nd, 2012  |  syntax: None  |  size: 6.67 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2011 James Thornton (http://jamesthornton.com)
  4. # BSD License (see LICENSE for details)
  5. #
  6. """
  7. An interface for executing Gremlin scripts on the resource.
  8.  
  9. """
  10. import os
  11. import yaml
  12. from string import Template
  13. from utils import initialize_element
  14.  
  15.    
  16. class Gremlin(object):
  17.     """An interface for executing Gremlin scripts on the resource."""
  18.  
  19.     def __init__(self,resource):
  20.         self.resource = resource
  21.         # Registering it here isn't a good idea b/c you will
  22.         # have a chicken and egg scneario if you try to use
  23.         # the sripts inside Resource -- register it at the resource level
  24.         #self.register_scripts("gremlin","gremlin.yaml")
  25.  
  26.     def query(self,script,**kwds):
  27.         """
  28.         Returns initialized results of an arbitrary Gremlin scripts
  29.         run on the resource.
  30.  
  31.         :param script: Gremlin script to send to the resource.
  32.         :param kwds: Resource-specific keyword params.
  33.  
  34.         """
  35.         resp = self.resource.gremlin(script,**kwds)
  36.         for result in resp.results:
  37.             yield initialize_element(self.resource,result)
  38.  
  39.     def execute(self,script,**kwds):
  40.         """
  41.         Returns raw results of an arbitrary Gremlin script.
  42.  
  43.         :param script: Gremlin script to send to the resource.
  44.         :param kwds: Resource-specific keyword params.
  45.  
  46.         """
  47.         resp = self.resource.gremlin(script,**kwds)
  48.         return list(resp.results)
  49.  
  50.     def register_scripts(self,name,file_name):
  51.         """Only load/register the scripts library once to reduce overhead."""
  52.         scripts = self.resource.config.get_scripts(name)
  53.         if not scripts:
  54.             scripts = Scripts(file_name)
  55.             self.resource.config.register_scripts(name,scripts)
  56.    
  57.     def get_scripts(self,name="gremlin"):
  58.         return self.resource.registry.get_scripts(name)
  59.  
  60.  
  61. class Scripts(object):
  62.     """Load Gremlin scripts from a YAML source file."""
  63.  
  64.     def __init__(self,file_name="gremlin.yaml"):
  65.         self.file_name = self._get_file_name(file_name)
  66.         self.templates = self._load_templates()
  67.  
  68.     def get(self,name,params={}):
  69.         """Return a Gremlin script, generated from the params."""
  70.         template = self.templates.get(name)
  71.         params = self._quote_params(params)
  72.         return template.substitute(params)
  73.        
  74.     def refresh(self):
  75.         """Refresh the stored templates from the YAML source."""
  76.         self.templates = self._load_templates()
  77.  
  78.     def _load_templates(self):
  79.         return self._parse_yaml(self.file_name)
  80.  
  81.     def _get_file_name(self,file_name):
  82.         if file_name == "gremlin.yaml":
  83.             dir_name = os.path.dirname(__file__)
  84.             file_name = "%s/%s" % (dir_name,file_name)
  85.         return file_name
  86.  
  87.     def _parse_yaml(self,file_name):
  88.         templates = dict()
  89.         f = open(file_name)
  90.         yaml_map = yaml.load(f)    
  91.         for name, template in yaml_map.items():
  92.             #template = ';'.join(lines.split('\n'))
  93.             templates[name] = Template(template)
  94.         return templates
  95.  
  96.     def _quote_params(self,params):
  97.         quoted_tuple = map(self._quote,params.items())
  98.         params = dict(quoted_tuple)
  99.         return params
  100.  
  101.     def _quote(self,pair):
  102.         key, value = pair
  103.         if type(value) == str:
  104.             value = "'%s'" % value
  105.         elif value is None:
  106.             value = ""
  107.         return key, value
  108.  
  109.  
  110. class ScriptWriter(object):
  111.     """
  112.     ScriptWriter is an experiment that would be akin to a Python-based
  113.     Google Web Toolkit (http://code.google.com/webtoolkit/) for
  114.     building Gremlin scripts. And while it works well, I think it's simpler
  115.     to source Gremlin code from gremlin.yaml. But I'm leaving ScriptWriter
  116.     in the codebase for now so others can experiment with it. - James
  117.  
  118.     Example:
  119.  
  120.     def create_indexed_vertex(index_name,data,keys=None):
  121.         s = ScriptWriter()
  122.         s.start_transaction()
  123.         s.add_vertex("v")
  124.         s.set_property_data("v",data)
  125.         s.get_index("i",index_name,"Vertex")
  126.         keys = s.get_keys(data,keys)
  127.         for key, value in data.items():
  128.             if key in keys:
  129.                 s.index_put("i",key,value,"v")
  130.         s.end_transaction()
  131.         s.return_var("v")
  132.         return s.get()
  133.  
  134.     data = dict(name="James",age=34)
  135.     script = create_indexed_vertex("people",data)
  136.     resp = self.resource.gremlin(script)
  137.     """
  138.    
  139.     def __init__(self):
  140.         self.lines = []
  141.  
  142.     def __add__(self,line):
  143.         self.lines.append(line)
  144.  
  145.     # Elements
  146.     def add_vertex(self,varname):
  147.         line = "Vertex %s = g.addVertex(null)" % (varname)
  148.         self.lines.append(line)
  149.  
  150.     def add_edge(self,varname,outV,label,inV):
  151.         line  = "Edge %s = g.addEdge(null,%s,%s,%s)" % (varname,outV,inV,label)
  152.         self.lines.append(line)
  153.  
  154.     def set_property(self,element,key,value):
  155.         line = "%s.setProperty('%s',%s)" % (element,key,self.quote(value))
  156.         self.lines.append(line)
  157.  
  158.     def set_property_data(self,element,data):
  159.         for key, value in data.items():
  160.             self.set_property(element,key,value)
  161.  
  162.     # Indices
  163.     def get_index(self,varname,index_name,index_class):
  164.         line = "%s = g.getIndex(%s,%s)" % (varname, index_name,index_class)
  165.         self.lines.append(line)
  166.  
  167.     def index_put(self,index,key,value,element):
  168.         line = "%s.put('%s',%s,%s)" % (index,key,self.quote(value),element)
  169.         self.lines.append(line)
  170.  
  171.     def index_get(self,index,key,value):
  172.         line = "%s.get('%s',%s,%s)" % (index,key,self.quote(value))
  173.        
  174.     def index_remove(self,index,key,value,element):
  175.         line = "%s.remove('%s',%s,%s)" % (index,key,self.quote(value),element)
  176.         self.lines.append(line)
  177.  
  178.     # Graph
  179.     def return_var(self,varname):
  180.         self.lines.append("return %s" % varname)
  181.  
  182.     def start_transaction(self,buffer_size=0):
  183.         self.lines.append("g.setMaxBufferSize(%d)" % buffer_size)
  184.         self.lines.append("g.startTransaction()")
  185.        
  186.     def end_transaction(self):
  187.         self.lines.append("g.stopTransaction(TransactionalGraph.Conclusion.SUCCESS)")
  188.  
  189.     # Script Methods
  190.     def append(self,script):
  191.         self.lines.append(script)
  192.  
  193.     def get(self):
  194.         script = ";".join(self.lines)
  195.         return script
  196.  
  197.     def display(self):
  198.         script = ";\n".join(self.lines)
  199.         print script
  200.  
  201.     def compile(self):
  202.         # store pre-compiled tempaltes in config?
  203.         pass
  204.  
  205.     # Utils
  206.     def quote(value):
  207.         # quote it if it's a string, set to null if None, else return the value
  208.         if type(value) == str:
  209.             value = "'%s'" % value
  210.         elif value is None:
  211.             value = "null"
  212.         return value
  213.  
  214.     def get_keys(data,keys):
  215.         if not keys:
  216.             keys = data.keys()
  217.         return keys