Master database schema design, migrations, and seeding with Knex.js.
Learn how to effectively use SQLite Studio for database management:
Understand the core concepts of database schema design:
Master the art of database migrations:
Learn how to populate your database with test data:
SQLite Studio is a powerful GUI tool for working with SQLite databases, allowing you to explore, query, and modify database structure and content.
Working with SQLite Studio is straightforward:
A database schema is the blueprint that defines the structure, organization, and relationships of data in a database system.
Example of a well-designed schema:
-- Users table CREATE TABLE users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Posts table with relationship to users CREATE TABLE posts ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); -- Create an index for faster lookups CREATE INDEX idx_posts_user_id ON posts(user_id);
Migrations are like version control for your database schema, allowing you to evolve your database structure over time.
Example of a Knex.js migration:
// Creating a migration $ npx knex migrate:make create_users_table // Migration file: 20230510123456_create_users_table.js exports.up = function(knex) { return knex.schema.createTable('users', function(table) { table.increments('id'); // creates auto-incrementing id column table.string('username').notNullable().unique(); table.string('email').notNullable().unique(); table.timestamp('created_at').defaultTo(knex.fn.now()); }); }; exports.down = function(knex) { return knex.schema.dropTable('users'); }; // Running migrations $ npx knex migrate:latest // Rolling back migrations $ npx knex migrate:rollback
Seeds allow you to populate your database with initial or test data, making development and testing easier.
Example of Knex.js seeds:
// Creating a seed file $ npx knex seed:make 01_users // Seed file: 01_users.js exports.seed = function(knex) { // Truncate all existing tables return knex.raw('PRAGMA foreign_keys = OFF;') .then(() => knex('users').truncate()) .then(() => knex.raw('PRAGMA foreign_keys = ON;')) .then(() => { // Insert seed data return knex('users').insert([ { username: 'admin', email: 'admin@example.com' }, { username: 'test_user', email: 'test@example.com' } ]); }); }; // Running seeds $ npx knex seed:run
In this module's guided project, you will:
After completing this module, you'll move on to Module 3: Multi-Table Queries, where you'll learn about: