File: database.py

package info (click to toggle)
python-sasync 0.7-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 288 kB
  • ctags: 515
  • sloc: python: 2,559; makefile: 27; sh: 9
file content (566 lines) | stat: -rw-r--r-- 21,066 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# sAsync:
# An enhancement to the SQLAlchemy package that provides persistent
# dictionaries, text indexing and searching, and an access broker for
# conveniently managing database access, table setup, and
# transactions. Everything is run in an asynchronous fashion using the Twisted
# framework and its deferred processing capabilities.
#
# Copyright (C) 2006-2007 by Edwin A. Suominen, http://www.eepatents.com
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the file COPYING for more details.
# 
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

"""
Asynchronous database transactions via SQLAlchemy.
"""

import sys
from twisted.internet import defer
from twisted.python import failure

import sqlalchemy as SA

######################################################################
# SA 0.4 support contributed by Ricky Iacovou,  based upon:
#
#   http://www.sqlalchemy.org/docs/04/intro.html#overview_migration
#
# Determine the version of SQLAlchemy used, 0.3 or 0.4, and set the
# Boolean variable "SA04" accordingly.
#
# We could also use a capability-based approach, like:
#
# try:
#     MetaData = SA.BoundMetaData
# except AttributeError:
#     MetaData = SA.MetaData
#
# However, late 0.3.x versions also supported some 0.4 constructs,
# so better use an explicit 0.3.x -> 0.4.x cutoff in order to avoid
# ambiguity.
######################################################################
_sv = SA.__version__.split ('.')
try:
    _v = int (_sv[0]) + (int(_sv[1]) / 10.0)
except:
    # Not strictly an Import Error, but close enough.
    raise ImportError("Failed to determine SQLAlchemy version: %s", _sv)
if _v >= 0.4:
    SA04 = True
else:
    SA04 = False
del _sv, _v
# End of version check


from asynqueue import ThreadQueue

import misc


class DatabaseError(Exception):
    """
    A problem occured when trying to access the database.
    """


def transact(f):
    """
    Use this function as a decorator to wrap the supplied method I{f} of
    L{AccessBroker} in a transaction that runs C{f(*args, **kw)} in its own
    transaction.

    Immediately returns an instance of L{twisted.internet.defer.Deferred} that
    will eventually have its callback called with the result of the
    transaction. Inspired by and largely copied from Valentino Volonghi's
    C{makeTransactWith} code.

    You can add the following keyword options to your function call:

    @keyword niceness: Scheduling niceness, an integer between -20 and 20,
      with lower numbers having higher scheduling priority as in UNIX C{nice}
      and C{renice}.

    @keyword doNext: Set C{True} to assign highest possible priority, even
      higher than with niceness = -20.                

    @keyword doLast: Set C{True} to assign lower possible priority, even
      lower than with niceness = 20.

    @keyword session: Set this option to C{True} to get a I{session} attribute
      for use within the transaction, which will be flushed at the end of the
      transaction.

    @type session: Boolean option, default C{False}

    @keyword ignore: Set this option to C{True} to have errors in the
      transaction function ignored and just do the rollback quietly.

    @type ignore: Boolean option, default C{False}
    
    """
    def substituteFunction(self, *args, **kw):
        """
        Puts the original function in the synchronous task queue and returns a
        deferred to its result when it is eventually run.

        This function will be given the same name as the original function so
        that it can be asked to masquerade as the original function. As a
        result, the threaded call to the original function that it makes inside
        its C{transaction} sub-function will be able to use the arguments for
        that original function. (The caller will actually be calling this
        substitute function, but it won't know that.)

        The original function should be a method of a L{AccessBroker} subclass
        instance, and the queue for that instance will be used to run it.
        """
        def transaction(usingSession, func, *t_args, **t_kw):
            """
            Everything making up a transaction, and everything run in the
            thread, is contained within this little function, including of
            course a call to C{func}.
            """
            if not usingSession:
                trans = self.connection.begin()
            if not hasattr(func, 'im_self'):
                t_args = (self,) + t_args
            try:
                result = func(*t_args, **t_kw)
            except Exception, e:
                if not usingSession:
                    trans.rollback()
                if not ignore:
                    raise e
            else:
                if usingSession:
                    self.session.flush()
                else:
                    trans.commit()
                return result
            return failure.Failure()

        def doTransaction(usingSession):
            """
            Queues up the transaction and immediately returns a deferred to
            its eventual result.
            """
            if isNested():
                return f(self, *args, **kw)
            return self.q.call(transaction, usingSession, f, *args, **kw)

        def started(null):
            self.ranStart = True
            del self._transactionStartupDeferred
            if useSession:
                d = self.getSession()
            else:
                d = self.connect()
            d.addCallback(lambda _: self.q.call(
                transaction, False, self.first, doNext=True))
            return d

        def isNested():
            frame = sys._getframe()
            while True:
                frame = frame.f_back
                if frame is None:
                    return False
                if frame.f_code == transaction.func_code:
                    return True

        ignore = kw.pop('ignore', False)
        useSession = kw.pop('session', False)
        if hasattr(self, 'connection') and getattr(self, 'ranStart', False):
            # We already have a connection, let's get right to the transaction
            if useSession:
                d = self.getSession()
                d.addCallback(lambda _: doTransaction(True))
            else:
                d = doTransaction(False)
        elif hasattr(self, '_transactionStartupDeferred') and \
             not self._transactionStartupDeferred.called:
            # Startup is in progress, make a new Deferred to the start of the
            # transaction and chain it to the startup Deferred.
            d = defer.Deferred()
            if useSession:
                d.addCallback(lambda _: self.getSession())
            d.addCallback(lambda _: doTransaction(useSession))
            self._transactionStartupDeferred.chainDeferred(d)
        else:
            # We need to start things up before doing this first transaction
            d = defer.maybeDeferred(self.startup)
            self._transactionStartupDeferred = d
            d.addCallback(started)
            d.addCallback(lambda _: doTransaction(useSession))
        # Return whatever Deferred we've got
        return d

    if f.func_name == 'first':
        return f
    substituteFunction.func_name = f.func_name
    return substituteFunction


