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')

  or

  db = DAL(**{"uri": ..., "tables": [...]...}) # experimental

  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=None, db_codec='UTF-8', check_reserved=None, migrate=True, fake_migrate=False, migrate_enabled=True, fake_migrate_all=False, decode_credentials=False, driver_args=None, adapter_args=None, attempts=5, auto_import=False, bigint_id=False, debug=False, lazy_tables=False, db_uid=None, do_connect=True, after_connection=None, tables=None, ignore_field_case=True, entity_quoting=False)
Creates a new Database Abstraction Layer instance.
source code
 
import_table_definitions(self, path, migrate=False, fake_migrate=False, tables=None) 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=None, nested_select=True)
EXAMPLE:
source code
 
define_table(self, tablename, *fields, **args) source code
 
lazy_define_table(self, tablename, *fields, **args) source code
 
as_dict(self, flat=False, sanitize=True) source code
 
as_xml(self, sanitize=True) source code
 
as_json(self, sanitize=True) source code
 
as_yaml(self, sanitize=True) source code
 
__contains__(self, tablename) source code
 
has_key(self, tablename) source code
 
get(self, key, default=None) 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
source code
 
__repr__(self)
repr(x)
source code
 
smart_query(self, fields, text) source code
 
__call__(self, query=None, ignore_common_filters=None) source code
 
commit(self) source code
 
rollback(self) source code
 
close(self) source code
 
executesql(self, query, placeholders=None, as_dict=False, fields=None, colnames=None, as_ordered_dict=False)
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=None, null='<NULL>', unique='uuid', map_tablenames=None, ignore_missing_tables=False, *args, **kwargs) source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __reduce__, __reduce_ex__, __sizeof__, __str__, __subclasshook__

Static Methods [hide private]
a new object with type S, a subtype of T
__new__(cls, uri='sqlite://dummy.db', *args, **kwargs) 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=None, db_codec='UTF-8', check_reserved=None, migrate=True, fake_migrate=False, migrate_enabled=True, fake_migrate_all=False, decode_credentials=False, driver_args=None, adapter_args=None, attempts=5, auto_import=False, bigint_id=False, debug=False, lazy_tables=False, db_uid=None, do_connect=True, after_connection=None, tables=None, ignore_field_case=True, entity_quoting=False)
(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')

        experimental: you can specify a dictionary as uri
        parameter i.e. with
        db = DAL({"uri": "sqlite://storage.sqlite",
                  "tables": {...}, ...})

        for an example of dict input you can check the output
        of the scaffolding db model with

        db.as_dict()

        Note that for compatibility with Python older than
        version 2.6.5 you should cast your dict input keys
        to str due to a syntax limitation on kwarg names.
        for proper DAL dictionary input you can use one of:

        obj = serializers.cast_keys(dict, [encoding="utf-8"])

        or else (for parsing json input)

        obj = serializers.loads_json(data, unicode_keys=False)

:pool_size: How many open connections to make to the database object.
:folder: where .table files will be created.
         automatically set within web2py
         use an explicit path when using DAL outside web2py
:db_codec: string encoding of the database (default: 'UTF-8')
:check_reserved: list of adapters to check tablenames and column names
                 against sql/nosql 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
:auto_import (defaults to False). If set, import automatically table definitions from the
         databases folder
:bigint_id (defaults to False): If set, turn on bigint instead of int for id fields
:lazy_tables (defaults to False): delay table definition until table access
:after_connection (defaults to None): a callable that will be execute after the connection

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=None, nested_select=True)

source code 

        EXAMPLE:

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

@request.restful()
def index():
    def GET(*args,**vars):
        patterns = [
            "/friends[person]",
            "/{person.name}/:field",
            "/{person.name}/pets[pet.ownedby]",
            "/{person.name}/pets[pet.ownedby]/{pet.name}",
            "/{person.name}/pets[pet.ownedby]/{pet.name}/:field",
            ("/dogs[pet]", db.pet.info=='dog'),
            ("/dogs[pet]/{pet.name.startswith}", db.pet.info=='dog'),
            ]
        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=None, as_dict=False, fields=None, colnames=None, as_ordered_dict=False)

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. If "as_ordered_dict"=True the behaviour is the same as when "as_dict"=True with the keys (field names) guaranteed to be in the same order as returned by the select name executed on the database.

[{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)