Skip to content

Relational Lenses

James Cheney edited this page Sep 26, 2018 · 2 revisions

Requirements

In order to use relational lenses it is necessary to set the relational_lenses flag in the config to true, e.g. by creating a file called config with the contents:

relational_lenses=true

And then by running linx --config=config myfile.links.

Usage

Creating Lenses

Primitive Lenses

Primitive lenses are lenses which wrap over links relational database tables. They allow the specification of functional dependencies for a table.

We begin by defining a database connection and a table:

var db = database "links";

var albumsTable =
    table "albums"
    with (album: String, quantity: Int)
    tablekeys [["album"]]
    from db;

This specifies that the table albumsTable has the table key album, and so we would like to generate a primitive lens with the functional dependency album -> quantity. This means that the album name defines the quantity column.

var albumsLens = lens albumsTable with { album -> quantity };

Relational Lenses

Join Lens

The join lens takes two lenses and combines all records which have an identical value for the join columns. Deleting a record from a joined lens can sometimes leave it open whether to delete the record from the left table, the right table or both. This makes it necessary to specify the deletion behaviour for these records when defining a join lens. In the simplest case, we can specify that we should simply delete from the left table, e.g.:

var joinedLens = lensjoin albumsLens with tracksLens on album delete_left;

It is also possible to define arbitrary expressions which determine where to delete the row from:

var joinedLens = lensjoin albumsLens with tracksLens on album delete { quantity <= 3, quantity > 3 };

It is important that for any record either the left or the right delete expression should be true.

Drop Lens

The drop lens projects a record down to fewer columns.

var droppedLens = lensdrop date determined by track default 2018 from joinedLens;

Select Lens

The select lens filters out undesired records by specifying a predicate which has to be satisfied. In this case we only want entries with more than two albums.

lensselect from droppedLens by quantity > 2;

Using Lenses

We can get the view by using lensget, e.g.:

var tracks = lensget filteredLens;

It is then possible to make any desired changes to tracks to as newTracks, which we can then commit to the database by running:

var r = lensput filteredLens with newTracks;