Exercises
Objectives
By the end of this lesson, you should be able to:
- Design a model with a realistic mix of field types and attributes
- Run an initial migration, then evolve the schema with a second one
- Confirm every step by reading the actual generated SQL and checking the real table
⚠️ A note on verification: as throughout this module, the Prisma CLI can’t run inside this course’s own sandboxed tooling, so the expected output below reflects Prisma’s stable, documented behavior rather than this course’s own live execution. Run every step yourself, on your own machine, against a real database.
Exercise: A Product Catalog
a) Design the model. In a new or existing Prisma project, add a Product model with:
id, an auto-incrementing integer primary keyname, a required stringsku, a required, unique string (a stock-keeping unit code)price, aFloatinStock, aBoolean, defaulting totruecreatedAt, aDateTime, defaulting tonow()
b) Run the initial migration.
npx prisma migrate dev --name init
Confirm a migrations/ folder was created, and read the generated migration.sql, matching every line back to a field above.
c) Confirm the table exists. Connect with psql, and run \d "Product" to see the real column definitions PostgreSQL created.
d) Add a field. Add a description field (String?, optional), and migrate it:
npx prisma migrate dev --name add_description
Confirm the generated migration is an ALTER TABLE, not a new CREATE TABLE.
e) Add a required field, safely. Add a category field (String, required) with a @default("uncategorized"), and migrate it. Explain why the default was necessary here, referencing what the last lesson covered about required fields on existing tables.
f) Review the full history. List every file under prisma/migrations/, in order, and explain, in one or two sentences each, what each one changed.
Recap
This module went from a bare model block to a real, evolving database schema: scalar types and attributes, an initial migration creating tables from nothing, and a second migration safely adding a required field to a table that already had data.
Next module: modeling relationships, one-to-many and many-to-many, between models like these.