4. Going live, and the first bad data · Your task

Your task

1. Apply migrations 001 to 004 in order. Check with \dt that you have 7 tables.

2. Reproduce the tickets, so you've seen the database accept bad data:

  • Insert a user alice with email alice@example.com. Insert a second user with the same username.
  • Insert a post by user 1 with a body but no title.
  • Select everything from users and look at created_at.

3. Now see what the database does already protect. Insert a post with user_id 999. Read the error and say which migration is responsible for it.

4. Write 005_constraints.sql to make the bad data impossible. Decide the rules yourself from these requirements:

  • Every user has a username and an email, and neither can be shared with another user. A bio is optional.
  • Every post has an author and a title. The body is optional (drafts start empty). A post is a draft unless told otherwise.
  • Every comment has a post, an author and a body.
  • created_at is always filled in automatically, on every table that has it.
  • A user cannot follow themselves.

Running it will fail at first, because of the rows from step 2. Fix the data (DELETE FROM table WHERE ...;), then run it again.

5. Prove each rule. Re-run the bad inserts from step 2, and try to make user 1 follow user 1. Each should be rejected with a different error.

6. Insert a valid user giving only a username and email, and a post giving only user_id and title. Select them back and check the defaults filled in.