Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docker-compose.base.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
5 changes: 3 additions & 2 deletions docs/getting-started/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
106 changes: 106 additions & 0 deletions docs/migrations.md
Original file line number Diff line number Diff line change
@@ -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='<at least 32 bytes of randomness>'

# 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.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
# 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='<value of DB_NAME from .env>'
export DB_PORT_HOST='<value of DB_PORT_HOST from .env>'
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
export DB_ROOT_PASS='<value of DB_ROOT_PASS from .env>'
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 = '<value of DB_NAME from .env>'
$env:DB_PORT_HOST = '<value of DB_PORT_HOST from .env>'
$env:DB_ROOT_PASS = '<value of DB_ROOT_PASS from .env>'
$env:JWT_SECRET = '<at least 32 bytes of randomness>'
./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 `<rollback>` 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.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>3.1.1</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-liquibase</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
9 changes: 5 additions & 4 deletions src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 =====
# ====================================
Expand Down
7 changes: 4 additions & 3 deletions src/main/resources/application-prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

###### THIS IS THE DEV PROPERTIES #####
###### THIS IS THE PRODUCTION PROPERTIES #####

# =====================================
# ========= SPRING SECURITY ===========
Expand All @@ -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}
Expand Down Expand Up @@ -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
10 changes: 10 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading