Package web2py :: Package gluon :: Module dal :: Class DAL
[hide private]
[frames] | no frames]

Class DAL

source code

object --+
         |
        DAL

an instance of this class represents a database connection

Example:
  db = DAL('sqlite://test.db')
  db.define_table('tablename', Field('fieldname1'),
                               Field('fieldname2'))


Nested Classes [hide private]
  Field
  Table
an instance of this class represents a database table
Instance Methods [hide private]
 
__init__(self, uri='sqlite://dummy.db', pool_size=0, folder=threading.local(), db_codec='UTF-8', check_reserved=threading.local(), migrate=True, fake_migrate=True, migrate_enabled=True, fake_migrate_all=True, decode_credentials=True, driver_args=threading.local(), adapter_args=threading.local(), attempts=5, auto_import=True, bigint_id=True, debug=True, lazy_tables=True, db_uid=threading.local(), do_connect=True)
Creates a new Database Abstraction Layer instance.
source code
 
import_table_definitions(self, path, migrate=True, fake_migrate=True) source code
 
check_reserved_keyword(self, name)
Validates ``name`` against SQL keywords Uses self.check_reserve which is a list of operators to use.
source code
 
parse_as_rest(self, patterns, args, vars, queries=threading.local(), nested_select=True)
EXAMPLE:...
source code
 
define_table(self, tablename, *fields, **args) source code
 
lazy_define_table(self, tablename, *fields, **args) source code
 
__contains__(self, tablename) source code
 
has_key(self, tablename) source code
 
get(self, key, default=threading.local()) source code
 
__iter__(self) source code
 
__getitem__(self, key) source code
 
__getattr__(self, key) source code
 
__setitem__(self, key, value) source code
 
__setattr__(self, key, value)
x.__setattr__('name', value) <==> x.name = value
source code
 
__delitem__(...)
x.__delattr__('name') <==> del x.name
 
__repr__(self)
repr(x)
source code
 
smart_query(self, fields, text) source code
 
__call__(self, query=threading.local(), ignore_common_filters=threading.local()) source code
 
commit(self) source code
 
rollback(self) source code
 
close(self) source code
 
executesql(self, query, placeholders=threading.local(), as_dict=True, fields=threading.local(), colnames=threading.local())
placeholders is optional and will always be None.
source code
 
_remove_references_to(self, thistable) source code
 
export_to_csv_file(self, ofile, *args, **kwargs) source code
 
import_from_csv_file(self, ifile, id_map=threading.local(), null='<NULL>', unique='uuid', *args, **kwargs) source code

Inherited from object: __delattr__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __str__

Static Methods [hide private]
 
__new__(cls, uri='sqlite://dummy.db', *args, **kwargs)
Returns: a new object with type S, a subtype of T
source code
 
set_folder(folder)
# ## this allows gluon to set a folder for this thread # ## <<<<<<<<< Should go away as new DAL replaces old sql.py
source code
 
get_instances()
Returns a dictionary with uri as key with timings and defined tables...
source code
 
distributed_transaction_begin(*instances) source code
 
distributed_transaction_commit(*instances) source code
Properties [hide private]
  tables

Inherited from object: __class__

Method Details [hide private]

__new__(cls, uri='sqlite://dummy.db', *args, **kwargs)
Static Method

source code 
Returns:
a new object with type S, a subtype of T

Overrides: object.__new__
(inherited documentation)

get_instances()
Static Method

source code 

Returns a dictionary with uri as key with timings and defined tables
{'sqlite://storage.sqlite': {
    'dbstats': [(select auth_user.email from auth_user, 0.02009)],
    'dbtables': {
        'defined': ['auth_cas', 'auth_event', 'auth_group',
            'auth_membership', 'auth_permission', 'auth_user'],
        'lazy': '[]'
        }
    }
}

__init__(self, uri='sqlite://dummy.db', pool_size=0, folder=threading.local(), db_codec='UTF-8', check_reserved=threading.local(), migrate=True, fake_migrate=True, migrate_enabled=True, fake_migrate_all=True, decode_credentials=True, driver_args=threading.local(), adapter_args=threading.local(), attempts=5, auto_import=True, bigint_id=True, debug=True, lazy_tables=True, db_uid=threading.local(), do_connect=True)
(Constructor)

source code 

Creates a new Database Abstraction Layer instance.

Keyword arguments:

:uri: string that contains information for connecting to a database.
       (default: 'sqlite://dummy.db')
