Created
March 23, 2025 08:50
-
-
Save MdSadiqMd/26635280addd263fc0df0f6800127ee8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
To create SQLx migrations for PostgreSQL via the terminal, follow these steps: | |
1. First, install the SQLx CLI if you haven't already: | |
```bash | |
cargo install sqlx-cli | |
``` | |
2. Set up your database URL as an environment variable: | |
```bash | |
export DATABASE_URL=postgres://username:password@localhost:5432/your_database | |
``` | |
3. Create a new migration: | |
```bash | |
sqlx migrate add create_notes_table | |
``` | |
This will create a new directory called `migrations` if it doesn't exist, and within it, two files with timestamps and the name you provided: | |
- `TIMESTAMP_create_notes_table.up.sql` (for applying the migration) | |
- `TIMESTAMP_create_notes_table.down.sql` (for reverting the migration) | |
4. Edit the `.up.sql` file to add your SQL for creating the table: | |
```bash | |
cd migrations | |
nano TIMESTAMP_create_notes_table.up.sql | |
``` | |
Add your SQL: | |
```sql | |
CREATE TABLE IF NOT EXISTS notes ( | |
id SERIAL PRIMARY KEY, | |
title VARCHAR(255) UNIQUE NOT NULL, | |
content TEXT NOT NULL, | |
categeory VARCHAR(100), | |
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP | |
); | |
``` | |
5. Edit the `.down.sql` file to add SQL for reverting the change: | |
```bash | |
nano TIMESTAMP_create_notes_table.down.sql | |
``` | |
Add: | |
```sql | |
DROP TABLE IF EXISTS notes; | |
``` | |
6. Run the migration: | |
```bash | |
sqlx migrate run | |
``` | |
7. To verify the migration succeeded: | |
```bash | |
sqlx migrate info | |
``` | |
This will show you which migrations have been applied. | |
If you want to revert a migration: | |
```bash | |
sqlx migrate revert | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment