home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_1432 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  12.0 KB  |  353 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. __license__ = 'GPL v3'
  6. __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
  7. __docformat__ = 'restructuredtext en'
  8. import sqlite3 as sqlite
  9. import traceback
  10. import time
  11. import uuid
  12. from sqlite3 import IntegrityError, OperationalError
  13. from threading import Thread
  14. from Queue import Queue
  15. from threading import RLock
  16. from datetime import datetime
  17. from functools import partial
  18. from calibre.ebooks.metadata import title_sort, author_to_author_sort
  19. from calibre.utils.config import tweaks
  20. from calibre.utils.date import parse_date, isoformat
  21. from calibre import isbytestring
  22. global_lock = RLock()
  23.  
  24. def convert_timestamp(val):
  25.     if val:
  26.         return parse_date(val, as_utc = False)
  27.  
  28.  
  29. def adapt_datetime(dt):
  30.     return isoformat(dt, sep = ' ')
  31.  
  32. sqlite.register_adapter(datetime, adapt_datetime)
  33. sqlite.register_converter('timestamp', convert_timestamp)
  34.  
  35. def convert_bool(val):
  36.     return bool(int(val))
  37.  
  38. sqlite.register_adapter(bool, (lambda x: if x:
  39. 10))
  40. sqlite.register_converter('bool', convert_bool)
  41.  
  42. class DynamicFilter(object):
  43.     
  44.     def __init__(self, name):
  45.         self.name = name
  46.         self.ids = frozenset([])
  47.  
  48.     
  49.     def __call__(self, id_):
  50.         return int(id_ in self.ids)
  51.  
  52.     
  53.     def change(self, ids):
  54.         self.ids = frozenset(ids)
  55.  
  56.  
  57.  
  58. class Concatenate(object):
  59.     
  60.     def __init__(self, sep = ','):
  61.         self.sep = sep
  62.         self.ans = []
  63.  
  64.     
  65.     def step(self, value):
  66.         if value is not None:
  67.             self.ans.append(value)
  68.         
  69.  
  70.     
  71.     def finalize(self):
  72.         if not self.ans:
  73.             return None
  74.         return self.sep.join(self.ans)
  75.  
  76.  
  77.  
  78. class SortedConcatenate(object):
  79.     sep = ','
  80.     
  81.     def __init__(self):
  82.         self.ans = { }
  83.  
  84.     
  85.     def step(self, ndx, value):
  86.         if value is not None:
  87.             self.ans[ndx] = value
  88.         
  89.  
  90.     
  91.     def finalize(self):
  92.         if len(self.ans) == 0:
  93.             return None
  94.         return self.sep.join(map(self.ans.get, sorted(self.ans.keys())))
  95.  
  96.  
  97.  
  98. class SafeSortedConcatenate(SortedConcatenate):
  99.     sep = '|'
  100.  
  101.  
  102. class Connection(sqlite.Connection):
  103.     
  104.     def get(self, *args, **kw):
  105.         ans = self.execute(*args)
  106.         if not kw.get('all', True):
  107.             ans = ans.fetchone()
  108.             if not ans:
  109.                 ans = [
  110.                     None]
  111.             
  112.             return ans[0]
  113.         return ans.fetchall()
  114.  
  115.  
  116.  
  117. def _author_to_author_sort(x):
  118.     if not x:
  119.         return ''
  120.     return author_to_author_sort(x.replace('|', ','))
  121.  
  122.  
  123. def pynocase(one, two, encoding = 'utf-8'):
  124.     if isbytestring(one):
  125.         
  126.         try:
  127.             one = one.decode(encoding, 'replace')
  128.  
  129.     
  130.     if isbytestring(two):
  131.         
  132.         try:
  133.             two = two.decode(encoding, 'replace')
  134.  
  135.     
  136.     return cmp(one.lower(), two.lower())
  137.  
  138.  
  139. class DBThread(Thread):
  140.     CLOSE = '-------close---------'
  141.     
  142.     def __init__(self, path, row_factory):
  143.         Thread.__init__(self)
  144.         self.setDaemon(True)
  145.         self.path = path
  146.         self.unhandled_error = (None, '')
  147.         self.row_factory = row_factory
  148.         self.requests = Queue(1)
  149.         self.results = Queue(1)
  150.         self.conn = None
  151.  
  152.     
  153.     def connect(self):
  154.         self.conn = sqlite.connect(self.path, factory = Connection, detect_types = sqlite.PARSE_DECLTYPES | sqlite.PARSE_COLNAMES)
  155.         encoding = self.conn.execute('pragma encoding').fetchone()[0]
  156.         self.conn.row_factory = None if self.row_factory else (lambda cursor, row: list(row))
  157.         self.conn.create_aggregate('concat', 1, Concatenate)
  158.         self.conn.create_aggregate('sortconcat', 2, SortedConcatenate)
  159.         self.conn.create_aggregate('sort_concat', 2, SafeSortedConcatenate)
  160.         self.conn.create_collation('PYNOCASE', partial(pynocase, encoding = encoding))
  161.         if tweaks['title_series_sorting'] == 'strictly_alphabetic':
  162.             self.conn.create_function('title_sort', 1, (lambda x: x))
  163.         else:
  164.             self.conn.create_function('title_sort', 1, title_sort)
  165.         self.conn.create_function('author_to_author_sort', 1, _author_to_author_sort)
  166.         self.conn.create_function('uuid4', 0, (lambda : str(uuid.uuid4())))
  167.         self.conn.create_function('books_list_filter', 1, (lambda x: 1))
  168.  
  169.     
  170.     def run(self):
  171.         
  172.         try:
  173.             self.connect()
  174.             while True:
  175.                 (func, args, kwargs) = self.requests.get()
  176.                 if func == self.CLOSE:
  177.                     self.conn.close()
  178.                     break
  179.                 
  180.                 if func == 'dump':
  181.                     
  182.                     try:
  183.                         ok = True
  184.                         res = tuple(self.conn.iterdump())
  185.                     except Exception:
  186.                         err = None
  187.                         ok = False
  188.                         res = (err, traceback.format_exc())
  189.                     except:
  190.                         None<EXCEPTION MATCH>Exception
  191.                     
  192.  
  193.                 None<EXCEPTION MATCH>Exception
  194.                 if func == 'create_dynamic_filter':
  195.                     
  196.                     try:
  197.                         f = DynamicFilter(args[0])
  198.                         self.conn.create_function(args[0], 1, f)
  199.                         ok = True
  200.                         res = f
  201.                     except Exception:
  202.                         err = None
  203.                         ok = False
  204.                         res = (err, traceback.format_exc())
  205.                     except:
  206.                         None<EXCEPTION MATCH>Exception
  207.                     
  208.  
  209.                 None<EXCEPTION MATCH>Exception
  210.                 func = getattr(self.conn, func)
  211.                 
  212.                 try:
  213.                     for i in range(3):
  214.                         
  215.                         try:
  216.                             ok = True
  217.                             res = func(*args, **kwargs)
  218.                         except OperationalError:
  219.                             err = None
  220.                             if 'unable to open' not in str(err) or i == 2:
  221.                                 raise 
  222.                             i == 2
  223.                             traceback.print_exc()
  224.  
  225.                         time.sleep(0.5)
  226.                 except Exception:
  227.                     err = None
  228.                     ok = False
  229.                     res = (err, traceback.format_exc())
  230.  
  231.                 self.results.put((ok, res))
  232.         except Exception:
  233.             err = None
  234.             self.unhandled_error = (err, traceback.format_exc())
  235.  
  236.  
  237.  
  238.  
  239. class DatabaseException(Exception):
  240.     
  241.     def __init__(self, err, tb):
  242.         tb = '\n\t'.join(('\tRemote' + tb).splitlines())
  243.         msg = unicode(err) + '\n' + tb
  244.         Exception.__init__(self, msg)
  245.         self.orig_err = err
  246.         self.orig_tb = tb
  247.  
  248.  
  249.  
  250. def proxy(fn):
  251.     
  252.     def run(self, *args, **kwargs):
  253.         if self.closed:
  254.             raise DatabaseException('Connection closed', '')
  255.         self.closed
  256.         global_lock.__enter__()
  257.         
  258.         try:
  259.             if self.proxy.unhandled_error[0] is not None:
  260.                 raise DatabaseException(*self.proxy.unhandled_error)
  261.             self.proxy.unhandled_error[0] is not None
  262.             self.proxy.requests.put((fn.__name__, args, kwargs))
  263.             (ok, res) = self.proxy.results.get()
  264.             if not ok:
  265.                 if isinstance(res[0], IntegrityError):
  266.                     raise IntegrityError(unicode(res[0]))
  267.                 isinstance(res[0], IntegrityError)
  268.                 raise DatabaseException(*res)
  269.             ok
  270.             return res
  271.         finally:
  272.             pass
  273.  
  274.  
  275.     return run
  276.  
  277.  
  278. class ConnectionProxy(object):
  279.     
  280.     def __init__(self, proxy):
  281.         self.proxy = proxy
  282.         self.closed = False
  283.  
  284.     
  285.     def close(self):
  286.         if self.proxy.unhandled_error[0] is None:
  287.             self.proxy.requests.put((self.proxy.CLOSE, [], { }))
  288.             self.closed = True
  289.         
  290.  
  291.     
  292.     def get(self, query, all = True):
  293.         pass
  294.  
  295.     get = proxy(get)
  296.     
  297.     def commit(self):
  298.         pass
  299.  
  300.     commit = proxy(commit)
  301.     
  302.     def execute(self):
  303.         pass
  304.  
  305.     execute = proxy(execute)
  306.     
  307.     def executemany(self):
  308.         pass
  309.  
  310.     executemany = proxy(executemany)
  311.     
  312.     def executescript(self):
  313.         pass
  314.  
  315.     executescript = proxy(executescript)
  316.     
  317.     def create_aggregate(self):
  318.         pass
  319.  
  320.     create_aggregate = proxy(create_aggregate)
  321.     
  322.     def create_function(self):
  323.         pass
  324.  
  325.     create_function = proxy(create_function)
  326.     
  327.     def cursor(self):
  328.         pass
  329.  
  330.     cursor = proxy(cursor)
  331.     
  332.     def dump(self):
  333.         pass
  334.  
  335.     dump = proxy(dump)
  336.     
  337.     def create_dynamic_filter(self):
  338.         pass
  339.  
  340.     create_dynamic_filter = proxy(create_dynamic_filter)
  341.  
  342.  
  343. def connect(dbpath, row_factory = None):
  344.     conn = ConnectionProxy(DBThread(dbpath, row_factory))
  345.     conn.proxy.start()
  346.     while conn.proxy.unhandled_error[0] is None and conn.proxy.conn is None:
  347.         time.sleep(0.01)
  348.     if conn.proxy.unhandled_error[0] is not None:
  349.         raise DatabaseException(*conn.proxy.unhandled_error)
  350.     conn.proxy.unhandled_error[0] is not None
  351.     return conn
  352.  
  353.