class AccessBroker(object):
    """
    I manage asynchronous access to a database.

    Before you use any instance of me, you must specify the parameters for
    creating an SQLAlchemy database engine. A single argument is used, which
    specifies a connection to a database via an RFC-1738 url. In addition, the
    following keyword options can be employed, which are listed below with
    their default values.

    You can set an engine globally, for all instances of me via the
    L{sasync.engine} package-level function, or via my L{engine} class
    method. Alternatively, you can specify an engine for one particular
    instance by supplying the parameters to the constructor.
          
    SQLAlchemy has excellent documentation, which describes the engine
    parameters in plenty of detail. See
    U{http://www.sqlalchemy.org/docs/dbengine.myt}.

    @ivar dt: A property-generated reference to a deferred tracker that you can
      use to wait for database writes. See L{misc.DeferredTracker}.

    @ivar q: A property-generated reference to a threaded task queue that is
      dedicated to my database connection.

    @ivar connection: The current SQLAlchemy connection object, if
      any yet exists. Generated by my L{connect} method.
    
    """
    globalParams = ('', {})
    queues = {}
    
    def __init__(self, *url, **kw):
        """
        Constructs an instance of me, optionally specifying parameters for an
        SQLAlchemy engine object that serves this instance only.
        """
        self.selects = {}
        if url:
            self.engineParams = (url[0], kw)
        else:
            self.engineParams = self.globalParams
        self.running = False

    @classmethod
    def engine(cls, url, **kw):
        """
        Sets default connection parameters for all instances of me.
        """
        cls.globalParams = (url, kw)

    def _getDeferredTracker(self):
        """
        Returns an instance of L{misc.DeferredTracker} that is dedicated to the
        bound method's instance of me. Creates the deferred tracker the first
        time this method is called for a given instance of me.
        """
        if not hasattr(self, '_deferredTracker'):
            self._deferredTracker = misc.DeferredTracker()
        return self._deferredTracker
    dt = property(_getDeferredTracker)

    def _getQueue(self):
        """
        Returns a threaded task queue that is dedicated to my database
        connection. Creates the queue the first time the property is accessed.
        """
        def newQueue():
            queue = ThreadQueue(1)
            self.running = True
            self.queues[key] = queue
            return queue

        if hasattr(self, '_currentQueue'):
            return self._currentQueue
        url, kw = self.engineParams
        key = hash((url,) + tuple(kw.items()))
        if key in self.queues:
            queue = self.queues[key]
            if not queue.isRunning():
                queue = newQueue()
        else:
            queue = newQueue()
        self._currentQueue = queue
        return queue

    q = property(_getQueue, doc="""
    Accessing the 'q' attribute will always return a running queue object that
    is dedicated to this instance's connection parameters
    """)

    def connect(self, forceNew=False):
        """
        Generates and returns a singleton connection object.
        """
        def getEngine():
            if hasattr(self, '_dEngine'):
                d = defer.Deferred()
                d.addCallback(lambda _: getConnection())
                self._dEngine.chainDeferred(d)
            else:
                d = self._dEngine = \
                    self.q.call(createEngine, doNext=True)
                d.addCallback(gotEngine)
            return d

        def createEngine():
            url, kw = self.engineParams
            # The 'threadlocal' keyword value is unchanged from SA 0.3 to 0.4
            kw['strategy'] = 'threadlocal'
            return SA.create_engine(url, **kw)
        
        def gotEngine(engine):
            del self._dEngine
            self._engine = engine
            return getConnection()

        def getConnection():
            if not forceNew and hasattr(self, 'connection'):
                d = defer.succeed(self.connection)
            elif not forceNew and hasattr(self, '_dConnect'):
                d = defer.Deferred().addCallback(lambda _: self.connection)
                self._dConnect.chainDeferred(d)
            else:
                d = self._dConnect = \
                    self.q.call(self._engine.contextual_connect, doNext=True)
                d.addCallback(gotConnection)
            return d

        def gotConnection(connection):
            if hasattr(self, '_dConnect'):
                del self._dConnect
            self.connection = connection
            return connection

        # After all these function definitions, the method begins here
        if hasattr(self, '_engine'):
            return getConnection()
        else:
            return getEngine()

    def _sessionClose(self):
        """
        Replacement C{close} method for session objects.
        """
        self.isActive = False
        return self.session._close()

    def getSession(self):
        """
        Get a commitable session object
        """
        def gotConnection(connection):
            if SA04:
                d = self.q.call(
                    SA.orm.create_session, bind=connection, doNext=True)
            else:
                d = self.q.call(
                    SA.create_session, bind_to=connection, doNext=True)
            d.addCallback(gotSession)
            return d

        def gotSession(session):
            session.isActive = True
            session._close = session.close
            session.close = self._sessionClose
            self.session = session
            return session

        if hasattr(self, 'session') and self.session.isActive:
            return defer.succeed(self.session)
        return self.connect(forceNew=True).addCallback(gotConnection)
    
    def table(self, name, *cols, **kw):
        """
        Instantiates a new table object, creating it in the transaction thread
        as needed.

        One or more indexes other than the primary key can be defined
        via a keyword prefixed with I{index_} or I{unique_} and having
        the index name as the suffix. Use the I{unique_} prefix if the
        index is to be a unique one. The value of the keyword is a
        list or tuple containing the names of all columns in the
        index.
        """
        def _table():
            if not hasattr(self, '_meta'):
                if SA04:
                    self._meta = SA.MetaData(self._engine)
                else:
                    self._meta = SA.BoundMetaData(self._engine)
            indexes = {}
            for key in kw.keys():
                if key.startswith('index_'):
                    unique = False
                elif key.startswith('unique_'):
                    unique = True
                else:
                    continue
                indexes[key] = kw.pop(key), unique
            kw.setdefault('useexisting', True)
            table = SA.Table(name, self._meta, *cols, **kw)
            table.create(checkfirst=True)
            setattr(self, name, table)
            return table, indexes

        def _index(tableInfo):
            table, indexes = tableInfo
            for key, info in indexes.iteritems():
                kwIndex = {'unique':info[1]}
                try:
                    # This is stupid. Why can't I see if the index
                    # already exists and only create it if needed?
                    index = SA.Index(key, *[
                        getattr(table.c, x) for x in info[0]
                        ], **kwIndex)
                    index.create()
                except:
                    pass
        
        if hasattr(self, name):
            d = defer.succeed(False)
        else:
            d = self.connect()
            d.addCallback(lambda _: self.q.call(_table, doNext=True))
            d.addCallback(lambda x: self.q.call(_index, x, doNext=True))
        return d
    
    def startup(self):
        """
        This method runs before the first transaction to start my synchronous
        task queue. B{Override it} to get whatever pre-transaction stuff you
        have run.

        Alternatively, with legacy support for the old API, your
        pre-transaction code can reside in a L{userStartup} method of your
        subclass.
        """
        userStartup = getattr(self, 'userStartup', None)
        if callable(userStartup):
            return defer.maybeDeferred(userStartup)

    def userStartup(self):
        """
        If this method is defined and L{startup} is not overridden in your
        subclass, however, this method will be run as the first callback in the
        deferred processing chain, after my synchronous task queue is safely
        underway.

        The method should return either an immediate result or a deferred to
        an eventual result.

        B{Deprecated}: Instead of defining this method, your subclass should
        simply override L{startup} with your custom startup stuff.

        """

    def first(self):
        """
        This method automatically runs as the first transaction after
        completion of L{startup} (or L{userStartup}). B{Override it} to define
        table contents or whatever else you want as a first transaction that
        immediately follows your pre-transaction stuff.

        You don't need to decorate the method with C{@transact}, but it doesn't
        break anything if you do.
        """

    def shutdown(self, *null):
        """
        Shuts down my database transaction functionality and threaded task
        queue, returning a deferred that fires when all queued tasks are
        done and the shutdown is complete.
        """
        def finalTask():
            if hasattr(self, 'connection'):
                self.connection.close()
            self.running = False

        if self.running:
            d = self.q.call(finalTask)
            d.addBoth(lambda _: self.q.shutdown())
        else:
            d = defer.succeed(None)
        if hasattr(self, '_deferredTracker'):
            d.addCallback(lambda _: self._deferredTracker.deferToAll())
        return d
    
    def s(self, *args, **kw):
        """
        Polymorphic method for working with C{select} instances within a cached
        selection subcontext.

            - When called with a single argument (the select object's name as a
              string) and no keywords, this method indicates if the named
              select object already exists and sets its selection subcontext to
              I{name}.
            
            - With multiple arguments or any keywords, the method acts like a
              call to C{sqlalchemy.select(...).compile()}, except that nothing
              is returned. Instead, the resulting select object is stored in
              the current selection subcontext.
            
            - With no arguments or keywords, the method returns the select
              object for the current selection subcontext.
              
        """
        if kw or (len(args) > 1):
            # It's a compilation.
            context = getattr(self, 'context', None)
            self.selects[context] = SA.select(*args, **kw).compile()
        elif len(args) == 1:
            # It's a lookup to see if the select has been previously
            # seen and compiled; return True or False.
            self.context = args[0]
            return self.context in self.selects
        else:
            # It's a retrieval of a compiled selection object, keyed off
            # the most recently mentioned context.
            context = getattr(self, 'context', None)
            return self.selects.get(context)

    def queryToList(self, **kw):
        """
        Executes my current select object with the bind parameters supplied as
        keywords, returning a list containing the first element of each row in
        the result.
        """
        rows = self.s().execute(**kw).fetchall()
        if rows is None:
            return []
        return [row[0] for row in rows]

    def deferToQueue(self, func, *args, **kw):
        """
        Dispatches I{callable(*args, **kw)} as a task via the like-named method
        of my synchronous queue, returning a deferred to its eventual result.

        Scheduling of the task is impacted by the I{niceness} keyword that can
        be included in I{**kw}. As with UNIX niceness, the value should be an
        integer where 0 is normal scheduling, negative numbers are higher
        priority, and positive numbers are lower priority.
        
        @keyword niceness: Scheduling niceness, an integer between -20 and 20,
            with lower numbers having higher scheduling priority as in UNIX
            C{nice} and C{renice}.
        
        """
        return self.q.call(func, *args, **kw)


__all__ = ['transact', 'AccessBroker', 'SA']