createdb
index
../createdb.py

This module includes:
 
A set of functions that create the database needed for this project.
 
 1- All table's names must be compound by singular words.
    Right: scheduled_task
    Wrong: scheduled_tasks
 2- All tables' names lowercase, underscore separating words.
 3- All columns from a table must follow these guidelines:
    i.   xxx_column_name where xxx stands for an identification for the
         table: if the table name has only one word, the first three
         letters. if the table name has two words, the first two from the
         first word and the the first one from the second word. If a table
         has three words in its name, the first letter from each word. If a
         table has four words, think a better name.
    ii.  If the column is a primary key, then its name must be xxx_id
    iii. If the column is a date, then its name must be xxx_<action>_dt
         (where <action> represents what's this date use for, e.g.: last
         modification date should be xxx_modification_dt).
   iv.   If the column is a foreign key it must be xxx_<referenced_column>
         where <referenced_column> is the name of the column we want to
         enforce (e.g. task.tas_id would be scheduled_task.sct_tas_id)
         Because of no enforced foreign key control in sqlite we are using
         triggers to keep it error prone.
 
SQLConnection: a mini ORM to abstract the commonest queries and handle
               several regular database actions: connect, commit, rollback,
               etc.

 
Modules
       
gettext
os
cPickle
sqlite3
types

 
Classes
       
__builtin__.object
CommonProperty
SQLConnection
exceptions.Exception(exceptions.BaseException)
SQLError

 
class CommonProperty(__builtin__.object)
    Ref. Python CookBook 2d ed., by Alex Martelli, Anna Martelli
