Migrating Data to PostgreSQL and Modeling Data in Deno
In this step, we will create our first data model and create a corresponding table using a migration
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
Duck model#
Now that our application has a database connection, and we are ready to create
and run our migrations, we can add our duck
table so that we can implement our
first endpoints.
Migration#
Start by creating a new migration.
xxxxxxxxxx
deno run -A --unstable https://deno.land/x/nessie@2.0.7/cli.ts make:migration create_duck_table
You should now see the migration file in db/migrations
.
In the duck
table, we need three columns:
xxxxxxxxxx
| Name | Type |
| ---------- | ----------- |
| `id` | VARCHAR(30) |
| `username` | VARCHAR(40) |
| `password` | VARCHAR(60) |
Using PostgreSQL's syntax, we need something like this in ourcreate_duck_table
migration:
xxxxxxxxxx
import { AbstractMigration, ClientPostgreSQL } from "nessie";
​
export default class extends AbstractMigration<ClientPostgreSQL> {
async up(): Promise<void> {
await this.client.queryArray(`CREATE TABLE duck (
id VARCHAR(30) PRIMARY KEY,
username VARCHAR(40) UNIQUE,
password VARCHAR(60)
)`);
}
​
async down(): Promise<void> {
await this.client.queryArray(`DROP TABLE duck`);
}
}
To explain the query above, the id
column is our primary key and as it is a
CUID, we need to make it 30 char long to follow the cuid specs. The username
is a unique string of reasonable size (max length 40), and the password
is a
string of max length 60 which will make more sense later.
Run the migration, roll back, and migrate again to check that everything works as expected.
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.
