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