Menu

Database Development Examples

For those unfamiliar with server-side development, even with a complete full-stack boilerplate, they may still be confused about database creation, updates, and other operations.

This chapter will introduce how to update built-in database tables and create new database tables to support feature development when developing products based on the Nexty boilerplate.

Initialize Database

Initialize the database and seed data through commands:

# Initialize database
npm run db:migrate
 
# Import sample pricing plan seed data
npm run db:seed

After completion, you can see the complete data tables in the database.

tables

Adding Fields to Existing Tables

Assume a scenario where we want to record the source based on URL parameters when users register, then the user table needs to add a new field referral.

First modify the table definition in the lib/db/schema.ts file, then execute the command to generate a migration file:

npm run db:generate

After executing the command, a migration file will be added to lib/db/migrations/, then push the migration file to the database through the command:

npm run db:migrate

Now check the user table in the database, you will find that the referral field has been successfully added.

This is an example of extending table fields. Requirements such as deleting fields and updating field definitions can also be completed using the same steps.

Adding New Tables

First add the new table definition in the lib/db/schema.ts file, then execute the command to generate a migration file:

npm run db:generate

After executing the command, a migration file will be added to lib/db/migrations/, then push the migration file to the database through the command:

npm run db:migrate

This completes the creation of a new database table.

Visual Management:

If you are using a local database or a self-deployed database, you can use this command to open the database visualization window:

npm run db:studio