├── .github
└── workflows
│ └── maven.yml
├── .gitignore
├── .mvn
└── wrapper
│ ├── MavenWrapperDownloader.java
│ └── maven-wrapper.properties
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── app
├── .gitignore
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── io
│ │ └── graphqlcrud
│ │ └── app
│ │ ├── GraphQLResource.java
│ │ └── QueryParameters.java
│ └── resources
│ ├── META-INF
│ └── resources
│ │ └── index.html
│ ├── application.properties
│ └── db
│ └── migration
│ └── V1.0.0__Quarkus.sql
├── engine
├── .gitignore
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── io
│ │ └── graphqlcrud
│ │ ├── DatabaseSchemaBuilder.java
│ │ ├── FilterBuilder.java
│ │ ├── FilterScanner.java
│ │ ├── Filters.java
│ │ ├── GraphQLSchemaBuilder.java
│ │ ├── QueryScanner.java
│ │ ├── QueryVisitor.java
│ │ ├── ResultSetList.java
│ │ ├── RowFetcher.java
│ │ ├── RowFetcherFactory.java
│ │ ├── SQLContext.java
│ │ ├── SQLDataFetcher.java
│ │ ├── SQLDataFetcherFactory.java
│ │ ├── SQLDirective.java
│ │ ├── SQLFilterBuilder.java
│ │ ├── SQLMutationQueryBuilderVisitor.java
│ │ ├── SQLQueryBuilderVisitor.java
│ │ ├── StringUtil.java
│ │ ├── model
│ │ ├── Attribute.java
│ │ ├── Cardinality.java
│ │ ├── Entity.java
│ │ ├── Relation.java
│ │ └── Schema.java
│ │ └── types
│ │ ├── JdbcTypeMap.java
│ │ └── TypeMap.java
│ └── test
│ ├── java
│ └── io
│ │ └── graphqlcrud
│ │ ├── DatabaseSchemaTest.java
│ │ ├── FilterInputTest.java
│ │ ├── GraphQLSchemaBuilderTest.java
│ │ ├── SQLDataFetcherTest.java
│ │ ├── SQLMutationDataFetcherTest.java
│ │ └── TestParse.java
│ └── resources
│ ├── application.properties
│ └── import.sql
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
└── main
└── docker
├── Dockerfile.jvm
└── Dockerfile.native
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Maven
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
3 |
4 | name: Java CI with Maven
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Set up JDK 11
20 | uses: actions/setup-java@v1
21 | with:
22 | java-version: 11
23 | - name: Build with Maven
24 | run: mvn clean install
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 |
25 | # General
26 | .DS_Store
27 | .AppleDouble
28 | .LSOverride
29 |
30 | # Icon must end with two \r
31 | Icon
32 |
33 | # Thumbnails
34 | ._*
35 |
36 | # Files that might appear in the root of a volume
37 | .DocumentRevisions-V100
38 | .fseventsd
39 | .Spotlight-V100
40 | .TemporaryItems
41 | .Trashes
42 | .VolumeIcon.icns
43 | .com.apple.timemachine.donotpresent
44 |
45 | # Directories potentially created on remote AFP share
46 | .AppleDB
47 | .AppleDesktop
48 | Network Trash Folder
49 | Temporary Items
50 | .apdisk
51 |
52 | /target/
53 | .classpath
54 | .project
55 | .settings/
56 |
57 | #IntelliJ IDEA
58 | *.iml
59 | .idea
60 |
--------------------------------------------------------------------------------
/.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.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 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at . All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/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 | # graphqlcrud-java
2 |
3 | This is framework built in Java to build GraphQLCRUD based API to a provided database. You simply bring existing your database and its data, and use the framework to build simple application using the given template or embed into your Java application to expose the GraphQL API over your relational database.
4 |
5 | The GraphQLCrud specification is defined at https://graphqlcrud.org specification.
6 |
7 | ## Build the Application
8 | To build the application using maven run
9 |
10 | ```
11 | mvn clean package
12 | ```
13 |
14 | ## Running the application
15 |
16 | The default application requires a Postgresql database. If you do not have one, you start a docker container for same by executing
17 |
18 | ```
19 | docker run -p 5432:5432 --name sampledb -e POSTGRES_DB=sampledb \
20 | -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password \
21 | -d postgres -c log_statement=all
22 | ```
23 |
24 | You can run your application in dev mode that enables live coding, switch into the `app` directory and run
25 |
26 | ```
27 | ../mvnw quarkus:dev
28 | ```
29 |
30 | > ** NOTE: **
31 | The sample application is designed to load a sample schema to work with, if you bring your own database make sure to disable update of the schema
32 |
33 | once the application starts, using the browser goto URL [http://localhost:8080](http://localhost:8080)
34 |
35 |
36 | to run in non development mode:
37 |
38 | The application is now runnable using `java -jar app/target/app-1.0.0-SNAPSHOT-runner.jar`.
39 |
40 |
41 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 |
--------------------------------------------------------------------------------
/app/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 | 4.0.0
7 |
8 | org.graphqlcrudjava
9 | graphqlcrud-java
10 | 1.0.0-SNAPSHOT
11 |
12 | app
13 |
14 |
15 | org.graphqlcrudjava
16 | engine
17 |
18 |
19 | io.quarkus
20 | quarkus-resteasy
21 |
22 |
23 | io.quarkus
24 | quarkus-junit5
25 | test
26 |
27 |
28 | io.rest-assured
29 | rest-assured
30 | test
31 |
32 |
33 | io.quarkus
34 | quarkus-agroal
35 |
36 |
37 | io.quarkus
38 | quarkus-jdbc-postgresql
39 |
40 |
41 | io.quarkus
42 | quarkus-flyway
43 |
44 |
45 | io.quarkus
46 | quarkus-resteasy-jackson
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/app/src/main/java/io/graphqlcrud/app/GraphQLResource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.app;
17 |
18 |
19 | import java.sql.Connection;
20 | import java.sql.SQLException;
21 | import java.util.Map;
22 |
23 | import javax.enterprise.event.Observes;
24 | import javax.inject.Inject;
25 | import javax.ws.rs.Consumes;
26 | import javax.ws.rs.POST;
27 | import javax.ws.rs.Path;
28 | import javax.ws.rs.Produces;
29 | import javax.ws.rs.core.MediaType;
30 |
31 | import io.quarkus.runtime.StartupEvent;
32 | import org.eclipse.microprofile.config.inject.ConfigProperty;
33 | import org.slf4j.Logger;
34 | import org.slf4j.LoggerFactory;
35 |
36 | import graphql.ExecutionInput;
37 | import graphql.ExecutionResult;
38 | import graphql.GraphQL;
39 | import graphql.schema.GraphQLSchema;
40 | import graphql.schema.idl.SchemaPrinter;
41 | import io.agroal.api.AgroalDataSource;
42 | import io.graphqlcrud.DatabaseSchemaBuilder;
43 | import io.graphqlcrud.GraphQLSchemaBuilder;
44 | import io.graphqlcrud.SQLContext;
45 | import io.graphqlcrud.model.Schema;
46 |
47 | @Path("/graphql")
48 | @Produces(MediaType.APPLICATION_JSON)
49 | @Consumes(MediaType.APPLICATION_JSON)
50 | public class GraphQLResource {
51 | private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLResource.class);
52 |
53 | private AgroalDataSource datasource;
54 | private GraphQLSchema schema;
55 | private String dbSchemaName;
56 | private String dialect;
57 |
58 |
59 | @Inject
60 | public GraphQLResource(AgroalDataSource datasource, @ConfigProperty(name = "graphqlcrud.datasource.schema") String dbSchemaName, @ConfigProperty(name = "graphqlcrud.datasource.dialect") String dialect) {
61 | this.datasource = datasource;
62 | this.dbSchemaName = dbSchemaName;
63 | this.dialect = dialect;
64 | }
65 |
66 |
67 | void init(@Observes StartupEvent event) throws SQLException {
68 | try (Connection conn = this.datasource.getConnection()) {
69 | Schema dbSchema = DatabaseSchemaBuilder.getSchema(conn, this.dbSchemaName);
70 | this.schema = GraphQLSchemaBuilder.getSchema(dbSchema);
71 | SchemaPrinter sp = new SchemaPrinter();
72 | LOGGER.info(sp.print(this.schema));
73 | }
74 | }
75 |
76 | @POST
77 | public Map graphql(String query) throws Exception {
78 | QueryParameters qp = QueryParameters.from(query);
79 |
80 | ExecutionInput.Builder executionInput = ExecutionInput.newExecutionInput()
81 | .query(qp.getQuery())
82 | .operationName(qp.getOperationName())
83 | .variables(qp.getVariables());
84 |
85 | // pass the datasource around
86 | try (SQLContext ctx = new SQLContext(this.datasource.getConnection())) {
87 | ctx.setDialect(this.dialect);
88 | executionInput.context(ctx);
89 |
90 | GraphQL graphQL = GraphQL
91 | .newGraphQL(schema)
92 | //.instrumentation(connectionInstrumentation)
93 | .build();
94 |
95 | ExecutionResult executionResult = graphQL.execute(executionInput.build());
96 | return executionResult.toSpecification();
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/app/src/main/java/io/graphqlcrud/app/QueryParameters.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.app;
17 |
18 | import java.util.Collections;
19 | import java.util.HashMap;
20 | import java.util.Map;
21 |
22 | import com.fasterxml.jackson.core.type.TypeReference;
23 | import com.fasterxml.jackson.databind.ObjectMapper;
24 |
25 | public class QueryParameters {
26 | String query;
27 | String operationName;
28 | Map variables = Collections.emptyMap();
29 |
30 | public String getQuery() {
31 | return query;
32 | }
33 |
34 | public String getOperationName() {
35 | return operationName;
36 | }
37 |
38 | public Map getVariables() {
39 | return variables;
40 | }
41 |
42 | public static QueryParameters from(String request) throws Exception {
43 | QueryParameters parameters = new QueryParameters();
44 | Map json = readJSON(request);
45 | parameters.query = (String) json.get("query");
46 | parameters.operationName = (String) json.get("operationName");
47 | parameters.variables = getVariables(json.get("variables"));
48 | return parameters;
49 | }
50 |
51 |
52 | private static Map getVariables(Object variables) {
53 | Map vars = new HashMap<>();
54 | if (variables != null) {
55 | Map, ?> inputVars = (Map) variables;
56 | inputVars.forEach((k, v) -> vars.put(String.valueOf(k), v));
57 | }
58 | return vars;
59 | }
60 |
61 | private static Map readJSON(String json) throws Exception {
62 | ObjectMapper mapper = new ObjectMapper();
63 | return mapper.readValue(json, new TypeReference>(){});
64 | }
65 | }
--------------------------------------------------------------------------------
/app/src/main/resources/META-INF/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
16 |
17 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | Loading...
35 |
134 |
135 |
--------------------------------------------------------------------------------
/app/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | # Configuration file
2 | # key = value
3 |
4 | quarkus.log.console.enable=true
5 | quarkus.log.console.level=DEBUG
6 | quarkus.log.console.color=false
7 | quarkus.log.category."org.grphqlcrud".level=DEBUG
8 |
9 | quarkus.datasource.db-kind=postgresql
10 | quarkus.datasource.username=user
11 | quarkus.datasource.password=password
12 | quarkus.datasource.jdbc.url=jdbc:postgresql://127.0.0.1:5432/sampledb
13 |
14 | quarkus.flyway.migrate-at-start=true
15 |
16 | # set schema name you need to expose and JOOQ's SQLDialect that needs to be used
17 | graphqlcrud.datasource.schema=public
18 | graphqlcrud.datasource.dialect=POSTGRES
--------------------------------------------------------------------------------
/app/src/main/resources/db/migration/V1.0.0__Quarkus.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE IF EXISTS CUSTOMER CASCADE;
2 | DROP TABLE IF EXISTS ADDRESS CASCADE;
3 | DROP TABLE IF EXISTS ACCOUNT CASCADE;
4 | DROP TABLE IF EXISTS PRODUCT CASCADE;
5 | DROP TABLE IF EXISTS HOLDINGS CASCADE;
6 |
7 |
8 | CREATE TABLE CUSTOMER
9 | (
10 | SSN char(10),
11 | FIRSTNAME varchar(64),
12 | LASTNAME varchar(64),
13 | PHONE varchar(15),
14 | CONSTRAINT CUSTOMER_PK PRIMARY KEY(SSN)
15 | );
16 |
17 | CREATE TABLE ADDRESS
18 | (
19 | SSN char(10),
20 | ST_ADDRESS varchar(256),
21 | APT_NUMBER varchar(32),
22 | CITY varchar(64),
23 | STATE varchar(32),
24 | ZIPCODE varchar(10),
25 | CONSTRAINT ADDRESS_FK FOREIGN KEY(SSN) REFERENCES CUSTOMER(SSN) ON DELETE CASCADE ON UPDATE CASCADE
26 | );
27 |
28 | CREATE TABLE ACCOUNT
29 | (
30 | ACCOUNT_ID integer,
31 | SSN char(10),
32 | STATUS char(10),
33 | TYPE char(10),
34 | DATEOPENED timestamp,
35 | DATECLOSED timestamp,
36 | CONSTRAINT ACCOUNT_PK PRIMARY KEY(ACCOUNT_ID),
37 | CONSTRAINT CUSTOMER_FK FOREIGN KEY(SSN) REFERENCES CUSTOMER(SSN) ON DELETE CASCADE ON UPDATE CASCADE
38 | );
39 |
40 |
41 | CREATE TABLE PRODUCT (
42 | ID integer,
43 | SYMBOL varchar(16),
44 | COMPANY_NAME varchar(256),
45 | CONSTRAINT PRODUCT_PK PRIMARY KEY(ID)
46 | );
47 |
48 |
49 | CREATE TABLE HOLDINGS
50 | (
51 | TRANSACTION_ID serial,
52 | ACCOUNT_ID integer,
53 | PRODUCT_ID integer,
54 | PURCHASE_DATE timestamp,
55 | SHARES_COUNT integer,
56 | CONSTRAINT HOLDINGS_PK PRIMARY KEY (TRANSACTION_ID),
57 | CONSTRAINT ACCOUNT_FK FOREIGN KEY(ACCOUNT_ID) REFERENCES ACCOUNT(ACCOUNT_ID) ON DELETE CASCADE ON UPDATE CASCADE,
58 | CONSTRAINT PRODUCT_FK FOREIGN KEY(PRODUCT_ID) REFERENCES PRODUCT(ID) ON DELETE CASCADE ON UPDATE CASCADE
59 | );
60 |
61 |
62 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01002','John','Doe','(646)555-1776');
63 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01003','Bob','Smith','(412)555-4327');
64 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01004','Jane','Aire','(814)555-6789');
65 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01005','Charles','Jones','(203)555-3947');
66 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01006','Virginia','Jefferson','(718)555-2693');
67 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01007','Ralph','Bacon','(704)555-4576');
68 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01008','Bonnie','Dragon','(904)555-6514');
69 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01009','Herbert','Smith','(971)555-7803');
70 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01015','Jack','Corby','(469)555-8023');
71 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01019','Robin','Evers','(470)555-4390');
72 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01020','Lloyd','Abercrombie','(213)555-2312');
73 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01021','Scott','Watters','(206)555-6790');
74 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01022','Sandra','King','(651)555-9017');
75 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01027','Maryanne','Peters','(513)555-9067');
76 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01034','Corey','Snyder','(617)555-3546');
77 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01035','Henry','Thomas','(415)555-2093');
78 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01036','James','Drew','(216)555-6523');
79 |
80 |
81 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01002','1234 Main Street','Apartment 56','New York','New York','10174');
82 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01003','202 Palomino Drive',null,'Pittsburgh','Pennsylvania','15071');
83 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01004','15 State Street',null,'Philadelphia','Pennsylvania','19154');
84 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01005','1819 Maple Street','Apartment 17F','Stratford','Connecticut','06614');
85 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01006','1710 South 51st Street','Apartment 3245','New York','New York','10175');
86 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01007','57 Barn Swallow Avenue',null,'Charlotte','North Carolina','28205');
87 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01008','88 Cinderella Lane',null,'Jacksonville','Florida','32225');
88 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01009','12225 Waterfall Way','Building 100, Suite 9','Portland','Oregon','97220');
89 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01015','1 Lone Star Way',null,'Dallas','Texas','75231');
90 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01019','1814 Falcon Avenue',null,'Atlanta','Georgia','30355');
91 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01020','1954 Hughes Parkway',null,'Los Angeles','California','90099');
92 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01021','24 Mariner Way',null,'Seattle','Washington','98124');
93 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01022','96 Lakefront Parkway',null,'Minneapolis','Minnesota','55426');
94 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01027','35 Grand View Circle','Apartment 5F','Cincinnati','Ohio','45232');
95 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01034','1760 Boston Commons Avenue','Suite 543','Boston','Massachusetts','02136 ');
96 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01035','345 Hilltop Parkway',null,'San Francisco','California','94129');
97 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01036','876 Lakefront Lane',null,'Cleveland','Ohio','44107');
98 |
99 |
100 |
101 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980001,'CST01002','Personal ','Active ','1998-01-01 00:00:00.000', NULL);
102 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980002,'CST01002','Personal ','Active ','1998-02-01 00:00:00.000', NULL);
103 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980003,'CST01003','Personal ','Active ','1998-03-06 00:00:00.000',null);
104 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980004,'CST01004','Personal ','Active ','1998-03-07 00:00:00.000',null);
105 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980005,'CST01005','Personal ','Active ','1998-06-15 00:00:00.000',null);
106 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980006,'CST01006','Personal ','Active ','1998-09-15 00:00:00.000',null);
107 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19990007,'CST01007','Personal ','Active ','1999-01-20 00:00:00.000',null);
108 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19990008,'CST01008','Personal ','Active ','1999-04-16 00:00:00.000',null);
109 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19990009,'CST01009','Business ','Active ','1999-06-25 00:00:00.000',null);
110 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000015,'CST01015','Personal ','Closed ','2000-04-20 00:00:00.000','2001-06-22 00:00:00.000');
111 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000019,'CST01019','Personal ','Active ','2000-10-08 00:00:00.000',null);
112 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000020,'CST01020','Personal ','Active ','2000-10-20 00:00:00.000',null);
113 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000021,'CST01021','Personal ','Active ','2000-12-05 00:00:00.000',null);
114 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20010022,'CST01022','Personal ','Active ','2001-01-05 00:00:00.000',null);
115 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20010027,'CST01027','Personal ','Active ','2001-08-22 00:00:00.000',null);
116 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20020034,'CST01034','Business ','Active ','2002-01-22 00:00:00.000',null);
117 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20020035,'CST01035','Personal ','Active ','2002-02-12 00:00:00.000',null);
118 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20020036,'CST01036','Personal ','Active ','2002-03-22 00:00:00.000',null);
119 |
120 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1002,'BA','The Boeing Company');
121 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1004,'VIX','Vix Index');
122 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1006,'BTU','Peabody Energy');
123 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1007,'IBM','International Business Machines Corporation');
124 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1008,'DELL','Dell Computer Corporation');
125 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1010,'HPQ','Hewlett-Packard Company');
126 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1012,'GE','General Electric Company');
127 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1013,'MRK','Merck and Company Incorporated');
128 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1014,'DIS','Walt Disney Company');
129 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1015,'MCD','McDonalds Corporation');
130 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1016,'DOW','Dow Chemical Company');
131 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1018,'GM','General Motors Corporation');
132 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1024,'SBGI','Sinclair Broadcast Group Incorporated');
133 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1025,'COLM','Columbia Sportsware Company');
134 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1026,'COLB','Columbia Banking System Incorporated');
135 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1028,'BAC','Bank Of America');
136 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1029,'CSVFX','Columbia Strategic Value Fund');
137 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1030,'CMTFX','Columbia Technology Fund');
138 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1031,'F','Ford Motor Company');
139 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1033,'CRM','Salesforce');
140 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1034,'SAP','SAP AG');
141 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1036,'TM','Toyota Motor Corporation');
142 |
143 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980002,1008,'1998-02-01 00:00:00.000',50);
144 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980002,1036,'1998-02-01 00:00:00.000',25);
145 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1002,'1998-03-06 00:00:00.000',100);
146 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1029,'1998-03-06 00:00:00.000',25);
147 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1016,'1998-03-06 00:00:00.000',51);
148 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980005,1024,'1998-06-15 00:00:00.000',18);
149 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980006,1033,'1998-09-15 00:00:00.000',200);
150 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990007,1031,'1999-01-20 00:00:00.000',65);
151 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990008,1012,'1999-04-16 00:00:00.000',102);
152 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990007,1008,'1999-05-11 00:00:00.000',85);
153 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990009,1004,'1999-06-25 00:00:00.000',120);
154 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1024,'1999-07-22 00:00:00.000',150);
155 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000015,1018,'2000-04-20 00:00:00.000',135);
156 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980006,1030,'2000-06-12 00:00:00.000',91);
157 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000019,1029,'2000-10-08 00:00:00.000',351);
158 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000020,1030,'2000-10-20 00:00:00.000',127);
159 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000020,1018,'2000-11-14 00:00:00.000',100);
160 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000019,1031,'2000-11-15 00:00:00.000',125);
161 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000021,1028,'2000-12-05 00:00:00.000',400);
162 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010022,1006,'2001-01-05 00:00:00.000',237);
163 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990008,1015,'2001-01-23 00:00:00.000',180);
164 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980005,1025,'2001-03-23 00:00:00.000',125);
165 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010027,1024,'2001-08-22 00:00:00.000',70);
166 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000020,1006,'2001-11-14 00:00:00.000',125);
167 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1029,'2001-11-15 00:00:00.000',100);
168 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010027,1028,'2001-12-19 00:00:00.000',115);
169 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020034,1024,'2002-01-22 00:00:00.000',189);
170 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990009,1029,'2002-01-24 00:00:00.000',30);
171 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020035,1013,'2002-02-12 00:00:00.000',110);
172 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020035,1034,'2002-02-13 00:00:00.000',70);
173 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000019,1013,'2002-02-26 00:00:00.000',195);
174 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980004,1007,'2002-03-05 00:00:00.000',250);
175 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000021,1014,'2002-03-12 00:00:00.000',300);
176 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010027,1024,'2002-03-14 00:00:00.000',136);
177 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020036,1012,'2002-03-22 00:00:00.000',54);
178 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020036,1010,'2002-03-26 00:00:00.000',189);
179 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980005,1010,'2002-04-01 00:00:00.000',26);
180 |
--------------------------------------------------------------------------------
/engine/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 |
--------------------------------------------------------------------------------
/engine/pom.xml:
--------------------------------------------------------------------------------
1 |
8 |
12 | 4.0.0
13 |
14 | org.graphqlcrudjava
15 | graphqlcrud-java
16 | 1.0.0-SNAPSHOT
17 |
18 |
19 | engine
20 |
21 |
22 |
23 | com.graphql-java
24 | graphql-java
25 |
26 |
27 | io.quarkus
28 | quarkus-junit5
29 | test
30 |
31 |
32 | io.quarkus
33 | quarkus-resteasy-jackson
34 |
35 |
36 | com.graphql-java
37 | graphql-java-extended-scalars
38 |
39 |
40 | org.jooq
41 | jooq
42 |
43 |
44 | org.jooq
45 | jooq-meta
46 |
47 |
48 | io.quarkus
49 | quarkus-flyway
50 | test
51 |
52 |
53 | io.quarkus
54 | quarkus-test-h2
55 | test
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/DatabaseSchemaBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.sql.Connection;
19 | import java.sql.DatabaseMetaData;
20 | import java.sql.ResultSet;
21 | import java.sql.SQLException;
22 | import java.util.ArrayList;
23 | import java.util.HashMap;
24 | import java.util.List;
25 | import java.util.Map;
26 | import java.util.TreeMap;
27 |
28 | import org.slf4j.Logger;
29 | import org.slf4j.LoggerFactory;
30 |
31 | import io.graphqlcrud.model.Attribute;
32 | import io.graphqlcrud.model.Cardinality;
33 | import io.graphqlcrud.model.Entity;
34 | import io.graphqlcrud.model.Relation;
35 | import io.graphqlcrud.model.Schema;
36 |
37 | public class DatabaseSchemaBuilder {
38 | private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSchemaBuilder.class);
39 | private final DatabaseMetaData databaseMetaData;
40 | private final String schema;
41 |
42 | protected DatabaseSchemaBuilder(Connection connection, String schema) throws SQLException {
43 | this.databaseMetaData = connection.getMetaData();
44 | this.schema = schema;
45 | }
46 |
47 | public static Schema getSchema(Connection connection, String schema) throws SQLException {
48 | DatabaseSchemaBuilder analyzer = new DatabaseSchemaBuilder(connection, schema);
49 | return analyzer.buildSchema();
50 | }
51 |
52 | protected Schema buildSchema() throws SQLException {
53 | Schema s = new Schema(this.schema);
54 | Map entityMap = new TreeMap();
55 | try (ResultSet results = this.databaseMetaData.getTables(null, this.schema, null,
56 | new String[] { "TABLE", "VIEW" })) {
57 | while (results.next()) {
58 | String tableName = results.getString("TABLE_NAME");
59 | if (tableName.equals("flyway_schema_history")) {
60 | continue;
61 | }
62 | Entity entity = buildEntity(tableName);
63 | entity.setParent(s);
64 | entityMap.put(tableName, entity);
65 | LOGGER.debug(entity.toString());
66 | }
67 | }
68 | // build relations
69 | buildRelations(entityMap);
70 |
71 | // fill the schema
72 | s.setEntities(new ArrayList(entityMap.values()));
73 | return s;
74 | }
75 |
76 | protected Entity buildEntity(String tableName) throws SQLException {
77 | Entity entity = new Entity(tableName);
78 | List primaryKeys = new ArrayList<>();
79 |
80 | try (ResultSet results = this.databaseMetaData.getPrimaryKeys(null, this.schema, tableName)) {
81 | LOGGER.debug("Loading primary keys for table: " + tableName);
82 | while (results.next()) {
83 | String name = results.getString("COLUMN_NAME");
84 | primaryKeys.add(name);
85 | }
86 | }
87 | entity.setPrimaryKeys(primaryKeys);
88 |
89 | try (ResultSet results = this.databaseMetaData.getColumns(null, this.schema, tableName, "%")) {
90 | LOGGER.debug("Loading columns for table: " + tableName);
91 | while (results.next()) {
92 | String name = results.getString("COLUMN_NAME");
93 | int dataType = results.getInt("DATA_TYPE");
94 | boolean isNullable = results.getInt("NULLABLE") == 1;
95 |
96 | Attribute attribute = new Attribute(name, dataType, isNullable);
97 | entity.addAttribute(attribute);
98 | }
99 | }
100 | return entity;
101 | }
102 |
103 | private short safeGetShort(ResultSet rs, String pos) throws SQLException {
104 | short val;
105 | try {
106 | val = rs.getShort(pos);
107 | } catch (SQLException e) {
108 | int valInt = rs.getInt(pos);
109 | if (valInt > Short.MAX_VALUE) {
110 | throw new SQLException("invalid short value " + valInt); //$NON-NLS-1$
111 | }
112 | val = (short) valInt;
113 | }
114 | return val;
115 | }
116 |
117 | private void buildRelations(Map entityMap) throws SQLException {
118 | for (Entity entity : entityMap.values()) {
119 | HashMap allRelations = new HashMap();
120 |
121 | ResultSet metaDataExportedKeys = this.databaseMetaData.getExportedKeys(null,this.schema,entity.getName());
122 | setDatabaseMetaData(metaDataExportedKeys, entityMap, allRelations, true);
123 |
124 | ResultSet metaDataImportedKeys = this.databaseMetaData.getImportedKeys(null, this.schema, entity.getName());
125 | setDatabaseMetaData(metaDataImportedKeys, entityMap, allRelations, false);
126 |
127 | entity.setRelations(new ArrayList(allRelations.values()));
128 | }
129 | }
130 |
131 | public void setDatabaseMetaData(ResultSet resultSet, Map entityMap, HashMap allRelations, boolean ctr) throws SQLException {
132 | while (resultSet.next()) {
133 | String pkTable = resultSet.getString("PKTABLE_NAME");
134 | String pkColumn = resultSet.getString("PKCOLUMN_NAME");
135 | String fkTable = resultSet.getString("FKTABLE_NAME");
136 | String fkColumn = resultSet.getString("FKCOLUMN_NAME");
137 | short seqNumber = safeGetShort(resultSet,"KEY_SEQ");
138 |
139 | Entity pkEntity = entityMap.get(pkTable);
140 | if (pkEntity == null) {
141 | continue;
142 | }
143 |
144 | Entity fkEntity = entityMap.get(fkTable);
145 | if (fkEntity == null) {
146 | continue;
147 | }
148 |
149 | Relation key;
150 |
151 | if(ctr) {
152 | key = allRelations.get(fkTable);
153 | if (key == null) {
154 | key = new Relation(pkTable.toLowerCase());
155 | key.setForeignEntity(fkEntity);
156 | allRelations.put(fkTable, key);
157 | }
158 | key.getKeyColumns().put(seqNumber, fkColumn);
159 | key.getReferencedKeyColumns().put(seqNumber, pkColumn);
160 | key.setExportedKey(true);
161 | } else {
162 | key = allRelations.get(pkTable);
163 | if (key == null) {
164 | key = new Relation(StringUtil.plural(fkTable).toLowerCase());
165 | key.setForeignEntity(pkEntity);
166 | allRelations.put(pkTable, key);
167 | }
168 | key.getKeyColumns().put(seqNumber, pkColumn);
169 | key.getReferencedKeyColumns().put(seqNumber, fkColumn);
170 | }
171 |
172 | if (pkEntity.isPartOfPrimaryKey(pkColumn) && fkEntity.isPartOfPrimaryKey(fkColumn)) {
173 | key.setCardinality(Cardinality.ONE_TO_ONE);
174 | } else {
175 | key.setNullable(fkEntity.getAttribute(fkColumn).isNullable());
176 | key.setCardinality(Cardinality.ONE_TO_MANY);
177 | }
178 | }
179 | }
180 | }
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/FilterBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import graphql.language.Value;
19 |
20 | public interface FilterBuilder {
21 | C buildCondition(String left, String operation, Value> value);
22 | C and(C left, C right);
23 | C or(C left, C right);
24 | C not(C left);
25 | }
26 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/FilterScanner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import graphql.language.ObjectField;
19 | import graphql.language.ObjectValue;
20 |
21 | public class FilterScanner {
22 | private FilterBuilder visitor;
23 | enum Clause {and, or, not}
24 |
25 | class WrappedCondition {
26 | C condition;
27 | Clause clause = Clause.and;
28 | WrappedCondition(C c, Clause clause){
29 | this.condition = c;
30 | this.clause = clause;
31 | }
32 | }
33 |
34 | public FilterScanner(FilterBuilder visitor) {
35 | this.visitor = visitor;
36 | }
37 |
38 | public WrappedCondition scan(ObjectValue filterInput, Clause wrappedClause) {
39 |
40 | // first lets walk the naked filter fields for example, that are not "and/or/not"
41 | // foo : {
42 | // eq: "bar"
43 | // }
44 | WrappedCondition prevCondition = null;
45 | for (ObjectField field : filterInput.getObjectFields()) {
46 | if (field.getName().equals("and") || field.getName().equals("or") || field.getName().equals("not")) {
47 | continue;
48 | } else {
49 | ObjectValue value = (ObjectValue)field.getValue();
50 | if (!value.getChildren().isEmpty()) {
51 | ObjectField child = value.getObjectFields().get(0);
52 | C condition = this.visitor.buildCondition(field.getName(), child.getName(), child.getValue());
53 | if (prevCondition != null) {
54 | condition = applyClause(prevCondition.condition, Clause.and, condition);
55 | }
56 | prevCondition = new WrappedCondition(condition, wrappedClause);
57 | }
58 | }
59 | }
60 |
61 | // now walk only and/not first because both are "and"
62 | for (ObjectField field : filterInput.getObjectFields()) {
63 | if (field.getChildren().isEmpty()) {
64 | continue;
65 | }
66 | if (field.getName().equals("and")) {
67 | WrappedCondition w = scan((ObjectValue)field.getValue(), Clause.and);
68 | if (prevCondition == null) {
69 | prevCondition = w;
70 | } else {
71 | C condition = applyClause(prevCondition.condition, prevCondition.clause, w.condition);
72 | prevCondition = new WrappedCondition(condition, w.clause);
73 | }
74 | } else if (field.getName().equals("not")) {
75 | WrappedCondition w = scan((ObjectValue)field.getValue(), Clause.and);
76 | if (prevCondition == null) {
77 | C condition = this.visitor.not(w.condition);
78 | prevCondition = new WrappedCondition(condition, Clause.and);
79 | } else {
80 | C condition = applyClause(prevCondition.condition, prevCondition.clause, this.visitor.not(w.condition));
81 | prevCondition = new WrappedCondition(condition, Clause.and);
82 | }
83 | }
84 | }
85 | // walk the or conditions
86 | for (ObjectField field : filterInput.getObjectFields()) {
87 | if (field.getChildren().isEmpty()) {
88 | continue;
89 | }
90 | if (field.getName().equals("or")) {
91 | WrappedCondition w = scan((ObjectValue)field.getValue(), Clause.or);
92 | if (prevCondition == null) {
93 | prevCondition = w;
94 | } else {
95 | C condition = applyClause(prevCondition.condition, Clause.or, w.condition);
96 | prevCondition = new WrappedCondition(condition, w.clause);
97 | }
98 | }
99 | }
100 | return prevCondition;
101 | }
102 |
103 | private C applyClause(C left, Clause clause, C right) {
104 | switch(clause) {
105 | case and:
106 | return this.visitor.and(left, right);
107 | case or:
108 | return this.visitor.or(left, right);
109 | default:
110 | throw new RuntimeException("Wrong clause");
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/Filters.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import graphql.Scalars;
19 | import graphql.schema.GraphQLEnumType;
20 | import graphql.schema.GraphQLInputObjectField;
21 | import graphql.schema.GraphQLInputObjectType;
22 | import graphql.schema.GraphQLList;
23 | import graphql.schema.GraphQLNonNull;
24 | import graphql.schema.GraphQLTypeReference;
25 |
26 | public class Filters {
27 |
28 | public static GraphQLInputObjectType.Builder pageInputBuilder() {
29 | return GraphQLInputObjectType.newInputObject().name("PageRequest")
30 | .field(GraphQLInputObjectField.newInputObjectField().name("limit").type(Scalars.GraphQLInt))
31 | .field(GraphQLInputObjectField.newInputObjectField().name("offset").type(Scalars.GraphQLInt));
32 | }
33 |
34 | public static GraphQLInputObjectType.Builder stringInputBuilder() {
35 | return GraphQLInputObjectType.newInputObject().name("StringInput")
36 | .field(GraphQLInputObjectField.newInputObjectField().name("ne").type(Scalars.GraphQLString))
37 | .field(GraphQLInputObjectField.newInputObjectField().name("eq").type(Scalars.GraphQLString))
38 | .field(GraphQLInputObjectField.newInputObjectField().name("le").type(Scalars.GraphQLString))
39 | .field(GraphQLInputObjectField.newInputObjectField().name("lt").type(Scalars.GraphQLString))
40 | .field(GraphQLInputObjectField.newInputObjectField().name("ge").type(Scalars.GraphQLString))
41 | .field(GraphQLInputObjectField.newInputObjectField().name("gt").type(Scalars.GraphQLString))
42 | .field(GraphQLInputObjectField.newInputObjectField().name("in").type(GraphQLList.list(GraphQLNonNull.nonNull(Scalars.GraphQLString))))
43 | .field(GraphQLInputObjectField.newInputObjectField().name("contains").type(Scalars.GraphQLString))
44 | .field(GraphQLInputObjectField.newInputObjectField().name("startsWith").type(Scalars.GraphQLString))
45 | .field(GraphQLInputObjectField.newInputObjectField().name("endsWith").type(Scalars.GraphQLString))
46 | .field(GraphQLInputObjectField.newInputObjectField().name("matchesPattern").type(Scalars.GraphQLString));
47 | }
48 |
49 | public static GraphQLInputObjectType.Builder idInputBuilder() {
50 | return GraphQLInputObjectType.newInputObject().name("IDInput")
51 | .field(GraphQLInputObjectField.newInputObjectField().name("ne").type(Scalars.GraphQLID))
52 | .field(GraphQLInputObjectField.newInputObjectField().name("eq").type(Scalars.GraphQLID))
53 | .field(GraphQLInputObjectField.newInputObjectField().name("in").type(GraphQLList.list(GraphQLNonNull.nonNull(Scalars.GraphQLID))));
54 |
55 | }
56 |
57 | public static GraphQLInputObjectType.Builder booleanInputBuilder() {
58 | return GraphQLInputObjectType.newInputObject().name("BooleanInput")
59 | .field(GraphQLInputObjectField.newInputObjectField().name("ne").type(Scalars.GraphQLBoolean))
60 | .field(GraphQLInputObjectField.newInputObjectField().name("eq").type(Scalars.GraphQLBoolean));
61 | }
62 |
63 | public static GraphQLInputObjectType.Builder floatInputBuilder() {
64 | return GraphQLInputObjectType.newInputObject().name("FloatInput")
65 | .field(GraphQLInputObjectField.newInputObjectField().name("ne").type(Scalars.GraphQLFloat))
66 | .field(GraphQLInputObjectField.newInputObjectField().name("eq").type(Scalars.GraphQLFloat))
67 | .field(GraphQLInputObjectField.newInputObjectField().name("le").type(Scalars.GraphQLFloat))
68 | .field(GraphQLInputObjectField.newInputObjectField().name("lt").type(Scalars.GraphQLFloat))
69 | .field(GraphQLInputObjectField.newInputObjectField().name("ge").type(Scalars.GraphQLFloat))
70 | .field(GraphQLInputObjectField.newInputObjectField().name("gt").type(Scalars.GraphQLFloat))
71 | .field(GraphQLInputObjectField.newInputObjectField().name("in").type(GraphQLList.list(GraphQLNonNull.nonNull(Scalars.GraphQLFloat))))
72 | .field(GraphQLInputObjectField.newInputObjectField().name("between").type(GraphQLList.list(GraphQLNonNull.nonNull(Scalars.GraphQLFloat))));
73 | }
74 |
75 | public static GraphQLInputObjectType.Builder intInputBuilder() {
76 | return GraphQLInputObjectType.newInputObject().name("IntInput")
77 | .field(GraphQLInputObjectField.newInputObjectField().name("ne").type(Scalars.GraphQLInt))
78 | .field(GraphQLInputObjectField.newInputObjectField().name("eq").type(Scalars.GraphQLInt))
79 | .field(GraphQLInputObjectField.newInputObjectField().name("le").type(Scalars.GraphQLInt))
80 | .field(GraphQLInputObjectField.newInputObjectField().name("lt").type(Scalars.GraphQLInt))
81 | .field(GraphQLInputObjectField.newInputObjectField().name("ge").type(Scalars.GraphQLInt))
82 | .field(GraphQLInputObjectField.newInputObjectField().name("gt").type(Scalars.GraphQLInt))
83 | .field(GraphQLInputObjectField.newInputObjectField().name("in").type(GraphQLList.list(GraphQLNonNull.nonNull(Scalars.GraphQLInt))))
84 | .field(GraphQLInputObjectField.newInputObjectField().name("between").type(GraphQLList.list(GraphQLNonNull.nonNull(Scalars.GraphQLInt))));
85 | }
86 |
87 | public static GraphQLInputObjectType.Builder orderByInputBuilder() {
88 | return GraphQLInputObjectType.newInputObject().name("OrderByInput")
89 | .field(GraphQLInputObjectField.newInputObjectField().name("field").type(GraphQLNonNull.nonNull(Scalars.GraphQLString)))
90 | .field(GraphQLInputObjectField.newInputObjectField().name("order").type(GraphQLTypeReference.typeRef("SortDirectionEnum")).defaultValue("ASC"));
91 | }
92 |
93 | public static GraphQLEnumType.Builder sortDirectionEnumBuilder() {
94 | return GraphQLEnumType.newEnum().name("SortDirectionEnum")
95 | .value("ASC")
96 | .value("DESC");
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/QueryScanner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.util.List;
19 |
20 | import graphql.language.Argument;
21 | import graphql.language.Field;
22 | import graphql.language.Selection;
23 | import graphql.schema.DataFetchingEnvironment;
24 | import graphql.schema.GraphQLFieldDefinition;
25 | import graphql.schema.GraphQLModifiedType;
26 | import graphql.schema.GraphQLObjectType;
27 | import graphql.schema.GraphQLType;
28 | import graphql.schema.GraphQLTypeUtil;
29 | import graphql.schema.SelectedField;
30 |
31 | public class QueryScanner {
32 | private QueryVisitor visitor;
33 | private DataFetchingEnvironment environment;
34 |
35 | public QueryScanner(DataFetchingEnvironment environment, QueryVisitor visitor) {
36 | this.environment = environment;
37 | this.visitor = visitor;
38 | }
39 |
40 | public void scanQuery(Field field, GraphQLFieldDefinition definition, String fqn, boolean root) {
41 |
42 | GraphQLType type = definition.getType();
43 | if (type instanceof GraphQLModifiedType) {
44 | type = ((GraphQLModifiedType) type).getWrappedType();
45 | }
46 |
47 | if (GraphQLTypeUtil.isScalar(type)) {
48 | this.visitor.visitScalar(field, definition, type);
49 | scanArguments(field, definition, type);
50 | } else if (type instanceof GraphQLObjectType) {
51 |
52 | if (root) {
53 | this.visitor.startVisitRootObject(field, definition, (GraphQLObjectType)type);
54 | } else {
55 | this.visitor.startVisitObject(field, definition, (GraphQLObjectType)type);
56 | }
57 |
58 | // walk the selected fields
59 | List fields = field.getSelectionSet().getSelections();
60 | for (int i = 0; i < fields.size(); i++) {
61 | Field f = (Field)fields.get(i);
62 | String name = f.getAlias() != null ? f.getAlias() : f.getName();
63 | String fieldName = fqn == null ? name : fqn+"/"+name;
64 | SelectedField childField = this.environment.getSelectionSet().getField(fieldName);
65 | GraphQLFieldDefinition childDefinition = childField.getFieldDefinition();
66 | scanQuery(f, childDefinition, fieldName, false);
67 | }
68 |
69 | // now walk the arguments, maybe specific ones later
70 | scanArguments(field, definition, type);
71 |
72 | if (root) {
73 | this.visitor.endVisitRootObject(field, definition, (GraphQLObjectType)type);
74 | } else {
75 | this.visitor.endVisitObject(field, definition, (GraphQLObjectType)type);
76 | }
77 | }
78 | }
79 |
80 | public void scanMutation(Field field, GraphQLFieldDefinition definition, String fqn, boolean root) {
81 |
82 | GraphQLType type = definition.getType();
83 | if (type instanceof GraphQLModifiedType) {
84 | type = ((GraphQLModifiedType) type).getWrappedType();
85 | }
86 |
87 | if (type instanceof GraphQLObjectType) {
88 | if (root) {
89 | this.visitor.startVisitRootObject(field, definition, (GraphQLObjectType) type);
90 | scanArguments(field, definition, type);
91 | this.visitor.endVisitRootObject(field, definition, (GraphQLObjectType) type);
92 | }
93 | }
94 | }
95 |
96 | private void scanArguments(Field field, GraphQLFieldDefinition definition, GraphQLType type) {
97 | List args = field.getArguments();
98 | if (args != null && !args.isEmpty()) {
99 | for (int i = 0; i < args.size(); i++) {
100 | Argument arg = args.get(i);
101 | this.visitor.visitArgument(field, definition, (GraphQLObjectType)type, arg);
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/QueryVisitor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import graphql.language.Argument;
19 | import graphql.language.Field;
20 | import graphql.schema.GraphQLFieldDefinition;
21 | import graphql.schema.GraphQLObjectType;
22 | import graphql.schema.GraphQLType;
23 |
24 | public interface QueryVisitor {
25 |
26 | void visitScalar(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLType type);
27 |
28 | void startVisitObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type);
29 | void endVisitObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type);
30 |
31 | void startVisitRootObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type);
32 | void endVisitRootObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type);
33 |
34 | void visitArgument(Field field, GraphQLFieldDefinition definition, GraphQLObjectType type, Argument arg);
35 | }
36 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/ResultSetList.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.sql.ResultSet;
19 | import java.sql.SQLException;
20 | import java.util.AbstractList;
21 | import java.util.Iterator;
22 |
23 | class ResultSetList extends AbstractList {
24 | private ResultSet rs;
25 | private Iterator itr;
26 | private Object current;
27 | private boolean advanceCursor;
28 |
29 | ResultSetList(ResultSet rs, boolean advanceCursor){
30 | this.rs = rs;
31 | this.advanceCursor = advanceCursor;
32 | }
33 |
34 | public Object get() {
35 | if (this.itr == null) {
36 | this.itr = iterator();
37 | if (!this.itr.hasNext()) {
38 | return null;
39 | }
40 | this.current = this.itr.next();
41 | }
42 | return this.current;
43 | }
44 |
45 | @Override
46 | public Object get(int index) {
47 | return this.rs;
48 | }
49 |
50 | @Override
51 | public Iterator iterator() {
52 | final Iterator real = super.iterator();
53 | return new Iterator() {
54 | // this just makes sure that before advancing the cursor next() has been called
55 | @Override
56 | public boolean hasNext() {
57 | try {
58 | if (ResultSetList.this.rs.isClosed()) {
59 | return false;
60 | }
61 | boolean hasNext = ResultSetList.this.advanceCursor ? ResultSetList.this.rs.next() : true;
62 | if (!hasNext) {
63 | ResultSetList.this.rs.close();
64 | }
65 | ResultSetList.this.advanceCursor = true;
66 | return hasNext;
67 | } catch (SQLException e) {
68 | throw new RuntimeException("Failed to walk the results", e);
69 | }
70 | }
71 | @Override
72 | public Object next() {
73 | return real.next();
74 | }
75 | };
76 | }
77 |
78 | @Override
79 | public int size() {
80 | return Integer.MAX_VALUE;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/RowFetcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.sql.ResultSet;
19 | import java.util.Collections;
20 | import java.util.List;
21 | import java.util.Map;
22 |
23 | import com.fasterxml.jackson.databind.ObjectMapper;
24 |
25 | import graphql.language.Field;
26 | import graphql.schema.DataFetcher;
27 | import graphql.schema.DataFetchingEnvironment;
28 | import graphql.schema.GraphQLFieldDefinition;
29 | import graphql.schema.GraphQLObjectType;
30 | import graphql.schema.GraphQLType;
31 |
32 | // This must be thread safe, as it will be called by multiple threads at same time
33 | public class RowFetcher implements DataFetcher {
34 | ObjectMapper mapper = new ObjectMapper();
35 |
36 | @Override
37 | public Object get(DataFetchingEnvironment environment) throws Exception {
38 | Object source = environment.getSource();
39 | if (source == null) {
40 | return null;
41 | }
42 | ResultSet rs = null;
43 | if (source instanceof ResultSetList) {
44 | rs = (ResultSet)((ResultSetList) source).get();
45 | } else if (source instanceof ResultSet){
46 | rs = (ResultSet)source;
47 | }
48 | Field f = environment.getField();
49 | String colName = SQLQueryBuilderVisitor.fieldName(f);
50 |
51 | SQLDirective sqlDirective = SQLDirective.find(environment.getFieldDefinition().getDirectives());
52 | // this is link to another table
53 | if (sqlDirective != null && rs != null){
54 | GraphQLFieldDefinition definition = environment.getFieldDefinition();
55 | GraphQLType type = definition.getType();
56 | byte[] data = rs.getBytes(f.getName());
57 | if (data != null) {
58 | List> node = this.mapper.readValue(data, List.class);
59 | if (type instanceof GraphQLObjectType) {
60 | return node.get(0);
61 | }
62 | return node;
63 | } else {
64 | if (type instanceof GraphQLObjectType) {
65 | return null;
66 | } else {
67 | return Collections.emptyList();
68 | }
69 | }
70 | }
71 | if (rs != null) {
72 | return rs.getObject(f.getName());
73 | } else {
74 | return ((Map,?>)source).get(colName);
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/RowFetcherFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import graphql.schema.DataFetcher;
19 | import graphql.schema.DataFetcherFactory;
20 | import graphql.schema.DataFetcherFactoryEnvironment;
21 |
22 | // This must be thread safe
23 | public class RowFetcherFactory implements DataFetcherFactory {
24 | private static RowFetcher fetcher = new RowFetcher();
25 | @Override
26 | public DataFetcher get(DataFetcherFactoryEnvironment environment) {
27 | return fetcher;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.io.Closeable;
19 | import java.io.IOException;
20 | import java.sql.Connection;
21 | import java.sql.ResultSet;
22 | import java.sql.SQLException;
23 | import java.sql.Statement;
24 |
25 | public class SQLContext implements Closeable{
26 |
27 | private Connection connection;
28 | private Statement stmt;
29 | private ResultSet rs;
30 | private String sql;
31 | private String dialect;
32 | private String sqlMutation;
33 | private Object autoGeneratedPrimaryKey;
34 |
35 | public Object getAutoGeneratedPrimaryKey() {
36 | return autoGeneratedPrimaryKey;
37 | }
38 |
39 | public void setAutoGeneratedPrimaryKey(Object autoGeneratedPrimaryKey) {
40 | this.autoGeneratedPrimaryKey = autoGeneratedPrimaryKey;
41 | }
42 |
43 | public String getSqlMutation() {
44 | return sqlMutation;
45 | }
46 |
47 | public void setSqlMutation(String sqlMutation) {
48 | this.sqlMutation = sqlMutation;
49 | }
50 |
51 | public String getSQL() {
52 | return this.sql;
53 | }
54 |
55 | public void setSQL(String sql) {
56 | this.sql = sql;
57 | }
58 |
59 | public SQLContext(Connection connection) {
60 | this.connection = connection;
61 | }
62 |
63 | public Connection getConnection() {
64 | return this.connection;
65 | }
66 |
67 | public void setConnection(Connection connection) {
68 | this.connection = connection;
69 | }
70 |
71 | public ResultSet getResultSet() {
72 | return this.rs;
73 | }
74 |
75 | public void setResultSet(ResultSet rs) {
76 | this.rs = rs;
77 | }
78 |
79 | public Statement getStmt() {
80 | return this.stmt;
81 | }
82 |
83 | public void setStmt(Statement stmt) {
84 | this.stmt = stmt;
85 | }
86 |
87 | public String getDialect() {
88 | return this.dialect;
89 | }
90 |
91 | public void setDialect(String dialect) {
92 | this.dialect = dialect;
93 | }
94 |
95 | @Override
96 | public void close() throws IOException {
97 | try {
98 | if (this.rs != null) {
99 | this.rs.close();
100 | }
101 | if (this.stmt != null) {
102 | this.stmt.close();
103 | }
104 | if (this.connection != null) {
105 | this.connection.close();
106 | }
107 | } catch (SQLException e) {
108 | throw new IOException(e);
109 | }
110 | }
111 | }
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLDataFetcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.sql.Connection;
19 | import java.sql.ResultSet;
20 | import java.sql.SQLException;
21 | import java.sql.Statement;
22 |
23 | import graphql.schema.GraphQLObjectType;
24 | import graphql.schema.GraphQLType;
25 | import org.slf4j.Logger;
26 | import org.slf4j.LoggerFactory;
27 |
28 | import graphql.schema.DataFetcher;
29 | import graphql.schema.DataFetchingEnvironment;
30 |
31 | // This must be thread safe, as it will be called by multiple threads at same time
32 | // This is very simple naively written class, will require more structure here
33 | public class SQLDataFetcher implements DataFetcher{
34 | private static final Logger LOGGER = LoggerFactory.getLogger(SQLDataFetcher.class);
35 |
36 | @Override
37 | public ResultSetList get(DataFetchingEnvironment environment) throws Exception {
38 | SQLContext ctx = environment.getContext();
39 | ResultSet rs = null;
40 |
41 | GraphQLType type = environment.getParentType();
42 |
43 | if(type instanceof GraphQLObjectType) {
44 | String name = ((GraphQLObjectType) type).getName();
45 | String fieldName = environment.getField().getName();
46 |
47 | if(name.equals("MutationType")) {
48 | if(fieldName.contains("create") || fieldName.contains("update")) {
49 | if(executeMutation(environment, ctx) > 0) {
50 | rs = executeSQL(environment, ctx);
51 | } else {
52 | throw new SQLException("Something went wrong");
53 | }
54 | } else if(fieldName.contains("delete")) {
55 | rs = executeSQL(environment,ctx);
56 | if(rs != null) {
57 | executeMutation(environment,ctx);
58 | } else {
59 | throw new SQLException("Something went wrong");
60 | }
61 | }
62 | } else if(name.equals("QueryType")) {
63 | rs = executeSQL(environment,ctx);
64 | }
65 | }
66 | return new ResultSetList(rs, true);
67 | }
68 |
69 | private int executeMutation(DataFetchingEnvironment environment, SQLContext ctx) throws Exception {
70 | String mutation = buildMutation(environment);
71 | ctx.setSqlMutation(mutation);
72 | Connection connection = ctx.getConnection();
73 | Statement statement = connection.createStatement();
74 | int count = statement.executeUpdate(mutation);
75 |
76 | // if there are auto generated PKs, fetch those.
77 | try (ResultSet rs = statement.getGeneratedKeys()) {
78 | if(rs.next()) {
79 | Object key = rs.getObject(1);
80 | ctx.setAutoGeneratedPrimaryKey(key);
81 | }
82 | }
83 | LOGGER.info("SQL executed: " + mutation);
84 |
85 | return count;
86 | }
87 |
88 | private ResultSet executeSQL(DataFetchingEnvironment environment, SQLContext ctx) throws Exception {
89 | String sql = buildSQL(environment);
90 | ctx.setSQL(sql);
91 | LOGGER.info("SQL Executed:" + sql);
92 |
93 | ResultSet rs = null;
94 | Connection c = ctx.getConnection();
95 | Statement stmt = c.createStatement();
96 | boolean hasResults = stmt.execute(sql);
97 | if (hasResults) {
98 | rs = stmt.getResultSet();
99 | }
100 | ctx.setStmt(stmt);
101 | ctx.setResultSet(rs);
102 |
103 | return rs;
104 | }
105 |
106 | private String buildSQL(DataFetchingEnvironment environment) {
107 | SQLQueryBuilderVisitor visitor = new SQLQueryBuilderVisitor(environment.getContext());
108 | QueryScanner scanner = new QueryScanner(environment, visitor);
109 | scanner.scanQuery(environment.getField(), environment.getFieldDefinition(), null, true);
110 | String sql = visitor.getSQL();
111 | return sql;
112 | }
113 |
114 | private String buildMutation(DataFetchingEnvironment environment) {
115 | SQLMutationQueryBuilderVisitor visitor = new SQLMutationQueryBuilderVisitor(environment.getContext());
116 | QueryScanner scanner = new QueryScanner(environment,visitor);
117 | scanner.scanMutation(environment.getField(), environment.getFieldDefinition(), null, true);
118 | String sql = visitor.getSQL();
119 | return sql;
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLDataFetcherFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 | import graphql.schema.DataFetcher;
18 | import graphql.schema.DataFetcherFactory;
19 | import graphql.schema.DataFetcherFactoryEnvironment;
20 |
21 | // This must be thread safe
22 | public class SQLDataFetcherFactory implements DataFetcherFactory {
23 | private static SQLDataFetcher fetcher = new SQLDataFetcher();
24 | @Override
25 | public DataFetcher get(DataFetcherFactoryEnvironment environment) {
26 | return fetcher;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLDirective.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.util.HashSet;
19 | import java.util.List;
20 | import java.util.Set;
21 |
22 | import graphql.Scalars;
23 | import graphql.introspection.Introspection;
24 | import graphql.schema.GraphQLArgument;
25 | import graphql.schema.GraphQLDirective;
26 | import graphql.schema.GraphQLList;
27 |
28 | public class SQLDirective {
29 | private String tableName;
30 | private List primaryFields;
31 | private List foreignFields;
32 |
33 | public static SQLDirective find(List directives) {
34 | if (directives == null) {
35 | return null;
36 | }
37 | for (GraphQLDirective d : directives) {
38 | if (d.getName().equals("sql")) {
39 | return SQLDirective.newDirective(d);
40 | }
41 | }
42 | return null;
43 | }
44 |
45 | public static SQLDirective newDirective(GraphQLDirective d) {
46 | SQLDirective sql = new SQLDirective();
47 |
48 | if (d.getArgument("table") != null) {
49 | sql.tableName = d.getArgument("table").getValue().toString();
50 | }
51 |
52 | if (d.getArgument("keys") != null) {
53 | sql.primaryFields = (List)d.getArgument("keys").getValue();
54 | }
55 |
56 | if (d.getArgument("reference_keys") != null) {
57 | sql.foreignFields = (List)d.getArgument("reference_keys").getValue();
58 | }
59 |
60 | return sql;
61 | }
62 |
63 | public static Set addDirectiveToSchema(String directiveName) {
64 | Set set = new HashSet<>();
65 | GraphQLDirective directive = null;
66 | if(directiveName.equals("sql")) {
67 | directive = GraphQLDirective.newDirective()
68 | .name(directiveName)
69 | .argument(GraphQLArgument.newArgument().name("keys").type(GraphQLList.list(Scalars.GraphQLString)).build())
70 | .argument(GraphQLArgument.newArgument().name("reference_keys").type(GraphQLList.list(Scalars.GraphQLString)).build())
71 | .validLocations(Introspection.DirectiveLocation.FIELD_DEFINITION)
72 | .build();
73 | }
74 | set.add(directive);
75 | return set;
76 | }
77 |
78 | public String getTableName() {
79 | return tableName;
80 | }
81 |
82 | public void setTableName(String tableName) {
83 | this.tableName = tableName;
84 | }
85 |
86 | public List getPrimaryFields() {
87 | return primaryFields;
88 | }
89 |
90 | public void setPrimaryFields(List primaryFields) {
91 | this.primaryFields = primaryFields;
92 | }
93 |
94 | public List getForeignFields() {
95 | return foreignFields;
96 | }
97 |
98 | public void setForeignFields(List foreignFields) {
99 | this.foreignFields = foreignFields;
100 | }
101 |
102 | public static Builder newDirective() {
103 | return new Builder();
104 | }
105 |
106 | public static class Builder {
107 | private String tableName;
108 | private List primaryFields;
109 | private List foreignFields;
110 |
111 | public Builder() {
112 | }
113 |
114 | public Builder tableName(String name) {
115 | this.tableName = name;
116 | return this;
117 | }
118 |
119 | public Builder primaryFields(List fields) {
120 | this.primaryFields = fields;
121 | return this;
122 | }
123 |
124 | public Builder foreignFields(List fields) {
125 | this.foreignFields = fields;
126 | return this;
127 | }
128 |
129 | public GraphQLDirective build() {
130 | GraphQLDirective.Builder b = GraphQLDirective.newDirective().name("sql");
131 | if (this.tableName != null) {
132 | b.argument(GraphQLArgument.newArgument().name("table").type(GraphQLList.list(Scalars.GraphQLString)).value(tableName));
133 | }
134 | if (this.primaryFields != null) {
135 | b.argument(GraphQLArgument.newArgument().name("keys").type(Scalars.GraphQLString)
136 | .value(this.primaryFields));
137 | }
138 | if (this.foreignFields != null) {
139 | b.argument(GraphQLArgument.newArgument().name("reference_keys")
140 | .type(GraphQLList.list(Scalars.GraphQLString)).value(this.foreignFields));
141 | }
142 | b.validLocations(Introspection.DirectiveLocation.FIELD, Introspection.DirectiveLocation.FIELD_DEFINITION);
143 | return b.build();
144 | }
145 | }
146 | }
147 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLFilterBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import static org.jooq.impl.DSL.field;
19 | import static org.jooq.impl.DSL.name;
20 |
21 | import java.math.BigDecimal;
22 | import java.math.BigInteger;
23 | import java.util.ArrayList;
24 | import java.util.List;
25 |
26 | import org.jooq.Condition;
27 |
28 | import graphql.language.ArrayValue;
29 | import graphql.language.BooleanValue;
30 | import graphql.language.FloatValue;
31 | import graphql.language.IntValue;
32 | import graphql.language.StringValue;
33 | import graphql.language.Value;
34 |
35 | public class SQLFilterBuilder implements FilterBuilder {
36 | private String alias;
37 |
38 | public SQLFilterBuilder(String tableAlias) {
39 | this.alias = tableAlias;
40 | }
41 |
42 | @Override
43 | public Condition buildCondition(String left, String operation, Value> v) {
44 | Condition c = null;
45 | if (v instanceof StringValue) {
46 | c = visitStringValue(((StringValue) v).getValue(),left, operation);
47 | } else if (v instanceof BooleanValue) {
48 | c = visitBooleanValue(((BooleanValue) v).isValue(),left, operation);
49 | } else if (v instanceof IntValue) {
50 | c = visitIntValue(((IntValue) v).getValue(),left, operation);
51 | } else if (v instanceof FloatValue) {
52 | c = visitFloatValue(((FloatValue) v).getValue(),left, operation);
53 | } else if(v instanceof ArrayValue) {
54 | c = visitArrayValue(((ArrayValue) v).getValues(),left,operation);
55 | }
56 | return c;
57 | }
58 |
59 | @Override
60 | public Condition and(Condition left, Condition right) {
61 | return left.and(right);
62 | }
63 |
64 | @Override
65 | public Condition or(Condition left, Condition right) {
66 | return left.or(right);
67 | }
68 |
69 | @Override
70 | public Condition not(Condition left) {
71 | return left.not();
72 | }
73 |
74 | Condition visitStringValue(String value, String fieldName, String conditionName) {
75 | org.jooq.Field left = this.alias != null ? field(name(this.alias, fieldName)) : field(fieldName);
76 | Condition c = null;
77 | switch (conditionName) {
78 | case "eq":
79 | c = left.eq(value);
80 | break;
81 | case "ne":
82 | c = left.ne(value);
83 | break;
84 | case "lt":
85 | c = left.lt(value);
86 | break;
87 | case "le":
88 | c = left.le(value);
89 | break;
90 | case "gt":
91 | c = left.gt(value);
92 | break;
93 | case "ge":
94 | c = left.in(value);
95 | break;
96 | case "contains":
97 | c = left.contains(value);
98 | break;
99 | case "startsWith":
100 | c = left.startsWith(value);
101 | break;
102 | case "endsWith":
103 | c = left.endsWith(value);
104 | break;
105 | case "matchesPattern":
106 | c = left.likeRegex(value);
107 | break;
108 | default:
109 | throw new RuntimeException("Unexpected value: " + conditionName);
110 | }
111 | return c;
112 | }
113 |
114 | Condition visitBooleanValue(Boolean value, String fieldName, String conditionName) {
115 | org.jooq.Field left = this.alias != null ? field(name(this.alias, fieldName)) : field(fieldName);
116 | Condition c = null;
117 | switch (conditionName) {
118 | case "eq":
119 | c = left.eq(value);
120 | break;
121 | case "ne":
122 | c = left.ne(value);
123 | break;
124 | default:
125 | throw new RuntimeException("Unexpected value: " + conditionName);
126 | }
127 | return c;
128 | }
129 |
130 | Condition visitIntValue(BigInteger value, String fieldName, String conditionName) {
131 | org.jooq.Field left = this.alias != null ? field(name(this.alias, fieldName)) : field(fieldName);
132 | Condition c = null;
133 | switch (conditionName) {
134 | case "eq":
135 | c = left.eq(value);
136 | break;
137 | case "ne":
138 | c = left.ne(value);
139 | break;
140 | case "lt":
141 | c = left.lt(value);
142 | break;
143 | case "le":
144 | c = left.le(value);
145 | break;
146 | case "gt":
147 | c = left.gt(value);
148 | break;
149 | case "ge":
150 | c = left.ge(value);
151 | break;
152 | default:
153 | throw new RuntimeException("Unexpected value: " + conditionName);
154 | }
155 | return c;
156 | }
157 |
158 | Condition visitFloatValue(BigDecimal value, String fieldName, String conditionName) {
159 | org.jooq.Field left = this.alias != null ? field(name(this.alias, fieldName)) : field(fieldName);
160 | Condition c = null;
161 | switch (conditionName) {
162 | case "eq":
163 | c = left.eq(value);
164 | break;
165 | case "ne":
166 | c = left.ne(value);
167 | break;
168 | case "lt":
169 | c = left.lt(value);
170 | break;
171 | case "le":
172 | c = left.le(value);
173 | break;
174 | case "gt":
175 | c = left.gt(value);
176 | break;
177 | case "ge":
178 | c = left.ge(value);
179 | break;
180 | default:
181 | throw new RuntimeException("Unexpected value: " + conditionName);
182 | }
183 | return c;
184 | }
185 |
186 |
187 | Condition visitArrayValue(List v, String fieldName, String conditionName) {
188 | org.jooq.Field left = this.alias != null ? field(name(this.alias, fieldName)) : field(fieldName);
189 | Condition c = null;
190 | switch (conditionName) {
191 | case "between":
192 | if (v.get(0) instanceof FloatValue) {
193 | c = left.between(((FloatValue) v.get(0)).getValue(), ((FloatValue) v.get(1)).getValue());
194 | } else if (v.get(0) instanceof IntValue) {
195 | c = left.between(((IntValue) v.get(0)).getValue(), ((IntValue) v.get(1)).getValue());
196 | }
197 | break;
198 | case "in":
199 | if (v.get(0) instanceof StringValue) {
200 | List list = new ArrayList<>();
201 | for (Value> value : v) {
202 | list.add(((StringValue) value).getValue());
203 | }
204 | c = left.in(list);
205 | } else if (v.get(0) instanceof FloatValue) {
206 | List list = new ArrayList<>();
207 | for (Value> value : v) {
208 | list.add(((FloatValue) value).getValue());
209 | }
210 | c = left.in(list);
211 | } else if (v.get(0) instanceof IntValue) {
212 | List list = new ArrayList<>();
213 | for (Value> value : v) {
214 | list.add(((IntValue) value).getValue());
215 | }
216 | c = left.in(list);
217 | }
218 | break;
219 | default:
220 | throw new RuntimeException("Unexpected value: " + conditionName);
221 | }
222 | return c;
223 | }
224 |
225 | }
226 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLMutationQueryBuilderVisitor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 |
17 | package io.graphqlcrud;
18 |
19 | import graphql.language.*;
20 | import graphql.language.Field;
21 | import graphql.schema.GraphQLFieldDefinition;
22 | import graphql.schema.GraphQLObjectType;
23 | import graphql.schema.GraphQLType;
24 | import org.jooq.*;
25 | import org.jooq.Record;
26 | import org.jooq.impl.DSL;
27 |
28 | import java.util.*;
29 |
30 | import static org.jooq.impl.DSL.*;
31 |
32 | public class SQLMutationQueryBuilderVisitor implements QueryVisitor {
33 |
34 | protected SQLContext ctx;
35 | protected DSLContext create = null;
36 |
37 | public SQLMutationQueryBuilderVisitor(SQLContext ctx) {
38 | this.ctx = ctx;
39 | this.create = DSL.using(SQLDialect.valueOf(ctx.getDialect()));
40 | }
41 |
42 | private static class VisitorContext {
43 | String mutationType;
44 | InsertValuesStepN insertClause;
45 | UpdateSetFirstStep updateClause;
46 | DeleteUsingStep deleteClause;
47 | org.jooq.Condition condition;
48 | Collection> selectedFields = new ArrayList<>();
49 | Map selectedColumns = new LinkedHashMap<>();
50 | }
51 |
52 | private Stack stack = new Stack<>();
53 |
54 | @Override
55 | public void startVisitRootObject(Field field, GraphQLFieldDefinition definition, GraphQLObjectType type) {
56 | VisitorContext visitorContext = new VisitorContext();
57 |
58 | visitorContext.mutationType = field.getName() != null ? field.getName() : field.getAlias();
59 |
60 | List fields = field.getSelectionSet().getSelections();
61 | for(Selection selection : fields) {
62 | Field f = (Field) selection;
63 | if(!f.getName().contains("create") || !f.getName().contains("update") || !f.getName().contains("delete")) {
64 | visitorContext.selectedFields.add(field(f.getName()));
65 | }
66 | }
67 | this.stack.push(visitorContext);
68 | }
69 |
70 | @Override
71 | public void endVisitRootObject(Field field, GraphQLFieldDefinition definition, GraphQLObjectType type) {
72 | VisitorContext visitorContext = this.stack.peek();
73 | String mutationName = field.getName();
74 | Table tableName = table(type.getName());
75 |
76 | if(mutationName.contains("create")) {
77 | Collection> fields = new ArrayList<>();
78 | visitorContext.selectedColumns.forEach((key, value) -> fields.add(key));
79 |
80 | //build create clause
81 | visitorContext.insertClause = this.create.insertInto(tableName, fields);
82 |
83 | //insert values
84 | visitorContext.insertClause.values(visitorContext.selectedColumns.values());
85 | } else if (mutationName.contains("update")) {
86 | RowN columnValue = row(visitorContext.selectedColumns.values());
87 | RowN columnName = row(visitorContext.selectedColumns.keySet());
88 |
89 | //build the update clause
90 | visitorContext.updateClause = this.create.update(tableName);
91 |
92 | //set condition and add where condition
93 | if( visitorContext.condition != null) {
94 | visitorContext.updateClause.set(columnName, columnValue).where(visitorContext.condition);
95 | } else {
96 | visitorContext.updateClause.set(columnName, columnValue);
97 | }
98 | } else if (mutationName.contains("delete")) {
99 | //build delete clause
100 | visitorContext.deleteClause = this.create.delete(tableName);
101 |
102 | //add where condition
103 | if( visitorContext.condition != null) {
104 | visitorContext.deleteClause.where(visitorContext.condition);
105 | } else {
106 | throw new RuntimeException("Missing condition");
107 | }
108 | } else {
109 | throw new RuntimeException("Unexpected value: " + mutationName);
110 | }
111 | }
112 |
113 | @Override
114 | public void visitArgument(Field field, GraphQLFieldDefinition definition, GraphQLObjectType type, Argument arg) {
115 | VisitorContext visitorContext = this.stack.peek();
116 | String argumentName = arg.getName();
117 |
118 | if(argumentName.equals("input")) {
119 |
120 | if(!arg.getValue().getChildren().isEmpty()) {
121 | arg.getValue().getChildren().forEach(c -> {
122 | if (c instanceof ObjectField) {
123 | org.jooq.Field name = field(((ObjectField) c).getName());
124 | visitorContext.selectedColumns.put(name, getColumnValues(((ObjectField) c).getValue()));
125 | }
126 | });
127 | }
128 | } else if (argumentName.equals("filter")) {
129 | Value> argValue = arg.getValue();
130 |
131 | //build condition for update or delete clause
132 | SQLFilterBuilder filterBuilder = new SQLFilterBuilder(null);
133 | FilterScanner filterScanner = new FilterScanner<>(filterBuilder);
134 |
135 | Condition condition = filterScanner.scan((ObjectValue) argValue, FilterScanner.Clause.and).condition;
136 | if (visitorContext.condition == null) {
137 | visitorContext.condition = condition;
138 | } else {
139 | visitorContext.condition = visitorContext.condition.and(condition);
140 | }
141 | } else {
142 | throw new RuntimeException("Unexpected value: " + argumentName);
143 | }
144 | }
145 |
146 | public String getSQL() {
147 | VisitorContext visitorContext = this.stack.peek();
148 | if(visitorContext.mutationType.contains("create"))
149 | return visitorContext.insertClause.toString();
150 | else if(visitorContext.mutationType.contains("update"))
151 | return visitorContext.updateClause.toString();
152 | else if(visitorContext.mutationType.contains("delete"))
153 | return visitorContext.deleteClause.toString();
154 | else
155 | return new RuntimeException("Unexpected value: " + visitorContext.mutationType).toString();
156 | }
157 |
158 | private Object getColumnValues(Value field) {
159 | Object fieldValue = null;
160 | if (field instanceof IntValue) {
161 | fieldValue = ((IntValue) field).getValue();
162 | } else if (field instanceof StringValue) {
163 | fieldValue = ((StringValue) field).getValue();
164 | } else if (field instanceof FloatValue) {
165 | fieldValue = ((FloatValue) field).getValue();
166 | } else if (field instanceof BooleanValue) {
167 | fieldValue = ((BooleanValue) field).isValue();
168 | }
169 | return fieldValue;
170 | }
171 |
172 | @Override
173 | public void visitScalar(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLType type) {
174 |
175 | }
176 |
177 | @Override
178 | public void startVisitObject(Field field, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type) {
179 |
180 | }
181 |
182 | @Override
183 | public void endVisitObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type) {
184 |
185 | }
186 |
187 | }
188 |
189 |
190 |
191 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/SQLQueryBuilderVisitor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import static org.jooq.impl.DSL.field;
19 | import static org.jooq.impl.DSL.jsonEntry;
20 | import static org.jooq.impl.DSL.jsonObject;
21 | import static org.jooq.impl.DSL.jsonbArrayAgg;
22 | import static org.jooq.impl.DSL.name;
23 | import static org.jooq.impl.DSL.table;
24 | import static org.jooq.impl.DSL.val;
25 |
26 | import java.math.BigInteger;
27 | import java.util.*;
28 | import java.util.concurrent.atomic.AtomicInteger;
29 |
30 | import graphql.Scalars;
31 | import graphql.schema.*;
32 | import org.jooq.Condition;
33 | import org.jooq.DSLContext;
34 | import org.jooq.JSONEntry;
35 | import org.jooq.Record;
36 | import org.jooq.SQLDialect;
37 | import org.jooq.SelectSelectStep;
38 | import org.jooq.impl.DSL;
39 | import org.slf4j.Logger;
40 | import org.slf4j.LoggerFactory;
41 |
42 | import graphql.language.Argument;
43 | import graphql.language.Field;
44 | import graphql.language.IntValue;
45 | import graphql.language.ObjectField;
46 | import graphql.language.ObjectValue;
47 | import graphql.language.Value;
48 | import io.graphqlcrud.FilterScanner.Clause;
49 |
50 | /**
51 | * This is root SQL builder, it is assumed any special cases are added as extensions to this class by extending it
52 | */
53 | public class SQLQueryBuilderVisitor implements QueryVisitor{
54 | private static final Logger LOGGER = LoggerFactory.getLogger(SQLQueryBuilderVisitor.class);
55 |
56 | protected AtomicInteger inc = new AtomicInteger(0);
57 | protected SQLContext ctx;
58 | protected DSLContext create = null;
59 |
60 | private static class VisitorContext {
61 | String alias;
62 | SelectSelectStep selectClause;
63 | Map> selectedColumns = new LinkedHashMap<>();
64 | Map selectedFields = new LinkedHashMap<>();
65 | org.jooq.Condition condition;
66 | AliasedTable table;
67 | Page page;
68 | List> orderby;
69 | }
70 |
71 | private static class Page {
72 | BigInteger limit;
73 | BigInteger offset;
74 | }
75 |
76 | private class AliasedTable {
77 | String name;
78 | String alias;
79 | public AliasedTable(String name, String alias) {
80 | this.name = name;
81 | this.alias = alias;
82 | }
83 | }
84 |
85 | private Stack stack = new Stack<>();
86 |
87 | public SQLQueryBuilderVisitor(SQLContext ctx) {
88 | this.ctx = ctx;
89 | this.create = DSL.using(SQLDialect.valueOf(ctx.getDialect()));
90 | }
91 |
92 | @Override
93 | public void visitScalar(Field field, GraphQLFieldDefinition definition, GraphQLType type) {
94 | VisitorContext vctx = this.stack.peek();
95 | boolean found = false;
96 | for (String column: vctx.selectedColumns.keySet()) {
97 | if (column.equals(field.getName())) {
98 | found = true;
99 | break;
100 | }
101 | }
102 | if (!found) {
103 | vctx.selectedColumns.put(field.getName(), field(name(vctx.alias, field.getName())));
104 | vctx.selectedFields.put(field.getName(), field);
105 | }
106 | }
107 |
108 | static String fieldName(Field field) {
109 | if (field.getAlias() != null) {
110 | return field.getAlias();
111 | }
112 | return field.getName();
113 | }
114 |
115 | @Override
116 | public void startVisitObject(Field field, GraphQLFieldDefinition definition, GraphQLObjectType type) {
117 | SQLDirective sqlDirective = SQLDirective.find(definition.getDirectives());
118 | VisitorContext vctx = this.stack.peek();
119 | String aliasLeft = vctx.alias;
120 |
121 | // add current object field as selected
122 | vctx.selectedFields.put(field.getName(), field);
123 |
124 | if (sqlDirective != null && sqlDirective.getPrimaryFields() != null) {
125 | String aliasRight = alias(this.inc.getAndIncrement());
126 | AliasedTable right = buildTable(definition, aliasRight);
127 |
128 | SelectSelectStep select = this.create.select();
129 |
130 | // build where clause based on join
131 | Condition where = null;
132 | for (int key = 0; key < sqlDirective.getPrimaryFields().size(); key++) {
133 | Condition cond = field(name(aliasLeft, sqlDirective.getPrimaryFields().get(key)))
134 | .eq(field(name(sqlDirective.getForeignFields().get(key))));
135 | if (key == 0) {
136 | where = cond;
137 | } else {
138 | where = where.and(cond);
139 | }
140 | }
141 |
142 | // next level deep as context
143 | vctx = new VisitorContext();
144 | vctx.table = right;
145 | vctx.alias = aliasRight;
146 | vctx.selectClause = select;
147 | vctx.condition = where;
148 |
149 | this.stack.push(vctx);
150 | } else {
151 | throw new RuntimeException("@sql directive missing on " + field.getName());
152 | }
153 | }
154 |
155 | @Override
156 | public void endVisitObject(Field field, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type) {
157 | VisitorContext vctx = this.stack.pop();
158 |
159 | SelectSelectStep select = this.create.select();
160 | select.from(vctx.table.name);
161 |
162 | // add orderby
163 | if (vctx.orderby == null) {
164 | List identityColumns = getIdentityColumns(type);
165 | List> orderby = new ArrayList<>();
166 | identityColumns.stream().forEach(col -> {
167 | org.jooq.Field> f = field(name(col));
168 | orderby.add(f);
169 | });
170 | select.orderBy(orderby);
171 | } else {
172 | select.orderBy(vctx.orderby);
173 | }
174 |
175 | // has limit/offset
176 | if (vctx.page != null) {
177 | if (vctx.page.limit != null) {
178 | select.limit(vctx.page.limit.intValue());
179 | }
180 | if (vctx.page.offset != null) {
181 | select.offset(vctx.page.offset.intValue());
182 | }
183 | }
184 |
185 | // has where clause
186 | if (vctx.condition != null) {
187 | select.where(vctx.condition);
188 | }
189 | vctx.selectClause.from(table(select).as(vctx.table.alias));
190 |
191 | // build the nested json object
192 | List> list = new ArrayList<>();
193 | for (Map.Entry entry: vctx.selectedFields.entrySet()) {
194 | list.add(jsonEntry(val(fieldName(entry.getValue()), String.class),
195 | vctx.selectedColumns.get(entry.getKey())));
196 | }
197 |
198 | org.jooq.Field> json = vctx.selectClause.select(jsonbArrayAgg(jsonObject(list))).asField();
199 |
200 | // add the above as a field to parent query
201 | this.stack.peek().selectedColumns.put(field.getName(), json);
202 | }
203 |
204 | private List> buildOrderBy(String alias, List identityColumns) {
205 | List> orderby = new ArrayList<>();
206 | identityColumns.stream().forEach(col -> {
207 | org.jooq.Field> f = field(name(alias, col));
208 | orderby.add(f);
209 | });
210 | return orderby;
211 | }
212 |
213 | @Override
214 | public void startVisitRootObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type) {
215 | VisitorContext vctx = new VisitorContext();
216 | SQLDirective sqlDirective = SQLDirective.find(type.getDirectives());
217 | if (sqlDirective == null) {
218 | throw new RuntimeException("No SQL Directive found on field " + rootField.getName());
219 | }
220 |
221 | String alias = alias(this.inc.getAndIncrement());
222 | AliasedTable table = new AliasedTable(sqlDirective.getTableName(), alias);
223 |
224 | SelectSelectStep select = this.create.select();
225 |
226 | // add from
227 | vctx.table = table;
228 |
229 | // put the current table on stack
230 | vctx.alias = alias;
231 | vctx.selectClause = select;
232 |
233 | this.stack.push(vctx);
234 | }
235 |
236 | @Override
237 | public void endVisitRootObject(Field rootField, GraphQLFieldDefinition rootDefinition, GraphQLObjectType type) {
238 | VisitorContext vctx = this.stack.peek();
239 |
240 | // add table
241 | vctx.selectClause.from(table(vctx.table.name).as(vctx.table.alias));
242 |
243 | // add orderby
244 | if (vctx.orderby == null) {
245 | List identityColumns = getIdentityColumns(type);
246 | List> orderby = buildOrderBy(vctx.alias, identityColumns);
247 | vctx.selectClause.orderBy(orderby);
248 | } else {
249 | vctx.selectClause.orderBy(vctx.orderby);
250 | }
251 |
252 | // add where
253 | if (vctx.condition != null) {
254 | vctx.selectClause.where(vctx.condition);
255 | }
256 |
257 | List> projected = new ArrayList<>();
258 | vctx.selectedColumns.forEach((k,v) -> {
259 | projected.add(v.as(fieldName(vctx.selectedFields.get(k))));
260 | });
261 | vctx.selectClause.select(projected);
262 |
263 | // add limit & offset
264 | if (vctx.page != null) {
265 | if (vctx.page.limit != null) {
266 | vctx.selectClause.limit(vctx.page.limit.intValue());
267 | }
268 | if (vctx.page.offset != null) {
269 | vctx.selectClause.offset(vctx.page.offset.intValue());
270 | }
271 | }
272 | }
273 |
274 | private String alias(int i) {
275 | return "g"+i;
276 | }
277 |
278 | public static List getIdentityColumns(GraphQLObjectType type) {
279 | ArrayList names = new ArrayList<>();
280 | for (GraphQLFieldDefinition fd:type.getFieldDefinitions()) {
281 | GraphQLType fieldType = fd.getType();
282 | if (fieldType instanceof GraphQLModifiedType) {
283 | fieldType = ((GraphQLModifiedType) fieldType).getWrappedType();
284 | if (GraphQLTypeUtil.isScalar(fieldType)) {
285 | if (((GraphQLScalarType)fieldType).getName().equals("ID")) {
286 | names.add(fd.getName());
287 | }
288 | }
289 | }
290 | }
291 | return names;
292 | }
293 |
294 | private AliasedTable buildTable(GraphQLFieldDefinition definition, String alias) {
295 | SQLDirective parentDirective = null;
296 | if (definition.getType() instanceof GraphQLModifiedType) {
297 | GraphQLObjectType type = (GraphQLObjectType)((GraphQLModifiedType)definition.getType()).getWrappedType();
298 | parentDirective = SQLDirective.find(type.getDirectives());
299 | } else {
300 | GraphQLObjectType type = (GraphQLObjectType)definition.getType();
301 | parentDirective = SQLDirective.find(type.getDirectives());
302 | }
303 |
304 | // Build the main table
305 | AliasedTable table = new AliasedTable(parentDirective.getTableName(), alias);
306 | return table;
307 | }
308 |
309 | public String getSQL() {
310 | VisitorContext vctx = this.stack.peek();
311 | return vctx.selectClause.toString();
312 | }
313 |
314 | @Override
315 | public void visitArgument(Field field, GraphQLFieldDefinition definition, GraphQLObjectType type, Argument arg) {
316 | VisitorContext vctx = this.stack.peek();
317 |
318 | String argName = arg.getName();
319 | Value> argValue = arg.getValue();
320 |
321 | SQLFilterBuilder filterBuilder = new SQLFilterBuilder(vctx.alias);
322 |
323 | if(argName.equals("page")) {
324 | Page p = new Page();
325 | ObjectValue v = (ObjectValue)argValue;
326 | for (ObjectField of: v.getObjectFields()) {
327 | if (of.getName().equals("limit")) {
328 | p.limit = ((IntValue)of.getValue()).getValue();
329 | } else if (of.getName().equals("offset")) {
330 | p.offset = ((IntValue)of.getValue()).getValue();
331 | }
332 | }
333 | vctx.page = p;
334 | } else if (argName.equals("orderBy")) {
335 | // handle orderBy
336 | } else if(argName.equals("filter")) {
337 | LOGGER.debug("Walk through filter results");
338 | FilterScanner filterScanner = new FilterScanner<>(filterBuilder);
339 | Condition condition = filterScanner.scan((ObjectValue)argValue, Clause.and).condition;
340 | if (vctx.condition == null) {
341 | vctx.condition = condition;
342 | } else {
343 | vctx.condition = vctx.condition.and(condition);
344 | }
345 | } else if (argName.equals("input") && field.getName().contains("create")) {
346 | Condition condition;
347 | String pkName = null;
348 | boolean flag = false;
349 | for (GraphQLFieldDefinition f : type.getFieldDefinitions()) {
350 | // check for fields of ID type ie primary keys
351 | if (f.getType().equals(GraphQLNonNull.nonNull(Scalars.GraphQLID))) {
352 | pkName = f.getName();
353 | for (ObjectField objectField : ((ObjectValue) argValue).getObjectFields()) {
354 | if (f.getName().equals(objectField.getName())) {
355 | flag = true;
356 | String name = objectField.getName();
357 | Value> value = objectField.getValue();
358 | condition = filterBuilder.buildCondition(name, "eq", value);
359 | vctx.condition = vctx.condition == null ? condition : filterBuilder.and(vctx.condition, condition);
360 | }
361 | }
362 | }
363 | }
364 | if(!flag) {
365 | // fetch auto generated primary key
366 | Object keyValue = ctx.getAutoGeneratedPrimaryKey();
367 | if(keyValue != null) {
368 | condition = filterBuilder.buildCondition(pkName, "eq", (Value>) keyValue);
369 | vctx.condition = vctx.condition == null ? condition : filterBuilder.and(vctx.condition, condition);
370 | } else {
371 | throw new RuntimeException("No ID value is provided");
372 | }
373 | }
374 | }
375 | else {
376 | Condition condition = filterBuilder.buildCondition(argName, "eq", argValue);
377 | if (vctx.condition == null) {
378 | vctx.condition = condition;
379 | } else {
380 | vctx.condition = filterBuilder.and(vctx.condition, condition);
381 | }
382 | }
383 | }
384 | }
385 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/StringUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | public class StringUtil {
19 |
20 | public static String capitalize(String str) {
21 | return str.substring(0, 1).toUpperCase() + str.substring(1);
22 | }
23 |
24 | public static String plural(String str) {
25 | // stupid pluralizer, but can use a better one,
26 | // need to find a simple library
27 | if (str.toLowerCase().endsWith("s")) {
28 | return str.substring(0, str.length()-1)+"es";
29 | } else if (str.toLowerCase().endsWith("y")) {
30 | return str.substring(0, str.length()-1)+"ies";
31 | } else {
32 | return str + "s";
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/model/Attribute.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.model;
17 |
18 | public class Attribute {
19 | private final String name;
20 | private final boolean isNullable;
21 | private final int type;
22 |
23 | public Attribute(String name, int type, boolean isNullable) {
24 | this.name = name;
25 | this.type = type;
26 | this.isNullable = isNullable;
27 | }
28 |
29 | public boolean isNullable() {
30 | return isNullable;
31 | }
32 |
33 | public String getName() {
34 | return name;
35 | }
36 |
37 | public int getType() {
38 | return type;
39 | }
40 |
41 | @Override
42 | public String toString() {
43 | return "Attribute [name=" + name + ", isNullable=" + isNullable + ", type=" + type + "]";
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/model/Cardinality.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.model;
17 |
18 | public enum Cardinality {
19 | ONE_TO_ONE, ONE_TO_MANY, MANY_TO_MANY;
20 | }
21 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/model/Entity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.model;
17 |
18 |
19 | import java.util.ArrayList;
20 | import java.util.List;
21 | import java.util.Map;
22 | import java.util.TreeMap;
23 |
24 | public class Entity implements Comparable{
25 | private String name;
26 | private Map attributes = new TreeMap<>();
27 | private List relations = new ArrayList();
28 | private List pks = new ArrayList<>();
29 | private Schema parent;
30 |
31 | public Entity(String name) {
32 | this.name = name;
33 | }
34 |
35 | public void addAttribute(Attribute attribute) {
36 | this.attributes.put(attribute.getName(), attribute);
37 | }
38 |
39 | public String getFullName() {
40 | return parent.getName() + "." + getName();
41 | }
42 |
43 | public String getName() {
44 | return this.name;
45 | }
46 |
47 | // TODO: this needs to built for GraphQLCRUD
48 | public String getDescription() {
49 | return null;
50 | }
51 |
52 | public List getAttributes() {
53 | return new ArrayList(attributes.values());
54 | }
55 |
56 | public Attribute getAttribute(String name) {
57 | return attributes.get(name);
58 | }
59 |
60 | public boolean isPartOfPrimaryKey(String name) {
61 | return this.pks.contains(name);
62 | }
63 |
64 | public List getRelations() {
65 | return relations;
66 | }
67 |
68 | public void setRelations(List relations) {
69 | this.relations = relations;
70 | }
71 |
72 | public List getPrimaryKeys() {
73 | return pks;
74 | }
75 |
76 | public void setPrimaryKeys(List pks) {
77 | this.pks = pks;
78 | }
79 |
80 | @Override
81 | public String toString() {
82 | return "Entity [name=" + name + ", attributes=" + attributes + ", relations="
83 | + relations + ", pks=" + pks + "]";
84 | }
85 |
86 | @Override
87 | public int compareTo(Entity o) {
88 | if (o == null) {
89 | return -1;
90 | }
91 | return o.getName().compareTo(this.getName());
92 | }
93 |
94 | public Schema getParent() {
95 | return parent;
96 | }
97 |
98 | public void setParent(Schema parent) {
99 | this.parent = parent;
100 | }
101 |
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/model/Relation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.model;
17 |
18 |
19 | import java.util.TreeMap;
20 |
21 | public class Relation {
22 | private String name;
23 | private Entity foreignEntity;
24 | private TreeMap keyColumns = new TreeMap();
25 | private TreeMap referencedKeyColumns = new TreeMap();
26 | private Cardinality cardinality;
27 | private boolean nullable;
28 | private boolean exportedKey;
29 |
30 | public Relation(String name) {
31 | this.name = name;
32 | }
33 |
34 | public String getName() {
35 | return name;
36 | }
37 |
38 | public void setName(String name) {
39 | this.name = name;
40 | }
41 |
42 | public Entity getForeignEntity() {
43 | return foreignEntity;
44 | }
45 |
46 | public Cardinality getCardinality() {
47 | return cardinality;
48 | }
49 |
50 | public void setForeignEntity(Entity foreignEntity) {
51 | this.foreignEntity = foreignEntity;
52 | }
53 |
54 | public void setCardinality(Cardinality cardinality) {
55 | this.cardinality = cardinality;
56 | }
57 |
58 | public TreeMap getKeyColumns() {
59 | return keyColumns;
60 | }
61 |
62 | public void setKeyColumns(TreeMap keyColumns) {
63 | this.keyColumns = keyColumns;
64 | }
65 |
66 | public TreeMap getReferencedKeyColumns() {
67 | return referencedKeyColumns;
68 | }
69 |
70 | public void setReferencedKeyColumns(TreeMap referencedKeyColumns) {
71 | this.referencedKeyColumns = referencedKeyColumns;
72 | }
73 |
74 | public boolean isNullable() {
75 | return nullable;
76 | }
77 |
78 | public void setNullable(boolean nullable) {
79 | this.nullable = nullable;
80 | }
81 |
82 | public boolean isExportedKey() {
83 | return exportedKey;
84 | }
85 |
86 | public void setExportedKey(boolean exportedKey) {
87 | this.exportedKey = exportedKey;
88 | }
89 |
90 | @Override
91 | public String toString() {
92 | return "Relation{" +
93 | "name='" + name + '\'' +
94 | ", foreignEntity=" + foreignEntity +
95 | ", keyColumns=" + keyColumns +
96 | ", referencedKeyColumns=" + referencedKeyColumns +
97 | ", cardinality=" + cardinality +
98 | ", nullable=" + nullable +
99 | ", exportedKey=" + exportedKey +
100 | '}';
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/model/Schema.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.model;
17 |
18 | import java.util.List;
19 |
20 | public class Schema {
21 | private String name;
22 | private List entities;
23 |
24 | public Schema(String name) {
25 | this.name = name;
26 | }
27 |
28 | public String getName() {
29 | return name;
30 | }
31 | public List getEntities() {
32 | return entities;
33 | }
34 | public void setEntities(List entities) {
35 | this.entities = entities;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/types/JdbcTypeMap.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.types;
17 |
18 | import java.sql.Types;
19 |
20 | import graphql.Scalars;
21 | import graphql.scalars.ExtendedScalars;
22 | import graphql.schema.GraphQLInputType;
23 | import graphql.schema.GraphQLOutputType;
24 | import graphql.schema.GraphQLTypeReference;
25 |
26 | public class JdbcTypeMap implements TypeMap {
27 |
28 | @Override
29 | public GraphQLOutputType getAsGraphQLTypeString(int dataType) {
30 | GraphQLOutputType typeString;
31 | switch (dataType) {
32 | case Types.TINYINT:
33 | case Types.INTEGER:
34 | case Types.SMALLINT:
35 | typeString = Scalars.GraphQLInt;
36 | break;
37 | case Types.DOUBLE:
38 | case Types.FLOAT:
39 | case Types.REAL:
40 | case Types.NUMERIC:
41 | case Types.DECIMAL:
42 | typeString = Scalars.GraphQLFloat;
43 | break;
44 | case Types.DATE:
45 | case Types.TIMESTAMP:
46 | case Types.TIME:
47 | typeString = ExtendedScalars.DateTime;
48 | break;
49 | case Types.BIT:
50 | typeString = Scalars.GraphQLBoolean;
51 | break;
52 | case Types.OTHER:
53 | case Types.BINARY:
54 | case Types.VARBINARY:
55 | case Types.LONGVARBINARY:
56 | typeString = ExtendedScalars.Object;
57 | break;
58 | case Types.CHAR:
59 | case Types.VARCHAR:
60 | case Types.LONGVARCHAR:
61 | default:
62 | typeString = Scalars.GraphQLString;
63 | break;
64 | }
65 | return typeString;
66 | }
67 |
68 | @Override
69 | public GraphQLInputType getAsGraphQLFilterType (int dataType) {
70 | GraphQLInputType outputType;
71 | switch (dataType) {
72 | case Types.TINYINT:
73 | case Types.INTEGER:
74 | case Types.SMALLINT:
75 | outputType = GraphQLTypeReference.typeRef("IntInput");
76 | break;
77 | case Types.CHAR:
78 | case Types.VARCHAR:
79 | case Types.LONGVARCHAR:
80 | outputType = GraphQLTypeReference.typeRef("StringInput");
81 | break;
82 | case Types.DOUBLE:
83 | case Types.FLOAT:
84 | case Types.REAL:
85 | case Types.NUMERIC:
86 | case Types.DECIMAL:
87 | outputType = GraphQLTypeReference.typeRef("FloatInput");
88 | break;
89 | case Types.DATE:
90 | case Types.TIMESTAMP:
91 | case Types.TIME:
92 | outputType = GraphQLTypeReference.typeRef("StringInput");
93 | break;
94 | case Types.BIT:
95 | outputType = GraphQLTypeReference.typeRef("BooleanInput");
96 | break;
97 | default:
98 | outputType = GraphQLTypeReference.typeRef("StringInput");
99 | break;
100 | }
101 | return outputType;
102 | }
103 |
104 | @Override
105 | public GraphQLInputType getAsGraphQLTypeStringForInput(int dataType) {
106 | GraphQLInputType typeString;
107 | switch (dataType) {
108 | case Types.TINYINT:
109 | case Types.INTEGER:
110 | case Types.SMALLINT:
111 | typeString = Scalars.GraphQLInt;
112 | break;
113 | case Types.DOUBLE:
114 | case Types.FLOAT:
115 | case Types.REAL:
116 | case Types.NUMERIC:
117 | case Types.DECIMAL:
118 | typeString = Scalars.GraphQLFloat;
119 | break;
120 | case Types.DATE:
121 | case Types.TIMESTAMP:
122 | case Types.TIME:
123 | typeString = ExtendedScalars.DateTime;
124 | break;
125 | case Types.BIT:
126 | typeString = Scalars.GraphQLBoolean;
127 | break;
128 | case Types.OTHER:
129 | case Types.BINARY:
130 | case Types.VARBINARY:
131 | case Types.LONGVARBINARY:
132 | typeString = ExtendedScalars.Object;
133 | break;
134 | case Types.CHAR:
135 | case Types.VARCHAR:
136 | case Types.LONGVARCHAR:
137 | default:
138 | typeString = Scalars.GraphQLString;
139 | break;
140 | }
141 | return typeString;
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/engine/src/main/java/io/graphqlcrud/types/TypeMap.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud.types;
17 |
18 | import graphql.schema.GraphQLInputType;
19 | import graphql.schema.GraphQLOutputType;
20 |
21 | public interface TypeMap {
22 | GraphQLOutputType getAsGraphQLTypeString(int dataType);
23 |
24 | GraphQLInputType getAsGraphQLFilterType (int dataType);
25 |
26 | GraphQLInputType getAsGraphQLTypeStringForInput(int dataType);
27 | }
28 |
--------------------------------------------------------------------------------
/engine/src/test/java/io/graphqlcrud/DatabaseSchemaTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.sql.Connection;
19 | import java.sql.Types;
20 | import java.util.Collections;
21 | import java.util.List;
22 |
23 | import javax.inject.Inject;
24 |
25 | import org.junit.jupiter.api.Assertions;
26 | import org.junit.jupiter.api.Test;
27 |
28 | import io.agroal.api.AgroalDataSource;
29 | import io.graphqlcrud.model.Attribute;
30 | import io.graphqlcrud.model.Cardinality;
31 | import io.graphqlcrud.model.Entity;
32 | import io.graphqlcrud.model.Relation;
33 | import io.graphqlcrud.model.Schema;
34 | import io.quarkus.test.common.QuarkusTestResource;
35 | import io.quarkus.test.h2.H2DatabaseTestResource;
36 | import io.quarkus.test.junit.QuarkusTest;
37 |
38 | @QuarkusTestResource(H2DatabaseTestResource.class)
39 | @QuarkusTest
40 | public class DatabaseSchemaTest {
41 |
42 | @Inject
43 | private AgroalDataSource datasource;
44 |
45 | @Test
46 | public void testSchemaPrint() throws Exception {
47 | try (Connection connection = this.datasource.getConnection()){
48 | Assertions.assertNotNull(connection);
49 | Schema s = DatabaseSchemaBuilder.getSchema(connection, "PUBLIC");
50 | Assertions.assertNotNull(s);
51 | List entities = s.getEntities();
52 | Collections.sort(entities);
53 | Assertions.assertEquals(5, entities.size());
54 |
55 | Assertions.assertEquals("CUSTOMER", entities.get(2).getName());
56 | List customerAttributes = entities.get(2).getAttributes();
57 | Assertions.assertEquals(4, customerAttributes.size());
58 | Assertions.assertEquals("SSN", customerAttributes.get(3).getName());
59 | Assertions.assertEquals(Types.CHAR, customerAttributes.get(3).getType());
60 |
61 | Assertions.assertEquals("ACCOUNT",entities.get(4).getName());
62 | List accountRelations = entities.get(4).getRelations();
63 | Assertions.assertEquals(Cardinality.ONE_TO_MANY, accountRelations.get(0).getCardinality());
64 | Assertions.assertEquals("account",accountRelations.get(0).getName());
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/engine/src/test/java/io/graphqlcrud/FilterInputTest.java:
--------------------------------------------------------------------------------
1 | package io.graphqlcrud;
2 |
3 | import graphql.schema.GraphQLSchema;
4 | import io.agroal.api.AgroalDataSource;
5 | import io.graphqlcrud.model.Schema;
6 | import io.quarkus.test.common.QuarkusTestResource;
7 | import io.quarkus.test.h2.H2DatabaseTestResource;
8 | import io.quarkus.test.junit.QuarkusTest;
9 | import org.junit.jupiter.api.Assertions;
10 | import org.junit.jupiter.api.BeforeEach;
11 | import org.junit.jupiter.api.Test;
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import javax.inject.Inject;
16 | import java.sql.Connection;
17 |
18 | @QuarkusTestResource(H2DatabaseTestResource.class)
19 | @QuarkusTest
20 | public class FilterInputTest {
21 | private static final Logger LOGGER = LoggerFactory.getLogger(FilterInputTest.class);
22 |
23 | @Inject
24 | private AgroalDataSource datasource;
25 | private GraphQLSchema graphQLSchema;
26 |
27 | @BeforeEach
28 | public void setup() throws Exception {
29 | try (Connection connection = datasource.getConnection()) {
30 | Assertions.assertNotNull(connection);
31 | Schema schema = DatabaseSchemaBuilder.getSchema(connection, "PUBLIC");
32 | Assertions.assertNotNull(schema);
33 | this.graphQLSchema = GraphQLSchemaBuilder.getSchema(schema);
34 | Assertions.assertNotNull(this.graphQLSchema);
35 | }
36 | }
37 |
38 | @Test
39 | public void testFloatInput() {
40 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
41 | if(parent.getKey().equals("FloatInput")) {
42 | Assertions.assertEquals("FloatInput", parent.getValue().getName());
43 | parent.getValue().getChildren().forEach(child -> {
44 | if(child.toString().contains("name=ne"))
45 | Assertions.assertTrue(child.toString().contains("name=Float"));
46 | else if(child.toString().contains("name=eq"))
47 | Assertions.assertTrue(child.toString().contains("name=Float"));
48 | else if(child.toString().contains("name=le"))
49 | Assertions.assertTrue(child.toString().contains("name=Float"));
50 | else if(child.toString().contains("name=lt"))
51 | Assertions.assertTrue(child.toString().contains("name=Float"));
52 | else if(child.toString().contains("name=ge"))
53 | Assertions.assertTrue(child.toString().contains("name=Float"));
54 | else if(child.toString().contains("name=gt"))
55 | Assertions.assertTrue(child.toString().contains("name=Float"));
56 | else if(child.toString().contains("name=in"))
57 | Assertions.assertTrue(child.toString().contains("originalType=[Float!]"));
58 | });
59 | }
60 | });
61 | }
62 |
63 | @Test
64 | public void testBooleanInput() {
65 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
66 | if(parent.getKey().equals("BooleanInput")) {
67 | Assertions.assertEquals("BooleanInput", parent.getValue().getName());
68 | parent.getValue().getChildren().forEach(child -> {
69 | if (child.toString().contains("name=eq"))
70 | Assertions.assertTrue(child.toString().contains("name=Boolean"));
71 | else if (child.toString().contains("name=ne"))
72 | Assertions.assertTrue(child.toString().contains("name=Boolean"));
73 | });
74 | }
75 | });
76 | }
77 |
78 | @Test
79 | public void testIDInput() {
80 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
81 | if(parent.getKey().equals("IDInput")) {
82 | Assertions.assertEquals("IDInput", parent.getValue().getName());
83 | parent.getValue().getChildren().forEach(child -> {
84 | if (child.toString().contains("name=eq"))
85 | Assertions.assertTrue(child.toString().contains("name=ID"));
86 | else if (child.toString().contains("name=ne"))
87 | Assertions.assertTrue(child.toString().contains("name=ID"));
88 | else if (child.toString().contains("name=in"))
89 | Assertions.assertTrue(child.toString().contains("name=originalType=[ID!]"));
90 | });
91 | }
92 | });
93 | }
94 |
95 | @Test
96 | public void testOrderByInput() {
97 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
98 | if(parent.getKey().equals("OrderByInput")) {
99 | Assertions.assertEquals("OrderByInput",parent.getValue().getName());
100 | parent.getValue().getChildren().forEach(child -> {
101 | if(child.toString().contains("name=field"))
102 | Assertions.assertTrue(child.toString().contains("originalType=String!"));
103 | else if(child.toString().contains("name=order"))
104 | Assertions.assertTrue(child.toString().contains("defaultValue=ASC"));
105 | });
106 | }
107 | });
108 | }
109 |
110 | @Test
111 | public void testSortDirectionEnumInput() {
112 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
113 | if(parent.getKey().equals("SortDirectionEnum")) {
114 | Assertions.assertEquals("SortDirectionEnum",parent.getValue().getName());
115 | }
116 | });
117 | }
118 |
119 | @Test
120 | public void testIntInput() {
121 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
122 | if(parent.getKey().equals("IntInput")) {
123 | Assertions.assertEquals("IntInput", parent.getValue().getName());
124 | parent.getValue().getChildren().forEach(child -> {
125 | if(child.toString().contains("name=ne"))
126 | Assertions.assertTrue(child.toString().contains("name=Int"));
127 | else if(child.toString().contains("name=eq"))
128 | Assertions.assertTrue(child.toString().contains("name=Int"));
129 | else if(child.toString().contains("name=le"))
130 | Assertions.assertTrue(child.toString().contains("name=Int"));
131 | else if(child.toString().contains("name=lt"))
132 | Assertions.assertTrue(child.toString().contains("name=Int"));
133 | else if(child.toString().contains("name=ge"))
134 | Assertions.assertTrue(child.toString().contains("name=Int"));
135 | else if(child.toString().contains("name=gt"))
136 | Assertions.assertTrue(child.toString().contains("name=Int"));
137 | else if(child.toString().contains("name=in"))
138 | Assertions.assertTrue(child.toString().contains("originalType=[Int!]"));
139 | });
140 | }
141 | });
142 | }
143 |
144 | @Test
145 | public void testStringInput() {
146 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
147 | if(parent.getKey().equals("StringInput")) {
148 | Assertions.assertEquals("StringInput", parent.getValue().getName());
149 | parent.getValue().getChildren().forEach(child -> {
150 | if(child.toString().contains("name=ne"))
151 | Assertions.assertTrue(child.toString().contains("name=String"));
152 | else if(child.toString().contains("name=eq"))
153 | Assertions.assertTrue(child.toString().contains("name=String"));
154 | else if(child.toString().contains("name=le"))
155 | Assertions.assertTrue(child.toString().contains("name=String"));
156 | else if(child.toString().contains("name=lt"))
157 | Assertions.assertTrue(child.toString().contains("name=String"));
158 | else if(child.toString().contains("name=ge"))
159 | Assertions.assertTrue(child.toString().contains("name=String"));
160 | else if(child.toString().contains("name=gt"))
161 | Assertions.assertTrue(child.toString().contains("name=String"));
162 | else if(child.toString().contains("name=in"))
163 | Assertions.assertTrue(child.toString().contains("originalType=[String!]"));
164 | else if(child.toString().contains("name=contains"))
165 | Assertions.assertTrue(child.toString().contains("name=String"));
166 | else if(child.toString().contains("name=endsWith"))
167 | Assertions.assertTrue(child.toString().contains("name=String"));
168 | else if(child.toString().contains("name=startsWith"))
169 | Assertions.assertTrue(child.toString().contains("name=String"));
170 | });
171 | }
172 | });
173 | }
174 |
175 | @Test
176 | public void testPageRequestInput() {
177 | graphQLSchema.getTypeMap().entrySet().forEach( parent -> {
178 | if(parent.getKey().equals("PageRequest")) {
179 | parent.getValue().getChildren().forEach(child -> {
180 | if(child.toString().contains("name=limit"))
181 | Assertions.assertTrue(child.toString().contains("name=Int"));
182 | else if(child.toString().contains("name=offset"))
183 | Assertions.assertTrue(child.toString().contains("name=Int"));
184 | });
185 | }
186 | });
187 | }
188 |
189 | }
190 |
--------------------------------------------------------------------------------
/engine/src/test/java/io/graphqlcrud/GraphQLSchemaBuilderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 | package io.graphqlcrud;
17 |
18 | import java.sql.Connection;
19 |
20 | import javax.inject.Inject;
21 |
22 | import org.junit.jupiter.api.Assertions;
23 | import org.junit.jupiter.api.Test;
24 |
25 | import graphql.schema.GraphQLFieldDefinition;
26 | import graphql.schema.GraphQLObjectType;
27 | import graphql.schema.GraphQLSchema;
28 | import io.agroal.api.AgroalDataSource;
29 | import io.graphqlcrud.model.Schema;
30 | import io.quarkus.test.common.QuarkusTestResource;
31 | import io.quarkus.test.h2.H2DatabaseTestResource;
32 | import io.quarkus.test.junit.QuarkusTest;
33 |
34 | @QuarkusTestResource(H2DatabaseTestResource.class)
35 | @QuarkusTest
36 | public class GraphQLSchemaBuilderTest {
37 |
38 | @Inject
39 | private AgroalDataSource datasource;
40 |
41 | @Test
42 | public void testSchemaPrint() throws Exception {
43 | try (Connection connection = this.datasource.getConnection()){
44 | Assertions.assertNotNull(connection);
45 | Schema s = DatabaseSchemaBuilder.getSchema(connection, "PUBLIC");
46 | Assertions.assertNotNull(s);
47 |
48 | GraphQLSchema schema = GraphQLSchemaBuilder.getSchema(s);
49 | // SchemaPrinter sp = new SchemaPrinter();
50 | // System.out.println(sp.print(schema));
51 |
52 | GraphQLObjectType objectType = schema.getQueryType();
53 | Assertions.assertNotNull(objectType);
54 | Assertions.assertEquals("QueryType", objectType.getName());
55 | Assertions.assertEquals("account",objectType.getFieldDefinition("account").getName());
56 | Assertions.assertEquals("ACCOUNT_ID",objectType.getFieldDefinition("account").getArguments().get(0).getName());
57 |
58 | GraphQLObjectType customer = schema.getObjectType("CUSTOMER");
59 | Assertions.assertNotNull(customer);
60 | Assertions.assertEquals("PUBLIC.CUSTOMER", customer.getDirective("sql").getArgument("table").getValue().toString());
61 | GraphQLFieldDefinition accountsDef = customer.getFieldDefinition("accounts");
62 | Assertions.assertNotNull(accountsDef.getDirective("sql"));
63 | Assertions.assertEquals("[SSN]", accountsDef.getDirective("sql").getArgument("keys").getValue().toString());
64 | Assertions.assertEquals("[SSN]", accountsDef.getDirective("sql").getArgument("reference_keys").getValue().toString());
65 |
66 | GraphQLObjectType account = schema.getObjectType("ACCOUNT");
67 | Assertions.assertNotNull(account);
68 | Assertions.assertEquals("PUBLIC.ACCOUNT", account.getDirective("sql").getArgument("table").getValue().toString());
69 | GraphQLFieldDefinition holdings = account.getFieldDefinition("holdinges");
70 | Assertions.assertNotNull(holdings.getDirective("sql"));
71 | Assertions.assertEquals("[ACCOUNT_ID]", holdings.getDirective("sql").getArgument("keys").getValue().toString());
72 | Assertions.assertEquals("[ACCOUNT_ID]", holdings.getDirective("sql").getArgument("reference_keys").getValue().toString());
73 |
74 | GraphQLFieldDefinition customers = account.getFieldDefinition("customer");
75 | Assertions.assertNotNull(customers.getDirective("sql"));
76 | Assertions.assertEquals("[SSN]", customers.getDirective("sql").getArgument("keys").getValue().toString());
77 | Assertions.assertEquals("[SSN]", customers.getDirective("sql").getArgument("reference_keys").getValue().toString());
78 |
79 | GraphQLObjectType product = schema.getObjectType("PRODUCT");
80 | Assertions.assertNotNull(product);
81 | Assertions.assertEquals("PUBLIC.PRODUCT", product.getDirective("sql").getArgument("table").getValue().toString());
82 | holdings = product.getFieldDefinition("holdinges");
83 | Assertions.assertNotNull(holdings.getDirective("sql"));
84 | Assertions.assertEquals("[ID]", holdings.getDirective("sql").getArgument("keys").getValue().toString());
85 | Assertions.assertEquals("[PRODUCT_ID]", holdings.getDirective("sql").getArgument("reference_keys").getValue().toString());
86 |
87 | Assertions.assertEquals("page", holdings.getArgument("page").getName());
88 | Assertions.assertTrue(holdings.getArgument("page").getType().toString().contains("PageRequest"));
89 | Assertions.assertEquals("orderBy", holdings.getArgument("orderBy").getName());
90 | Assertions.assertTrue(holdings.getArgument("orderBy").getType().toString().contains("OrderByInput"));
91 | Assertions.assertEquals("filter", holdings.getArgument("filter").getName());
92 | Assertions.assertTrue(holdings.getArgument("filter").getType().toString().contains("HoldingsFilterInput"));
93 | }
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/engine/src/test/java/io/graphqlcrud/SQLMutationDataFetcherTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2017 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 |
17 | package io.graphqlcrud;
18 | import java.sql.Connection;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 | import javax.inject.Inject;
22 | import org.junit.jupiter.api.Assertions;
23 | import org.junit.jupiter.api.BeforeEach;
24 | import org.junit.jupiter.api.Test;
25 |
26 | import graphql.ExecutionInput;
27 | import graphql.ExecutionResult;
28 | import graphql.GraphQL;
29 |
30 | import graphql.schema.GraphQLSchema;
31 | import graphql.schema.idl.SchemaPrinter;
32 | import io.agroal.api.AgroalDataSource;
33 | import io.graphqlcrud.model.Schema;
34 | import io.quarkus.test.common.QuarkusTestResource;
35 | import io.quarkus.test.h2.H2DatabaseTestResource;
36 | import io.quarkus.test.junit.QuarkusTest;
37 |
38 | @QuarkusTestResource(H2DatabaseTestResource.class)
39 | @QuarkusTest
40 | class SQLMutationDataFetcherTest {
41 |
42 | @Inject
43 | AgroalDataSource datasource;
44 | GraphQLSchema graphQLSchema;
45 |
46 | @BeforeEach
47 | public void setup() throws Exception {
48 | try (Connection connection = this.datasource.getConnection()) {
49 | Assertions.assertNotNull(connection);
50 | Schema schema = DatabaseSchemaBuilder.getSchema(connection, "PUBLIC");
51 | Assertions.assertNotNull(schema);
52 | this.graphQLSchema = GraphQLSchemaBuilder.getSchema(schema);
53 | Assertions.assertNotNull(this.graphQLSchema);
54 |
55 | SchemaPrinter sp = new SchemaPrinter();
56 | System.out.println(sp.print(this.graphQLSchema));
57 | }
58 | }
59 |
60 | @Test
61 | public void CreateMutation() throws Exception {
62 | String create_query = "mutation {\n" +
63 | " createCustomer (input: {\n" +
64 | " SSN: \"CST01040\",\n" +
65 | " FIRSTNAME: \"Gorge\",\n" +
66 | " LASTNAME: \"Corners\",\n" +
67 | " PHONE: \"(651)590-9023\"\n" +
68 | " }) {\n" +
69 | " SSN\n" +
70 | " FIRSTNAME\n" +
71 | " LASTNAME\n" +
72 | " PHONE\n" +
73 | " }\n" +
74 | "}";
75 | List create_result = executeSQL(create_query);
76 |
77 | String create_expected_mutation = "insert into CUSTOMER (\n" +
78 | " SSN,\n" +
79 | " FIRSTNAME,\n" +
80 | " LASTNAME,\n" +
81 | " PHONE\n" +
82 | ")\n" +
83 | "values (\n" +
84 | " 'CST01040', \n" +
85 | " 'Gorge', \n" +
86 | " 'Corners', \n" +
87 | " '(651)590-9023'\n" +
88 | ")";
89 |
90 | String create_expected_sql = "select\n" +
91 | " \"g0\".\"SSN\" \"SSN\",\n" +
92 | " \"g0\".\"FIRSTNAME\" \"FIRSTNAME\",\n" +
93 | " \"g0\".\"LASTNAME\" \"LASTNAME\",\n" +
94 | " \"g0\".\"PHONE\" \"PHONE\"\n" +
95 | "from PUBLIC.CUSTOMER \"g0\"\n" +
96 | "where \"g0\".\"SSN\" = 'CST01040'\n" +
97 | "order by \"g0\".\"SSN\"";
98 |
99 | Assertions.assertEquals(create_expected_mutation,create_result.get(1));
100 | Assertions.assertEquals(create_expected_sql, create_result.get(0));
101 | }
102 |
103 | @Test
104 | public void UpdateMutation() throws Exception {
105 | String update_query = "mutation {\n" +
106 | " updateCustomer(input: {\n" +
107 | " FIRSTNAME: \"James\"\n" +
108 | " }, filter: {\n" +
109 | " SSN: {\n" +
110 | " eq: \"CST01002\"\n" +
111 | " }\n" +
112 | " }) {\n" +
113 | " SSN\n" +
114 | " FIRSTNAME\n" +
115 | " LASTNAME\n" +
116 | " PHONE\n" +
117 | " }\n" +
118 | "}";
119 |
120 | List update_result = executeSQL(update_query);
121 |
122 | String update_expected_mutation = "update CUSTOMER\n" +
123 | "set\n" +
124 | " FIRSTNAME = 'James'\n" +
125 | "where SSN = 'CST01002'";
126 |
127 | String update_expected_sql = "select\n" +
128 | " \"g0\".\"SSN\" \"SSN\",\n" +
129 | " \"g0\".\"FIRSTNAME\" \"FIRSTNAME\",\n" +
130 | " \"g0\".\"LASTNAME\" \"LASTNAME\",\n" +
131 | " \"g0\".\"PHONE\" \"PHONE\"\n" +
132 | "from PUBLIC.CUSTOMER \"g0\"\n" +
133 | "where \"g0\".\"SSN\" = 'CST01002'\n" +
134 | "order by \"g0\".\"SSN\"";
135 |
136 | Assertions.assertEquals(update_expected_mutation,update_result.get(1));
137 | Assertions.assertEquals(update_expected_sql, update_result.get(0));
138 | }
139 |
140 | @Test
141 | public void DeleteMutation() throws Exception {
142 | String delete_query = "mutation {\n" +
143 | " deleteCustomer (filter: {\n" +
144 | " SSN: {\n" +
145 | " eq: \"CST01002\"\n" +
146 | " }\n" +
147 | " }) {\n" +
148 | " SSN\n" +
149 | " FIRSTNAME\n" +
150 | " LASTNAME\n" +
151 | " PHONE\n" +
152 | " }\n" +
153 | "}";
154 | List delete_result = executeSQL(delete_query);
155 |
156 | String delete_expected_mutation = "delete from CUSTOMER\n" +
157 | "where SSN = 'CST01002'";
158 |
159 | String delete_expected_sql = "select\n" +
160 | " \"g0\".\"SSN\" \"SSN\",\n" +
161 | " \"g0\".\"FIRSTNAME\" \"FIRSTNAME\",\n" +
162 | " \"g0\".\"LASTNAME\" \"LASTNAME\",\n" +
163 | " \"g0\".\"PHONE\" \"PHONE\"\n" +
164 | "from PUBLIC.CUSTOMER \"g0\"\n" +
165 | "where \"g0\".\"SSN\" = 'CST01002'\n" +
166 | "order by \"g0\".\"SSN\"";
167 |
168 | Assertions.assertEquals(delete_expected_mutation,delete_result.get(1));
169 | Assertions.assertEquals(delete_expected_sql, delete_result.get(0));
170 | }
171 |
172 | @Test
173 | public List executeSQL(String query) throws Exception {
174 | List sql = new ArrayList<>();
175 | ExecutionInput.Builder executionInput = ExecutionInput.newExecutionInput()
176 | .query(query);
177 |
178 | try (SQLContext ctx = new SQLContext(this.datasource.getConnection())) {
179 | executionInput.context(ctx);
180 | ctx.setDialect("DEFAULT");
181 |
182 | GraphQL graphQL = GraphQL
183 | .newGraphQL(this.graphQLSchema)
184 | .build();
185 |
186 | ExecutionResult executionResult = graphQL.execute(executionInput.build());
187 | Assertions.assertNotNull(executionResult);
188 |
189 | sql.add(ctx.getSQL());
190 | sql.add(ctx.getSqlMutation());
191 | Assertions.assertNotNull(sql);
192 | }
193 | return sql;
194 | }
195 | }
--------------------------------------------------------------------------------
/engine/src/test/java/io/graphqlcrud/TestParse.java:
--------------------------------------------------------------------------------
1 | package io.graphqlcrud;
2 |
3 | import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | import org.junit.jupiter.api.Test;
11 |
12 | import graphql.ExecutionResult;
13 | import graphql.GraphQL;
14 | import graphql.schema.DataFetcher;
15 | import graphql.schema.DataFetchingEnvironment;
16 | import graphql.schema.GraphQLSchema;
17 | import graphql.schema.idl.RuntimeWiring;
18 | import graphql.schema.idl.SchemaGenerator;
19 | import graphql.schema.idl.SchemaParser;
20 | import graphql.schema.idl.TypeDefinitionRegistry;
21 |
22 | class TestParse {
23 |
24 | @Test
25 | void test() {
26 | String sdl = " schema {query: Query}\n"
27 | + "type Query {\n" +
28 | " books: [Book] \n" +
29 | "}\n" +
30 | "\n" +
31 | "type Book {\n" +
32 | " id: ID\n" +
33 | " name: String\n" +
34 | " pageCount: Int\n" +
35 | " author: Author\n" +
36 | "}\n" +
37 | "\n" +
38 | "type Author {\n" +
39 | " id: ID\n" +
40 | " firstName: String\n" +
41 | " lastName: String\n" +
42 | "}" ;
43 | TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
44 |
45 | RuntimeWiring runtimeWiring = buildWiring();
46 | SchemaGenerator schemaGenerator = new SchemaGenerator();
47 | GraphQLSchema schema = schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
48 | String query = "{ books {id, name} }";
49 | //GraphQL build = GraphQL.newGraphQL(schema).queryExecutionStrategy(new SQLExcecutionStrategy()).build();
50 | GraphQL build = GraphQL.newGraphQL(schema).build();
51 | ExecutionResult executionResult = build.execute(query);
52 |
53 | System.out.println(executionResult.getData().toString());
54 |
55 | }
56 |
57 | static class MyFetcher implements DataFetcher>> {
58 | @Override
59 | public List> get(DataFetchingEnvironment environment) throws Exception {
60 | List> list = new ArrayList>();
61 |
62 | HashMap results = new HashMap();
63 | results.put("id", "1");
64 | results.put("name", "foo");
65 | results.put("pageCount", "200");
66 | list.add(results);
67 |
68 | results = new HashMap();
69 | results.put("id", "2");
70 | results.put("name", "bar");
71 | results.put("pageCount", "100");
72 | list.add(results);
73 |
74 | return list;
75 | }
76 | };
77 |
78 | private RuntimeWiring buildWiring() {
79 | return RuntimeWiring.newRuntimeWiring()
80 | .type(newTypeWiring("Query").dataFetcher("books", new MyFetcher()))
81 | .type(newTypeWiring("Book").dataFetcher("author", new MyFetcher()))
82 | .build();
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/engine/src/test/resources/application.properties:
--------------------------------------------------------------------------------
1 | quarkus.datasource.url=jdbc:h2:tcp://localhost/mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'classpath:import.sql'
2 | quarkus.datasource.driver=org.h2.Driver
3 | quarkus.hibernate-orm.database.generation = drop-and-create
4 | quarkus.hibernate-orm.log.sql=true
--------------------------------------------------------------------------------
/engine/src/test/resources/import.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE IF EXISTS CUSTOMER CASCADE;
2 | DROP TABLE IF EXISTS ADDRESS CASCADE;
3 | DROP TABLE IF EXISTS ACCOUNT CASCADE;
4 | DROP TABLE IF EXISTS PRODUCT CASCADE;
5 | DROP TABLE IF EXISTS HOLDINGS CASCADE;
6 |
7 |
8 | CREATE TABLE CUSTOMER
9 | (
10 | SSN char(10),
11 | FIRSTNAME varchar(64),
12 | LASTNAME varchar(64),
13 | PHONE varchar(15),
14 | CONSTRAINT CUSTOMER_PK PRIMARY KEY(SSN)
15 | );
16 |
17 | CREATE TABLE ADDRESS
18 | (
19 | SSN char(10),
20 | ST_ADDRESS varchar(256),
21 | APT_NUMBER varchar(32),
22 | CITY varchar(64),
23 | STATE varchar(32),
24 | ZIPCODE varchar(10),
25 | CONSTRAINT ADDRESS_FK FOREIGN KEY(SSN) REFERENCES CUSTOMER(SSN) ON DELETE CASCADE ON UPDATE CASCADE
26 | );
27 |
28 | CREATE TABLE ACCOUNT
29 | (
30 | ACCOUNT_ID integer,
31 | SSN char(10),
32 | STATUS char(10),
33 | TYPE char(10),
34 | DATEOPENED timestamp,
35 | DATECLOSED timestamp,
36 | CONSTRAINT ACCOUNT_PK PRIMARY KEY(ACCOUNT_ID),
37 | CONSTRAINT CUSTOMER_FK FOREIGN KEY(SSN) REFERENCES CUSTOMER(SSN) ON DELETE CASCADE ON UPDATE CASCADE
38 | );
39 |
40 |
41 | CREATE TABLE PRODUCT (
42 | ID integer,
43 | SYMBOL varchar(16),
44 | COMPANY_NAME varchar(256),
45 | CONSTRAINT PRODUCT_PK PRIMARY KEY(ID)
46 | );
47 |
48 |
49 | CREATE TABLE HOLDINGS
50 | (
51 | TRANSACTION_ID integer auto_increment,
52 | ACCOUNT_ID integer,
53 | PRODUCT_ID integer,
54 | PURCHASE_DATE timestamp,
55 | SHARES_COUNT integer,
56 | CONSTRAINT HOLDINGS_PK PRIMARY KEY (TRANSACTION_ID),
57 | CONSTRAINT ACCOUNT_FK FOREIGN KEY(ACCOUNT_ID) REFERENCES ACCOUNT(ACCOUNT_ID) ON DELETE CASCADE ON UPDATE CASCADE,
58 | CONSTRAINT PRODUCT_FK FOREIGN KEY(PRODUCT_ID) REFERENCES PRODUCT(ID) ON DELETE CASCADE ON UPDATE CASCADE
59 | );
60 |
61 |
62 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01002','John','Doe','(646)555-1776');
63 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01003','Bob','Smith','(412)555-4327');
64 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01004','Jane','Aire','(814)555-6789');
65 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01005','Charles','Jones','(203)555-3947');
66 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01006','Virginia','Jefferson','(718)555-2693');
67 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01007','Ralph','Bacon','(704)555-4576');
68 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01008','Bonnie','Dragon','(904)555-6514');
69 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01009','Herbert','Smith','(971)555-7803');
70 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01015','Jack','Corby','(469)555-8023');
71 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01019','Robin','Evers','(470)555-4390');
72 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01020','Lloyd','Abercrombie','(213)555-2312');
73 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01021','Scott','Watters','(206)555-6790');
74 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01022','Sandra','King','(651)555-9017');
75 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01027','Maryanne','Peters','(513)555-9067');
76 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01034','Corey','Snyder','(617)555-3546');
77 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01035','Henry','Thomas','(415)555-2093');
78 | INSERT INTO CUSTOMER (SSN,FIRSTNAME,LASTNAME,PHONE) VALUES ('CST01036','James','Drew','(216)555-6523');
79 |
80 |
81 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01002','1234 Main Street','Apartment 56','New York','New York','10174');
82 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01003','202 Palomino Drive',null,'Pittsburgh','Pennsylvania','15071');
83 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01004','15 State Street',null,'Philadelphia','Pennsylvania','19154');
84 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01005','1819 Maple Street','Apartment 17F','Stratford','Connecticut','06614');
85 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01006','1710 South 51st Street','Apartment 3245','New York','New York','10175');
86 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01007','57 Barn Swallow Avenue',null,'Charlotte','North Carolina','28205');
87 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01008','88 Cinderella Lane',null,'Jacksonville','Florida','32225');
88 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01009','12225 Waterfall Way','Building 100, Suite 9','Portland','Oregon','97220');
89 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01015','1 Lone Star Way',null,'Dallas','Texas','75231');
90 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01019','1814 Falcon Avenue',null,'Atlanta','Georgia','30355');
91 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01020','1954 Hughes Parkway',null,'Los Angeles','California','90099');
92 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01021','24 Mariner Way',null,'Seattle','Washington','98124');
93 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01022','96 Lakefront Parkway',null,'Minneapolis','Minnesota','55426');
94 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01027','35 Grand View Circle','Apartment 5F','Cincinnati','Ohio','45232');
95 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01034','1760 Boston Commons Avenue','Suite 543','Boston','Massachusetts','02136 ');
96 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01035','345 Hilltop Parkway',null,'San Francisco','California','94129');
97 | INSERT INTO ADDRESS (SSN,ST_ADDRESS,APT_NUMBER,CITY,STATE,ZIPCODE) VALUES ('CST01036','876 Lakefront Lane',null,'Cleveland','Ohio','44107');
98 |
99 |
100 |
101 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980001,'CST01002','Personal ','Active ','1998-01-01 00:00:00.000', NULL);
102 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980002,'CST01002','Personal ','Active ','1998-02-01 00:00:00.000', NULL);
103 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980003,'CST01003','Personal ','Active ','1998-03-06 00:00:00.000',null);
104 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980004,'CST01004','Personal ','Active ','1998-03-07 00:00:00.000',null);
105 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980005,'CST01005','Personal ','Active ','1998-06-15 00:00:00.000',null);
106 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19980006,'CST01006','Personal ','Active ','1998-09-15 00:00:00.000',null);
107 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19990007,'CST01007','Personal ','Active ','1999-01-20 00:00:00.000',null);
108 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19990008,'CST01008','Personal ','Active ','1999-04-16 00:00:00.000',null);
109 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (19990009,'CST01009','Business ','Active ','1999-06-25 00:00:00.000',null);
110 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000015,'CST01015','Personal ','Closed ','2000-04-20 00:00:00.000','2001-06-22 00:00:00.000');
111 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000019,'CST01019','Personal ','Active ','2000-10-08 00:00:00.000',null);
112 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000020,'CST01020','Personal ','Active ','2000-10-20 00:00:00.000',null);
113 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20000021,'CST01021','Personal ','Active ','2000-12-05 00:00:00.000',null);
114 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20010022,'CST01022','Personal ','Active ','2001-01-05 00:00:00.000',null);
115 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20010027,'CST01027','Personal ','Active ','2001-08-22 00:00:00.000',null);
116 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20020034,'CST01034','Business ','Active ','2002-01-22 00:00:00.000',null);
117 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20020035,'CST01035','Personal ','Active ','2002-02-12 00:00:00.000',null);
118 | INSERT INTO ACCOUNT (ACCOUNT_ID,SSN,STATUS,TYPE,DATEOPENED,DATECLOSED) VALUES (20020036,'CST01036','Personal ','Active ','2002-03-22 00:00:00.000',null);
119 |
120 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1002,'BA','The Boeing Company');
121 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1004,'VIX','Vix Index');
122 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1006,'BTU','Peabody Energy');
123 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1007,'IBM','International Business Machines Corporation');
124 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1008,'DELL','Dell Computer Corporation');
125 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1010,'HPQ','Hewlett-Packard Company');
126 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1012,'GE','General Electric Company');
127 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1013,'MRK','Merck and Company Incorporated');
128 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1014,'DIS','Walt Disney Company');
129 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1015,'MCD','McDonalds Corporation');
130 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1016,'DOW','Dow Chemical Company');
131 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1018,'GM','General Motors Corporation');
132 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1024,'SBGI','Sinclair Broadcast Group Incorporated');
133 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1025,'COLM','Columbia Sportsware Company');
134 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1026,'COLB','Columbia Banking System Incorporated');
135 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1028,'BAC','Bank Of America');
136 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1029,'CSVFX','Columbia Strategic Value Fund');
137 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1030,'CMTFX','Columbia Technology Fund');
138 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1031,'F','Ford Motor Company');
139 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1033,'CRM','Salesforce');
140 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1034,'SAP','SAP AG');
141 | INSERT INTO PRODUCT (ID,SYMBOL,COMPANY_NAME) VALUES(1036,'TM','Toyota Motor Corporation');
142 |
143 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980002,1008,'1998-02-01 00:00:00.000',50);
144 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980002,1036,'1998-02-01 00:00:00.000',25);
145 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1002,'1998-03-06 00:00:00.000',100);
146 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1029,'1998-03-06 00:00:00.000',25);
147 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1016,'1998-03-06 00:00:00.000',51);
148 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980005,1024,'1998-06-15 00:00:00.000',18);
149 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980006,1033,'1998-09-15 00:00:00.000',200);
150 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990007,1031,'1999-01-20 00:00:00.000',65);
151 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990008,1012,'1999-04-16 00:00:00.000',102);
152 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990007,1008,'1999-05-11 00:00:00.000',85);
153 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990009,1004,'1999-06-25 00:00:00.000',120);
154 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1024,'1999-07-22 00:00:00.000',150);
155 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000015,1018,'2000-04-20 00:00:00.000',135);
156 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980006,1030,'2000-06-12 00:00:00.000',91);
157 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000019,1029,'2000-10-08 00:00:00.000',351);
158 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000020,1030,'2000-10-20 00:00:00.000',127);
159 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000020,1018,'2000-11-14 00:00:00.000',100);
160 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000019,1031,'2000-11-15 00:00:00.000',125);
161 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000021,1028,'2000-12-05 00:00:00.000',400);
162 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010022,1006,'2001-01-05 00:00:00.000',237);
163 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990008,1015,'2001-01-23 00:00:00.000',180);
164 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980005,1025,'2001-03-23 00:00:00.000',125);
165 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010027,1024,'2001-08-22 00:00:00.000',70);
166 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000020,1006,'2001-11-14 00:00:00.000',125);
167 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980003,1029,'2001-11-15 00:00:00.000',100);
168 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010027,1028,'2001-12-19 00:00:00.000',115);
169 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020034,1024,'2002-01-22 00:00:00.000',189);
170 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19990009,1029,'2002-01-24 00:00:00.000',30);
171 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020035,1013,'2002-02-12 00:00:00.000',110);
172 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020035,1034,'2002-02-13 00:00:00.000',70);
173 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000019,1013,'2002-02-26 00:00:00.000',195);
174 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980004,1007,'2002-03-05 00:00:00.000',250);
175 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20000021,1014,'2002-03-12 00:00:00.000',300);
176 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20010027,1024,'2002-03-14 00:00:00.000',136);
177 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020036,1012,'2002-03-22 00:00:00.000',54);
178 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (20020036,1010,'2002-03-26 00:00:00.000',189);
179 | INSERT INTO HOLDINGS (ACCOUNT_ID,PRODUCT_ID,PURCHASE_DATE,SHARES_COUNT) VALUES (19980005,1010,'2002-04-01 00:00:00.000',26);
180 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # http://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Mingw, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | fi
118 |
119 | if [ -z "$JAVA_HOME" ]; then
120 | javaExecutable="`which javac`"
121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
122 | # readlink(1) is not available as standard on Solaris 10.
123 | readLink=`which readlink`
124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
125 | if $darwin ; then
126 | javaHome="`dirname \"$javaExecutable\"`"
127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
128 | else
129 | javaExecutable="`readlink -f \"$javaExecutable\"`"
130 | fi
131 | javaHome="`dirname \"$javaExecutable\"`"
132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
133 | JAVA_HOME="$javaHome"
134 | export JAVA_HOME
135 | fi
136 | fi
137 | fi
138 |
139 | if [ -z "$JAVACMD" ] ; then
140 | if [ -n "$JAVA_HOME" ] ; then
141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
142 | # IBM's JDK on AIX uses strange locations for the executables
143 | JAVACMD="$JAVA_HOME/jre/sh/java"
144 | else
145 | JAVACMD="$JAVA_HOME/bin/java"
146 | fi
147 | else
148 | JAVACMD="`which java`"
149 | fi
150 | fi
151 |
152 | if [ ! -x "$JAVACMD" ] ; then
153 | echo "Error: JAVA_HOME is not defined correctly." >&2
154 | echo " We cannot execute $JAVACMD" >&2
155 | exit 1
156 | fi
157 |
158 | if [ -z "$JAVA_HOME" ] ; then
159 | echo "Warning: JAVA_HOME environment variable is not set."
160 | fi
161 |
162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
163 |
164 | # traverses directory structure from process work directory to filesystem root
165 | # first directory with .mvn subdirectory is considered project base directory
166 | find_maven_basedir() {
167 |
168 | if [ -z "$1" ]
169 | then
170 | echo "Path not specified to find_maven_basedir"
171 | return 1
172 | fi
173 |
174 | basedir="$1"
175 | wdir="$1"
176 | while [ "$wdir" != '/' ] ; do
177 | if [ -d "$wdir"/.mvn ] ; then
178 | basedir=$wdir
179 | break
180 | fi
181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
182 | if [ -d "${wdir}" ]; then
183 | wdir=`cd "$wdir/.."; pwd`
184 | fi
185 | # end of workaround
186 | done
187 | echo "${basedir}"
188 | }
189 |
190 | # concatenates all lines of a file
191 | concat_lines() {
192 | if [ -f "$1" ]; then
193 | echo "$(tr -s '\n' ' ' < "$1")"
194 | fi
195 | }
196 |
197 | BASE_DIR=`find_maven_basedir "$(pwd)"`
198 | if [ -z "$BASE_DIR" ]; then
199 | exit 1;
200 | fi
201 |
202 | ##########################################################################################
203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
204 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
205 | ##########################################################################################
206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
207 | if [ "$MVNW_VERBOSE" = true ]; then
208 | echo "Found .mvn/wrapper/maven-wrapper.jar"
209 | fi
210 | else
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
213 | fi
214 | if [ -n "$MVNW_REPOURL" ]; then
215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
216 | else
217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
218 | fi
219 | while IFS="=" read key value; do
220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
221 | esac
222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
223 | if [ "$MVNW_VERBOSE" = true ]; then
224 | echo "Downloading from: $jarUrl"
225 | fi
226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
227 | if $cygwin; then
228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
229 | fi
230 |
231 | if command -v wget > /dev/null; then
232 | if [ "$MVNW_VERBOSE" = true ]; then
233 | echo "Found wget ... using wget"
234 | fi
235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
236 | wget "$jarUrl" -O "$wrapperJarPath"
237 | else
238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
239 | fi
240 | elif command -v curl > /dev/null; then
241 | if [ "$MVNW_VERBOSE" = true ]; then
242 | echo "Found curl ... using curl"
243 | fi
244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
245 | curl -o "$wrapperJarPath" "$jarUrl" -f
246 | else
247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
248 | fi
249 |
250 | else
251 | if [ "$MVNW_VERBOSE" = true ]; then
252 | echo "Falling back to using Java to download"
253 | fi
254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
255 | # For Cygwin, switch paths to Windows format before running javac
256 | if $cygwin; then
257 | javaClass=`cygpath --path --windows "$javaClass"`
258 | fi
259 | if [ -e "$javaClass" ]; then
260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
261 | if [ "$MVNW_VERBOSE" = true ]; then
262 | echo " - Compiling MavenWrapperDownloader.java ..."
263 | fi
264 | # Compiling the Java class
265 | ("$JAVA_HOME/bin/javac" "$javaClass")
266 | fi
267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
268 | # Running the downloader
269 | if [ "$MVNW_VERBOSE" = true ]; then
270 | echo " - Running MavenWrapperDownloader.java ..."
271 | fi
272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
273 | fi
274 | fi
275 | fi
276 | fi
277 | ##########################################################################################
278 | # End of extension
279 | ##########################################################################################
280 |
281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
282 | if [ "$MVNW_VERBOSE" = true ]; then
283 | echo $MAVEN_PROJECTBASEDIR
284 | fi
285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
286 |
287 | # For Cygwin, switch paths to Windows format before running java
288 | if $cygwin; then
289 | [ -n "$M2_HOME" ] &&
290 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
291 | [ -n "$JAVA_HOME" ] &&
292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
293 | [ -n "$CLASSPATH" ] &&
294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
295 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
297 | fi
298 |
299 | # Provide a "standardized" way to retrieve the CLI args that will
300 | # work with both Windows and non-Windows executions.
301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
302 | export MAVEN_CMD_LINE_ARGS
303 |
304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
305 |
306 | exec "$JAVACMD" \
307 | $MAVEN_OPTS \
308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
311 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM http://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
124 |
125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
162 | if ERRORLEVEL 1 goto error
163 | goto end
164 |
165 | :error
166 | set ERROR_CODE=1
167 |
168 | :end
169 | @endlocal & set ERROR_CODE=%ERROR_CODE%
170 |
171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
175 | :skipRcPost
176 |
177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
179 |
180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
181 |
182 | exit /B %ERROR_CODE%
183 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 | 4.0.0
6 | org.graphqlcrudjava
7 | graphqlcrud-java
8 | 1.0.0-SNAPSHOT
9 | pom
10 | graphqlcrud-java
11 | https://graphqlcrud.org
12 | Java based implementation engine for GraphQLCrud Specification
13 |
14 |
15 |
16 | Apache License, Version 2.0
17 | https://www.apache.org/licenses/LICENSE-2.0.txt
18 | repo
19 |
20 |
21 |
22 |
23 | scm:git:git@github.com:graphqlcrud/graphqlcrud-java.git
24 | scm:git:git@github.com:graphqlcrud/graphqlcrud-java.git
25 | https://graphqlcrud.org
26 | HEAD
27 |
28 |
29 |
30 | 3.8.1
31 | true
32 | 11
33 | 11
34 | UTF-8
35 | UTF-8
36 | 1.7.0.Final
37 | quarkus-universe-bom
38 | io.quarkus
39 | 1.7.0.Final
40 | 2.22.1
41 | 3.0.0-M3
42 | 15.0
43 | 3.14.0
44 |
45 |
46 |
47 |
48 |
49 | ${quarkus.platform.group-id}
50 | ${quarkus.platform.artifact-id}
51 | ${quarkus.platform.version}
52 | pom
53 | import
54 |
55 |
56 | com.graphql-java
57 | graphql-java
58 | ${version.com.graphql-java}
59 |
60 |
61 | org.graphqlcrudjava
62 | engine
63 | ${project.version}
64 |
65 |
66 | com.graphql-java
67 | graphql-java-extended-scalars
68 | 1.0
69 |
70 |
71 | org.jooq
72 | jooq
73 | ${version.org.jooq}
74 |
75 |
76 | org.jooq
77 | jooq-meta
78 | ${version.org.jooq}
79 |
80 |
81 |
82 |
83 |
84 | engine
85 | app
86 |
87 |
88 |
89 |
90 |
91 | io.quarkus
92 | quarkus-maven-plugin
93 | ${quarkus-plugin.version}
94 |
95 |
96 |
97 | build
98 |
99 |
100 |
101 |
102 |
103 | maven-compiler-plugin
104 | ${compiler-plugin.version}
105 |
106 |
107 | maven-surefire-plugin
108 | ${surefire-plugin.version}
109 |
110 |
111 | org.jboss.logmanager.LogManager
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 | native
120 |
121 |
122 | native
123 |
124 |
125 |
126 |
127 |
128 | maven-failsafe-plugin
129 | ${failsafe-plugin.version}
130 |
131 |
132 |
133 | integration-test
134 | verify
135 |
136 |
137 |
138 | ${project.build.directory}/${project.build.finalName}-runner
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 | native
148 |
149 |
150 |
151 |
152 |
--------------------------------------------------------------------------------
/src/main/docker/Dockerfile.jvm:
--------------------------------------------------------------------------------
1 | ####
2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
3 | #
4 | # Before building the docker image run:
5 | #
6 | # mvn package
7 | #
8 | # Then, build the image with:
9 | #
10 | # docker build -f src/main/docker/Dockerfile.jvm -t quarkus/graphqlcrud-java-jvm .
11 | #
12 | # Then run the container using:
13 | #
14 | # docker run -i --rm -p 8080:8080 quarkus/graphqlcrud-java-jvm
15 | #
16 | # If you want to include the debug port into your docker image
17 | # you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5050
18 | #
19 | # Then run the container using :
20 | #
21 | # docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/graphqlcrud-java-jvm
22 | #
23 | ###
24 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.1
25 |
26 | ARG JAVA_PACKAGE=java-11-openjdk-headless
27 | ARG RUN_JAVA_VERSION=1.3.8
28 |
29 | ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en'
30 |
31 | # Install java and the run-java script
32 | # Also set up permissions for user `1001`
33 | RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \
34 | && microdnf update \
35 | && microdnf clean all \
36 | && mkdir /deployments \
37 | && chown 1001 /deployments \
38 | && chmod "g+rwX" /deployments \
39 | && chown 1001:root /deployments \
40 | && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \
41 | && chown 1001 /deployments/run-java.sh \
42 | && chmod 540 /deployments/run-java.sh \
43 | && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/lib/security/java.security
44 |
45 | # Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size.
46 | ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
47 |
48 | COPY target/lib/* /deployments/lib/
49 | COPY target/*-runner.jar /deployments/app.jar
50 |
51 | EXPOSE 8080
52 | USER 1001
53 |
54 | ENTRYPOINT [ "/deployments/run-java.sh" ]
--------------------------------------------------------------------------------
/src/main/docker/Dockerfile.native:
--------------------------------------------------------------------------------
1 | ####
2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode
3 | #
4 | # Before building the docker image run:
5 | #
6 | # mvn package -Pnative -Dquarkus.native.container-build=true
7 | #
8 | # Then, build the image with:
9 | #
10 | # docker build -f src/main/docker/Dockerfile.native -t quarkus/graphqlcrud-java .
11 | #
12 | # Then run the container using:
13 | #
14 | # docker run -i --rm -p 8080:8080 quarkus/graphqlcrud-java
15 | #
16 | ###
17 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.1
18 | WORKDIR /work/
19 | COPY --chown=1001:root target/*-runner /work/application
20 |
21 | EXPOSE 8080
22 | USER 1001
23 |
24 | CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]
--------------------------------------------------------------------------------