Generating raw sql

Sometimes you need to generate the SQL but not execute it. This is easy to do with web2py since every command that performs database IO has an equivalent command that does not, and simply returns the SQL that would have been executed. These commands have the same names and syntax as the functional ones, but they start with an underscore:

Here is _insert

  1. >>> print db.person._insert(name='Alex')
  2. INSERT INTO "person"("name") VALUES ('Alex');

Here is _count

  1. >>> print db(db.person.name == 'Alex')._count()
  2. SELECT COUNT(*) FROM "person" WHERE ("person"."name" = 'Alex');

Here is _select

  1. >>> print db(db.person.name == 'Alex')._select()
  2. SELECT "person"."id", "person"."name" FROM "person" WHERE ("person"."name" = 'Alex');

Here is _delete

  1. >>> print db(db.person.name == 'Alex')._delete()
  2. DELETE FROM "person" WHERE ("person"."name" = 'Alex');

And finally, here is _update

  1. >>> print db(db.person.name == 'Alex')._update(name='Susan')
  2. UPDATE "person" SET "name"='Susan' WHERE ("person"."name" = 'Alex');

Moreover you can always use db._lastsql to return the most recent SQL code, whether it was executed manually using executesql or was SQL generated by the DAL.