def COUNT(builder, kind, *expr_list): if kind == 'ALL': if not expr_list: return ['COUNT(*)'] return 'COUNT(', join(', ', imap(builder, expr_list)), ')' elif kind == 'DISTINCT': if not expr_list: throw(AstError, 'COUNT(DISTINCT) without argument') if len(expr_list) == 1: return 'COUNT(DISTINCT ', builder(expr_list[0]), ')' if builder.dialect == 'PostgreSQL': return 'COUNT(DISTINCT ', builder.ROW(*expr_list), ')' elif builder.dialect == 'MySQL': return 'COUNT(DISTINCT ', join(', ', imap(builder, expr_list)), ')' # Oracle and SQLite queries translated to completely different subquery syntax else: throw(NotImplementedError) # This line must not be executed throw(AstError, 'Invalid COUNT kind (must be ALL or DISTINCT)')
def COUNT(builder, kind, *expr_list): if kind == 'ALL': if not expr_list: return ['COUNT(*)'] return 'COUNT(', join(', ', imap(builder, expr_list)), ')' elif kind == 'DISTINCT': if not expr_list: throw(AstError, 'COUNT(DISTINCT) without argument') if len(expr_list) == 1: return 'COUNT(DISTINCT ', builder(expr_list[0]), ')' if builder.dialect == 'PostgreSQL': return 'COUNT(DISTINCT ', builder.ROW(*expr_list), ')' elif builder.dialect == 'MySQL': return 'COUNT(DISTINCT ', join(', ', imap(builder, expr_list)), ')' # Oracle and SQLite queries translated to completely different subquery syntax else: throw(NotImplementedError) # This line must not be executed throw(AstError, 'Invalid COUNT kind (must be ALL or DISTINCT)')
def COUNT(builder, distinct, *expr_list): assert distinct in (None, True, False) if not distinct: if not expr_list: return ['COUNT(*)'] return 'COUNT(', join(', ', imap(builder, expr_list)), ')' if not expr_list: throw(AstError, 'COUNT(DISTINCT) without argument') if len(expr_list) == 1: return 'COUNT(DISTINCT ', builder(expr_list[0]), ')' if builder.dialect == 'PostgreSQL': return 'COUNT(DISTINCT ', builder.ROW(*expr_list), ')' elif builder.dialect == 'MySQL': return 'COUNT(DISTINCT ', join(', ', imap(builder, expr_list)), ')' # Oracle and SQLite queries translated to completely different subquery syntax else: throw(NotImplementedError) # This line must not be executed
def __init__(builder, provider, ast): builder.provider = provider builder.quote_name = provider.quote_name builder.paramstyle = paramstyle = provider.paramstyle builder.ast = ast builder.indent = 0 builder.keys = {} builder.inner_join_syntax = options.INNER_JOIN_SYNTAX builder.suppress_aliases = False builder.result = flat(builder(ast)) params = tuple(x for x in builder.result if isinstance(x, Param)) layout = [] for i, param in enumerate(params): if param.id is None: param.id = i + 1 layout.append(param.paramkey) builder.layout = layout builder.sql = u''.join(imap(unicode, builder.result)).rstrip('\n') if paramstyle in ('qmark', 'format'): def adapter(values): return tuple(param.eval(values) for param in params) elif paramstyle == 'numeric': def adapter(values): return tuple(param.eval(values) for param in params) elif paramstyle in ('named', 'pyformat'): def adapter(values): return {'p%d' % param.id: param.eval(values) for param in params} else: throw(NotImplementedError, paramstyle) builder.params = params builder.adapter = adapter
def __init__(builder, provider, ast): builder.provider = provider builder.quote_name = provider.quote_name builder.paramstyle = paramstyle = provider.paramstyle builder.ast = ast builder.indent = 0 builder.keys = {} builder.inner_join_syntax = options.INNER_JOIN_SYNTAX builder.result = flat(builder(ast)) builder.sql = u''.join(imap(unicode, builder.result)).rstrip('\n') if paramstyle in ('qmark', 'format'): params = tuple(x for x in builder.result if isinstance(x, Param)) def adapter(values): return tuple(convert(values, params)) elif paramstyle == 'numeric': params = tuple(param for param in sorted(itervalues(builder.keys), key=attrgetter('id'))) def adapter(values): return tuple(convert(values, params)) elif paramstyle in ('named', 'pyformat'): params = tuple(param for param in sorted(itervalues(builder.keys), key=attrgetter('id'))) def adapter(values): return dict(('p%d' % param.id, value) for param, value in izip(params, convert(values, params))) else: throw(NotImplementedError, paramstyle) builder.params = params builder.layout = tuple(param.paramkey for param in params) builder.adapter = adapter
def __init__(builder, provider, ast): builder.provider = provider builder.quote_name = provider.quote_name builder.paramstyle = paramstyle = provider.paramstyle builder.ast = ast builder.indent = 0 builder.keys = {} builder.inner_join_syntax = options.INNER_JOIN_SYNTAX builder.result = flat(builder(ast)) builder.sql = u''.join(imap(unicode, builder.result)).rstrip('\n') if paramstyle in ('qmark', 'format'): params = tuple(x for x in builder.result if isinstance(x, Param)) def adapter(values): return tuple(convert(values, params)) elif paramstyle == 'numeric': params = tuple(param for param in sorted(itervalues(builder.keys), key=attrgetter('id'))) def adapter(values): return tuple(convert(values, params)) elif paramstyle in ('named', 'pyformat'): params = tuple(param for param in sorted(itervalues(builder.keys), key=attrgetter('id'))) def adapter(values): return dict(('p%d' % param.id, value) for param, value in izip(params, convert(values, params))) else: throw(NotImplementedError, paramstyle) builder.params = params builder.layout = tuple(param.paramkey for param in params) builder.adapter = adapter
def str2datetime(s): if 19 < len(s) < 26: s += '000000'[:26-len(s)] s = s.replace('-', ' ').replace(':', ' ').replace('.', ' ').replace('T', ' ') try: return datetime(*imap(int, s.split())) except ValueError: return None # for incorrect values like 0000-00-00 00:00:00
def isbn10_checksum(digits): if len(digits) != 9: raise ValueError() reminder = sum(digit * coef for digit, coef in izip(imap(int, digits), xrange(10, 1, -1))) % 11 if reminder == 1: return "X" return reminder and str(11 - reminder) or "0"
def isbn10_checksum(digits): if len(digits) != 9: raise ValueError() reminder = sum( digit * coef for digit, coef in izip(imap(int, digits), xrange(10, 1, -1))) % 11 if reminder == 1: return 'X' return reminder and str(11 - reminder) or '0'
def str2timedelta(s): if '.' in s: s, fractional = s.split('.') microseconds = int((fractional + '000000')[:6]) else: microseconds = 0 h, m, s = imap(int, s.split(':')) td = timedelta(hours=abs(h), minutes=m, seconds=s, microseconds=microseconds) return -td if h < 0 else td
def _decode_color(color): if not PIL: raise ValueError try: color = ImageColor.colormap[color][1:] except KeyError: pass size = len(color) if size in (3, 4): color = ''.join(char+char for char in color) elif size not in (6, 8): raise ValueError try: return tuple(imap(ord, unhexlify(color))) except: raise ValueError
def str2timedelta(s): if "." in s: s, fractional = s.split(".") microseconds = int((fractional + "000000")[:6]) else: microseconds = 0 h, m, s = imap(int, s.split(":")) td = timedelta(hours=abs(h), minutes=m, seconds=s, microseconds=microseconds) return -td if h < 0 else td
def _extract_time_parts(groupdict): hh, mm, ss, am, pm = imap(groupdict.get, ('hh', 'mm', 'ss', 'am', 'pm')) if hh is None: hh, mm, ss = 12, 00, 00 elif am and hh == '12': hh = 0 elif pm and hh != '12': hh = int(hh) + 12 if isinstance(ss, basestring) and '.' in ss: ss, mcs = ss.split('.', 1) if len('mcs') < 6: mcs = (mcs + '000000')[:6] else: mcs = 0 return int(hh), int(mm or 0), int(ss or 0), int(mcs)
def _extract_time_parts(groupdict): hh, mm, ss, am, pm = imap(groupdict.get, ('hh', 'mm', 'ss', 'am', 'pm')) if hh is None: hh, mm, ss = 12, 00, 00 elif am and hh == '12': hh = 0 elif pm and hh != '12': hh = int(hh) + 12 if ss is not None and '.' in ss: ss, mcs = ss.split('.', 1) if len('mcs') < 6: mcs = (mcs + '000000')[:6] else: mcs = 0 return int(hh), int(mm or 0), int(ss or 0), int(mcs)
def _decode_color(color): if not PIL: raise ValueError try: color = ImageColor.colormap[color][1:] except KeyError: pass size = len(color) if size in (3, 4): color = ''.join(char + char for char in color) elif size not in (6, 8): raise ValueError try: return tuple(imap(ord, unhexlify(color))) except: raise ValueError
def deserialize(x): t = type(x) if t is list: return list(imap(deserialize, x)) if t is dict: if '_id_' not in x: return dict((key, deserialize(val)) for key, val in iteritems(x)) obj = objmap.get(x['_id_']) if obj is None: entity_name = x['class'] entity = db.entities[entity_name] pk = x['_pk_'] obj = entity[pk] return obj return x
def _extract_time_parts(groupdict): hh, mm, ss, am, pm = imap(groupdict.get, ("hh", "mm", "ss", "am", "pm")) if hh is None: hh, mm, ss = 12, 00, 00 elif am and hh == "12": hh = 0 elif pm and hh != "12": hh = int(hh) + 12 if ss is not None and "." in ss: ss, mcs = ss.split(".", 1) if len("mcs") < 6: mcs = (mcs + "000000")[:6] else: mcs = 0 return int(hh), int(mm or 0), int(ss or 0), int(mcs)
def MAX(builder, distinct, *args): assert not distinct, distinct if len(args) == 0: assert False # pragma: no cover elif len(args) == 1: fname = 'MAX' else: fname = builder.greatest_func_name return fname, '(', join(', ', imap(builder, args)), ')'
def MIN(builder, *args): if len(args) == 0: assert False # pragma: no cover elif len(args) == 1: fname = 'MIN' else: fname = 'least' return fname, '(', join(', ', imap(builder, args)), ')'
def names_row(schema, col_names): quote_name = schema.provider.quote_name return '(%s)' % ', '.join(imap(quote_name, col_names))
def MAX(builder, *args): if len(args) == 0: assert False # pragma: no cover elif len(args) == 1: fname = 'MAX' else: fname = 'greatest' return fname, '(', join(', ', imap(builder, args)), ')'
def COALESCE(builder, *args): if len(args) < 2: assert False # pragma: no cover return 'coalesce(', join(', ', imap(builder, args)), ')'
def COALESCE(builder, *args): if len(args) < 2: assert False # pragma: no cover return 'coalesce(', join(', ', imap(builder, args)), ')'
def __str__(self): insts = imap(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts))
def ROW(builder, *items): return '(', join(', ', imap(builder, items)), ')'
def init(self, kwargs): if self.provider.server_version < (5, 7, 8): version = '.'.join(imap(str, self.provider.server_version)) raise NotImplementedError("MySQL %s has no JSON support" % version)
def isbn13_checksum(digits): if len(digits) != 12: raise ValueError() reminder = sum(digit * coef for digit, coef in izip(imap(int, digits), (1, 3) * 6)) % 10 return reminder and str(10 - reminder) or '0'
def getTable(self): return ''.join(imap(chr, self.lnotab))
def addNext(self, block): self.next.append(block) assert len(self.next) == 1, list(imap(str, self.next)) block.prev.append(self) assert len(block.prev) == 1, list(imap(str, block.prev))
def CONCAT(builder, *args): return 'concat(', join(', ', imap(builder, args)), ')'
def getTable(self): return ''.join(imap(chr, self.lnotab))
def CONCAT(builder, *args): return '(', join(' || ', imap(builder, args)), ')'
def str2datetime(s): if 19 < len(s) < 26: s += '000000'[:26 - len(s)] s = s.replace('-', ' ').replace(':', ' ').replace('.', ' ').replace('T', ' ') return datetime(*imap(int, s.split()))
def str2datetime(s): if 19 < len(s) < 26: s += '000000'[:26-len(s)] s = s.replace('-', ' ').replace(':', ' ').replace('.', ' ').replace('T', ' ') return datetime(*imap(int, s.split()))
def ROW(builder, *items): return '(', join(', ', imap(builder, items)), ')'
def isbn13_checksum(digits): if len(digits) != 12: raise ValueError() reminder = sum(digit*coef for digit, coef in izip(imap(int, digits), (1, 3)*6)) % 10 return reminder and str(10 - reminder) or '0'
def CONCAT(builder, *args): return 'concat(', join(', ', imap(builder, args)), ')'
def __str__(self): insts = imap(str, self.insts) return "<block %s %d:\n%s>" % (self.label, self.bid, '\n'.join(insts))
def CONCAT(builder, *args): return '(', join(' || ', imap(builder, args)), ')'
def MAX(builder, *args): if len(args) == 0: assert False # pragma: no cover elif len(args) == 1: fname = 'MAX' else: fname = 'max' return fname, '(', join(', ', imap(builder, args)), ')'
def addNext(self, block): self.next.append(block) assert len(self.next) == 1, list(imap(str, self.next)) block.prev.append(self) assert len(block.prev) == 1, list(imap(str, block.prev))