Skip to main content
Reading progress: 0%

Lesson 5.3: Setting Up Your Database (SQLite, PostgreSQL, Schemas & Migrations)

Lesson Quick-Jump (10 Sections)

1. What Are We Learning?​

In this lesson, you will learn how to:

  • Understand the 3 steps required to set up any database for a project.
  • Choose between SQLite (a single file on your computer) and PostgreSQL (a database server—local or cloud-hosted).
  • Read a DATABASE_URL connection string safely.
  • Create your initial tables using a schema / migration and verify your app can connect.

2. Why Does It Matter?​

info

Beginners often ask an AI agent to build an app that "saves users and items," only to hit confusing crashes like ECONNREFUSED 127.0.0.1:5432 or no such table: bookmarks. Usually nothing is wrong with the app's logic—the database simply wasn't created, started, or initialized with tables yet.

Once you understand the 3-step database setup ritual, connecting any project to SQLite or PostgreSQL becomes predictable and stress-free.


3. Simple Explanation for a Complete Beginner​

Setting up a database always comes down to three steps:

  1. Have a running database (a place for data to live).
  2. Tell your app where to find it (via DATABASE_URL in your private .env file).
  3. Build the empty shelves inside it (schema / migration—creating the tables and columns before your app tries to save anything).

Two Common Beginner Choices​

  • Option A: SQLite (Simplest for Local Apps & Learning) SQLite is just one file on your computer (for example, data/app.db). You do not install or start a separate database server! When your app runs its setup script, it creates the .db file automatically.

    • Best for: Single-user apps, early prototypes, and Project 1.
    • Important rule: Add *.db to .gitignore so you don't upload personal test data to GitHub.
  • Option B: PostgreSQL (Standard for Multi-User & Live Web Apps) PostgreSQL ("Postgres") is a dedicated database program that stores data safely for multi-user apps. You have two easy ways to get one during development:

    1. Local Postgres: Install PostgreSQL on your computer, make sure it is running, and create one empty database (e.g., createdb bookmark_vault).
    2. Managed Cloud Dev Database (Often Easiest for Beginners): Many database hosts offer a free starter tier where you click "Create Database" in a browser dashboard and copy the connection string—no local database installation needed! (Recommended practice: always use a separate dev database on your laptop from your live production database.)

How to Read a DATABASE_URL Connection String​

postgresql://myuser:mypassword@localhost:5432/bookmark_vault
└────┘ └────────┘ └───────┘ └──┘ └────────────┘
username password server port database name

This single line lives inside .env (never committed to Git!).


4. Practical Example​

Setting up the database for Project 2 (Bookmark Vault):

  1. Step 1 — Get a Postgres database ready: Either create a local database (createdb bookmark_vault) OR create a free starter Postgres database in a cloud dashboard.
  2. Step 2 — Put the connection string in .env:
    DATABASE_URL="postgresql://myuser:mypassword@localhost:5432/bookmark_vault"
    (And keep a safe dummy version in .env.example!)
  3. Step 3 — Create tables (Schema / Migration): Ask the AI agent to write a clean migration or init-db script creating users and bookmarks tables, run it once (e.g., npm run db:migrate or python init_db.py), and confirm it finishes without errors.
  4. Step 4 — Verify connectivity: Open http://localhost:3000/api/health (an endpoint that runs a harmless SELECT 1 database check) and verify it returns {"ok": true, "database": "connected"}—and inspect the tables directly using your database viewer or CLI.

5. Step-by-Step Instructions​

  1. Check docs/architecture.md to see which database you chose (SQLite or PostgreSQL) and what tables/columns your MVP needs.
  2. Provision the database:
    • For SQLite: Decide the file path (e.g., data/app.db) and ensure *.db is in .gitignore.
    • For PostgreSQL: Install Postgres locally and create the database (createdb your_app_name), OR create a free starter Postgres instance in a cloud database provider and copy its connection URL.
  3. Add DATABASE_URL to your local .env (and update .env.example with a placeholder).
  4. Create and run your initial schema / migration so your tables exist before you start building UI forms.
  5. Verify the database actually works using a /api/health check or by inserting and inspecting one test row.
tip

If a database dashboard feels unfamiliar: Don't get lost in long database courses. Search YouTube for a quick 5–20 minute setup video on your exact tool (for example, "how to set up Postgres in Neon"), get the visual idea, then take a screenshot of Chrome or copy-paste what you see on screen into AI using Prompt 6: Break Down a Confusing Screen—just remember to hide your password or full connection string first.


6. Ready-to-Use AI Prompt​

Context:
I am setting up the database for my project for the first time.
- Operating system: [Windows / macOS / Linux]
- Tech stack: [e.g., Node.js + Express / Python + FastAPI]
- Chosen database: [SQLite OR PostgreSQL (local or managed cloud)]
- Data model from `docs/architecture.md`:
[Paste your tables and fields]

Objective:
Guide me step-by-step to set up the database connection, create the initial tables (schema/migration), and add a `/api/health` endpoint that verifies database connectivity.

Boundaries:
- Inspect the existing repo first before editing files.
- Never hardcode database credentials or real `DATABASE_URL` values in code—always read from `.env` and update `.env.example` with placeholders.
- Ensure `.gitignore` ignores `.env` and any local `.db` files.
- Do NOT build feature screens or user endpoints yet—only database setup, initial migration, and health check.

Expected Output:
1. Exact steps to create/start the database (or connect a cloud dev URL).
2. Schema/migration script and exact command to create the tables.
3. `/api/health` check confirming the server can talk to the database.
4. Exact command to inspect the created tables and verify they exist.

7. What to Expect from the AI Agent​

Good ResponseWarning Sign
The agent explains how to create/connect the database for your OS, configures .env.example + .gitignore, creates a repeatable migration/init script, and gives you a clear command to verify the tables exist.The agent pastes a real password into db.js instead of reading process.env.DATABASE_URL / os.environ["DATABASE_URL"], OR tells you to run raw CREATE TABLE SQL manually inside a GUI without saving a repeatable schema/migration file in your repo (if you don't save the schema in your repo, you won't be able to recreate the tables in production later!).

8. What You Must Personally Verify​

  • .env and *.db are ignored by Git: Run git status to confirm neither appears as untracked/staged.
  • Tables actually exist: Run the verification command or open your database viewer and confirm your table names and column names match docs/architecture.md.
  • Health check proves live connection: Start the app and visit /api/health; temporarily test what happens if .env has a wrong database name so you know the check isn't faking "connected".

9. Common Mistakes​

  1. Forgetting to start the local Postgres service: Installing Postgres isn't enough—the background server must be running, otherwise your app gets ECONNREFUSED.
  2. Creating tables by hand without saving a schema/migration file: When you deploy to production in Phase 9, your new cloud database will be empty. Having your schema/migration file inside Git lets you build identical tables in seconds.
  3. Sharing one database between local testing and live users: Always keep separate local/dev and production databases so running tests never deletes real user data.

10. Small Practical Exercise​

  1. Run the AI prompt above for your chosen project (SQLite for a simple local app like Project 1, or PostgreSQL for a multi-user app like Project 2).
  2. Set DATABASE_URL in your local .env, run your initial migration/setup script, and confirm your tables were created.
  3. Start your server, open /api/health in your browser, and verify it confirms the database connection is alive.

Completed the exercise? Track your progress

Check off this lesson in PROGRESS-CHECKLIST.md once you have verified every step in Section 8.