Skip to content

Commit

Permalink
Merge pull request #15 from Throyer/development
Browse files Browse the repository at this point in the history
Migrate database to postgresql
  • Loading branch information
Throyer committed Jan 16, 2022
2 parents 1b49db2 + e15a933 commit 0f1dc5c
Show file tree
Hide file tree
Showing 14 changed files with 74 additions and 66 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
[In Portuguese](https://github.com/Throyer/springboot-api-crud/blob/master/assets/readme.md#spring-boot-api-crud)
>[🇧🇷 In Portuguese](https://github.com/Throyer/springboot-api-crud/blob/master/assets/readme.md#spring-boot-api-crud)
>
> [🐬 MySQL/MariaDB implementation](https://github.com/Throyer/springboot-api-crud/tree/mariadb#readme)
<p align="center">
<a href="https://github.com/Throyer" target="blank"><img src="./assets/tecnologias.png" width="560" alt="Tecnologias" /></a>
Expand Down Expand Up @@ -39,7 +41,7 @@

## Requirements

- MariaDB: `^10.6.1`
- Postgres: `^13`
- Java: `^17`
- Maven: `^3.8.4`

Expand Down Expand Up @@ -132,6 +134,7 @@ Creating database migration files
> ```shell
> # to change the value of some environment variable at runtime
> # on execution, just pass it as a parameter. (like --SERVER_PORT=80).
> $ java -jar api-3.0.4.RELEASE.jar --SERVER_PORT=80
> ```
>
Expand Down
9 changes: 5 additions & 4 deletions assets/readme.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[Em Inglês](../README.md)

> [🇺🇸 Em Inglês](../README.md)
>
> [🐬 Implementação com MySQL/MariaDB](https://github.com/Throyer/springboot-api-crud/tree/mariadb#readme)
<p align="center">
<a href="https://github.com/Throyer" target="blank"><img src="./tecnologias.png" width="560" alt="Tecnologias" /></a>
</p>
Expand Down Expand Up @@ -40,7 +41,7 @@

## Requisitos

- MariaDB: `^10.6.1`
- Postgres: `^13`
- Java: `^17`
> recomendo a instalação do maven localmente, mas o projeto tem uma versão portatil nos arquivos [`mvnw`](./mvnw) e [`mvnw.cmd`](./mvnw.cmd)
Expand Down Expand Up @@ -144,7 +145,7 @@ Criando arquivos de arquivos de migração
> ```shell
> # para mudar o valor de alguma variável de ambiente
> # na execução basta passar ela como parâmetro. (como --SERVER_PORT=80 por exemplo).
> $ java -jar api-3.0.3.RELEASE.jar --SERVER_PORT=80
> $ java -jar api-4.0.0.RELEASE.jar --SERVER_PORT=80
> ```
>
> > [Todas opções do `aplication.properties` **padrões** no Spring Boot](https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html).
Expand Down
Binary file modified assets/tecnologias.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 18 additions & 11 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
version: '3'
services:

mariadb:
image: mariadb:10.6.1
container_name: mariadb-container

postgresql:
image: postgres:13
restart: unless-stopped
container_name: postgres-container
command: ["postgres", "-c", "log_statement=all", "-c", "log_destination=stderr"]
ports:
- 3306:3306
- 5432:5432
environment:
MYSQL_ROOT_PASSWORD: "root"
MYSQL_DATABASE: "common_app"
- POSTGRES_USER=root
- POSTGRES_PASSWORD=root
- POSTGRES_DB=common_app
- TZ=America/Sao_Paulo
- PGTZ=America/Sao_Paulo
volumes:
- ./.volumes/database:/var/lib/mysql
- ./.volumes/database:/var/lib/postgresql/data

api:
image: maven:3.8.3
restart: unless-stopped
container_name: api-container
links:
- mariadb
- postgresql
depends_on:
- mariadb
- postgresql
ports:
- 8080:8080
- 8000:8000
environment:
DB_URL: "mariadb:3306/common_app"
DB_URL: "postgresql:5432/common_app"
DB_USERNAME: "root"
DB_PASSWORD: "root"
volumes:
Expand Down
9 changes: 5 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
</parent>
<groupId>com.github.throyer.common.spring-boot</groupId>
<artifactId>api</artifactId>
<version>3.0.4</version>
<name>Common API</name>
<version>4.0.0</version>
<name>CRUD API</name>

<description>Exemplo de api simples com Spring Boot</description>

<properties>
Expand Down Expand Up @@ -151,8 +152,8 @@
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
@Configuration
@OpenAPIDefinition(info = @Info(
title = "Common CRUD API",
version = "v3.0.4",
version = "v4.0.0",
description = """
A complete user registry, with access permissions,
JWT token, integration and unit tests, using
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long
UPDATE
RefreshToken
SET
available = 0
available = false
WHERE
user_id = ?1 AND available = 1
user_id = ?1 AND available = true
""")
public void disableOldRefreshTokens(Long id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public interface UserRepository extends SoftDeleteRepository<User> {
WHERE id = ?1),
email = NULL,
deleted_at = CURRENT_TIMESTAMP,
active = 0,
active = false,
deleted_by = ?#{principal?.id}
WHERE id = ?1
""")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,27 +35,31 @@ public Page<UserDetails> findAll(
Optional<Integer> size
) {
var sql = """
with user_roles as (
select
ur.user_id, string_agg(r.initials, ',') roles
from "role" r
left join user_role ur on r.id = ur.role_id
group by ur.user_id
)
select
u.id,
u.name,
u.email,
(select
GROUP_CONCAT(r.initials)
from role r
left join user_role ur on r.id = ur.role_id
where ur.user_id = u.id) as roles
u.id,
u."name",
u.email,
urs.roles
from
user u
where u.deleted_at is null
"user" u
left join user_roles as urs on urs.user_id = u.id
""";

var query = manager.createNativeQuery(sql, Tuple.class);
var count = ((BigInteger) manager.createNativeQuery("""
select
count(u.id)
count(id)
from
user u
where u.deleted_at is null
"user"
where deleted_at is null
""").getSingleResult()).longValue();

var pageable = Pagination.of(page, size);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ public static class SECURITY {
public static final Integer DAY_MILLISECONDS = 86400;

public static final String ROLES_KEY_ON_JWT = "roles";
public static final String INVALID_USERNAME = "Nome de usuário invalido.";
public static final String CREATE_SESSION_ERROR_MESSAGE = "Senha ou Usuário inválidos.";
public static final String REFRESH_SESSION_ERROR_MESSAGE = "Refresh token expirado ou inválido.";
public static final String INVALID_USERNAME = "Invalid username.";
public static final String CREATE_SESSION_ERROR_MESSAGE = "Invalid password or username.";
public static final String REFRESH_SESSION_ERROR_MESSAGE = "Refresh token expired or invalid.";

public static final String USERNAME_PARAMETER = "email";
public static final String PASSWORD_PARAMETER = "password";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@ public void migrate(Context context) throws Exception {
using(configuration)
.alterTable("recovery")
.addColumn("confirmed", BOOLEAN.nullable(true))
.after("code")
.execute();
.execute();

using(configuration)
.alterTable("recovery")
.addColumn("used", BOOLEAN.nullable(true))
.after("confirmed")
.execute();
.execute();
});
}
}
6 changes: 4 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ spring.jpa.show-sql=${DB_SHOW_SQL:true}

# Banco de dados
spring.datasource.hikari.maximum-pool-size=${DB_MAX_CONNECTIONS:5}
spring.datasource.url=jdbc:mysql://${DB_URL:localhost:3306/common_app}?useSSL=false&createDatabaseIfNotExist=true&serverTimezone=America/Sao_Paulo
spring.datasource.url=jdbc:postgresql://${DB_URL:localhost:5432/common_app}
spring.datasource.username=${DB_USERNAME:root}
spring.datasource.password=${DB_PASSWORD:root}
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.javax.persistence.validation.mode=none
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.h2.console.enabled=false
spring.jpa.open-in-view=false

# swagger
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
-- variables
SET @name = 'admin';
SET @email = 'admin@email.com';
SET @password = '$2a$10$QBuMJLbVmHzgvTwpxDynSetACNdCBjU5zgo.81RWEDzH46aUrgcNK';
SET @adm = 'ADM';
SET @user = 'USER';

-- insert admin
INSERT INTO user
(name, email, password)
INSERT INTO "user"
("name", email, password)
VALUES
(@name, @email, @password);
('admin', 'admin@email.com', '$2a$10$QBuMJLbVmHzgvTwpxDynSetACNdCBjU5zgo.81RWEDzH46aUrgcNK');

-- insert roles
INSERT INTO role
INSERT INTO "role"
(name, initials, description, created_by)
VALUES
('ADMINISTRADOR', @adm, 'Administrador do sistema', (SELECT id FROM user WHERE email = @email)),
('USER', @user, 'Usuário do sistema', (SELECT id FROM user WHERE email = @email));
('ADMINISTRADOR', 'ADM', 'Administrador do sistema', (SELECT id FROM "user" WHERE email = 'admin@email.com')),
('USER', 'USER', 'Usuário do sistema', (SELECT id FROM "user" WHERE email = 'admin@email.com'));

-- put roles into admin
INSERT INTO user_role
(user_id, role_id)
VALUES
(
(SELECT id FROM user WHERE email = @email),
(SELECT id FROM role WHERE initials = @adm)
(SELECT id FROM "user" WHERE email = 'admin@email.com'),
(SELECT id FROM "role" WHERE initials = 'ADM')
),(
(SELECT id FROM user WHERE email = @email),
(SELECT id FROM role WHERE initials = @user)
(SELECT id FROM "user" WHERE email = 'admin@email.com'),
(SELECT id FROM "role" WHERE initials = 'USER')
);
3 changes: 1 addition & 2 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# configuracao do banco de testes em memoria H2.
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:test;mode=MYSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1
spring.datasource.url=jdbc:h2:mem:test;mode=PostgreSQL;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
spring.jpa.properties.javax.persistence.validation.mode=none
Expand All @@ -19,7 +19,6 @@ springdoc.api-docs.path=/documentation/schemas

# configuracoes do spring JPA.
spring.jpa.hibernate.ddl-auto=none
spring.datasource.initialization-mode=always

# token
token.expiration-in-hours=24
Expand Down

0 comments on commit 0f1dc5c

Please sign in to comment.