In an earlier post I talked about how I was recording site visitors with some home grown custom analytics code and FaunaDB. The basic idea was that I would generate a unique ID for each visitor that would be based on public information. No strange fingerprinting using canvas or any other bad ad tech.
Then I would insert that user into the database. Each of these records would represent a session, in addition to recording the pageview. If the user existed within the session time window, then I would increment the count within that session.
This was the heart of the UPSERT. In traditional SQL, you can tell the database to update an item if it is found, otherwise insert a new record. FaunaDB is exactly the same, in that it can do ACID transactions like this.
This works because we can give FQL a basic
Ifstatement. In the code above,
Existsdetermines a record is within the collection. If it does, then it runs
Update, otherwise it runs
There is more happening above, like getting data from
Varand checking if the entry is within a range. But UPSERTS are possible just like other query languages. It is also worth pointing out, that the
Letbasically allows you to run multiple queries at once. So the UPSERT is really trying to modify our session table. Every entry also gets recorded as a pageview in the pageview collection as well. This really shows the power of FQL.