Ravenscroft and David Ascher (O'Reilly Media, 2005) 0-596-00797-3
Recipe 20.5 by Raymond Hettinger, page 752
 
  Methods defined here:
__delete__(self, obj)
__get__(self, obj, objtype=None)
__init__(self, realname, fget=<built-in function getattr>, fset=<built-in function setattr>, fdel=<built-in function delattr>, doc=None)
__set__(self, obj, value)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class SQLConnection(__builtin__.object)
    Base clase for handling connections with the database
 
  Methods defined here:
__init__(self, timeout_=5)
Returns connection and cursor objects
commit(self)
Commit the transaction
delete(self, cls, deletedCriteria=None, commit=True)
Deletes tuples from a table that match certain criteria.
 
Parameters:
    cls: calling object. The class' object needs a __table__ and a
         __pk__ attributes stating the table's name and the primary
        key's column(s)' name(s). In case it's a composity a tuple
        should be sent.
    deletedCriteria: if its a single value, will match the __pk__
            attribute for the class. If its a dict it will containe
            the the column=filter criteria that will be concatenated
            with "and".
            Additional tips:
            1- If you need to specify a more complex criteria
            (e.g. with "or") use the word 'SQL' as key and
            write the exact 'where' filter you need. SQL will
            be append to the rest of the filters with an
            'and' unless it's the only one filter.
            2- If you want to use a "like" expression the
            value will be scannned to find a % token.
            3- To pass a "is null" criteria, use None as the
            key's value.
            4- To pass a "is not null" criteria, use '!None'
            as the key's value.
            5- If "filter" is a tuple or list it will be use
            to construct an "in (tuple)" filter.
            6- If deletedCriteria is None all table will be
            deleted.
    commit: indicates if the statement should be committed or not.
            Default Yes
disconnects(self)
Closes the database connection
find(self, cls, selectColumns=None, filterCriteria=None, returnAsInstance=False)
Find the results in a table given by cls.__table__ and return
a list of dicts with the object's attributes that fullfill
filterCriteria.
 
Parameters:
    cls: object to query
    selectColumns: the columns the query must return. If it's a
                   tuple it will return these columns as if.
                   If it's a dictionary it will use the key for the
                   column and the value as the column's alias.
                   If None it will execute a "select * ..."
    filterCriteria: a dict containing the the column=filter criteria
                    that will be concatenated with "and".
                    Additional tips:
                    1- If you need to specify a more complex criteria
                    (e.g. with "or") use the word 'SQL' as key and
                    write the exact 'where' filter you need. SQL will
                    be append to the rest of the filters with an
                    'and' unless it's the only one filter.
                    2- If you want to use a "like" expression the
                    value will be scannned to find a % token.
                    3- To pass a "is null" criteria, use None as the
                    key's value.
                    4- To pass a "is not null" criteria, use '!None'
                    as the key's value.
                    5- If "filter" is a tuple or list it will be use
                    to construct an "in (tuple)" filter.
                    6- If filterCriteria is None all table will be
                    retrieved.
    returnAsInstance: in certain cases user will want to retrieve a
                      list of live objects: if this parameter is True
                      will call the cls.__init__ for every tuple
                      returned by the database. Default to False.
get(self, cls, pk_id, **kwargs)
Retrieves information from a table using the primary key. It
should always retrieve just one row (duh!).
If no information is found a SQLError will be raised.
 
Parameters:
    cls: calling object. The class' object needs a __table__ and a
         __pk__ attributes stating the table's name and the primary
        key's column(s)' name(s). In case it's a composity a tuple
        should be sent.
    pk_id: the primary key's value we'll use to query.
    kwargs: a "column name":"alias" to use for the query. If no
            value is provided it will execute a "select * from ...".
            Otherwise, just the columns listed will be retrieved.
            Example:
                kwargs = 'tas_from'='from', 'tas_max'='max'
                will be turned into
                select tas_from as from, tas_max as max from ...
insert(self, cls, values, constraint_action, commit=True)
Inserts a new value in the database. Returns the primary key value
in case the queried class defines one.
 
Parameters:
    cls: calling object. The class' object needs a __table__ and a
         __pk__ attributes stating the table's name and the primary
        key's column(s)' name(s). In case it's a composity a tuple
        should be sent.
    values: a "column name":"inserted value" dict to use for the
            query.
            Example:
                values = {'tas_from':u'/tmp',
                'tas_add_date'='2008-03-20 12:34:56.0'}
                will be turned into
                insert into __table__ (tas_from, tas_add_date)
                values (u'/tmp', '2008-03-20 12:34:56.0')
    if "values" is a list of dicts (following the up supra rules)
    it will perform a bulk execute (à la executemany)
    constraint_action: what action the system must apply in case
                       of contraint violation. The possible values
                       are the ones supported by the SQL engine:
                       ABORT, REPLACE, IGNORE, ROLLBACK, FAIL.
    commit: indicates if the statement should be committed or not.
            Default Yes
rollback(self)
Rollback the transaction
update(self, cls, updatedValue, updatedCriteria, commit=True)
Updates a table.
   In case updatedValue and updatedCriteria are lists (of dicts)
   will execute a bulk update (à la executemany). If they're dicts
   will execute just one update (see respective parameter docs for
   more on this).
   In case it's a bulk update both updatedCriteria and updatedValue
   must be a list of dicts.
 
Parameters:
    cls: calling object. The class' object needs a __table__ and a
         __pk__ attributes stating the table's name and the primary
        key's column(s)' name(s). In case it's a composity a tuple
        should be sent.
    updatedValue: a "column name":"update value" dict to use for the
            query.
            Example:
                values = {'tas_from'=u'/tmp',
                'tas_add_date'='2008-03-20 12:34:56.0'}
                will be turned into
                update __table__ set tas_from=u'/tmp',
                tas_add_date='2008-03-20 12:34:56.0'
                where ...
    updatedCriteria: if its a single value, will match the __pk__
            attribute for the class. If its a dict it will containe
            the the column=filter criteria that will be concatenated
            with "and".
            Additional tips:
            1- If you need to specify a more complex criteria
            (e.g. with "or") use the word 'SQL' as key and
            write the exact 'where' filter you need. SQL will
            be append to the rest of the filters with an
            'and' unless it's the only one filter.
            2- If you want to use a "like" expression the
            value will be scannned to find a % token.
            3- To pass a "is null" criteria, use None as the
            key's value.
            4- To pass a "is not null" criteria, use '!None'
            as the key's value.
            5- If "filter" is a tuple or list it will be use
            to construct an "in (tuple)" filter.
            6- If updatedCriteria is None all table will be
            updated.
    commit: indicates if the statement should be committed or not.
            Default Yes

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class SQLError(exceptions.Exception)
    A generic error class for Database Errors
 
 
Method resolution order:
SQLError
exceptions.Exception
exceptions.BaseException
__builtin__.object

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Methods inherited from exceptions.Exception:
__init__(...)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Data and other attributes inherited from exceptions.Exception:
__new__ = <built-in method __new__ of type object at 0x8141680>
T.__new__(S, ...) -> a new object with type S, a subtype of T

Methods inherited from exceptions.BaseException:
__delattr__(...)
x.__delattr__('name') <==> del x.name
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__reduce__(...)
__repr__(...)
x.__repr__() <==> repr(x)
__setattr__(...)
x.__setattr__('name', value) <==> x.name = value
__setstate__(...)
__str__(...)
x.__str__() <==> str(x)

Data descriptors inherited from exceptions.BaseException:
__dict__
args
message
exception message

 
Functions
       
createdb(haltOnErrors=True, alwaysDrop=True)
Calling this function will create the database.
Parameters:
    haltOnErrors: boolean. If True, whenever we hit an error the
    def will inform this and stop. If False, it will inform the error
    but keep on with the next statement. This is can be useful if you
    try to create a db that already exists but you might want to add
    missing tables. This flag applies to errors in tables's creation.
    It can't do nothing about missing permissions, e.g. trying to create
    the db in a forbidden place, etc
    alwaysDrop: boolean. If True, in case of '...already exists' error,
    the function will drop the object and retry to create. If False,
    whatever is set in HaltOnError will happen.

 
Data
        __all__ = ['SQLError', 'CommonProperty', 'SQLConnection', 'createdb']