Skip to content

Latest commit

 

History

History
105 lines (77 loc) · 3.6 KB

08-Mapper.asciidoc

File metadata and controls

105 lines (77 loc) · 3.6 KB

Relational database persistence with Mapper

Sequence numbers and existing data

Problem

You have a table with data in it, but Lift inserts new records with a primary key starting from 1, or some other value that may already exist.

Solution

Work with the native sequence facility in your database to set the starting sequence value to be the value you want Lift to use.

The first step is to work out what value you want the sequence to start from. Most likely this will be just after the largest primary key ID in the table you’re working with. With PostgreSQL, for example, you can check this via the psql command:

SELECT MAX(id) FROM mytable;

To find out what sequences exist, run \ds in psql. The sequence to change will contain the name of your table. You can then change the value:

ALTER SEQUENCE mytable_id_seq RESTART WITH 1000;

Discussion

Lift defers to the database sequence facility to generate primary key values. If you insert data by-passing the sequence, the sequence value will not know about the specific primary key values you have used (this is not Lift-specific). The solution above resolves this by updating the starting sequence number to skip over the rows that already exist in your database.

The same instructions apply for using Record as well as Mapper.

See Also

Detect if the schema has changed

Problem

You do not want to automatically migrate your schema, but you want to know if it is out of date.

Solution

Run Schemifier and capture the changes it would make if allowed. For example, in Boot.scala:

val cmds = Schemifier.schemify(false, true, Schemifier.infoF _, User, Company)

if (!cmds.isEmpty) {
  error("Database schema is out of date. The following is missing: \n"+
    cmds.mkString("\n"))
}

Discussion

The arguments and return value for schemify are:

  • performWrite - the example uses false meaning the database won’t be updated.

  • structureOnly - true to check the tables and columns (not indexes).

  • logFunc - for logging, but only if we are writing to the database, which we are not.

  • tables (mapper objects) - the tables to include.

  • The result is a List[String] which are the statements required to update the database.

From the above description you may be able to select the parameters that best fit your needs.