:pool_size: How many open connections to make to the database object.
:folder: <please update me>
:db_codec: string encoding of the database (default: 'UTF-8')
:check_reserved: list of adapters to check tablenames and column names
                 against sql reserved keywords. (Default None)

* 'common' List of sql keywords that are common to all database types
        such as "SELECT, INSERT". (recommended)
* 'all' Checks against all known SQL keywords. (not recommended)
        <adaptername> Checks against the specific adapters list of keywords
        (recommended)
* '<adaptername>_nonreserved' Checks against the specific adapters
        list of nonreserved keywords. (if available)
:migrate (defaults to True) sets default migrate behavior for all tables
:fake_migrate (defaults to False) sets default fake_migrate behavior for all tables
:migrate_enabled (defaults to True). If set to False disables ALL migrations
:fake_migrate_all (defaults to False). If sets to True fake migrates ALL tables
:attempts (defaults to 5). Number of times to attempt connecting

Overrides: object.__init__

check_reserved_keyword(self, name)

source code 
Validates ``name`` against SQL keywords Uses self.check_reserve which is a list of operators to use. self.check_reserved ['common', 'postgres', 'mysql'] self.check_reserved ['all']

parse_as_rest(self, patterns, args, vars, queries=threading.local(), nested_select=True)

source code 

        EXAMPLE:

db.define_table('person',Field('name'),Field('info'))
db.define_table('pet',Field('owner',db.person),Field('name'),Field('info'))

@request.restful()
def index():
    def GET(*args,**vars):
        patterns = [
            "/friends[person]",
            "/{friend.name.startswith}",
            "/{friend.name}/:field",
            "/{friend.name}/pets[pet.owner]",
            "/{friend.name}/pet[pet.owner]/{pet.name}",
            "/{friend.name}/pet[pet.owner]/{pet.name}/:field"
            ]
        parser = db.parse_as_rest(patterns,args,vars)
        if parser.status == 200:
            return dict(content=parser.response)
        else:
            raise HTTP(parser.status,parser.error)
    def POST(table_name,**vars):
        if table_name == 'person':
            return db.person.validate_and_insert(**vars)
        elif table_name == 'pet':
            return db.pet.validate_and_insert(**vars)
        else:
            raise HTTP(400)
    return locals()
        

__setattr__(self, key, value)

source code 
x.__setattr__('name', value) <==> x.name = value
Overrides: object.__setattr__
(inherited documentation)

__repr__(self)
(Representation operator)

source code 
repr(x)
Overrides: object.__repr__
(inherited documentation)

executesql(self, query, placeholders=threading.local(), as_dict=True, fields=threading.local(), colnames=threading.local())

source code 

placeholders is optional and will always be None. If using raw SQL with placeholders, placeholders may be a sequence of values to be substituted in or, (if supported by the DB driver), a dictionary with keys matching named placeholders in your SQL.

Added 2009-12-05 "as_dict" optional argument. Will always be None when using DAL. If using raw SQL can be set to True and the results cursor returned by the DB driver will be converted to a sequence of dictionaries keyed with the db field names. Tested with SQLite but should work with any database since the cursor.description used to get field names is part of the Python dbi 2.0 specs. Results returned with as_dict=True are the same as those returned when applying .to_list() to a DAL query.

[{field1: value1, field2: value2}, {field1: value1b, field2: value2b}]

Added 2012-08-24 "fields" and "colnames" optional arguments. If either is provided, the results cursor returned by the DB driver will be converted to a DAL Rows object using the db._adapter.parse() method.

The "fields" argument is a list of DAL Field objects that match the fields returned from the DB. The Field objects should be part of one or more Table objects defined on the DAL object. The "fields" list can include one or more DAL Table objects in addition to or instead of including Field objects, or it can be just a single table (not in a list). In that case, the Field objects will be extracted from the table(s).

Instead of specifying the "fields" argument, the "colnames" argument can be specified as a list of field names in tablename.fieldname format. Again, these should represent tables and fields defined on the DAL object.

It is also possible to specify both "fields" and the associated "colnames". In that case, "fields" can also include DAL Expression objects in addition to Field objects. For Field objects in "fields", the associated "colnames" must still be in tablename.fieldname format. For Expression objects in "fields", the associated "colnames" can be any arbitrary labels.

Note, the DAL Table objects referred to by "fields" or "colnames" can be dummy tables and do not have to represent any real tables in the database. Also, note that the "fields" and "colnames" must be in the same order as the fields in the results cursor returned from the DB.

Property Details [hide private]

tables

Get Method:
unreachable.tables(self)
Set Method:
threading.local()
Delete Method:
threading.local()