Skip to content

Commit

Permalink
plugins: adds a maven plugin to generate hibernate schemas (#19)
Browse files Browse the repository at this point in the history
This PR adds a maven plugin that users can run to generate a hibernate
schema in a similar way to how the gradle plugin works.

To generate a schema using maven (after adding the plugin):

```
mvn -q hibernate-provider:schema
```

Installing the plugin is very standard to the maven eco-system, but it
does not belong in any natural phase, so it should go to the
`pluginManagement` section:

```
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>io.atlasgo</groupId>
                    <artifactId>hibernate-provider-maven-plugin</artifactId>
                    <version>0.1</version>
                    <executions>
                        <execution>
                            <phase>test</phase>
                            <goals>
                                <goal>schema</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
```


An example e2e run can be found here -
https://gh.atlasgo.cloud/explore/ab450014
  • Loading branch information
dorav authored Dec 6, 2023
1 parent 8f1ea1c commit f3c5e5b
Show file tree
Hide file tree
Showing 32 changed files with 691 additions and 58 deletions.
47 changes: 46 additions & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,45 @@ jobs:
echo "error string found"
fi
- name: Build Maven Plugin
run: |
mvn clean install --batch-mode
- name: Integration tests with maven plugin
run: |
cd examples/maven_project_example
mvn compile --batch-mode
cd allowed_types
set -x
mvn -q hibernate-provider:schema | tee maven_schema_output
diff maven_schema_output src/test/expected_default_schema
mvn -q hibernate-provider:schema@schema-using-postgresql-properties | tee maven_psql_output
diff maven_psql_output src/test/expected_postgresql_output
mvn -q hibernate-provider:schema -Dregistry-builder=com.example.H2ServiceRegistryBuilder | tee maven_h2_output
diff maven_h2_output src/test/expected_h2_output
mvn -q hibernate-provider:schema -Dmetadata-builder=com.example.MetadataBuilder | tee maven_mini_output
diff maven_mini_output src/test/expected_mini_output
mvn -q hibernate-provider:schema -Dpackages="com.example.model" | tee maven_employee_output
diff maven_employee_output src/test/expected_employee_output
mvn -q hibernate-provider:schema -Dpackages="com.example.model" -Dclasses="com.example.minimodel.Location" | tee maven_classes_and_packages_output
diff maven_classes_and_packages_output src/test/expected_default_schema
cd ../forbidden_types
if (set -o pipefail && atlas schema inspect --env hibernate --url env://src 2>&1 | tee /tmp/forbidden_output); then
echo "expected schema extraction to fail due to an unsupported SQL command" && false
else
echo "command failed successfully, checking output contains error string"
grep -i "unsupported GenerationType.SEQUENCE" /tmp/forbidden_output || (echo "Failed output comparison, output was:" && cat /tmp/forbidden_output && false)
echo "error string found"
fi
set +x
- uses: actions/setup-java@v3
with:
distribution: zulu
Expand All @@ -63,4 +102,10 @@ jobs:
run: |
cd examples/with_spring_gradle
output=$(atlas migrate diff --env hibernate)
[ "$output" = "The migration directory is synced with the desired state, no changes to be made" ] || (echo "diff detected? unexpected output: $output"; ls -l migrations; exit 1)
[ "$output" = "The migration directory is synced with the desired state, no changes to be made" ] || (echo "diff detected? unexpected output: $output"; ls -l migrations; exit 1)
- name: E2E test maven project
run: |
cd examples/maven_project_example/allowed_types
output=$(atlas migrate diff --env hibernate)
[ "$output" = "The migration directory is synced with the desired state, no changes to be made" ] || (echo "diff detected? unexpected output: $output"; ls -l migrations; exit 1)
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.local-plugin-repository
target
5 changes: 5 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ dependencies {
testImplementation("org.hibernate.orm:hibernate-core:6.3.1.Final")
testImplementation("com.h2database:h2:2.2.224")

// These are here for now just for editor support. The maven plugin is built using Maven
compileOnly("org.codehaus.mojo:exec-maven-plugin:3.1.1")
compileOnly("org.apache.maven:maven-plugin-api:3.6.3")
compileOnly("org.apache.maven:maven-project:2.2.1")
compileOnly("org.apache.maven.plugin-tools:maven-plugin-annotations:3.6.0")
}

tasks.test {
Expand Down
44 changes: 44 additions & 0 deletions examples/maven_project_example/allowed_types/atlas.hcl
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
data "external_schema" "hibernate" {
program = [
"mvn",
"-q",
"compile",
"hibernate-provider:schema"
]
}

data "external_schema" "hibernate_postgresql" {
program = [
"mvn",
"-q",
"compile",
"hibernate-provider:schema",
"-Dproperties=postgresql.properties"
]
}

env "hibernate" {
src = data.external_schema.hibernate.url
dev = "docker://mysql/8/dev"
migration {
dir = "file://migrations"
}
format {
migrate {
diff = "{{ sql . \" \" }}"
}
}
}

env "hibernate_postgresql" {
src = data.external_schema.hibernate_postgresql.url
dev = "docker://postgres/15/dev"
migration {
dir = "file://migrations_postgresql"
}
format {
migrate {
diff = "{{ sql . \" \" }}"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- Create "Location" table
CREATE TABLE `Location` (
`id` bigint NOT NULL AUTO_INCREMENT,
`title` varchar(255) NULL,
PRIMARY KEY (`id`)
) CHARSET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
-- Create "Department" table
CREATE TABLE `Department` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NULL,
PRIMARY KEY (`id`)
) CHARSET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
-- Create "Employee" table
CREATE TABLE `Employee` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NULL,
`department_id` bigint NULL,
PRIMARY KEY (`id`),
INDEX `FK14tijxqry9ml17nk86sqfp561` (`department_id`),
CONSTRAINT `FK14tijxqry9ml17nk86sqfp561` FOREIGN KEY (`department_id`) REFERENCES `Department` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION
) CHARSET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
h1:Dy0V88s6slIfSnpV4kis08iLeJAYX1uFL1V5kHXZKHQ=
20231205144835.sql h1:nWzM/ZCeVTFmjjC8/0RmmpcD0KndYZjOKWm9BrqyhGs=
24 changes: 24 additions & 0 deletions examples/maven_project_example/allowed_types/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven_project_example</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>

<groupId>com.example.allowed</groupId>
<artifactId>allowed_types</artifactId>
<version>1.0</version>

<name>allowed_types</name>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.example;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.service.ServiceRegistry;

import java.util.Map;
import java.util.Properties;
import java.util.function.Function;

public class H2ServiceRegistryBuilder implements Function<Properties, ServiceRegistry> {
public H2ServiceRegistryBuilder() {

}

@Override
public ServiceRegistry apply(Properties properties) {
return new StandardServiceRegistryBuilder()
.applySettings(Map.of(
"hibernate.connection.url","jdbc:h2:mem:testdb",
AvailableSettings.SCHEMA_MANAGEMENT_TOOL, properties.get(AvailableSettings.SCHEMA_MANAGEMENT_TOOL),
"hibernate.temp.use_jdbc_metadata_defaults", true,
"jakarta.persistence.database-product-name", "H2",
"jakarta.persistence.database-major-version", "",
"hibernate.connection.provider_class", ""))
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example;

import com.example.minimodel.Location;
import com.example.model.Department;
import com.example.model.Employee;
import jakarta.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world");

Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Location location = new Location();
location.setTitle("Darkness");
session.persist(location);
transaction.commit();
Query q = session.createQuery("From Location ", Location.class);
List<Location> resultList = q.getResultList();
System.out.println("num of locations:" + resultList.size());
for (Location next : resultList) {
System.out.println("next location: (" + next.id + ") - " + next.title);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.example;

import com.example.minimodel.Location;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.service.ServiceRegistry;

import java.util.function.Function;

public class MetadataBuilder implements Function<ServiceRegistry, Metadata> {
@Override
public Metadata apply(ServiceRegistry registry) {
return new MetadataSources(registry)
.addAnnotatedClasses(Location.class)
.buildMetadata();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.example.minimodel;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;

public String title = "hello";

public void setId(Long id) {
this.id = id;
}

public Long getId() {
return id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,12 @@ public class Department {
public Department() {
super();
}

public Department(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import jakarta.persistence.*;

@Entity
@Table
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,23 @@
"http://www.hibernate.org/dtd/hibernate-configuration">
<hibernate-configuration>
<session-factory>

<property name="connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
<property name="connection.username">root</property>
<property name="connection.password">my-secret-pw</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

<property name="show_sql">true</property>

<property name="hibernate.connection.autocommit">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create-drop</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="connection.pool_size">3</property>
<property name="current_session_context_class">thread</property>

<mapping class="com.example.model.Employee" />
<mapping class="com.example.model.Department" />
<mapping class="com.example.minimodel.Location" />

</session-factory>
</hibernate-configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
jakarta.persistence.database-product-name=MySQL
jakarta.persistence.database-major-version=8
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
jakarta.persistence.database-product-name=PostgreSQL
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
create table Department (id bigint not null auto_increment, name varchar(255), primary key (id)) engine=InnoDB;
create table Employee (id bigint not null auto_increment, name varchar(255), department_id bigint, primary key (id)) engine=InnoDB;
create table Location (id bigint not null auto_increment, title varchar(255), primary key (id)) engine=InnoDB;
alter table Employee add constraint FK14tijxqry9ml17nk86sqfp561 foreign key (department_id) references Department (id);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
create table Department (id bigint not null auto_increment, name varchar(255), primary key (id)) engine=InnoDB;
create table Employee (id bigint not null auto_increment, name varchar(255), department_id bigint, primary key (id)) engine=InnoDB;
alter table Employee add constraint FK14tijxqry9ml17nk86sqfp561 foreign key (department_id) references Department (id);
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
create table Department (id bigint generated by default as identity, name varchar(255), primary key (id));
create table Employee (id bigint generated by default as identity, name varchar(255), department_id bigint, primary key (id));
create table Location (id bigint generated by default as identity, title varchar(255), primary key (id));
alter table Employee add constraint FK14tijxqry9ml17nk86sqfp561 foreign key (department_id) references Department;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
create table Location (id bigint not null auto_increment, title varchar(255), primary key (id)) engine=InnoDB;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
create table Department (id bigint not null auto_increment, name varchar(255), primary key (id)) engine=InnoDB;
create table Employee (id bigint not null auto_increment, name varchar(255), department_id bigint, primary key (id)) engine=InnoDB;
create table Location (id bigint not null auto_increment, title varchar(255), primary key (id)) engine=InnoDB;
alter table Employee add constraint FK14tijxqry9ml17nk86sqfp561 foreign key (department_id) references Department (id);
Empty file.
Loading

0 comments on commit f3c5e5b

Please sign in to comment.