The DAL: A quick tour

web2py defines the following classes that make up the DAL:

The DAL object represents a database connection. For example:

  1. db = DAL('sqlite://storage.sqlite')

Table represents a database table. You do not directly instantiate Table; instead, DAL.define_table instantiates it.

  1. db.define_table('mytable', Field('myfield'))

The most important methods of a Table are:

insert, truncate, drop, and import_from_csv_file.

Field represents a database field. It can be instantiated and passed as an argument to DAL.define_table.

DAL Rows

is the object returned by a database select. It can be thought of as a list of Row rows:

  1. rows = db(db.mytable.myfield != None).select()

Row contains field values.

  1. for row in rows:
  2. print row.myfield

Query is an object that represents a SQL “where” clause:

  1. myquery = (db.mytable.myfield != None) | (db.mytable.myfield > 'A')

Set is an object that represents a set of records. Its most important methods are count, select, update, and delete. For example:

  1. myset = db(myquery)
  2. rows = myset.select()
  3. myset.update(myfield='somevalue')
  4. myset.delete()

Expression is something like an orderby or groupby expression. The Field class is derived from the Expression. Here is an example.

  1. myorder = db.mytable.myfield.upper() | db.mytable.id
  2. db().select(db.table.ALL, orderby=myorder)