This example of the RealWorld spec and API implementation is based on not widely used combination of Typelevel and Slick. The goal is to achieve more type safety in DB actions and make changes of DB schema easier.
The main use case of this composition style is the support of complex CRUD+L APIs that could get changes in DB schema. We make these changes "driven by DB schema" and perform them with steps below:
- add a Flyway change
- re-generate Slick Models
- fix compilation errors and make required changes in the codebase
+----------------+
| Routes |
+----------------+
|
v
+----------------+
| Service |
+----------------+
|
v
+--------------------+
| Repository |
+--------------------+
routes
package defines APIs and exposed models
services
package defines business rules and internal models
db
package defines persistence and DB models
# Run DB instance, for example, with docker
docker run -p 5432:5432 --name some-postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=condoit -d postgres
# Init schema with flyway (assume your working dir is the cloned repo)
flyway \flyway \
-url="jdbc:postgresql://localhost:5432/condoit" \
-user="postgres" \
-password="postgres" \
-createSchemas="true" \
-schemas="condoit" \
-locations="filesystem:./sql/" \
-X migrate
# Run server
# The configuration is made with .env file, default values are provided
sbt run
To perform changes, you need an initialized DB from the previous step above.
echo "ALTER TABLE users ADD COLUMN country TEXT NOT NULL;" > ./sql/V2__changeset.sql
# Perform schema changes at the running DB
flyway \
-url="jdbc:postgresql://localhost:5432/condoit" \
-user="postgres" \
-password="postgres" \
-createSchemas="true" \
-schemas="condoit" \
-locations="filesystem:./sql/" \
-X migrate -outputType=json
# Regenerate Slick Schema
sbt clean compile 'slickPgGen localhost 5432 condoit condoit postgres postgres'
# Fix compilation errors and add changes at business logic, routes and models