Create New Tables and Models With Deno Database Migration
We will create two new tables using a migration and create the equivalent models
Quack & Crumb Model#
The best way to start on the new namespaces is to get the migration out of the
way. In this migration we will be creating both the quack
and crumb
tables,
so let's dive into it!
Migration#
Create a new migration using the Nessie
CLI and populate it with the following
code:
deno run -A --unstable https://deno.land/x/nessie@2.0.7/cli.ts make:migration create_quack_crumb_table
created_by VARCHAR(30) REFERENCES duck(id) ON DELETE CASCADE,
Similar to the first two migrations the class and methods are the same, except that we now have the table creations wrapped in a transaction. As we briefly discussed earlier, when we learned about Nessie, we want to make a transaction when we are handling multiple changes or multiple calls to the database. The reason for this is so that should, for example, the
quack
table succeed, but thecrumb
table fail, we don't get stuck in the middle of an uncompleted migration. A migration should either be completely successful, or not make any changes at all.
We are also setting a couple of foreign keys and relations between the tables.
In the quack table, the created_by
column is related to the id
in the duck
table, and the crumb
table is simply a reference table between duck
andquack
giving us a "many-to-many" relationship.
As our application serves as a minimal example, we don't really care about data retention, so when a record gets deleted, we simply remove the related records. This should obviously not be the case for real-life applications.
Models#
This lesson preview is part of the Build and deploy a REST API with Deno course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Build and deploy a REST API with Deno, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
