diff --git a/by-language/java-jooq/.gitignore b/by-language/java-jooq/.gitignore new file mode 100644 index 00000000..27427779 --- /dev/null +++ b/by-language/java-jooq/.gitignore @@ -0,0 +1,8 @@ +.gradle/ +.idea +*.iws +*.iml +*.ipr +build/ +out/ +target/ diff --git a/by-language/java-jooq/.java-version b/by-language/java-jooq/.java-version new file mode 100644 index 00000000..98d9bcb7 --- /dev/null +++ b/by-language/java-jooq/.java-version @@ -0,0 +1 @@ +17 diff --git a/by-language/java-jooq/README.rst b/by-language/java-jooq/README.rst new file mode 100644 index 00000000..628cd431 --- /dev/null +++ b/by-language/java-jooq/README.rst @@ -0,0 +1,87 @@ +.. highlight:: sh + +############################################################ +Java jOOQ demo application for CrateDB using PostgreSQL JDBC +############################################################ + +***** +About +***** + +A demo application using `CrateDB`_ with `jOOQ`_ and the `PostgreSQL +JDBC driver`_. + +It is intended as a basic example to demonstrate what currently works, and as a +testing rig for eventually growing a full-fledged CrateDB dialect, or at least +making the code generator work. Contributions are welcome. + + +Introduction +============ + +The idea of jOOQ is to generate typesafe code based on the SQL schema. +Then, accessing a database table using the jOOQ DSL API looks like this: + +.. code-block:: java + + // Fetch records, with filtering and sorting. + Result result = db.select() + .from(AUTHOR) + .where(AUTHOR.NAME.like("Ja%")) + .orderBy(AUTHOR.NAME) + .fetch(); + +In some kind, jOOQ is similar to `LINQ`_, `but better `_. + + +Details +======= + +The code example will demonstrate a few of the `different use cases for jOOQ`_. +That is, `Dynamic SQL`_, the `jOOQ DSL API`_, and how to use `jOOQ as a SQL +builder without code generation`_. + + +Caveats +======= + +- Most of the jOOQ examples use uppercase letters for the database, table, and + field names. CrateDB currently only handles lowercase letters. + + +***** +Usage +***** + +1. Make sure `Java 17`_ is installed. +2. Run CrateDB:: + + docker run -it --rm --publish=4200:4200 --publish=5432:5432 \ + crate:latest -Cdiscovery.type=single-node + +3. Invoke demo application:: + + ./gradlew run + +3. Invoke software tests:: + + ./gradlew test + +4. Generate the jOOQ sources from the main jOOQ configuration, see ``jooq.gradle``:: + + ./gradlew generateJooq + + +.. _CrateDB: https://github.com/crate/crate +.. _Different use cases for jOOQ: https://www.jooq.org/doc/latest/manual/getting-started/use-cases/ +.. _Dynamic SQL: https://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql/ +.. _Gradle: https://gradle.org/ +.. _Insight into Language Integrated Querying: https://blog.jooq.org/jooq-tuesdays-ming-yee-iu-gives-insight-into-language-integrated-querying/ +.. _Java 17: https://adoptium.net/temurin/releases/?version=17 +.. _jOOQ: https://github.com/jOOQ/jOOQ +.. _jOOQ as a SQL builder without code generation: https://www.jooq.org/doc/latest/manual/getting-started/use-cases/jooq-as-a-sql-builder-without-codegeneration/ +.. _jOOQ's code generator: https://www.jooq.org/doc/latest/manual/code-generation/ +.. _jOOQ DSL API: https://www.jooq.org/doc/latest/manual/sql-building/dsl-api/ +.. _LINQ: https://en.wikipedia.org/wiki/Language_Integrated_Query +.. _PostgreSQL JDBC Driver: https://github.com/pgjdbc/pgjdbc diff --git a/by-language/java-jooq/build.gradle b/by-language/java-jooq/build.gradle new file mode 100644 index 00000000..871a3b55 --- /dev/null +++ b/by-language/java-jooq/build.gradle @@ -0,0 +1,64 @@ +/** + * A demo application using CrateDB with jOOQ and the PostgreSQL JDBC driver. + */ + +buildscript { + repositories { + mavenCentral() + } +} + +plugins { + id 'application' + id 'com.adarshr.test-logger' version '3.2.0' + id 'idea' + id 'java' +} + +repositories { + mavenCentral() + mavenLocal() +} + +dependencies { + implementation 'org.jooq:jooq:3.17.7' + implementation 'org.postgresql:postgresql:42.5.1' + implementation 'org.slf4j:slf4j-api:2.0.6' + implementation 'org.slf4j:slf4j-simple:2.0.6' + testImplementation 'junit:junit:4.13.2' +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +jar { + archiveBaseName = 'cratedb-demo-java-jooq' + archiveVersion = '0.0.1-SNAPSHOT' +} + +application { + mainClass = 'io.crate.demo.jooq.Application' +} + +sourceSets { + main { + java.srcDirs += [ + "src/generated/java", + "src/main/java", + ] + } +} + +test { + dependsOn 'cleanTest' +} + +// Activate jOOQ code generation add-on. +apply from: 'jooq.gradle' + +idea.module.inheritOutputDirs = true +processResources.destinationDir = compileJava.destinationDir +compileJava.dependsOn processResources diff --git a/by-language/java-jooq/gradle/wrapper/gradle-wrapper.jar b/by-language/java-jooq/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/by-language/java-jooq/gradle/wrapper/gradle-wrapper.jar differ diff --git a/by-language/java-jooq/gradle/wrapper/gradle-wrapper.properties b/by-language/java-jooq/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..070cb702 --- /dev/null +++ b/by-language/java-jooq/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/by-language/java-jooq/gradlew b/by-language/java-jooq/gradlew new file mode 100755 index 00000000..a69d9cb6 --- /dev/null +++ b/by-language/java-jooq/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/by-language/java-jooq/gradlew.bat b/by-language/java-jooq/gradlew.bat new file mode 100644 index 00000000..9109989e --- /dev/null +++ b/by-language/java-jooq/gradlew.bat @@ -0,0 +1,103 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/by-language/java-jooq/jooq.gradle b/by-language/java-jooq/jooq.gradle new file mode 100644 index 00000000..6a0caf1b --- /dev/null +++ b/by-language/java-jooq/jooq.gradle @@ -0,0 +1,89 @@ +/** + * About + * ===== + * + * Configure `gradle-jooq-plugin`, a Gradle plugin that integrates the jOOQ + * code generation tool. This layout manages the jOOQ configuration within + * a separate script file. + * + * Synopsis + * ======== + * + * ./gradlew generateJooq + * + * Resources + * ========= + * + * - https://github.com/etiennestuder/gradle-jooq-plugin#gradle-groovy-dsl-4 + * - https://github.com/etiennestuder/gradle-jooq-plugin/tree/main/example/extract_script_file + * - https://github.com/etiennestuder/gradle-jooq-plugin#examples + */ + +buildscript { + repositories { + gradlePluginPortal() + } + dependencies { + classpath 'nu.studer:gradle-jooq-plugin:8.1' + } +} + +repositories { + mavenCentral() +} + +apply plugin: nu.studer.gradle.jooq.JooqPlugin + +dependencies { + jooqGenerator 'org.postgresql:postgresql:42.5.1' +} + +jooq { + + // Defaults (can be omitted). + // version = '3.17.6' + // edition = nu.studer.gradle.jooq.JooqEdition.OSS + + configurations { + // Name of the jOOQ configuration. + main { + + // Do not *automatically* generate code. + generateSchemaSourceOnCompilation = false + + generationTool { + logging = org.jooq.meta.jaxb.Logging.WARN + jdbc { + driver = 'org.postgresql.Driver' + url = 'jdbc:postgresql://localhost:5432/testdrive' + user = 'crate' + password = '' + properties { + property { + key = 'PAGE_SIZE' + value = 2048 + } + } + } + generator { + name = 'org.jooq.codegen.DefaultGenerator' + database { + name = 'org.jooq.meta.postgres.PostgresDatabase' + inputSchema = 'testdrive' + } + generate { + deprecated = false + records = false + immutablePojos = false + fluentSetters = false + } + target { + packageName = 'io.crate.demo.jooq.model' + directory = 'src/generated/java' + } + strategy.name = "org.jooq.codegen.DefaultGeneratorStrategy" + } + } + } + } +} diff --git a/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/DefaultCatalog.java b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/DefaultCatalog.java new file mode 100644 index 00000000..d1cef101 --- /dev/null +++ b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/DefaultCatalog.java @@ -0,0 +1,63 @@ +/* + * This file is generated by jOOQ. + */ +package io.crate.demo.jooq.model; + + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.processing.Generated; + +import org.jooq.Constants; +import org.jooq.Schema; +import org.jooq.impl.CatalogImpl; + + +/** + * This class is generated by jOOQ. + */ +@Generated( + value = { + "https://www.jooq.org", + "jOOQ version:3.17.7" + }, + comments = "This class is generated by jOOQ." +) +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class DefaultCatalog extends CatalogImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of DEFAULT_CATALOG + */ + public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog(); + + /** + * The schema testdrive. + */ + public final DemoDatabase DEMO_DATABASE = DemoDatabase.DEMO_DATABASE; + + /** + * No further instances allowed + */ + private DefaultCatalog() { + super(""); + } + + @Override + public final List getSchemas() { + return Arrays.asList( + DemoDatabase.DEMO_DATABASE + ); + } + + /** + * A reference to the 3.17 minor release of the code generator. If this + * doesn't compile, it's because the runtime library uses an older minor + * release, namely: 3.17. You can turn off the generation of this reference + * by specifying /configuration/generator/generate/jooqVersionReference + */ + private static final String REQUIRE_RUNTIME_JOOQ_VERSION = Constants.VERSION_3_17; +} diff --git a/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/DemoDatabase.java b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/DemoDatabase.java new file mode 100644 index 00000000..6b5e93da --- /dev/null +++ b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/DemoDatabase.java @@ -0,0 +1,63 @@ +/* + * This file is generated by jOOQ. + */ +package io.crate.demo.jooq.model; + + +import io.crate.demo.jooq.model.tables.Author; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.processing.Generated; + +import org.jooq.Catalog; +import org.jooq.Table; +import org.jooq.impl.SchemaImpl; + + +/** + * This class is generated by jOOQ. + */ +@Generated( + value = { + "https://www.jooq.org", + "jOOQ version:3.17.7" + }, + comments = "This class is generated by jOOQ." +) +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class DemoDatabase extends SchemaImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of testdrive + */ + public static final DemoDatabase DEMO_DATABASE = new DemoDatabase(); + + /** + * The table testdrive.author. + */ + public final Author AUTHOR = Author.AUTHOR; + + /** + * No further instances allowed + */ + private DemoDatabase() { + super("testdrive", null); + } + + + @Override + public Catalog getCatalog() { + return DefaultCatalog.DEFAULT_CATALOG; + } + + @Override + public final List> getTables() { + return Arrays.asList( + Author.AUTHOR + ); + } +} diff --git a/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/Keys.java b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/Keys.java new file mode 100644 index 00000000..79ffd13f --- /dev/null +++ b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/Keys.java @@ -0,0 +1,36 @@ +/* + * This file is generated by jOOQ. + */ +package io.crate.demo.jooq.model; + + +import io.crate.demo.jooq.model.tables.Author; +import io.crate.demo.jooq.model.tables.records.AuthorRecord; + +import javax.annotation.processing.Generated; + +import org.jooq.TableField; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; + + +/** + * A class modelling foreign key relationships and constraints of tables of + * the testdb schema. + */ +@Generated( + value = { + "https://www.jooq.org", + "jOOQ version:3.17.7" + }, + comments = "This class is generated by jOOQ" +) +@SuppressWarnings({ "all", "unchecked", "rawtypes" })public class Keys { + + // ------------------------------------------------------------------------- + // UNIQUE and PRIMARY KEY definitions + // ------------------------------------------------------------------------- + + public static final UniqueKey PK_AUTHOR = Internal.createUniqueKey(Author.AUTHOR, DSL.name("PK_AUTHOR"), new TableField[] { Author.AUTHOR.ID }, true); +} diff --git a/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/Tables.java b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/Tables.java new file mode 100644 index 00000000..b7657f06 --- /dev/null +++ b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/Tables.java @@ -0,0 +1,28 @@ +/* + * This file is generated by jOOQ. + */ +package io.crate.demo.jooq.model; + + +import io.crate.demo.jooq.model.tables.Author; + +import javax.annotation.processing.Generated; + +/** + * Convenience access to all tables in testdb + */ +@Generated( + value = { + "https://www.jooq.org", + "jOOQ version:3.17.7" + }, + comments = "This class is generated by jOOQ" +) +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class Tables { + + /** + * The table testdrive.author. + */ + public static final Author AUTHOR = Author.AUTHOR; +} diff --git a/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/tables/Author.java b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/tables/Author.java new file mode 100644 index 00000000..edcec673 --- /dev/null +++ b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/tables/Author.java @@ -0,0 +1,175 @@ +/* + * This file is generated by jOOQ. + */ +package io.crate.demo.jooq.model.tables; + + +import io.crate.demo.jooq.model.DemoDatabase; +import io.crate.demo.jooq.model.Keys; +import io.crate.demo.jooq.model.tables.records.AuthorRecord; + +import java.util.function.Function; + +import org.jooq.Field; +import org.jooq.ForeignKey; +import org.jooq.Function2; +import org.jooq.Identity; +import org.jooq.Name; +import org.jooq.Record; +import org.jooq.Records; +import org.jooq.Row2; +import org.jooq.Schema; +import org.jooq.SelectField; +import org.jooq.Table; +import org.jooq.TableField; +import org.jooq.TableOptions; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; +import org.jooq.impl.TableImpl; + +import javax.annotation.processing.Generated; + +/** + * This class is generated by jOOQ. + */ +@Generated( + value = { + "https://www.jooq.org", + "jOOQ version:3.17.7" + }, + comments = "This class is generated by jOOQ." +) +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class Author extends TableImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of testdrive.author + */ + public static final Author AUTHOR = new Author(); + + /** + * The class holding records for this type + */ + @Override + public Class getRecordType() { + return AuthorRecord.class; + } + + public final TableField ID = createField(DSL.name("id"), SQLDataType.INTEGER.nullable(false).identity(true), this, "The author's identifier"); + + public final TableField NAME = createField(DSL.name("name"), SQLDataType.VARCHAR.nullable(true), this, "The author's name"); + + private Author(Name alias, Table aliased) { + this(alias, aliased, null); + } + + private Author(Name alias, Table aliased, Field[] parameters) { + super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); + } + + /** + * Create an aliased testdrive.author table reference + */ + public Author(String alias) { + this(DSL.name(alias), AUTHOR); + } + + /** + * Create an aliased testdrive.author table reference + */ + public Author(Name alias) { + this(alias, AUTHOR); + } + + /** + * Create an aliased testdrive.author table reference + */ + public Author() { + this(DSL.name("author"), null); + } + + public Author(Table child, ForeignKey key) { + super(child, key, AUTHOR); + } + + @Override + public Schema getSchema() { + return aliased() ? null : DemoDatabase.DEMO_DATABASE; + } + + @Override + public Identity getIdentity() { + return (Identity) super.getIdentity(); + } + + @Override + public UniqueKey getPrimaryKey() { + return Keys.PK_AUTHOR; + } + + @Override + public Author as(String alias) { + return new Author(DSL.name(alias), this); + } + + @Override + public Author as(Name alias) { + return new Author(alias, this); + } + + @Override + public Author as(Table alias) { + return new Author(alias.getQualifiedName(), this); + } + + /** + * Rename this table + */ + @Override + public Author rename(String name) { + return new Author(DSL.name(name), null); + } + + /** + * Rename this table + */ + @Override + public Author rename(Name name) { + return new Author(name, null); + } + + /** + * Rename this table + */ + @Override + public Author rename(Table name) { + return new Author(name.getQualifiedName(), null); + } + + // ------------------------------------------------------------------------- + // Row2 type methods + // ------------------------------------------------------------------------- + + @Override + public Row2 fieldsRow() { + return (Row2) super.fieldsRow(); + } + + /** + * Convenience mapping calling {@link SelectField#convertFrom(Function)}. + */ + public SelectField mapping(Function2 from) { + return convertFrom(Records.mapping(from)); + } + + /** + * Convenience mapping calling {@link SelectField#convertFrom(Class, + * Function)}. + */ + public SelectField mapping(Class toType, Function2 from) { + return convertFrom(toType, Records.mapping(from)); + } +} diff --git a/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/tables/records/AuthorRecord.java b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/tables/records/AuthorRecord.java new file mode 100644 index 00000000..fd2be9c7 --- /dev/null +++ b/by-language/java-jooq/src/generated/java/io/crate/demo/jooq/model/tables/records/AuthorRecord.java @@ -0,0 +1,138 @@ +package io.crate.demo.jooq.model.tables.records; + + +import io.crate.demo.jooq.model.tables.Author; + +import javax.annotation.processing.Generated; + +import org.jooq.Field; +import org.jooq.Record1; +import org.jooq.Record2; +import org.jooq.Row2; +import org.jooq.impl.UpdatableRecordImpl; + + +/** + * This class is generated by jOOQ. + */ +@Generated( + value = { + "https://www.jooq.org", + "jOOQ version:3.17.7" + }, + comments = "This class is generated by jOOQ." +) +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class AuthorRecord extends UpdatableRecordImpl implements Record2 { + + private static final long serialVersionUID = 1L; + + public void setId(Integer value) { + set(0, value); + } + + public Integer getId() { + return (Integer) get(0); + } + + public void setName(String value) { + set(1, value); + } + + public String getName() { + return (String) get(1); + } + + // ------------------------------------------------------------------------- + // Primary key information + // ------------------------------------------------------------------------- + + @Override + public Record1 key() { + return (Record1) super.key(); + } + + // ------------------------------------------------------------------------- + // Record2 type implementation + // ------------------------------------------------------------------------- + + @Override + public Row2 fieldsRow() { + return (Row2) super.fieldsRow(); + } + + @Override + public Row2 valuesRow() { + return (Row2) super.valuesRow(); + } + + @Override + public Field field1() { + return Author.AUTHOR.ID; + } + + @Override + public Field field2() { + return Author.AUTHOR.NAME; + } + + @Override + public Integer component1() { + return getId(); + } + + @Override + public String component2() { + return getName(); + } + + @Override + public Integer value1() { + return getId(); + } + + @Override + public String value2() { + return getName(); + } + + @Override + public AuthorRecord value1(Integer value) { + setId(value); + return this; + } + + @Override + public AuthorRecord value2(String value) { + setName(value); + return this; + } + + @Override + public AuthorRecord values(Integer value1, String value2) { + value1(value1); + value2(value2); + return this; + } + + // ------------------------------------------------------------------------- + // Constructors + // ------------------------------------------------------------------------- + + /** + * Create a detached AuthorRecord + */ + public AuthorRecord() { + super(Author.AUTHOR); + } + + /** + * Create a detached, initialised AuthorRecord + */ + public AuthorRecord(Integer id, String name) { + super(Author.AUTHOR); + + setId(id); + setName(name); + } +} diff --git a/by-language/java-jooq/src/main/java/io/crate/demo/jooq/Application.java b/by-language/java-jooq/src/main/java/io/crate/demo/jooq/Application.java new file mode 100644 index 00000000..0c3338fc --- /dev/null +++ b/by-language/java-jooq/src/main/java/io/crate/demo/jooq/Application.java @@ -0,0 +1,193 @@ +package io.crate.demo.jooq; + +import org.jooq.*; +import org.jooq.Record; +import org.jooq.conf.Settings; +import org.jooq.impl.DSL; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +import io.crate.demo.jooq.model.tables.records.AuthorRecord; + +import static io.crate.demo.jooq.model.Tables.*; +import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.table; + + +/** + * A demo application using CrateDB with jOOQ and the PostgreSQL JDBC driver. + * + * - https://github.com/crate/crate + * - https://github.com/jOOQ/jOOQ + * - https://github.com/pgjdbc/pgjdbc + */ +public class Application { + + public static void main(String[] args) throws IOException, SQLException { + Application app = new Application(); + + Tools.title("Example with generated code"); + app.exampleWithGeneratedCode(); + + Tools.title("Example with dynamic schema"); + app.exampleWithDynamicSchema(); + + System.out.println("Ready."); + } + + /** + * Create a new jOOQ DefaultDSLContext instance, wrapping the database connection. + * + * It will use database connection settings from the `application.properties` file, + * and will also enable SQL command logging for demonstration purposes. + */ + public DSLContext getDSLContext() throws SQLException { + + // Disable the jOOQ self-ad/banner and its tip of the day. + System.setProperty("org.jooq.no-logo", "true"); + System.setProperty("org.jooq.no-tips", "true"); + + // Read settings from `application.properties` file. + Properties app_settings = Tools.readSettingsFile("application.properties"); + + // Read database settings. + String DS_URL = app_settings.getProperty("application.datasource.url"); + String DS_USERNAME = app_settings.getProperty("application.datasource.username"); + String DS_PASSWORD = app_settings.getProperty("application.datasource.password"); + + // Connect to the database, with given settings and parameters, and select the PostgreSQL dialect. + Settings db_settings = new Settings(); + db_settings.setExecuteLogging(true); + Connection connection = DriverManager.getConnection(DS_URL, DS_USERNAME, DS_PASSWORD); + return DSL.using(connection, SQLDialect.POSTGRES, db_settings); + } + + /** + * jOOQ as a SQL builder with code generation [1] + * + * > Use jOOQ's code generation features in order to compile your SQL + * > statements using a Java compiler against an actual database schema. + * > + * > This adds a lot of power and expressiveness to just simply + * > constructing SQL using the query DSL and custom strings and + * > literals, as you can be sure that all database artefacts actually + * > exist in the database, and that their type is correct. + * > We strongly recommend using this approach. + * + * [1] https://www.jooq.org/doc/latest/manual/getting-started/use-cases/jooq-as-a-sql-builder-with-code-generation/ + * + * TODO: Code generation is currently not possible with CrateDB, because, + * with the PostgreSQL dialect, jOOQ issues a CTE using the + * `WITH RECURSIVE` directive to reflect the database schema. + * For this example, the "generated" code has been written manually. + * + */ + public void exampleWithGeneratedCode() throws IOException, SQLException { + + DSLContext db = getDSLContext(); + + // Create table. + String bootstrap_sql = Tools.readTextFile("bootstrap.sql"); + db.query(bootstrap_sql).execute(); + + // Truncate table. + db.delete(AUTHOR).where(DSL.trueCondition()).execute(); + db.query(String.format("REFRESH TABLE %s", AUTHOR)).execute(); + + // Insert records. + InsertSetMoreStep new_record1 = db.insertInto(AUTHOR).set(AUTHOR.ID, 1).set(AUTHOR.NAME, "John Doe"); + InsertSetMoreStep new_record2 = db.insertInto(AUTHOR).set(AUTHOR.ID, 2).set(AUTHOR.NAME, "Jane Doe"); + InsertSetMoreStep new_record3 = db.insertInto(AUTHOR).set(AUTHOR.ID, 3).set(AUTHOR.NAME, "Jack Black"); + new_record1.execute(); + new_record2.execute(); + new_record3.execute(); + db.query(String.format("REFRESH TABLE %s", AUTHOR)).execute(); + + // Fetch records, with filtering and sorting. + Result result = db.select() + .from(AUTHOR) + .where(AUTHOR.NAME.like("Ja%")) + .orderBy(AUTHOR.NAME) + .fetch(); + + // Display result. + // System.out.println("Result:"); + // System.out.println(result); + + // Iterate and display records. + System.out.println("By record:"); + for (Record record : result) { + Integer id = record.getValue(AUTHOR.ID); + String name = record.getValue(AUTHOR.NAME); + System.out.println("id: " + id + ", name: " + name); + } + System.out.println(); + + } + + /** + * jOOQ as a standalone SQL builder without code generation [1] + * + * If you have a dynamic schema, you don't have to use the code generator. + * This is the simplest of all use cases, allowing for construction of + * valid SQL for any database. In this use case, you will not use jOOQ's + * code generator and maybe not even jOOQ's query execution facilities. + * + * Instead, you'll use jOOQ's query DSL API to wrap strings, literals and + * other user-defined objects into an object-oriented, type-safe AST + * modelling your SQL statements. + * + * [1] https://www.jooq.org/doc/latest/manual/getting-started/use-cases/jooq-as-a-sql-builder-without-codegeneration/ + * + */ + public void exampleWithDynamicSchema() throws IOException, SQLException { + + DSLContext db = getDSLContext(); + + Table BOOK = table("\"testdrive\".\"book\""); + Field BOOK_ID = field("id"); + Field BOOK_TITLE = field("title"); + + // Create table. + String bootstrap_sql = Tools.readTextFile("bootstrap.sql"); + db.query(bootstrap_sql).execute(); + + // Truncate table. + db.delete(BOOK).where(DSL.trueCondition()).execute(); + db.query(String.format("REFRESH TABLE %s", BOOK)).execute(); + + // Insert records. + InsertSetMoreStep new_record1 = db.insertInto(BOOK).set(BOOK_ID, 1).set(BOOK_TITLE, "Foo"); + InsertSetMoreStep new_record2 = db.insertInto(BOOK).set(BOOK_ID, 2).set(BOOK_TITLE, "Bar"); + new_record1.execute(); + new_record2.execute(); + db.query(String.format("REFRESH TABLE %s", BOOK)).execute(); + + // Fetch records, with filtering and sorting. + Result result = db.select() + .from(BOOK) + .where(BOOK_TITLE.like("B%")) + .orderBy(BOOK_TITLE) + .fetch(); + + // Display result. + // System.out.println("Result:"); + // System.out.println(result); + + // Iterate and display records. + System.out.println("By record:"); + for (Record record : result) { + // TODO: How can we know about the index positions of the corresponding columns? + Integer id = (Integer) record.getValue(0); + String title = (String) record.getValue(1); + System.out.println("id: " + id + ", title: " + title); + } + System.out.println(); + + } + +} diff --git a/by-language/java-jooq/src/main/java/io/crate/demo/jooq/Tools.java b/by-language/java-jooq/src/main/java/io/crate/demo/jooq/Tools.java new file mode 100644 index 00000000..fdde67db --- /dev/null +++ b/by-language/java-jooq/src/main/java/io/crate/demo/jooq/Tools.java @@ -0,0 +1,61 @@ +package io.crate.demo.jooq; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + +public class Tools { + + /** + * Open file from resource folder as stream. + * + * https://mkyong.com/java/java-read-a-file-from-resources-folder/ + */ + public static InputStream openResourceStream(String fileName) { + // + // + ClassLoader classLoader = Application.class.getClassLoader(); + return classLoader.getResourceAsStream(fileName); + } + + /** + * Read text file from application resources. + */ + public static String readTextFile(String fileName) throws IOException { + InputStream inputStream = Tools.openResourceStream(fileName); + String text = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); + return text; + } + + /** + * Read settings from properties file. + */ + public static Properties readSettingsFile(String fileName) { + InputStream is = Tools.openResourceStream(fileName); + Properties properties = new Properties(); + try { + properties.load(is); + } catch (IOException e) { + e.printStackTrace(); + } + return properties; + } + + /** + * Some pretty printing. + */ + public static void title(String title) { + String dashes = "=".repeat(title.length()); + System.out.println(); + System.out.println(dashes); + System.out.println(title); + System.out.println(dashes); + System.out.println(); + } + + public static void print(Object o) { + System.out.println(o); + } + +} diff --git a/by-language/java-jooq/src/main/resources/application.properties b/by-language/java-jooq/src/main/resources/application.properties new file mode 100644 index 00000000..63a01274 --- /dev/null +++ b/by-language/java-jooq/src/main/resources/application.properties @@ -0,0 +1,3 @@ +application.datasource.url=jdbc:postgresql://localhost:5432/ +application.datasource.username=crate +application.datasource.password= diff --git a/by-language/java-jooq/src/main/resources/bootstrap.sql b/by-language/java-jooq/src/main/resources/bootstrap.sql new file mode 100644 index 00000000..5ca396f6 --- /dev/null +++ b/by-language/java-jooq/src/main/resources/bootstrap.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS "testdrive"."author" ( + id INTEGER PRIMARY KEY, + name VARCHAR(255) +); + +CREATE TABLE IF NOT EXISTS "testdrive"."book" ( + id INTEGER PRIMARY KEY, + title VARCHAR(255) +); diff --git a/by-language/java-jooq/src/main/resources/simplelogger.properties b/by-language/java-jooq/src/main/resources/simplelogger.properties new file mode 100644 index 00000000..0605dd76 --- /dev/null +++ b/by-language/java-jooq/src/main/resources/simplelogger.properties @@ -0,0 +1,2 @@ +# https://www.slf4j.org/api/org/slf4j/simple/SimpleLogger.html +org.slf4j.simpleLogger.defaultLogLevel=debug diff --git a/by-language/java-jooq/src/test/java/io/crate/demo/jooq/ApplicationTest.java b/by-language/java-jooq/src/test/java/io/crate/demo/jooq/ApplicationTest.java new file mode 100644 index 00000000..07fa02dc --- /dev/null +++ b/by-language/java-jooq/src/test/java/io/crate/demo/jooq/ApplicationTest.java @@ -0,0 +1,47 @@ +package io.crate.demo.jooq; + +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.sql.SQLException; + +import static io.crate.demo.jooq.model.Tables.AUTHOR; + +public class ApplicationTest { + + /** + * Run demo application example with generated code, and verify it works. + */ + @Test + public void testExampleWithGeneratedCode() throws SQLException, IOException { + + // Invoke example. + Application app = new Application(); + app.exampleWithGeneratedCode(); + + // Check number of records. + DSLContext db = app.getDSLContext(); + int count = db.fetchCount(DSL.selectFrom(AUTHOR)); + Assert.assertEquals(count, 3); + } + + /** + * Run demo application example with generated code, and verify it works. + */ + @Test + public void testExampleWithDynamicSchema() throws SQLException, IOException { + + // Invoke example. + Application app = new Application(); + app.exampleWithDynamicSchema(); + + // Check number of records. + DSLContext db = app.getDSLContext(); + int count = db.fetchCount(DSL.selectFrom("testdrive.book")); + Assert.assertEquals(count, 2); + } + +}