Using Database Schemas (Namespaces)

The word "Schema" is unfortunately quite overloaded with Torque. In this document, we will briefly talk about Database namespaces called Schema, as described in the PostgreSQL documentation. According to the docs, Schemas are a part of the SQL standard. YMMV, however.

Torque has some rudimentary support for Database schemas when accessing a database. Schema names can either be specified when generating classes via the generator, or they can be specified in the runtime.

Configuring Schema Names at Runtime

See the initialisation part of the runtime documentation for configuring schema names in the runtime configuration.

Changing the current Schema on the fly

The schema support happens per-Database. However, the schema name is queried dynamically whenever a Torque command accesses the database and can be changed (if you have the same table layout on multiple schemas, you can reuse your Peer classes thus reducing the number of classes used).


/* Set the schema name for database "bar" to "foo" */

Torque.setSchema("bar", "foo");

/* Reset the schema names (no longer qualify
 * accesses to the tables of the "bar" database
 */
Torque.setSchema("bar", null);

/* Get the current schema for the "bar" database */
String barSchema = Torque.getSchema("bar");

Using Schema Names at generate time

To define the schema of a table in the schema.xml, use the fully qualified table name as name attribute in the <table> element of your schema.xml. For example, to use the schema "bookstore" for the table "book", use the following table definition:

...
<table name="bookstore.book" description="Book table">
...

    

If the standard naming method is used, the resulting java class will be named BookstoreBook. If you want to omit the schema name in the java name (i.e. the resulting java class should be named "Book"), you can either use the javaName attribute of the table definition:

...
<table name="bookstore.book" javaName="Book" description="Book table">
...

    

or you can use the attribute defaultJavaNamingMethod="underscoreOmitSchema" in the database definition:

...
<database name="bookstore" defaultJavaNamingMethod="underscoreOmitSchema">
...

      

Note that the defaultJavaNamingMethod attribute of a table will only affect the column names in the table and cannot be used to change the name of the table itself.

If you use a sequence to autogenerate ids, the sequence will be generated in the same schema as the table.