Package omero :: Package plugins :: Module hql
[hide private]
[frames] | no frames]

Source Code for Module omero.plugins.hql

  1  #!/usr/bin/env python 
  2  """ 
  3     HQL plugin 
  4   
  5     Plugin read by omero.cli.Cli during initialization. The method(s) 
  6     defined here will be added to the Cli class for later use. 
  7   
  8     Copyright 2008 Glencoe Software, Inc. All rights reserved. 
  9     Use is subject to license terms supplied in LICENSE.txt 
 10   
 11  """ 
 12   
 13  from omero.cli import BaseControl, CLI 
 14  import exceptions 
 15  import cmd 
 16  import time 
 17  import cmd 
 18  import sys 
 19   
 20  HELP = """Executes an HQL statement with the given parameters. 
 21  If no query is given, then a shell is opened which 
 22  will run any entered query with the current parameters.""" 
 23   
24 -class HqlControl(BaseControl):
25
26 - def _configure(self, parser):
27 parser.set_defaults(func=self.__call__) 28 parser.add_argument("query", nargs="?", help="Single query to run") 29 parser.add_argument("-q", "--quiet", action="store_true", help="No user input") 30 parser.add_argument("--limit", help="Maximum number of return values", type=int, default=25) 31 parser.add_argument("--offset", help="Number of entries to skip", type=int, default=0)
32
33 - def __call__(self, args):
34 if args.query: 35 self.hql(args) 36 else: 37 if args.quiet: 38 self.ctx.die(67, "Can't ask for query with --quiet option") 39 while True: 40 args.query = self.ctx.input("Enter query:") 41 if not args.query: 42 break 43 if not self.hql(args, loop = True): 44 break
45
46 - def hql(self, args, loop = False):
47 from omero_sys_ParametersI import ParametersI 48 c = self.ctx.conn(args) 49 q = c.sf.getQueryService() 50 p = ParametersI() 51 p.page(args.offset, args.limit) 52 rv = self.project(q, args.query, p) 53 has_details = self.display(rv) 54 if args.quiet: 55 return 56 57 input = """ 58 To see details for object, enter line number. 59 To move ahead one page, enter 'p' 60 To re-display list, enter 'r'. 61 To quit, enter 'q' or just enter. 62 """ 63 if loop: 64 input = input + """To run another query, press enter\n""" 65 66 while True: 67 id = self.ctx.input(input) 68 id = id.lower() 69 70 # Exit loop 71 if not id: 72 return True 73 if id.startswith("q"): 74 return False 75 76 # Stay in loop 77 if id.startswith("p"): 78 p.page(p.getOffset().val + p.getLimit().val, p.getLimit()) 79 self.ctx.dbg("\nCurrent page: offset=%s, limit=%s\n" % (p.theFilter.offset.val, p.theFilter.limit.val)) 80 rv = self.project(q, args.query, p) 81 self.display(rv) 82 elif id.startswith("r"): 83 self.display(rv) 84 else: 85 try: 86 id = long(id) 87 obj = rv[id] 88 if id not in has_details: 89 self.ctx.out("No details available: %s" % id) 90 continue 91 else: 92 obj = obj[0].val # Unwrap the object_list from IQuery.projection 93 except: 94 self.ctx.out("Invalid choice: %s" % id) 95 continue 96 keys = sorted(obj.__dict__) 97 keys.remove("_id") 98 keys.remove("_details") 99 self.ctx.out("id = %s" % obj.id.val) 100 for key in keys: 101 value = self.unwrap(obj.__dict__[key]) 102 if isinstance(value, (str, unicode)): 103 value = "'%s'" % value 104 if key.startswith("_"): 105 key = key[1:] 106 self.ctx.out("%s = %s" % (key, value)) 107 continue
108
109 - def display(self, rv):
110 import omero_model_Details_ice 111 import omero_model_IObject_ice 112 import omero.rtypes 113 from omero.model import IObject 114 from omero.model import Details 115 from omero.util.text import TableBuilder 116 117 has_details = [] 118 tb = TableBuilder("#") 119 for idx, object_list in enumerate(rv): 120 klass = "Null" 121 id = "" 122 values = {} 123 # Handling for simple lookup 124 if len(object_list) == 1 and isinstance(object_list[0], omero.rtypes.RObjectI): 125 has_details.append(idx) 126 o = object_list[0].val 127 if o: 128 tb.cols(["Class", "Id"]) 129 klass = o.__class__.__name__ 130 id = o.id.val 131 for k, v in o.__dict__.items(): 132 values[k] = self.unwrap(v) 133 values = self.filter(values) 134 tb.cols(values.keys()) 135 tb.row(idx, klass, id, **values) 136 # Handling for true projections 137 else: 138 indices = range(1, len(object_list) + 1) 139 tb.cols(["Col%s" % x for x in indices]) 140 values = tuple([self.unwrap(x) for x in object_list]) 141 tb.row(idx, *values) 142 self.ctx.out(str(tb.build())) 143 return has_details
144
145 - def unwrap(self, object, cache = None):
146 147 if cache == None: 148 cache = {} 149 elif object in cache: 150 return cache[id(object)] 151 152 from omero.rtypes import unwrap 153 import omero_model_Details_ice 154 import omero_model_IObject_ice 155 from omero.model import IObject 156 from omero.model import Details 157 from omero.rtypes import RObjectI 158 from omero.rtypes import RTimeI 159 #if isinstance(object, list): 160 # return [self.unwrap(x, cache) for x in object] 161 #elif isinstance(object, RObject): 162 # return self.unwrap(object.val, cache) 163 unwrapped = unwrap(object, cache) 164 if isinstance(unwrapped, IObject): 165 rv = "%s:%s" % (unwrapped.__class__.__name__, unwrapped.id.val) 166 elif isinstance(object, RTimeI): 167 rv = time.ctime(unwrapped/1000.0) 168 elif isinstance(object, Details): 169 owner = None 170 group = None 171 if unwrapped.owner is not None: 172 owner = unwrapped.owner.id.val 173 if unwrapped.group is not None: 174 group = unwrapped.group.id.val 175 rv = "owner=%s;group=%s" % (owner, group) 176 else: 177 rv = unwrapped 178 179 cache[id(object)] = rv 180 return rv;
181
182 - def filter(self, values):
183 values = dict(values) 184 for x in ("_id", "_loaded"): 185 if x in values: 186 values.pop(x) 187 if "owner=None;group=None" == values.get("_details"): 188 values.pop("_details") 189 multi_valued = sorted([k for k in values if isinstance(values[k], list)]) 190 false_valued = sorted([k for k in values if not values[k]]) 191 for x in multi_valued + false_valued: 192 if x in values: 193 values.pop(x) 194 195 rv = dict() 196 for k, v in values.items(): 197 if k.startswith("_"): 198 rv[k[1:]] = v 199 else: 200 rv[k] = v 201 return rv
202
203 - def project(self, querySvc, queryStr, params):
204 import omero 205 try: 206 rv = querySvc.projection(queryStr, params) 207 self.ctx.set("last.hql.rv", rv) 208 return rv 209 except omero.QueryException, qe: 210 self.ctx.set("last.hql.rv", []) 211 self.ctx.die(52, "Bad query: %s" % qe.message)
212 213 try: 214 register("hql", HqlControl, HELP) 215 except NameError: 216 if __name__ == "__main__": 217 cli = CLI() 218 cli.register("hql", HqlControl, HELP) 219 cli.invoke(sys.argv[1:]) 220