├── .gitignore
├── .mvn
└── wrapper
│ ├── MavenWrapperDownloader.java
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── .travis.yml
├── DEVEL-README.md
├── LICENSE
├── README.md
├── jpa2ddl-core
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── devskiller
│ │ └── jpa2ddl
│ │ ├── Action.java
│ │ ├── FileResolver.java
│ │ ├── GenerationMode.java
│ │ ├── GeneratorSettings.java
│ │ ├── NoSequenceFilterProvider.java
│ │ ├── SchemaGenerator.java
│ │ ├── SchemaProcessor.java
│ │ ├── dialects
│ │ ├── H2MySQL57Dialect.java
│ │ ├── H2MySQL8Dialect.java
│ │ ├── H2PostgreSQL10Dialect.java
│ │ └── H2PostgreSQL95Dialect.java
│ │ └── engines
│ │ ├── EngineDecorator.java
│ │ ├── MySQLDecorator.java
│ │ ├── NoOpDecorator.java
│ │ ├── OracleDecorator.java
│ │ ├── PostgreSQLDecorator.java
│ │ └── SQLServerDecorator.java
│ └── test
│ ├── java
│ └── com
│ │ └── devskiller
│ │ └── jpa2ddl
│ │ ├── DatabaseComplexSchemaUpdateTest.java
│ │ ├── DatabaseSchemaGeneratorTest.java
│ │ ├── DatabaseSchemaUpdateTest.java
│ │ ├── FileResolverTest.java
│ │ ├── MetadataSchemaGeneratorTest.java
│ │ ├── complex
│ │ ├── Book.java
│ │ └── Chapter.java
│ │ └── sample
│ │ └── User.java
│ └── resources
│ ├── complex_migration
│ └── v1__jpa2ddl_init.sql
│ ├── sample_default_migration
│ └── v1__jpa2ddl_init.sql
│ ├── sample_empty_migration
│ └── v1__jpa2ddl_init.sql
│ ├── sample_migration
│ └── v1__jpa2ddl_init.sql
│ └── sample_postgres_migration
│ └── v1__jpa2ddl_init.sql
├── jpa2ddl-gradle-plugin
├── .gitignore
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── devskiller
│ │ │ └── jpa2ddl
│ │ │ ├── GeneratePlugin.java
│ │ │ ├── GeneratePluginExtension.java
│ │ │ └── GenerateTask.java
│ └── resources
│ │ └── META-INF
│ │ └── gradle-plugins
│ │ └── com.devskiller.jpa2ddl.properties
│ └── test
│ └── groovy
│ └── com
│ └── devskiller
│ └── jpa2ddl
│ └── GeneratePluginTest.groovy
├── jpa2ddl-maven-plugin
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── devskiller
│ │ │ └── jpa2ddl
│ │ │ └── GenerateMojo.java
│ └── resources
│ │ └── META-INF
│ │ └── plexus
│ │ └── components.xml
│ └── test
│ ├── java
│ └── com
│ │ └── devskiller
│ │ └── jpa2ddl
│ │ └── GenerateMojoTest.java
│ └── projects
│ ├── basic
│ └── pom.xml
│ └── full
│ └── pom.xml
├── jpa2ddl-querydsl-processor
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── devskiller
│ └── jpa2ddl
│ └── querydsl
│ └── QueryDslSchemaProcessor.java
├── jpa2ddl-samples
├── jpa2ddl-flyway-maven-sample
│ ├── .mvn
│ │ └── wrapper
│ │ │ ├── maven-wrapper.jar
│ │ │ └── maven-wrapper.properties
│ ├── README.md
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── oss
│ │ │ └── devskiller
│ │ │ └── model
│ │ │ └── User.java
│ │ └── resources
│ │ ├── db
│ │ └── flyway.mv.db
│ │ └── migrations
│ │ └── v1__jpa2ddl.sql
├── jpa2ddl-querydsl-maven-sample
│ ├── .mvn
│ │ └── wrapper
│ │ │ ├── maven-wrapper.jar
│ │ │ └── maven-wrapper.properties
│ ├── README.md
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── oss
│ │ │ └── devskiller
│ │ │ └── model
│ │ │ └── User.java
│ │ └── resources
│ │ └── migrations
│ │ └── v1__jpa2ddl.sql
└── pom.xml
├── mvnw
├── mvnw.cmd
└── pom.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | target
3 | *.iml
4 | *.releaseBackup
5 | release.properties
--------------------------------------------------------------------------------
/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2007-present the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | import java.net.*;
17 | import java.io.*;
18 | import java.nio.channels.*;
19 | import java.util.Properties;
20 |
21 | public class MavenWrapperDownloader {
22 |
23 | private static final String WRAPPER_VERSION = "0.5.6";
24 | /**
25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
26 | */
27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
29 |
30 | /**
31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
32 | * use instead of the default one.
33 | */
34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
35 | ".mvn/wrapper/maven-wrapper.properties";
36 |
37 | /**
38 | * Path where the maven-wrapper.jar will be saved to.
39 | */
40 | private static final String MAVEN_WRAPPER_JAR_PATH =
41 | ".mvn/wrapper/maven-wrapper.jar";
42 |
43 | /**
44 | * Name of the property which should be used to override the default download url for the wrapper.
45 | */
46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
47 |
48 | public static void main(String args[]) {
49 | System.out.println("- Downloader started");
50 | File baseDirectory = new File(args[0]);
51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
52 |
53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
54 | // wrapperUrl parameter.
55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
56 | String url = DEFAULT_DOWNLOAD_URL;
57 | if(mavenWrapperPropertyFile.exists()) {
58 | FileInputStream mavenWrapperPropertyFileInputStream = null;
59 | try {
60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
61 | Properties mavenWrapperProperties = new Properties();
62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
64 | } catch (IOException e) {
65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
66 | } finally {
67 | try {
68 | if(mavenWrapperPropertyFileInputStream != null) {
69 | mavenWrapperPropertyFileInputStream.close();
70 | }
71 | } catch (IOException e) {
72 | // Ignore ...
73 | }
74 | }
75 | }
76 | System.out.println("- Downloading from: " + url);
77 |
78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
79 | if(!outputFile.getParentFile().exists()) {
80 | if(!outputFile.getParentFile().mkdirs()) {
81 | System.out.println(
82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
83 | }
84 | }
85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
86 | try {
87 | downloadFileFromURL(url, outputFile);
88 | System.out.println("Done");
89 | System.exit(0);
90 | } catch (Throwable e) {
91 | System.out.println("- Error downloading");
92 | e.printStackTrace();
93 | System.exit(1);
94 | }
95 | }
96 |
97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
99 | String username = System.getenv("MVNW_USERNAME");
100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
101 | Authenticator.setDefault(new Authenticator() {
102 | @Override
103 | protected PasswordAuthentication getPasswordAuthentication() {
104 | return new PasswordAuthentication(username, password);
105 | }
106 | });
107 | }
108 | URL website = new URL(urlString);
109 | ReadableByteChannel rbc;
110 | rbc = Channels.newChannel(website.openStream());
111 | FileOutputStream fos = new FileOutputStream(destination);
112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
113 | fos.close();
114 | rbc.close();
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Devskiller/jpa2ddl/4652c4ecdc68d2aba31467a2c00279ed5fd3724d/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: required
2 | dist: trusty
3 | group: edge
4 |
5 | language: java
6 |
7 | jdk:
8 | - oraclejdk8
9 | - oraclejdk11
10 |
11 | script: ./mvnw install
12 |
13 | cache:
14 | directories:
15 | - ~/.m2/repository
16 | - ~/.m2/wrapper
17 |
18 | before_cache:
19 | - rm -Rf ~/.m2/repository/com/devskiller/jpa2ddl/
--------------------------------------------------------------------------------
/DEVEL-README.md:
--------------------------------------------------------------------------------
1 | # Developers guide
2 |
3 | ## Releasing the new version
4 |
5 | ```shell
6 | mvn release:clean
7 | mvn release:prepare
8 | mvn release:perform
9 | git pushtags
10 | git add README.md
11 | git commit -m "Readme version update"
12 | git push
13 | ```
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.org/Devskiller/jpa2ddl) [](https://maven-badges.herokuapp.com/maven-central/com.devskiller.jpa2ddl/jpa2ddl-maven-plugin)
2 |
3 | # JPA Schema Generator Plugin
4 |
5 | ## Motivation
6 |
7 | Why another tool to dump the JPA schema? All tools that we've found were related to legacy versions of Hibernate or were covering just simple cases, without options to configure dialect or naming strategy. Also all of the tools we've found are based on the `SchemaExport` class, which does not always correlate with the runtime schema - for example due to the lack of support for the `Integrator` services, used to register `UserType` classes like JodaTime or similar. We were also looking for a tool that is be able to handle further schema migrations, not just dump the current version.
8 |
9 | ## Configuration parameters
10 |
11 | - `packages` (required): list of packages containing JPA entities
12 | - `outputPath`: output file for the generated schema. By default:
13 | - for `UPDATE` action: `BUILD_OUTPUT_DIR/generated-resources/scripts/`
14 | - for other actions: `BUILD_OUTPUT_DIR/generated-resources/scripts/database.sql`
15 | - `jpaProperties`: additional properties like dialect or naming strategies which should be used in generation task. By default `empty`
16 | - `formatOutput`: should the output be formatted. By default `true`
17 | - `skipSequences`: should the generator skip sequences creation. By default `false`
18 | - `delimiter`: delimiter used to separate statements. By default `;`
19 | - `action`: which statements should be generated. By default: `CREATE`. Possible values:
20 | - `DROP`
21 | - `CREATE`
22 | - `DROP_AND_CREATE`
23 | - `UPDATE`
24 | - `generationMode`: schema generation mode. By default `DATABASE`. Possible values:
25 | - `DATABASE`: generation based on setting up embedded database and dumping the schema
26 | - `METADATA`: generation based on static metadata
27 | - `processorProperties`: properties passed to external `SchemaProcessor` classes
28 |
29 | ### Custom H2 dialects
30 |
31 | H2 is often used to imitate native database engines, however with usage going beyond simple SQL it has huge limitations.
32 | To resolve some of them related to sequences we provide custom database dialects.
33 |
34 | - `com.devskiller.jpa2ddl.dialects.H2PostgreSQL95Dialect`: Postgres 9.5 dialect for H2
35 | - `com.devskiller.jpa2ddl.dialects.H2PostgreSQL10Dialect`: Postgres 10 dialect for H2
36 | - `com.devskiller.jpa2ddl.dialects.H2MySQL57Dialect`: MySQL 5.7 dialect for H2
37 | - `com.devskiller.jpa2ddl.dialects.H2MySQL80Dialect`: MySQL 8.0 dialect for H2
38 |
39 | If you need different dialects please build them using above examples.
40 |
41 | ## Maven Plugin
42 |
43 | You can run this plugin directly or integrate it into the default build lifecycle.
44 |
45 | ### Simple configuration example
46 |
47 | ```xml
48 |
49 |
50 |
51 | com.devskiller.jpa2ddl
52 | jpa2ddl-maven-plugin
53 | 0.9.12
54 | true
55 |
56 |
57 | com.test.model
58 |
59 |
60 |
61 |
62 |
63 | ```
64 |
65 | ### Generate schema
66 |
67 | ```xml
68 |
69 |
70 |
71 | com.devskiller.jpa2ddl
72 | jpa2ddl-maven-plugin
73 | 0.9.12
74 | true
75 |
76 | ${basedir}/src/main/resources/database.sql
77 |
78 | com.test.model
79 | com.test.entities
80 |
81 |
82 |
83 | hibernate.dialect
84 | org.hibernate.dialect.MySQL57Dialect
85 |
86 |
87 | hibernate.default_schema
88 | prod
89 |
90 |
91 | true
92 | true
93 | ;
94 | DROP_AND_CREATE
95 |
96 |
97 |
98 |
99 | ```
100 |
101 | ### Generate migrations
102 |
103 | It's also possible to generate automated migrations scripts. JPA2DDL supports [Flyway naming patterns](https://flywaydb.org/documentation/migration/sql) for versioned migrations.
104 |
105 | All subsequent migration scripts are saved in the `outputPath`, in the following layout:
106 | ```sh
107 | src/main/resources/migrations/
108 | v1__jpa2ddl.sql
109 | v2__jpa2ddl.sql
110 | ... next
111 | ```
112 |
113 | Please note that after generation you can change the name of the file to make it more descriptive following the filename pattern `v(N)__jpa2ddl(_custom_description).sql` - for example `v1__jpa2ddl_init.sql`
114 |
115 | Sample configuration:
116 |
117 | ```xml
118 |
119 |
120 |
121 | com.devskiller.jpa2ddl
122 | jpa2ddl-maven-plugin
123 | 0.9.12
124 | true
125 |
126 | ${basedir}/src/main/resources/migrations/
127 |
128 | com.test.model
129 | com.test.entities
130 |
131 |
132 |
133 | hibernate.dialect
134 | org.hibernate.dialect.MySQL57Dialect
135 |
136 |
137 | true
138 | ;
139 | UPDATE
140 |
141 |
142 |
143 |
144 | ```
145 |
146 | ### Direct invocation
147 |
148 | ```
149 | ./mvnw com.devskiller.jpa2ddl:jpa2ddl-maven-plugin:0.9.12:generate
150 | ```
151 |
152 | ## Gradle Plugin
153 |
154 | Below you can find a sample `build.gradle` script configuration:
155 |
156 | ```groovy
157 | buildscript {
158 | repositories {
159 | mavenCentral()
160 | }
161 | dependencies {
162 | classpath "com.devskiller.jpa2ddl:jpa2ddl-gradle-plugin:0.9.12"
163 | }
164 | }
165 |
166 | apply plugin: 'com.devskiller.jpa2ddl'
167 |
168 | jpa2ddl {
169 | packages = ['com.test.model']
170 | }
171 | ```
172 |
173 | ## Extending jpa2ddl with SchemaProcessors
174 |
175 | Sometimes more actions that just saving the database migrations are needed.
176 | Example of such use case is when there is a need to generate QueryDSL or JOOQ mappings.
177 | The `SchemaProcessor` mechanism in jpa2ddl resolves such needs.
178 |
179 | ### QueryDSL processor
180 |
181 | Additional dependency `jpa2ddl-querydsl-processor` provides the processor to generate mappings for QueryDSL.
182 | To enable it:
183 | - add a `jpa2ddl-querydsl-processor` dependency to the plugin (`plugin->dependencies->dependency`)
184 | - configure the processor in the `plugin->configiration->processorProperties` section:
185 | - `queryDslOutputPath`: output path for generated mapping classes
186 | - `queryDslOutputPackage`: optionally set package for generated classes
187 |
188 | ```xml
189 |
190 |
191 |
192 | com.devskiller.jpa2ddl
193 | jpa2ddl-maven-plugin
194 | ${project.version}
195 | true
196 |
197 |
198 | oss.devskiller.model
199 |
200 | UPDATE
201 |
202 |
203 | queryDslOutputPath
204 | ${project.build.directory}/generated-sources/query-dsl
205 |
206 |
207 | queryDslOutputPackage
208 | oss.devskiller.querydsl
209 |
210 |
211 |
212 |
213 |
214 | com.devskiller.jpa2ddl
215 | jpa2ddl-querydsl-processor
216 | ${project.version}
217 |
218 |
219 |
220 |
221 |
222 | ```
223 |
224 | ### Building custom SchemaProcessors
225 |
226 | It's possible to build and inject your custom schema processors to jpa2ddl.
227 | The only thing you need to do is to implement the `com.devskiller.jpa2ddl.SchemaProcessor` interface, and add the jar with our implementation as a dependency for the plugin.
228 |
229 | Please refer to the [jpa2ddl-querydsl-processor](https://github.com/Devskiller/jpa2ddl/tree/master/jpa2ddl-querydsl-processor) to see an example.
--------------------------------------------------------------------------------
/jpa2ddl-core/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | com.devskiller.jpa2ddl
7 | jpa2ddl-parent
8 | 0.10.1-SNAPSHOT
9 |
10 |
11 | jpa2ddl-core
12 |
13 | ${project.artifactId}
14 | jpa2ddl core module
15 |
16 |
17 |
18 | org.hibernate
19 | hibernate-core
20 | 5.4.23.Final
21 |
22 |
23 | javax.validation
24 | validation-api
25 |
26 |
27 |
28 |
29 | javax.validation
30 | validation-api
31 | 2.0.1.Final
32 |
33 |
34 |
35 | net.oneandone.reflections8
36 | reflections8
37 | 0.11.7
38 |
39 |
40 |
41 | com.h2database
42 | h2
43 | 1.4.200
44 |
45 |
46 |
47 | javax.xml.bind
48 | jaxb-api
49 | 2.4.0-b180830.0359
50 | runtime
51 |
52 |
53 |
54 | org.glassfish.jaxb
55 | jaxb-runtime
56 | 2.4.0-b180830.0438
57 | runtime
58 |
59 |
60 |
61 |
62 | junit
63 | junit
64 | test
65 |
66 |
67 | org.assertj
68 | assertj-core
69 | test
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/Action.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import org.hibernate.tool.hbm2ddl.SchemaExport;
4 |
5 | public enum Action {
6 | CREATE(SchemaExport.Action.CREATE, "create"),
7 | DROP(SchemaExport.Action.DROP, "drop"),
8 | DROP_AND_CREATE(SchemaExport.Action.BOTH, "drop-and-create"),
9 | UPDATE(SchemaExport.Action.NONE, "update");
10 |
11 | private final SchemaExport.Action schemaExportAction;
12 | private final String schemaGenerationAction;
13 |
14 | Action(SchemaExport.Action schemaExportAction, String schemaGenerationAction) {
15 | this.schemaExportAction = schemaExportAction;
16 | this.schemaGenerationAction = schemaGenerationAction;
17 | }
18 |
19 | public SchemaExport.Action toSchemaExportAction() {
20 | return schemaExportAction;
21 | }
22 |
23 | public String toSchemaGenerationAction() {
24 | return schemaGenerationAction;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/FileResolver.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.net.URISyntaxException;
6 | import java.net.URL;
7 | import java.nio.file.FileSystems;
8 | import java.nio.file.FileVisitResult;
9 | import java.nio.file.Files;
10 | import java.nio.file.Path;
11 | import java.nio.file.PathMatcher;
12 | import java.nio.file.Paths;
13 | import java.nio.file.SimpleFileVisitor;
14 | import java.nio.file.attribute.BasicFileAttributes;
15 | import java.util.ArrayList;
16 | import java.util.Arrays;
17 | import java.util.Collections;
18 | import java.util.Comparator;
19 | import java.util.Enumeration;
20 | import java.util.HashSet;
21 | import java.util.List;
22 | import java.util.Optional;
23 | import java.util.Set;
24 | import java.util.regex.Matcher;
25 | import java.util.regex.Pattern;
26 | import java.util.stream.Collectors;
27 |
28 | import static java.util.regex.Pattern.CASE_INSENSITIVE;
29 |
30 | class FileResolver {
31 |
32 | private final static Pattern FILENAME_PATTERN = Pattern.compile("v([0-9]+)__.+\\.sql", CASE_INSENSITIVE);
33 | private final static Pattern SCHEMA_FILENAME_PATTERN = Pattern.compile("v([0-9]+)__jpa2ddl.*\\.sql", CASE_INSENSITIVE);
34 |
35 | static File resolveNextMigrationFile(File migrationDir) {
36 | Optional lastFile = resolveExistingMigrations(migrationDir, true, false)
37 | .stream()
38 | .findFirst();
39 |
40 | Long fileIndex = lastFile.map((Path input) -> FILENAME_PATTERN.matcher(input.getFileName().toString()))
41 | .map(matcher -> {
42 | if (matcher.find()) {
43 | return Long.valueOf(matcher.group(1));
44 | } else {
45 | return 0L;
46 | }
47 | }).orElse(0L);
48 |
49 | return migrationDir.toPath().resolve("v" + ++fileIndex + "__jpa2ddl.sql").toFile();
50 | }
51 |
52 | static List resolveExistingMigrations(File migrationsDir, boolean reversed, boolean onlySchemaMigrations) {
53 | if (!migrationsDir.exists()) {
54 | migrationsDir.mkdirs();
55 | }
56 |
57 | File[] files = migrationsDir.listFiles();
58 |
59 | if (files == null) {
60 | return Collections.emptyList();
61 | }
62 |
63 | Comparator pathComparator = Comparator.comparingLong(FileResolver::compareVersionedMigrations);
64 | if (reversed) {
65 | pathComparator = pathComparator.reversed();
66 | }
67 | return Arrays.stream(files)
68 | .map(File::toPath)
69 | .filter(path -> !onlySchemaMigrations || SCHEMA_FILENAME_PATTERN.matcher(path.getFileName().toString()).matches())
70 | .sorted(pathComparator)
71 | .collect(Collectors.toList());
72 | }
73 |
74 | static Set listClassNamesInPackage(String packageName) throws Exception {
75 | Set classes = new HashSet<>();
76 | Enumeration resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replace('.', File.separatorChar));
77 | if (!resources.hasMoreElements()) {
78 | throw new IllegalStateException("No package found: " + packageName);
79 | }
80 | PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:*.class");
81 | while (resources.hasMoreElements()) {
82 | URL resource = resources.nextElement();
83 | Files.walkFileTree(Paths.get(resource.toURI()), new SimpleFileVisitor() {
84 | @Override
85 | public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
86 | if (pathMatcher.matches(path.getFileName())) {
87 | try {
88 | String className = Paths.get(resource.toURI()).relativize(path).toString().replace(File.separatorChar, '.');
89 | classes.add(packageName + '.' + className.substring(0, className.length() - 6));
90 | } catch (URISyntaxException e) {
91 | throw new IllegalStateException(e);
92 | }
93 | }
94 | return FileVisitResult.CONTINUE;
95 | }
96 | });
97 | }
98 | return classes;
99 | }
100 |
101 | private static Long compareVersionedMigrations(Path path) {
102 | Matcher filenameMatcher = FILENAME_PATTERN.matcher(path.getFileName().toString());
103 | if (filenameMatcher.find()) {
104 | return Long.valueOf(filenameMatcher.group(1));
105 | } else {
106 | return Long.MIN_VALUE;
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/GenerationMode.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | public enum GenerationMode {
4 |
5 | /**
6 | * Generation based on setting up embedded database and dumping the schema
7 | */
8 | DATABASE,
9 |
10 | /**
11 | * Generation based on static metadata
12 | */
13 | METADATA
14 | }
15 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/GeneratorSettings.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.io.File;
4 | import java.util.List;
5 | import java.util.Properties;
6 |
7 | class GeneratorSettings {
8 |
9 | private final GenerationMode generationMode;
10 | private final File outputPath;
11 | private final List packages;
12 | private final Action action;
13 | private final Properties jpaProperties;
14 | private final boolean formatOutput;
15 | private final String delimiter;
16 | private final boolean skipSequences;
17 | private final Properties processorProperties;
18 |
19 | GeneratorSettings(GenerationMode generationMode, File outputPath, List packages, Action action,
20 | Properties jpaProperties, boolean formatOutput, String delimiter,
21 | boolean skipSequences, Properties processorProperties) {
22 | this.generationMode = generationMode;
23 | this.outputPath = outputPath;
24 | this.packages = packages;
25 | this.action = action;
26 | this.jpaProperties = jpaProperties;
27 | this.formatOutput = formatOutput;
28 | this.delimiter = delimiter;
29 | this.skipSequences = skipSequences;
30 | this.processorProperties = processorProperties;
31 | }
32 |
33 | GenerationMode getGenerationMode() {
34 | return generationMode;
35 | }
36 |
37 | File getOutputPath() {
38 | return outputPath;
39 | }
40 |
41 | List getPackages() {
42 | return packages;
43 | }
44 |
45 | Action getAction() {
46 | return action;
47 | }
48 |
49 | Properties getJpaProperties() {
50 | return jpaProperties;
51 | }
52 |
53 | boolean isFormatOutput() {
54 | return formatOutput;
55 | }
56 |
57 | String getDelimiter() {
58 | return delimiter;
59 | }
60 |
61 | boolean isSkipSequences() {
62 | return skipSequences;
63 | }
64 |
65 | Properties getProcessorProperties() {
66 | return processorProperties;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/NoSequenceFilterProvider.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import org.hibernate.boot.model.relational.Sequence;
4 | import org.hibernate.mapping.Table;
5 | import org.hibernate.tool.schema.internal.DefaultSchemaFilter;
6 | import org.hibernate.tool.schema.spi.SchemaFilter;
7 | import org.hibernate.tool.schema.spi.SchemaFilterProvider;
8 |
9 | public class NoSequenceFilterProvider implements SchemaFilterProvider {
10 |
11 | @Override
12 | public SchemaFilter getCreateFilter() {
13 | return NoSequenceSchemaFilter.INSTANCE;
14 | }
15 |
16 | @Override
17 | public SchemaFilter getDropFilter() {
18 | return NoSequenceSchemaFilter.INSTANCE;
19 | }
20 |
21 | @Override
22 | public SchemaFilter getMigrateFilter() {
23 | return NoSequenceSchemaFilter.INSTANCE;
24 | }
25 |
26 | @Override
27 | public SchemaFilter getValidateFilter() {
28 | return NoSequenceSchemaFilter.INSTANCE;
29 | }
30 |
31 | private static class NoSequenceSchemaFilter extends DefaultSchemaFilter {
32 |
33 | private static final SchemaFilter INSTANCE = new NoSequenceSchemaFilter();
34 |
35 | @Override
36 | public boolean includeTable(Table table) {
37 | return !isIdentifierTable(table);
38 | }
39 |
40 | private boolean isIdentifierTable(Table table) {
41 | return !table.getInitCommands().isEmpty();
42 | }
43 |
44 | @Override
45 | public boolean includeSequence(Sequence sequence) {
46 | return false;
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/SchemaGenerator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import com.devskiller.jpa2ddl.engines.EngineDecorator;
4 | import org.hibernate.boot.MetadataSources;
5 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
6 | import org.hibernate.tool.hbm2ddl.SchemaExport;
7 | import org.hibernate.tool.schema.TargetType;
8 | import org.reflections8.Reflections;
9 | import org.reflections8.scanners.SubTypesScanner;
10 | import org.reflections8.util.ConfigurationBuilder;
11 |
12 | import java.io.File;
13 | import java.net.URISyntaxException;
14 | import java.net.URL;
15 | import java.nio.file.Files;
16 | import java.nio.file.Path;
17 | import java.sql.Connection;
18 | import java.sql.DriverManager;
19 | import java.util.EnumSet;
20 | import java.util.List;
21 | import java.util.Set;
22 | import java.util.stream.Collectors;
23 |
24 | class SchemaGenerator {
25 |
26 | private static final String DB_URL = "jdbc:h2:mem:jpa2ddl";
27 | private static final String HIBERNATE_DIALECT = "hibernate.dialect";
28 | private static final String HIBERNATE_SCHEMA_FILTER_PROVIDER = "hibernate.hbm2ddl.schema_filter_provider";
29 |
30 | void generate(GeneratorSettings settings) throws Exception {
31 | validateSettings(settings);
32 |
33 | if (settings.getJpaProperties().getProperty(HIBERNATE_DIALECT) == null) {
34 | settings.getJpaProperties().setProperty(HIBERNATE_DIALECT, "org.hibernate.dialect.H2Dialect");
35 | }
36 |
37 | if (settings.isSkipSequences() && settings.getJpaProperties().getProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER) == null) {
38 | settings.getJpaProperties().setProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER, NoSequenceFilterProvider.class.getCanonicalName());
39 | }
40 |
41 | File outputFile = settings.getOutputPath();
42 |
43 | EngineDecorator engineDecorator = EngineDecorator.getEngineDecorator(settings.getJpaProperties().getProperty(HIBERNATE_DIALECT));
44 |
45 | String dbUrl = getDbUrl(engineDecorator);
46 |
47 | if (settings.getGenerationMode() == GenerationMode.DATABASE) {
48 |
49 | if (settings.getAction() == Action.UPDATE) {
50 | outputFile = FileResolver.resolveNextMigrationFile(settings.getOutputPath());
51 | }
52 |
53 | settings.getJpaProperties().setProperty("hibernate.connection.url", dbUrl);
54 | settings.getJpaProperties().setProperty("hibernate.connection.username", "sa");
55 | settings.getJpaProperties().setProperty("hibernate.connection.password", "");
56 | settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.action", settings.getAction().toSchemaGenerationAction());
57 | settings.getJpaProperties().setProperty("javax.persistence.schema-generation.database.action", settings.getAction().toSchemaGenerationAction());
58 |
59 | settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.create-target", outputFile.getAbsolutePath());
60 | settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.drop-target", outputFile.getAbsolutePath());
61 |
62 | settings.getJpaProperties().setProperty("hibernate.hbm2ddl.delimiter", settings.getDelimiter());
63 | settings.getJpaProperties().setProperty("hibernate.format_sql", String.valueOf(settings.isFormatOutput()));
64 | }
65 |
66 | MetadataSources metadata = new MetadataSources(
67 | new StandardServiceRegistryBuilder()
68 | .applySettings(settings.getJpaProperties())
69 | .build());
70 |
71 | for (String packageName: settings.getPackages().stream().sorted().collect(Collectors.toList())) {
72 | FileResolver.listClassNamesInPackage(packageName).stream().sorted().forEach(metadata::addAnnotatedClassName);
73 | metadata.addPackage(packageName);
74 | }
75 |
76 | if (settings.getAction() != Action.UPDATE) {
77 | Files.deleteIfExists(settings.getOutputPath().toPath());
78 | }
79 |
80 | if (settings.getGenerationMode() == GenerationMode.METADATA) {
81 | SchemaExport export = new SchemaExport();
82 | export.setFormat(settings.isFormatOutput());
83 | export.setDelimiter(settings.getDelimiter());
84 | export.setOutputFile(outputFile.getAbsolutePath());
85 | export.execute(EnumSet.of(TargetType.SCRIPT), settings.getAction().toSchemaExportAction(), metadata.buildMetadata());
86 | } else {
87 | Class.forName("org.h2.Driver"); // walkaround for the "No suitable driver found" caused by driver being not registered in the DriverManager
88 | Connection connection = DriverManager.getConnection(dbUrl, "SA", "");
89 | engineDecorator.decorateDatabaseInitialization(connection);
90 |
91 | if (settings.getAction() == Action.UPDATE) {
92 | List resolvedMigrations = FileResolver.resolveExistingMigrations(settings.getOutputPath(), false, true);
93 | for (Path resolvedMigration : resolvedMigrations) {
94 | String statement = new String(Files.readAllBytes(resolvedMigration));
95 | connection.prepareStatement(statement).execute();
96 | }
97 | }
98 |
99 | metadata.buildMetadata().buildSessionFactory().close();
100 |
101 | executePostProcessors(settings, connection);
102 |
103 | connection.close();
104 | }
105 |
106 | if (outputFile.exists()) {
107 | if (outputFile.length() == 0) {
108 | Files.delete(outputFile.toPath());
109 | } else {
110 | List lines = Files.readAllLines(outputFile.toPath())
111 | .stream()
112 | .map(line -> line.replaceAll("(?i)JPA2DDL\\.(PUBLIC\\.)?", ""))
113 | .collect(Collectors.toList());
114 | Files.write(outputFile.toPath(), lines);
115 | }
116 | }
117 | }
118 |
119 | private void executePostProcessors(GeneratorSettings settings, Connection connection) throws Exception {
120 | ConfigurationBuilder configuration = ConfigurationBuilder.build(".*")
121 | .setExpandSuperTypes(false)
122 | .setScanners(new SubTypesScanner(true));
123 | configuration.setUrls(getExistingUrls(configuration.getUrls()));
124 | Reflections reflections = new Reflections(configuration);
125 |
126 | Set> schemaProcessorClasses = reflections.getSubTypesOf(SchemaProcessor.class);
127 |
128 | for (Class extends SchemaProcessor> schemaProcessorClass : schemaProcessorClasses) {
129 | SchemaProcessor schemaProcessor = schemaProcessorClass.getDeclaredConstructor().newInstance();
130 | schemaProcessor.postProcess(connection, settings.getProcessorProperties());
131 | }
132 | }
133 |
134 | private Set getExistingUrls(Set urls) {
135 | return urls.stream()
136 | .filter(url -> {
137 | try {
138 | return new File(url.toURI()).exists();
139 | } catch (URISyntaxException e) {
140 | throw new RuntimeException(e);
141 | }
142 | })
143 | .collect(Collectors.toSet());
144 | }
145 |
146 | private String getDbUrl(EngineDecorator engineDecorator) {
147 | return engineDecorator.decorateConnectionString(DB_URL);
148 | }
149 |
150 | private void validateSettings(GeneratorSettings settings) {
151 | if (settings.getAction() == Action.UPDATE) {
152 | if (settings.getOutputPath().exists() && !settings.getOutputPath().isDirectory()) {
153 | throw new IllegalArgumentException("For UPDATE action outputPath must be a directory");
154 | }
155 | if (settings.getGenerationMode() != GenerationMode.DATABASE) {
156 | throw new IllegalArgumentException("For UPDATE action generation mode must be set to DATABASE");
157 | }
158 | }
159 | }
160 |
161 | }
162 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/SchemaProcessor.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.sql.Connection;
4 | import java.util.Properties;
5 |
6 | public interface SchemaProcessor {
7 |
8 | void postProcess(Connection connection, Properties properties);
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/dialects/H2MySQL57Dialect.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.dialects;
2 |
3 | import org.hibernate.dialect.MySQL57Dialect;
4 | import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorH2DatabaseImpl;
5 | import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
6 |
7 | public class H2MySQL57Dialect extends MySQL57Dialect {
8 |
9 | @Override
10 | public SequenceInformationExtractor getSequenceInformationExtractor() {
11 | return new SequenceInformationExtractorH2DatabaseImpl();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/dialects/H2MySQL8Dialect.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.dialects;
2 |
3 | import org.hibernate.dialect.MySQL8Dialect;
4 | import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorH2DatabaseImpl;
5 | import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
6 |
7 | public class H2MySQL8Dialect extends MySQL8Dialect {
8 |
9 | @Override
10 | public SequenceInformationExtractor getSequenceInformationExtractor() {
11 | return new SequenceInformationExtractorH2DatabaseImpl();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/dialects/H2PostgreSQL10Dialect.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.dialects;
2 |
3 | import org.hibernate.dialect.PostgreSQL10Dialect;
4 | import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorH2DatabaseImpl;
5 | import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
6 |
7 | public class H2PostgreSQL10Dialect extends PostgreSQL10Dialect {
8 |
9 | @Override
10 | public SequenceInformationExtractor getSequenceInformationExtractor() {
11 | return new SequenceInformationExtractorH2DatabaseImpl();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/dialects/H2PostgreSQL95Dialect.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.dialects;
2 |
3 | import org.hibernate.dialect.PostgreSQL95Dialect;
4 | import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorH2DatabaseImpl;
5 | import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
6 |
7 | public class H2PostgreSQL95Dialect extends PostgreSQL95Dialect {
8 |
9 | @Override
10 | public SequenceInformationExtractor getSequenceInformationExtractor() {
11 | return new SequenceInformationExtractorH2DatabaseImpl();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/engines/EngineDecorator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.engines;
2 |
3 | import java.io.IOException;
4 | import java.sql.Connection;
5 | import java.sql.SQLException;
6 |
7 | import org.hibernate.dialect.MySQLDialect;
8 | import org.hibernate.dialect.Oracle8iDialect;
9 | import org.hibernate.dialect.PostgreSQL81Dialect;
10 | import org.hibernate.dialect.SQLServerDialect;
11 |
12 | public abstract class EngineDecorator {
13 |
14 | public static EngineDecorator getEngineDecorator(String dialect) throws ClassNotFoundException {
15 | Class> dialectClass = Class.forName(dialect);
16 | if (MySQLDialect.class.isAssignableFrom(dialectClass)) {
17 | return new MySQLDecorator();
18 | } else if (PostgreSQL81Dialect.class.isAssignableFrom(dialectClass)) {
19 | return new PostgreSQLDecorator();
20 | } else if (Oracle8iDialect.class.isAssignableFrom(dialectClass)) {
21 | return new OracleDecorator();
22 | } else if (SQLServerDialect.class.isAssignableFrom(dialectClass)) {
23 | return new SQLServerDecorator();
24 | }
25 | return new NoOpDecorator();
26 |
27 | }
28 |
29 | public String decorateConnectionString(String connectionString) {
30 | return connectionString;
31 | }
32 |
33 | public void decorateDatabaseInitialization(Connection connection) throws IOException, SQLException {
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/engines/MySQLDecorator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.engines;
2 |
3 | class MySQLDecorator extends EngineDecorator {
4 |
5 | @Override
6 | public String decorateConnectionString(String connectionString) {
7 | return connectionString + ";MODE=MYSQL;DATABASE_TO_UPPER=FALSE";
8 | }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/engines/NoOpDecorator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.engines;
2 |
3 | class NoOpDecorator extends EngineDecorator {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/engines/OracleDecorator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.engines;
2 |
3 | import java.sql.Connection;
4 | import java.sql.SQLException;
5 |
6 | class OracleDecorator extends EngineDecorator {
7 |
8 | private static final String SEQUENCES_VIEW = "CREATE VIEW ALL_SEQUENCES(SEQUENCE_NAME, SEQUENCE_OWNER) AS SELECT SEQUENCE_NAME, '' FROM INFORMATION_SCHEMA.SEQUENCES;";
9 | private static final String EMPTY_SYNONYMS = "CREATE TABLE ALL_SYNONYMS (SYNONYM_NAME VARCHAR2(30), TABLE_OWNER VARCHAR2(30), TABLE_NAME VARCHAR2(30));";
10 |
11 | @Override
12 | public String decorateConnectionString(String connectionString) {
13 | return connectionString + ";MODE=Oracle";
14 | }
15 |
16 | @Override
17 | public void decorateDatabaseInitialization(Connection connection) throws SQLException {
18 | connection.prepareStatement(SEQUENCES_VIEW + "\n" + EMPTY_SYNONYMS).execute();
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/engines/PostgreSQLDecorator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.engines;
2 |
3 | import java.io.IOException;
4 | import java.sql.Connection;
5 | import java.sql.SQLException;
6 |
7 | import org.h2.util.Utils;
8 |
9 | class PostgreSQLDecorator extends EngineDecorator {
10 |
11 | @Override
12 | public String decorateConnectionString(String connectionString) {
13 | return connectionString + ";MODE=PostgreSQL;INIT=set search_path to pg_catalog,public;";
14 | }
15 |
16 | @Override
17 | public void decorateDatabaseInitialization(Connection connection) throws IOException, SQLException {
18 | String dbInit = new String(Utils.getResource("/org/h2/server/pg/pg_catalog.sql"));
19 | connection.prepareStatement(dbInit).execute();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/main/java/com/devskiller/jpa2ddl/engines/SQLServerDecorator.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.engines;
2 |
3 | class SQLServerDecorator extends EngineDecorator {
4 |
5 | @Override
6 | public String decorateConnectionString(String connectionString) {
7 | return connectionString + ";MODE=MSSQLServer";
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/DatabaseComplexSchemaUpdateTest.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import com.devskiller.jpa2ddl.dialects.H2MySQL57Dialect;
4 | import com.devskiller.jpa2ddl.dialects.H2PostgreSQL95Dialect;
5 | import org.hibernate.dialect.MySQL57Dialect;
6 | import org.hibernate.dialect.Oracle12cDialect;
7 | import org.hibernate.dialect.PostgreSQL9Dialect;
8 | import org.junit.Ignore;
9 | import org.junit.Rule;
10 | import org.junit.Test;
11 | import org.junit.rules.TemporaryFolder;
12 |
13 | import java.io.File;
14 | import java.nio.file.Files;
15 | import java.nio.file.Paths;
16 | import java.util.Arrays;
17 | import java.util.Properties;
18 |
19 | import static org.assertj.core.api.Assertions.assertThat;
20 |
21 | public class DatabaseComplexSchemaUpdateTest {
22 |
23 | @Rule
24 | public TemporaryFolder tempFolder = new TemporaryFolder();
25 |
26 | @Test
27 | @Ignore("should be resolved by introducing test containers in #40")
28 | public void shouldGenerateSchemaUpdate() throws Exception {
29 | // given
30 | File outputPath = tempFolder.newFolder();
31 |
32 | Files.copy(Paths.get(getClass().getClassLoader().getResource("complex_migration/v1__jpa2ddl_init.sql").toURI()),
33 | outputPath.toPath().resolve("v1__jpa2ddl_init.sql"));
34 |
35 | Properties jpaProperties = new Properties();
36 | jpaProperties.setProperty("hibernate.dialect", H2MySQL57Dialect.class.getCanonicalName());
37 |
38 | SchemaGenerator schemaGenerator = new SchemaGenerator();
39 |
40 | // when
41 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
42 | Arrays.asList("com.devskiller.jpa2ddl.complex"), Action.UPDATE, jpaProperties, true, ";", false, null));
43 |
44 | // then
45 | String sql = new String(Files.readAllBytes(outputPath.toPath().resolve("v2__jpa2ddl.sql")));
46 | assertThat(sql).doesNotContain("alter table Book_Chapter");
47 | assertThat(sql).doesNotContain("drop index");
48 | assertThat(sql).doesNotContain("add constraint");
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/DatabaseSchemaGeneratorTest.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.io.File;
4 | import java.nio.file.Files;
5 | import java.util.Arrays;
6 | import java.util.Properties;
7 |
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.TemporaryFolder;
11 |
12 | import static org.assertj.core.api.Assertions.assertThat;
13 |
14 | public class DatabaseSchemaGeneratorTest {
15 |
16 | @Rule
17 | public TemporaryFolder tempFolder = new TemporaryFolder();
18 |
19 | @Test
20 | public void shouldGenerateSchemaFromDatabaseWithDropAndCreate() throws Exception {
21 | // given
22 | SchemaGenerator schemaGenerator = new SchemaGenerator();
23 | File outputFile = tempFolder.newFile();
24 | File outputDir = tempFolder.newFolder();
25 |
26 | // when
27 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputFile,
28 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.DROP_AND_CREATE, new Properties(), true, ";", false, null));
29 |
30 | // then
31 | String sql = new String(Files.readAllBytes(outputFile.toPath()));
32 | assertThat(sql).contains("create table User");
33 | assertThat(sql).contains("drop table if exists User");
34 | }
35 |
36 | @Test
37 | public void shouldGenerateSchemaFromDatabaseWithDrop() throws Exception {
38 | // given
39 | SchemaGenerator schemaGenerator = new SchemaGenerator();
40 | File outputFile = tempFolder.newFile();
41 |
42 | // when
43 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputFile,
44 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.DROP, new Properties(), true, ";", false, null));
45 |
46 | // then
47 | String sql = new String(Files.readAllBytes(outputFile.toPath()));
48 | assertThat(sql).doesNotContain("create table User");
49 | assertThat(sql).contains("drop table if exists User");
50 | }
51 |
52 | @Test
53 | public void shouldGenerateSchemaFromDatabaseWithCreate() throws Exception {
54 | // given
55 | SchemaGenerator schemaGenerator = new SchemaGenerator();
56 | File outputFile = tempFolder.newFile();
57 | File outputDir = tempFolder.newFolder();
58 |
59 | // when
60 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputFile,
61 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.CREATE, new Properties(), true, ";", false, null));
62 |
63 | // then
64 | String sql = new String(Files.readAllBytes(outputFile.toPath()));
65 | assertThat(sql).contains("create table User");
66 | assertThat(sql).doesNotContain("drop table User");
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/DatabaseSchemaUpdateTest.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import com.devskiller.jpa2ddl.dialects.H2PostgreSQL95Dialect;
4 | import org.hibernate.dialect.MySQL57Dialect;
5 | import org.hibernate.dialect.Oracle12cDialect;
6 | import org.hibernate.dialect.PostgreSQL10Dialect;
7 | import org.junit.Rule;
8 | import org.junit.Test;
9 | import org.junit.rules.TemporaryFolder;
10 |
11 | import java.io.File;
12 | import java.nio.file.Files;
13 | import java.nio.file.Paths;
14 | import java.util.Arrays;
15 | import java.util.Properties;
16 |
17 | import static org.assertj.core.api.Assertions.assertThat;
18 |
19 | public class DatabaseSchemaUpdateTest {
20 |
21 | @Rule
22 | public TemporaryFolder tempFolder = new TemporaryFolder();
23 |
24 | @Test
25 | public void shouldGenerateSchemaUpdate() throws Exception {
26 | // given
27 | File outputPath = tempFolder.newFolder();
28 |
29 | Files.copy(Paths.get(getClass().getClassLoader().getResource("sample_migration/v1__jpa2ddl_init.sql").toURI()),
30 | outputPath.toPath().resolve("v1__jpa2ddl_init.sql"));
31 |
32 | Properties jpaProperties = new Properties();
33 | jpaProperties.setProperty("hibernate.dialect", MySQL57Dialect.class.getCanonicalName());
34 | jpaProperties.setProperty("hibernate.default_schema", "prod");
35 |
36 | SchemaGenerator schemaGenerator = new SchemaGenerator();
37 |
38 | // when
39 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
40 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.UPDATE, jpaProperties, true, ";", false, null));
41 |
42 | // then
43 | String sql = new String(Files.readAllBytes(outputPath.toPath().resolve("v2__jpa2ddl.sql")));
44 | assertThat(sql).containsIgnoringCase("alter table prod.User");
45 | assertThat(sql).containsIgnoringCase("add column email varchar(255);");
46 | assertThat(sql).containsIgnoringCase("create table prod.hibernate_sequence");
47 | assertThat(sql).containsIgnoringCase("insert into prod.hibernate_sequence values");
48 | assertThat(sql).doesNotContain("create table prod.User");
49 | }
50 |
51 | @Test
52 | public void shouldGenerateDefaultSchemaUpdate() throws Exception {
53 | // given
54 | File outputPath = tempFolder.newFolder();
55 |
56 | Files.copy(Paths.get(getClass().getClassLoader().getResource("sample_default_migration/v1__jpa2ddl_init.sql").toURI()),
57 | outputPath.toPath().resolve("v1__jpa2ddl_init.sql"));
58 |
59 | Properties jpaProperties = new Properties();
60 | jpaProperties.setProperty("hibernate.dialect", MySQL57Dialect.class.getCanonicalName());
61 |
62 | SchemaGenerator schemaGenerator = new SchemaGenerator();
63 |
64 | // when
65 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
66 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.UPDATE, jpaProperties, true, ";", true, null));
67 |
68 | // then
69 | String sql = new String(Files.readAllBytes(outputPath.toPath().resolve("v2__jpa2ddl.sql")));
70 | assertThat(sql).containsIgnoringCase("alter table User");
71 | assertThat(sql).containsIgnoringCase("add column email");
72 | assertThat(sql).doesNotContain("create table User");
73 | assertThat(sql).doesNotContain("create table hibernate_sequence");
74 | assertThat(sql).doesNotContain("insert into hibernate_sequence values");
75 | }
76 |
77 |
78 | @Test
79 | public void shouldSkipGenerationIfNoChanges() throws Exception {
80 | // given
81 | File outputPath = tempFolder.newFolder();
82 |
83 | Files.copy(Paths.get(getClass().getClassLoader().getResource("sample_empty_migration/v1__jpa2ddl_init.sql").toURI()),
84 | outputPath.toPath().resolve("v1__jpa2ddl_init.sql"));
85 |
86 | Properties jpaProperties = new Properties();
87 | jpaProperties.setProperty("hibernate.dialect", MySQL57Dialect.class.getCanonicalName());
88 |
89 | SchemaGenerator schemaGenerator = new SchemaGenerator();
90 |
91 | // when
92 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
93 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.UPDATE, jpaProperties, true, ";", true, null));
94 |
95 | // then
96 | File migrationFile = outputPath.toPath().resolve("v2__jpa2ddl.sql").toFile();
97 | assertThat(migrationFile).doesNotExist();
98 | }
99 |
100 | @Test
101 | public void shouldGenerateSchemaFromDatabaseWithUpdateWithPostgresDialect() throws Exception {
102 | // given
103 | File outputPath = tempFolder.newFolder();
104 | Properties jpaProperties = new Properties();
105 | jpaProperties.setProperty("hibernate.dialect", PostgreSQL10Dialect.class.getCanonicalName());
106 | jpaProperties.setProperty("hibernate.default_schema", "public");
107 |
108 | SchemaGenerator schemaGenerator = new SchemaGenerator();
109 |
110 | // when
111 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
112 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.UPDATE, jpaProperties, true, ";", false, null));
113 |
114 | // then
115 | String sql = new String(Files.readAllBytes(outputPath.toPath().resolve("v1__jpa2ddl.sql")));
116 | assertThat(sql).contains("create table public.User");
117 | assertThat(sql).doesNotContain("drop table public.User");
118 | }
119 |
120 | @Test
121 | public void shouldGenerateDefaultSchemaUpdateWithPostgresDialect() throws Exception {
122 | // given
123 | File outputPath = tempFolder.newFolder();
124 |
125 | Files.copy(Paths.get(getClass().getClassLoader().getResource("sample_postgres_migration/v1__jpa2ddl_init.sql").toURI()),
126 | outputPath.toPath().resolve("v1__jpa2ddl_init.sql"));
127 |
128 | Properties jpaProperties = new Properties();
129 | jpaProperties.setProperty("hibernate.dialect", H2PostgreSQL95Dialect.class.getCanonicalName());
130 |
131 | SchemaGenerator schemaGenerator = new SchemaGenerator();
132 |
133 | // when
134 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
135 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.UPDATE, jpaProperties, true, ";", true, null));
136 |
137 | // then
138 | String sql = new String(Files.readAllBytes(outputPath.toPath().resolve("v2__jpa2ddl.sql")));
139 | assertThat(sql).containsIgnoringCase("alter table if exists User");
140 | assertThat(sql).containsIgnoringCase("add column email");
141 | assertThat(sql).doesNotContain("create table User");
142 | assertThat(sql).doesNotContain("create sequence");
143 | }
144 |
145 | @Test
146 | public void shouldGenerateSchemaFromDatabaseWithUpdateWithOracleDialect() throws Exception {
147 | // given
148 | File outputPath = tempFolder.newFolder();
149 | Properties jpaProperties = new Properties();
150 | jpaProperties.setProperty("hibernate.dialect", Oracle12cDialect.class.getCanonicalName());
151 |
152 | SchemaGenerator schemaGenerator = new SchemaGenerator();
153 |
154 | // when
155 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.DATABASE, outputPath,
156 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.UPDATE, jpaProperties, true, ";", false, null));
157 |
158 | // then
159 | String sql = new String(Files.readAllBytes(outputPath.toPath().resolve("v1__jpa2ddl.sql")));
160 | assertThat(sql).contains("create table User");
161 | assertThat(sql).doesNotContain("drop table User");
162 | }
163 |
164 |
165 | }
166 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/FileResolverTest.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.io.File;
4 | import java.nio.file.Path;
5 | import java.util.List;
6 |
7 | import org.junit.Rule;
8 | import org.junit.Test;
9 | import org.junit.rules.TemporaryFolder;
10 |
11 | import static org.assertj.core.api.Assertions.assertThat;
12 |
13 | public class FileResolverTest {
14 |
15 | @Rule
16 | public TemporaryFolder tempFolder = new TemporaryFolder();
17 |
18 | @Test
19 | public void shouldReturnExistingMigrations() throws Exception {
20 | // given
21 | File migrationsDir = tempFolder.newFolder();
22 |
23 | Path first = migrationsDir.toPath().resolve("v1__jpa2ddl_init.sql");
24 | first.toFile().createNewFile();
25 | Path second = migrationsDir.toPath().resolve("v2__my_description.sql");
26 | second.toFile().createNewFile();
27 | Path third = migrationsDir.toPath().resolve("v3__jpa2ddl.sql");
28 | third.toFile().createNewFile();
29 |
30 | // when
31 | List file = FileResolver.resolveExistingMigrations(migrationsDir, false, true);
32 |
33 | // then
34 | assertThat(file).containsSequence(
35 | first,
36 | third
37 | );
38 | }
39 |
40 | @Test
41 | public void shouldResolveFirstMigration() throws Exception {
42 | // given
43 | File migrationsDir = tempFolder.newFolder();
44 |
45 | // when
46 | File file = FileResolver.resolveNextMigrationFile(migrationsDir);
47 |
48 | // then
49 | assertThat(file.toPath()).isEqualTo(migrationsDir.toPath().resolve("v1__jpa2ddl.sql"));
50 | }
51 |
52 | @Test
53 | public void shouldResolveNextMigration() throws Exception {
54 | // given
55 | File migrationsDir = tempFolder.newFolder();
56 | migrationsDir.toPath().resolve("v1__jpa2ddl.sql").toFile().createNewFile();
57 | migrationsDir.toPath().resolve("v2__my_description.sql").toFile().createNewFile();
58 |
59 | // when
60 | File file = FileResolver.resolveNextMigrationFile(migrationsDir);
61 |
62 | // then
63 | assertThat(file.toPath()).isEqualTo(migrationsDir.toPath().resolve("v3__jpa2ddl.sql"));
64 | }
65 |
66 | }
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/MetadataSchemaGeneratorTest.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.io.File;
4 | import java.nio.file.Files;
5 | import java.util.Arrays;
6 | import java.util.Properties;
7 |
8 | import org.junit.Rule;
9 | import org.junit.Test;
10 | import org.junit.rules.TemporaryFolder;
11 |
12 | import static org.assertj.core.api.Assertions.assertThat;
13 |
14 | public class MetadataSchemaGeneratorTest {
15 |
16 | @Rule
17 | public TemporaryFolder tempFolder = new TemporaryFolder();
18 |
19 | @Test
20 | public void shouldGenerateSchemaFromMetadataWithDropAndCreate() throws Exception {
21 | // given
22 | SchemaGenerator schemaGenerator = new SchemaGenerator();
23 | File outputFile = tempFolder.newFile();
24 |
25 | // when
26 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.METADATA, outputFile,
27 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.DROP_AND_CREATE, new Properties(), true, ";", false, null));
28 |
29 | // then
30 | String sql = new String(Files.readAllBytes(outputFile.toPath()));
31 | assertThat(sql).contains("create table User");
32 | assertThat(sql).contains("drop table if exists User");
33 | }
34 |
35 | @Test
36 | public void shouldGenerateSchemaFromMetadataWithDrop() throws Exception {
37 | // given
38 | SchemaGenerator schemaGenerator = new SchemaGenerator();
39 | File outputFile = tempFolder.newFile();
40 |
41 | // when
42 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.METADATA, outputFile,
43 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.DROP, new Properties(), true, ";", false, null));
44 |
45 | // then
46 | String sql = new String(Files.readAllBytes(outputFile.toPath()));
47 | assertThat(sql).doesNotContain("create table User");
48 | assertThat(sql).contains("drop table if exists User");
49 | }
50 |
51 | @Test
52 | public void shouldGenerateSchemaFromMetadataWithCreate() throws Exception {
53 | // given
54 | SchemaGenerator schemaGenerator = new SchemaGenerator();
55 | File outputFile = tempFolder.newFile();
56 |
57 | // when
58 | schemaGenerator.generate(new GeneratorSettings(GenerationMode.METADATA, outputFile,
59 | Arrays.asList("com.devskiller.jpa2ddl.sample"), Action.CREATE, new Properties(), true, ";", false, null));
60 |
61 | // then
62 | String sql = new String(Files.readAllBytes(outputFile.toPath()));
63 | assertThat(sql).contains("create table User");
64 | assertThat(sql).doesNotContain("drop table User");
65 | }
66 |
67 | @Test
68 | public void shouldGenerateSchemaFromH2() throws Exception {
69 |
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/complex/Book.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.complex;
2 |
3 | import org.hibernate.annotations.OnDelete;
4 | import org.hibernate.annotations.OnDeleteAction;
5 |
6 | import javax.persistence.CollectionTable;
7 | import javax.persistence.ElementCollection;
8 | import javax.persistence.Entity;
9 | import javax.persistence.Id;
10 | import javax.persistence.Index;
11 | import javax.persistence.JoinColumn;
12 | import java.util.HashSet;
13 | import java.util.Set;
14 |
15 | @Entity
16 | class Book {
17 |
18 | @Id
19 | private Long id;
20 |
21 | @ElementCollection
22 | @JoinColumn
23 | @OnDelete(action = OnDeleteAction.CASCADE)
24 | @CollectionTable(indexes = {@Index(name = "fk_book_chapter", columnList = "book_id")})
25 | public final Set chapters = new HashSet<>();
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/complex/Chapter.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.complex;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.Id;
5 |
6 | @Entity
7 | class Chapter {
8 |
9 | @Id
10 | private Long id;
11 | }
12 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/java/com/devskiller/jpa2ddl/sample/User.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl.sample;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.GenerationType;
6 | import javax.persistence.Id;
7 | import java.util.Date;
8 |
9 | @Entity
10 | class User {
11 |
12 | @Id
13 | @GeneratedValue(strategy = GenerationType.SEQUENCE)
14 | private long id;
15 |
16 | private Date date;
17 |
18 | private String email;
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/resources/complex_migration/v1__jpa2ddl_init.sql:
--------------------------------------------------------------------------------
1 | drop table if exists Book CASCADE ;
2 |
3 | drop table if exists Book_Chapter CASCADE ;
4 |
5 | drop table if exists Chapter CASCADE ;
6 |
7 | create table Book (
8 | id bigint not null,
9 | primary key (id)
10 | );
11 |
12 | create table Book_Chapter (
13 | Book_id bigint not null,
14 | chapters_id bigint not null,
15 | primary key (Book_id, chapters_id)
16 | );
17 |
18 | create table Chapter (
19 | id bigint not null,
20 | primary key (id)
21 | );
22 | create index fk_book_chapter on Book_Chapter (Book_id);
23 |
24 | alter table Book_Chapter
25 | add constraint UK_tokwoktdrnoke2coi76lqff1s unique (chapters_id);
26 |
27 | alter table Book_Chapter
28 | add constraint FKcsndnril8gfgxo6f7osu292dr
29 | foreign key (chapters_id)
30 | references Chapter;
31 |
32 | alter table Book_Chapter
33 | add constraint FKrylp6x2fsgdveg71fhss6riby
34 | foreign key (Book_id)
35 | references Book
36 | on delete cascade;
37 |
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/resources/sample_default_migration/v1__jpa2ddl_init.sql:
--------------------------------------------------------------------------------
1 | create table User (
2 | id bigint not null,
3 | date datetime(6),
4 | primary key (id)
5 | ) engine=InnoDB;
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/resources/sample_empty_migration/v1__jpa2ddl_init.sql:
--------------------------------------------------------------------------------
1 | create table User (
2 | id bigint not null,
3 | date datetime(6),
4 | email varchar(255),
5 | primary key (id)
6 | ) engine=InnoDB;
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/resources/sample_migration/v1__jpa2ddl_init.sql:
--------------------------------------------------------------------------------
1 | CREATE SCHEMA prod;
2 |
3 | create table prod.User (
4 | id bigint not null,
5 | date datetime(6),
6 | primary key (id)
7 | ) engine=InnoDB;
--------------------------------------------------------------------------------
/jpa2ddl-core/src/test/resources/sample_postgres_migration/v1__jpa2ddl_init.sql:
--------------------------------------------------------------------------------
1 | create table User (
2 | id int8 not null,
3 | date timestamp,
4 | primary key (id)
5 | );
6 |
7 | create sequence hibernate_sequence start 1 increment 1;
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 | out/
3 | .gradle
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'groovy'
3 | id 'java-gradle-plugin'
4 | }
5 |
6 | repositories {
7 | mavenLocal()
8 | mavenCentral()
9 | }
10 |
11 | group = 'com.devskiller.jpa2ddl'
12 | project.version = findProperty('jpa2ddlVersion') ?: '1.0.0-SNAPSHOT'
13 |
14 | sourceCompatibility = 1.8
15 | targetCompatibility = 1.8
16 |
17 | dependencies {
18 | compile gradleApi()
19 | compile localGroovy()
20 | compile "com.devskiller.jpa2ddl:jpa2ddl-core:${findProperty('jpa2ddlVersion') ?: '+'}"
21 | testCompile gradleTestKit()
22 | testCompile 'junit:junit:4.12'
23 | testCompile 'org.assertj:assertj-core:3.8.0'
24 | }
25 |
26 | task sourcesJar(type: Jar, dependsOn: classes) {
27 | classifier = 'sources'
28 | from sourceSets.main.allSource
29 | }
30 |
31 | task javadocJar(type: Jar, dependsOn: javadoc) {
32 | classifier = 'javadoc'
33 | from javadoc.destinationDir
34 | }
35 |
36 | task groovydocJar(type: Jar, dependsOn: groovydoc) {
37 | classifier = 'groovydoc'
38 | from groovydoc.destinationDir
39 | }
40 |
41 | artifacts {
42 | archives sourcesJar
43 | archives javadocJar
44 | archives groovydocJar
45 | }
46 |
47 | wrapper {
48 | gradleVersion = '6.3'
49 | }
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.daemon=false
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Devskiller/jpa2ddl/4652c4ecdc68d2aba31467a2c00279ed5fd3724d/jpa2ddl-gradle-plugin/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
6 |
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | com.devskiller.jpa2ddl
7 | jpa2ddl-parent
8 | 0.10.1-SNAPSHOT
9 |
10 |
11 | jpa2ddl-gradle-plugin
12 |
13 | ${project.artifactId}
14 | jpa2ddl Gradle Plugin
15 |
16 | pom
17 |
18 |
19 | ./
20 |
21 |
22 |
23 |
24 | com.devskiller.jpa2ddl
25 | jpa2ddl-core
26 | ${project.version}
27 |
28 |
29 |
30 |
31 |
32 |
33 | org.apache.maven.plugins
34 | maven-clean-plugin
35 | 3.0.0
36 |
37 |
38 |
39 | build
40 |
41 |
42 | target
43 |
44 |
45 |
46 |
47 |
48 | org.codehaus.mojo
49 | exec-maven-plugin
50 | 1.6.0
51 |
52 |
53 | gradle
54 | package
55 |
56 | ${script.prefix}gradlew
57 |
58 | clean
59 | build
60 | -Pjpa2ddlVersion=${project.version}
61 |
62 |
63 |
64 | exec
65 |
66 |
67 |
68 |
69 |
70 | org.codehaus.mojo
71 | build-helper-maven-plugin
72 | 1.12
73 |
74 |
75 | attach-artifacts
76 | package
77 |
78 | attach-artifact
79 |
80 |
81 |
82 |
83 | build/libs/${project.artifactId}-${project.version}.jar
84 | jar
85 |
86 |
87 | build/libs/${project.artifactId}-${project.version}-groovydoc.jar
88 | jar
89 | groovydoc
90 |
91 |
92 | build/libs/${project.artifactId}-${project.version}-javadoc.jar
93 | jar
94 | javadoc
95 |
96 |
97 | build/libs/${project.artifactId}-${project.version}-sources.jar
98 | jar
99 | sources
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 | windows
112 |
113 |
114 | windows
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/src/main/java/com/devskiller/jpa2ddl/GeneratePlugin.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import java.io.File;
4 | import java.util.HashMap;
5 | import java.util.HashSet;
6 | import java.util.Set;
7 |
8 | import org.gradle.api.Plugin;
9 | import org.gradle.api.Project;
10 | import org.gradle.api.internal.file.UnionFileCollection;
11 | import org.gradle.api.plugins.BasePlugin;
12 | import org.gradle.api.plugins.JavaBasePlugin;
13 | import org.gradle.api.tasks.SourceSet;
14 | import org.gradle.api.tasks.SourceSetContainer;
15 |
16 | class GeneratePlugin implements Plugin {
17 |
18 | private static final String EXTENSION_NAME = "jpa2ddl";
19 | private static final String TASK_NAME = "generateDdl";
20 |
21 | @Override
22 | public void apply(Project project) {
23 | GeneratePluginExtension generatePluginExtension = project.getExtensions().create(EXTENSION_NAME,
24 | GeneratePluginExtension.class, project);
25 |
26 | GenerateTask generateTask = project.getTasks().create(TASK_NAME, GenerateTask.class);
27 | generateTask.setGroup(BasePlugin.BUILD_GROUP);
28 | generateTask.setDescription("Generates DDL scripts based on JPA model.");
29 | generateTask.setExtension(generatePluginExtension);
30 | generateTask.dependsOn(JavaBasePlugin.BUILD_TASK_NAME);
31 |
32 |
33 | project.afterEvaluate(evaluatedProject -> {
34 | fillDefaults(evaluatedProject, generatePluginExtension);
35 | SourceSetContainer sourceSets = (SourceSetContainer) project.getProperties().get("sourceSets");
36 | Set paths;
37 | if (sourceSets != null) {
38 | UnionFileCollection mainClasspath = (UnionFileCollection) sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME).getRuntimeClasspath();
39 | paths = mainClasspath.getFiles();
40 | } else {
41 | paths = new HashSet<>();
42 | }
43 | generateTask.setOutputClassesDirs(paths);
44 | });
45 | }
46 |
47 | private void fillDefaults(Project project, GeneratePluginExtension generatePluginExtension) {
48 | if (!generatePluginExtension.getPackagesProvider().isPresent()) {
49 | throw new IllegalArgumentException("JPA2DDL: No packages property found - it must point to model packages");
50 | }
51 | if (!generatePluginExtension.getActionProvider().isPresent()) {
52 | generatePluginExtension.setAction(Action.CREATE);
53 | }
54 | if (!generatePluginExtension.getGenerationModeProvider().isPresent()) {
55 | generatePluginExtension.setGenerationMode(GenerationMode.DATABASE);
56 | }
57 | if (!generatePluginExtension.getDelimiterProvider().isPresent()) {
58 | generatePluginExtension.setDelimiter(";");
59 | }
60 | if (!generatePluginExtension.getFormatOutputProvider().isPresent()) {
61 | generatePluginExtension.setFormatOutput(true);
62 | }
63 | if (!generatePluginExtension.getSkipSequencesProvider().isPresent()) {
64 | generatePluginExtension.setSkipSequences(false);
65 | }
66 | if (!generatePluginExtension.getJpaPropertiesProvider().isPresent()) {
67 | generatePluginExtension.setJpaProperties(new HashMap<>());
68 | }
69 | if (!generatePluginExtension.getOutputPathProvider().isPresent()) {
70 | String filePath = generatePluginExtension.getAction() == Action.UPDATE ? "scripts/" : "scripts/database.sql";
71 | generatePluginExtension.setOutputPath(project.getBuildDir().toPath().resolve("generated-resources/main/" + filePath).toFile());
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/jpa2ddl-gradle-plugin/src/main/java/com/devskiller/jpa2ddl/GeneratePluginExtension.java:
--------------------------------------------------------------------------------
1 | package com.devskiller.jpa2ddl;
2 |
3 | import org.gradle.api.Project;
4 | import org.gradle.api.file.RegularFileProperty;
5 | import org.gradle.api.provider.ListProperty;
6 | import org.gradle.api.provider.MapProperty;
7 | import org.gradle.api.provider.Property;
8 | import org.gradle.api.provider.Provider;
9 |
10 | import java.io.File;
11 | import java.util.List;
12 | import java.util.Map;
13 |
14 | public class GeneratePluginExtension {
15 |
16 | private final RegularFileProperty outputPath;
17 | private final Property generationMode;
18 | private final ListProperty packages;
19 | private final Property action;
20 | private final MapProperty jpaProperties;
21 | private final Property formatOutput;
22 | private final Property skipSequences;
23 | private final Property delimiter;
24 | private final MapProperty processorProperties;
25 |
26 | public GeneratePluginExtension(Project project) {
27 | outputPath = project.getObjects().fileProperty();
28 | generationMode = project.getObjects().property(GenerationMode.class);
29 | packages = project.getObjects().listProperty(String.class);
30 | action = project.getObjects().property(Action.class);
31 | jpaProperties = project.getObjects().mapProperty(String.class, String.class);
32 | formatOutput = project.getObjects().property(Boolean.class);
33 | skipSequences = project.getObjects().property(Boolean.class);
34 | delimiter = project.getObjects().property(String.class);
35 | processorProperties = project.getObjects().mapProperty(String.class, String.class);
36 | }
37 |
38 | public File getOutputPath() {
39 | return outputPath.getAsFile().get();
40 | }
41 |
42 | public void setOutputPath(File outputPath) {
43 | this.outputPath.set(outputPath);
44 | }
45 |
46 | public GenerationMode getGenerationMode() {
47 | return generationMode.get();
48 | }
49 |
50 | public void setGenerationMode(GenerationMode generationMode) {
51 | this.generationMode.set(generationMode);
52 | }
53 |
54 | public List getPackages() {
55 | return packages.get();
56 | }
57 |
58 | public void setPackages(List packages) {
59 | this.packages.set(packages);
60 | }
61 |
62 | public Action getAction() {
63 | return action.get();
64 | }
65 |
66 | public void setAction(Action action) {
67 | this.action.set(action);
68 | }
69 |
70 | public Map getJpaProperties() {
71 | return jpaProperties.get();
72 | }
73 |
74 | public void setJpaProperties(Map jpaProperties) {
75 | this.jpaProperties.set(jpaProperties);
76 | }
77 |
78 | public Boolean getFormatOutput() {
79 | return formatOutput.get();
80 | }
81 |
82 | public void setFormatOutput(Boolean formatOutput) {
83 | this.formatOutput.set(formatOutput);
84 | }
85 |
86 | public Boolean getSkipSequences() {
87 | return skipSequences.get();
88 | }
89 |
90 | public void setSkipSequences(Boolean skipSequences) {
91 | this.skipSequences.set(skipSequences);
92 | }
93 |
94 | public String getDelimiter() {
95 | return delimiter.get();
96 | }
97 |
98 | public void setDelimiter(String delimiter) {
99 | this.delimiter.set(delimiter);
100 | }
101 |
102 | public Map getProcessorProperties() {
103 | return processorProperties.get();
104 | }
105 |
106 | public void setProcessorProperties(Map processorProperties) {
107 | this.processorProperties.set(processorProperties);
108 | }
109 |
110 | public Provider getOutputPathProvider() {
111 | return outputPath.getAsFile();
112 | }
113 |
114 | public Provider getGenerationModeProvider() {
115 | return generationMode;
116 | }
117 |
118 | public Provider> getPackagesProvider() {
119 | return packages;
120 | }
121 |
122 | public Provider getActionProvider() {
123 | return action;
124 | }
125 |
126 | public Provider