diff --git a/docker-compose.base.yml b/docker-compose.base.yml index de424fd..e8b9710 100644 --- a/docker-compose.base.yml +++ b/docker-compose.base.yml @@ -24,7 +24,6 @@ services: db: image: mysql:8.4 container_name: moo-db - command: --default-authentication-plugin=mysql_native_password environment: MYSQL_DATABASE: ${DB_NAME:?DB_NAME is required} MYSQL_USER: ${DB_USER:?DB_USER is required} diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index 0321bf7..9e0b8ba 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -27,8 +27,9 @@ The production profile reads: - `MYSQL_DB_UNAME` - `MYSQL_DB_PASSWD` -The development profile uses MySQL on `localhost:3306` with the local Compose -credentials. Tests use an in-memory H2 database in MySQL compatibility mode. +The development profile uses MySQL on `localhost` with the local Compose +credentials and `DB_PORT_HOST` port (`3306` by default). Tests use an in-memory +H2 database in MySQL compatibility mode. ## API documentation diff --git a/docs/migrations.md b/docs/migrations.md new file mode 100644 index 0000000..890a815 --- /dev/null +++ b/docs/migrations.md @@ -0,0 +1,106 @@ +# Database Migrations + +Schema is managed by [Liquibase](https://www.liquibase.org/) via +[`src/main/resources/db/changelog/db.changelog-master.xml`](../src/main/resources/db/changelog/db.changelog-master.xml). +Hibernate runs with `ddl-auto=validate` — it never creates or modifies tables. +**Only Liquibase changes the schema.** + +Liquibase applies pending changesets automatically when the application starts. +No manual migration step is required for local development or production — the +application applies migrations before Hibernate's `ddl-auto=validate` check runs. + +## Local development + +Set up the environment file and start the database: + +```bash +# 1. Copy the example environment file +cp .env.example .env + +# 2. Set nonempty values in .env for all required Compose variables +# (see docker-compose.base.yml for the full list). +# Wrap passwords in single quotes to prevent Compose from interpolating +# special characters (like $). For an apostrophe in a single-quoted +# value, escape it with a backslash (e.g., DB_ROOT_PASS='can\'t'). +# DB_PORT_HOST=3306 +# DB_NAME=twitter_clone +# DB_USER=moo_user +# DB_PASS='moo_pass' +# DB_ROOT_PASS='root_pass' +# JWT_SECRET='' + +# 3. Bash / zsh: clear a stale shell override so Compose uses the .env port +unset DB_PORT_HOST + +# 4. Start the database in detached mode so the command returns to the shell +docker compose up -d db +``` + +Shell variables take precedence over `.env`. If using PowerShell, run +`Remove-Item Env:DB_PORT_HOST -ErrorAction SilentlyContinue` before starting +Compose, or set `$env:DB_PORT_HOST` to the same value as `.env`. + +Maven does not read `.env` — export every value the application needs. +The dev profile reads the database port from `${DB_PORT_HOST:3306}`, the +database name from `${DB_NAME:twitter_clone}`, and the root password from +`${DB_ROOT_PASS:root_pass}`. It also requires `JWT_SECRET` to be set (root +`application.properties` uses `${JWT_SECRET}` with no default): + +```bash +# bash / zsh — use the values from your .env file +# Use single quotes to preserve special characters (like $) in the password. +# If your password contains a single quote, close the quote, insert an escaped +# quote, and open a new quote (e.g., 'can'\''t'). +export DB_NAME='' +export DB_PORT_HOST='' +export DB_ROOT_PASS='' +export JWT_SECRET="$(openssl rand -hex 32)" +./mvnw spring-boot:run -Dspring-boot.run.profiles=dev +``` + +```powershell +# PowerShell (Windows) — use the values from your .env file +# Use single quotes to preserve special characters (like $) in the password. +# If your password contains a single quote, double it (e.g., 'can''t'). +$env:DB_NAME = '' +$env:DB_PORT_HOST = '' +$env:DB_ROOT_PASS = '' +$env:JWT_SECRET = '' +./mvnw spring-boot:run "-Dspring-boot.run.profiles=dev" +``` + +## Production + +Production applies pending changesets on application startup +(`spring.liquibase.enabled=true` in `application.properties`). What happens +when a migration fails depends on the deployment topology: + +- **Password Quoting:** Docker Compose `.env` files and shell exports handle special characters differently. + Always single-quote values containing `$` in `.env` (e.g., `DB_ROOT_PASS='pa$word'`). + When exporting the same value in a shell, use the shell-specific single-quote escaping shown above. + If you use double quotes in a shell, the shell will expand `$`. +- **Rolling / blue-green deployments** (two app instances, traffic routed + between them): the previous instance keeps serving traffic while the new + instance applies migrations. If a migration fails, only the new instance is + affected, and the old one continues serving. +- **Single-container Compose** (this repository's default deployment): + `docker compose up` stops and recreates the app container when its image + changes. A migration failure at startup leaves no version serving traffic + until the failure is resolved and a working image is redeployed. + +For zero-downtime migrations, use a multi-instance setup where the previous +version keeps running while the new version applies changes. + +If a migration fails, inspect the application and Liquibase logs, the current +database schema, and `DATABASECHANGELOG`. Liquibase stops at the failed +changeset, so later corrections cannot run until the blocking failure is +resolved. Fix the reported database, data, configuration, or changelog problem, +then redeploy and verify that the failed changeset completes. + +Rollback is **not a supported recovery path**. The current changelog does not +define `` blocks, so `liquibase:rollback` can only reverse changesets +via Liquibase's auto-generated inverse operations — which for +`010-create-refresh-tokens-table` means dropping the table and all stored +refresh tokens. If a successfully applied migration needs to be reversed, add +a new forward-only changeset that compensates for it; do not edit the recorded +changeset. diff --git a/pom.xml b/pom.xml index f31d4a1..4a3a06b 100644 --- a/pom.xml +++ b/pom.xml @@ -183,6 +183,11 @@ springdoc-openapi-starter-webmvc-ui 3.1.1 + + + org.springframework.boot + spring-boot-starter-liquibase + diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index aae67c4..c3d4c71 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -29,11 +29,13 @@ # ===================================== # Set here configurations for the database connection -spring.datasource.url=jdbc:mysql://localhost:3306/${DB_NAME:twitter_clone}?createDatabaseIfNotExist=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Kolkata&useSSL=false +spring.datasource.url=jdbc:mysql://localhost:${DB_PORT_HOST:3306}/${DB_NAME:twitter_clone}?createDatabaseIfNotExist=true&sslMode=REQUIRED&serverTimezone=Asia/Kolkata # Username and secret spring.datasource.username=root -spring.datasource.password=root +spring.datasource.password=${DB_ROOT_PASS:root_pass} + + # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle=true @@ -59,12 +61,11 @@ spring.jpa.properties.hibernate.format_sql=true # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.generate-ddl=true -spring.jpa.hibernate.ddl-auto=update +spring.jpa.hibernate.ddl-auto=validate # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.id.new_generator_mappings=false - # ==================================== # ====== CHANGE SERVER PORT HERE ===== # ==================================== diff --git a/src/main/resources/application-prod.properties b/src/main/resources/application-prod.properties index e9f46a5..51460ed 100644 --- a/src/main/resources/application-prod.properties +++ b/src/main/resources/application-prod.properties @@ -16,7 +16,7 @@ # along with this program. If not, see . # -###### THIS IS THE DEV PROPERTIES ##### +###### THIS IS THE PRODUCTION PROPERTIES ##### # ===================================== # ========= SPRING SECURITY =========== @@ -29,8 +29,7 @@ # ===================================== # Set here configurations for the database connection -spring.datasource.url=jdbc:mysql://${MYSQL_DB_HOST}:${MYSQL_DB_PORT}/${MYSQL_DB_NAME}?createDatabaseIfNotExist=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Kolkata&useSSL=false - +spring.datasource.url=jdbc:mysql://${MYSQL_DB_HOST}:${MYSQL_DB_PORT}/${MYSQL_DB_NAME}?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Kolkata&sslMode=REQUIRED # Username and secret spring.datasource.username=${MYSQL_DB_UNAME} spring.datasource.password=${MYSQL_DB_PASSWD} @@ -58,3 +57,5 @@ spring.jpa.properties.hibernate.id.new_generator_mappings=false springdoc.api-docs.enabled=false springdoc.swagger-ui.enabled=false +spring.liquibase.enabled=true +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 2b330c3..e43e586 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -35,3 +35,13 @@ spring.data.web.pageable.default-page-size=20 spring.data.web.pageable.max-page-size=100 spring.jpa.properties.hibernate.default_batch_fetch_size=50 spring.jpa.open-in-view=false + +# Enable Liquibase +spring.liquibase.enabled=true + +# Specify the path to the master changelog file +spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml + +# IMPORTANT: Disable Hibernate's automatic table creation +# This prevents conflicts. Liquibase is now in charge of the schema. +spring.jpa.hibernate.ddl-auto=validate diff --git a/src/main/resources/db/changelog/001-initial-schema.xml b/src/main/resources/db/changelog/001-initial-schema.xml new file mode 100644 index 0000000..c8e6090 --- /dev/null +++ b/src/main/resources/db/changelog/001-initial-schema.xml @@ -0,0 +1,309 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SELECT COUNT(*) FROM ( + SELECT INDEX_NAME + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'follows' + AND NON_UNIQUE = 0 + AND INDEX_NAME != 'PRIMARY' + AND COLUMN_NAME IN ('follower_id', 'following_id') + GROUP BY INDEX_NAME + HAVING COUNT(DISTINCT COLUMN_NAME) = 2 + ) AS existing_composite_unique_indexes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SELECT COUNT(*) FROM ( + SELECT INDEX_NAME + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'likes' + AND NON_UNIQUE = 0 + AND INDEX_NAME != 'PRIMARY' + AND COLUMN_NAME IN ('users_id', 'posts_id') + GROUP BY INDEX_NAME + HAVING COUNT(DISTINCT COLUMN_NAME) = 2 + ) AS existing_composite_unique_indexes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/changelog/db.changelog-master.xml b/src/main/resources/db/changelog/db.changelog-master.xml new file mode 100644 index 0000000..29ed828 --- /dev/null +++ b/src/main/resources/db/changelog/db.changelog-master.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file