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

Source Code for Module omero.plugins.hql

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