├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── multi-tenancy-library ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── multitenancylibrary │ │ │ ├── MultiTenancyAutoConfigure.java │ │ │ ├── config │ │ │ ├── MultiTenancyProperties.java │ │ │ └── WebMvcConfig.java │ │ │ ├── network │ │ │ └── MultiTenancyStorage.java │ │ │ └── sql │ │ │ ├── TablesFinder.java │ │ │ ├── TenantIDCheckerExecuteListener.java │ │ │ ├── TenantIDException.java │ │ │ └── TenantIDModifierVisitListener.java │ └── resources │ │ ├── META-INF │ │ ├── additional-spring-configuration-metadata.json │ │ └── spring.factories │ │ ├── application-test.properties │ │ └── application.properties │ └── test │ ├── java │ └── com │ │ └── example │ │ └── multitenancylibrary │ │ ├── TestApplication.java │ │ └── sql │ │ ├── TenantIDCheckerExecuteListenerTest.java │ │ ├── TenantSQLDeleteTest.java │ │ ├── TenantSQLQuerySingleTableTest.java │ │ ├── TenantSQLQueryThreeTableTest.java │ │ ├── TenantSQLQueryTwoTableTest.java │ │ ├── TenantSQLQueryViewTest.java │ │ ├── TenantSQLSelfJoinTest.java │ │ └── TenantSQLUpdateTest.java │ └── resources │ ├── data-h2.sql │ └── schema-h2.sql ├── rls ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── rest-api.http ├── sql │ ├── ddl.sql │ └── policies.sql └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springbootpostgresjooq │ │ │ ├── SpringbootPostgresJooqApplication.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── model │ │ │ └── UserInput.java │ │ │ └── tenant │ │ │ ├── Configuration.java │ │ │ ├── RlsConnectionProvider.java │ │ │ ├── TenantNameInterceptor.java │ │ │ ├── ThreadLocalStorage.java │ │ │ └── WebMvcConfig.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── springbootpostgresjooq │ └── SpringbootPostgresJooqApplicationTests.java ├── settings.gradle ├── springboot-mysql-jooq ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── rest-api.http ├── sql │ └── ddl.sql └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── springbootmysqljooq │ │ │ ├── SpringbootMysqlJooqApplication.java │ │ │ ├── config │ │ │ └── WebMvcConfig.java │ │ │ ├── controller │ │ │ ├── OrderController.java │ │ │ └── UserController.java │ │ │ ├── job │ │ │ └── ScheduledJob.java │ │ │ └── model │ │ │ └── UserInput.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── com │ └── example │ └── springbootmysqljooq │ └── SpringbootMysqlJooqApplicationTests.java └── springboot-postgres-jooq ├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── rest-api.http ├── sql └── ddl.sql └── src ├── main ├── java │ └── com │ │ └── example │ │ └── springbootpostgresjooq │ │ ├── SpringbootPostgresJooqApplication.java │ │ ├── config │ │ └── WebMvcConfig.java │ │ ├── controller │ │ ├── OrderController.java │ │ └── UserController.java │ │ ├── job │ │ └── ScheduledJob.java │ │ └── model │ │ └── UserInput.java └── resources │ └── application.yml └── test └── java └── com └── example └── springbootpostgresjooq └── SpringbootPostgresJooqApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | bin/ 16 | !**/src/main/**/bin/ 17 | !**/src/test/**/bin/ 18 | 19 | ### IntelliJ IDEA ### 20 | .idea 21 | *.iws 22 | *.iml 23 | *.ipr 24 | out/ 25 | !**/src/main/**/out/ 26 | !**/src/test/**/out/ 27 | 28 | ### NetBeans ### 29 | /nbproject/private/ 30 | /nbbuild/ 31 | /dist/ 32 | /nbdist/ 33 | /.nb-gradle/ 34 | 35 | ### VS Code ### 36 | .vscode/ 37 | /multi-tenancy-library/testdb.trace.db 38 | /multi-tenancy-library/testdb.mv.db 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ## Technology 4 | 5 | - Spring boot 6 | - Postgresql 7 | - MySQL 8 | - Jooq 9 | 10 | ## PostgreSQL: Application Implementation 11 | 12 | - Same database, same schema, same table, filter by `tenant_id` column 13 | - Auto extend SQL, add `where tenant_id in` or `and tenant_id in` conditions 14 | - Check tenant_id related conditions when we `select`,`update`, `delete` tenant tables 15 | - See [multi-tenancy-library](./multi-tenancy-library) and [springboot-postgres-jooq](./springboot-postgres-jooq) 16 | 17 | ### Install Postgresql with Docker 18 | 19 | ``` 20 | docker run --name postgres -e POSTGRES_PASSWORD=123456 -e TZ=PRC -p 5432:5432 postgres:latest 21 | ``` 22 | 23 | ### Create Table and Insert Data into Table 24 | 25 | - Execute SQL in [ddl.sql](./springboot-postgres-jooq/sql/ddl.sql) 26 | 27 | ### Start Application 28 | 29 | - Run [multi-tenancy-library](./multi-tenancy-library) publish task to make sure `multi-tenancy-library.jar` installed 30 | to maven local repository 31 | - Start [springboot-postgres-jooq](./springboot-postgres-jooq) application 32 | 33 | ### Check Results 34 | 35 | - Execute http request in [rest-api.http](./springboot-postgres-jooq/rest-api.http) to check results 36 | 37 | ### Configuration 38 | 39 | ```yaml 40 | multi: 41 | tenancy: 42 | # enable multi tenancy 43 | enabled: true 44 | # tenant table tenant related column name 45 | tenant-identifier: tenant_id 46 | # tenant tables 47 | tables: 48 | - public.t_user 49 | - public.t_order 50 | # check tenant condition exist in SQL or not 51 | sql-check-filters-exist: true 52 | # auto add tenant condition to SQL 53 | sql-auto-add-filters: true 54 | ``` 55 | 56 | ### Scheduler 57 | 58 | - If there are SQL releated schedulers in application, we can not get tenantID 59 | through `request.getHeader("X-TenantID")` in `WebMvcConfig` 60 | - We need to add `MultiTenancyStorage.setTenantID(tenantID)` before scheduler logic 61 | and add `MultiTenancyStorage.setTenantID(null)` after scheduler logic 62 | - Please check `springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/job/ScheduledJob.java` 63 | for detailed information 64 | 65 | ## PostgreSQL: Row Level Security Implementation 66 | 67 | - Same database, same schema, same table, filter by `tenant_id` column 68 | - Using PostgreSQL Row Level Security 69 | - See [rls](./rls) 70 | 71 | ### Create Table and Insert Data into Table 72 | 73 | - Execute SQL in [ddl.sql](./rls/sql/ddl.sql) 74 | 75 | ### Enable RLS and Add Policies 76 | 77 | - Execute SQL in [policies.sql](./rls/sql/policies.sql) 78 | 79 | ### Start Application 80 | 81 | - Start [rls](./rls) application 82 | 83 | ### Check Results 84 | 85 | - Execute http request in [rest-api.http](./rls/rest-api.http) to check results 86 | 87 | ## MySQL: Application Implementation 88 | 89 | - Same database, same schema, same table, filter by `tenant_id` column 90 | - Auto extend SQL, add `where tenant_id in` or `and tenant_id in` conditions 91 | - Check tenant_id related conditions when we `select`,`update`, `delete` tenant tables 92 | - See [multi-tenancy-library](./multi-tenancy-library) and [springboot-mysql-jooq](./springboot-mysql-jooq) 93 | 94 | ### Install MySQL with Docker 95 | 96 | ``` 97 | docker run -itd --name mysql-test -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql 98 | ``` 99 | 100 | ### Create Table and Insert Data into Table 101 | 102 | - Execute SQL in [ddl.sql](./springboot-mysql-jooq/sql/ddl.sql) 103 | 104 | ### Start Application 105 | 106 | - Run [multi-tenancy-library](./multi-tenancy-library) publish task to make sure `multi-tenancy-library.jar` installed 107 | to maven local repository 108 | - Start [springboot-mysql-jooq](./springboot-mysql-jooq) application 109 | 110 | ### Check Results 111 | 112 | - Execute http request in [rest-api.http](./springboot-mysql-jooq/rest-api.http) to check results 113 | 114 | ### Configuration 115 | 116 | ```yaml 117 | multi: 118 | tenancy: 119 | # enable multi tenancy 120 | enabled: true 121 | # tenant table tenant related column name 122 | tenant-identifier: tenant_id 123 | # tenant tables 124 | tables: 125 | - multi_tenancy.t_user 126 | - multi_tenancy.t_order 127 | # check tenant condition exist in SQL or not 128 | sql-check-filters-exist: true 129 | # auto add tenant condition to SQL 130 | sql-auto-add-filters: true 131 | ``` 132 | 133 | ### Scheduler 134 | 135 | - If there are SQL releated schedulers in application, we can not get tenantID 136 | through `request.getHeader("X-TenantID")` in `WebMvcConfig` 137 | - We need to add `MultiTenancyStorage.setTenantID(tenantID)` before scheduler logic 138 | and add `MultiTenancyStorage.setTenantID(null)` after scheduler logic 139 | - Please check `springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/job/ScheduledJob.java` 140 | for detailed information -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.7.5' 3 | id 'io.spring.dependency-management' version '1.0.15.RELEASE' 4 | id 'java' 5 | id 'nu.studer.jooq' version '8.0' 6 | id 'maven-publish' 7 | } 8 | 9 | group = 'com.example' 10 | version = '0.0.1-SNAPSHOT' 11 | sourceCompatibility = '17' 12 | 13 | repositories { 14 | mavenLocal() 15 | mavenCentral() 16 | } 17 | 18 | subprojects { 19 | apply plugin: 'org.springframework.boot' 20 | apply plugin: 'io.spring.dependency-management' 21 | apply plugin: 'java' 22 | 23 | configurations.all { 24 | // check for updates every build 25 | resolutionStrategy.cacheChangingModulesFor 0, 'seconds' 26 | } 27 | 28 | dependencies { 29 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 30 | } 31 | 32 | tasks.named('test') { 33 | useJUnitPlatform() 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springmonster/multi-tenancy/6e7e3cefc9c61522915de8dbc01b8ecb9576039d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /multi-tenancy-library/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /multi-tenancy-library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | 3 | repositories { 4 | mavenCentral() 5 | } 6 | 7 | tasks.named("jar") { 8 | archiveClassifier = '' 9 | } 10 | 11 | publishing { 12 | publications { 13 | library(MavenPublication) { 14 | groupId = 'com.multi' 15 | artifactId = 'tenancy' 16 | version = '0.0.2-SNAPSHOT' 17 | 18 | from components.java 19 | } 20 | } 21 | repositories { 22 | mavenLocal() 23 | } 24 | } 25 | 26 | dependencies { 27 | implementation 'org.springframework.boot:spring-boot-starter-jooq' 28 | implementation 'org.springframework.boot:spring-boot-starter-web' 29 | implementation 'com.github.jsqlparser:jsqlparser:4.5' 30 | 31 | annotationProcessor 'org.springframework.boot:spring-boot-autoconfigure' 32 | annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' 33 | 34 | // test 35 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 36 | testRuntimeOnly 'com.h2database:h2' 37 | } -------------------------------------------------------------------------------- /multi-tenancy-library/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springmonster/multi-tenancy/6e7e3cefc9c61522915de8dbc01b8ecb9576039d/multi-tenancy-library/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /multi-tenancy-library/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/MultiTenancyAutoConfigure.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary; 2 | 3 | import com.example.multitenancylibrary.config.MultiTenancyProperties; 4 | import com.example.multitenancylibrary.sql.TenantIDCheckerExecuteListener; 5 | import com.example.multitenancylibrary.sql.TenantIDModifierVisitListener; 6 | import org.jooq.ExecuteListenerProvider; 7 | import org.jooq.VisitListenerProvider; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 11 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | 15 | @Configuration 16 | @EnableConfigurationProperties(MultiTenancyProperties.class) 17 | public class MultiTenancyAutoConfigure { 18 | 19 | @Autowired 20 | private MultiTenancyProperties multiTenancyProperties; 21 | 22 | @Bean 23 | @ConditionalOnMissingBean 24 | @ConditionalOnProperty(prefix = "multi.tenancy", value = {"enabled", "sql-auto-add-filters"}, havingValue = "true") 25 | public VisitListenerProvider visitListenerProvider() { 26 | return () -> new TenantIDModifierVisitListener(multiTenancyProperties); 27 | } 28 | 29 | @Bean 30 | @ConditionalOnMissingBean 31 | @ConditionalOnProperty(prefix = "multi.tenancy", value = {"enabled", "sql-check-filters-exist"}, havingValue = "true") 32 | public ExecuteListenerProvider executeListenerProvider() { 33 | return () -> new TenantIDCheckerExecuteListener(multiTenancyProperties); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/config/MultiTenancyProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | import java.util.List; 8 | 9 | @Configuration 10 | @ConfigurationProperties(prefix = "multi.tenancy") 11 | public class MultiTenancyProperties { 12 | @Value("${enabled:false}") 13 | private boolean enabled; 14 | @Value("${sql-check-filters-exist:false}") 15 | private boolean sqlCheckFiltersExist; 16 | @Value("${sql-auto-add-filters:false}") 17 | private boolean sqlAutoAddFilters; 18 | 19 | @Value("#{'${tables:}'.empty ? null: '${tables:}'}") 20 | private List tables; 21 | 22 | @Value("${tenant-identifier:tenant_id}") 23 | private String tenantIdentifier; 24 | 25 | public boolean isSqlCheckFiltersExist() { 26 | return sqlCheckFiltersExist; 27 | } 28 | 29 | public void setSqlCheckFiltersExist(boolean sqlCheckFiltersExist) { 30 | this.sqlCheckFiltersExist = sqlCheckFiltersExist; 31 | } 32 | 33 | public boolean isEnabled() { 34 | return enabled; 35 | } 36 | 37 | public void setEnabled(boolean enabled) { 38 | this.enabled = enabled; 39 | } 40 | 41 | public boolean isSqlAutoAddFilters() { 42 | return sqlAutoAddFilters; 43 | } 44 | 45 | public void setSqlAutoAddFilters(boolean sqlAutoAddFilters) { 46 | this.sqlAutoAddFilters = sqlAutoAddFilters; 47 | } 48 | 49 | public List getTables() { 50 | return tables; 51 | } 52 | 53 | public void setTables(List tables) { 54 | this.tables = tables; 55 | } 56 | 57 | public String getTenantIdentifier() { 58 | return tenantIdentifier; 59 | } 60 | 61 | public void setTenantIdentifier(String tenantIdentifier) { 62 | this.tenantIdentifier = tenantIdentifier; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/config/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.config; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.springframework.web.servlet.HandlerInterceptor; 5 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | //@Configuration 12 | public class WebMvcConfig implements WebMvcConfigurer { 13 | 14 | @Override 15 | public void addInterceptors(InterceptorRegistry registry) { 16 | registry.addInterceptor(new HandlerInterceptor() { 17 | @Override 18 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 19 | String tenantID = request.getHeader("X-TenantID"); 20 | MultiTenancyStorage.setTenantID(Integer.valueOf(tenantID)); 21 | return true; 22 | } 23 | 24 | @Override 25 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 26 | MultiTenancyStorage.setTenantID(null); 27 | } 28 | }); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/network/MultiTenancyStorage.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.network; 2 | 3 | public class MultiTenancyStorage { 4 | 5 | private MultiTenancyStorage() { 6 | } 7 | 8 | private static final ThreadLocal tenant = new InheritableThreadLocal<>(); 9 | 10 | public static void setTenantID(Integer tenantName) { 11 | tenant.set(tenantName); 12 | } 13 | 14 | public static Integer getTenantID() { 15 | return tenant.get(); 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/sql/TablesFinder.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import net.sf.jsqlparser.schema.Table; 4 | import net.sf.jsqlparser.util.TablesNamesFinder; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class TablesFinder extends TablesNamesFinder { 10 | 11 | private final List tables = new ArrayList<>(); 12 | 13 | @Override 14 | public void visit(Table tableName) { 15 | super.visit(tableName); 16 | this.tables.add(tableName); 17 | } 18 | 19 | public List
getTables() { 20 | return this.tables; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/sql/TenantIDCheckerExecuteListener.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.config.MultiTenancyProperties; 4 | import net.sf.jsqlparser.JSQLParserException; 5 | import net.sf.jsqlparser.expression.Alias; 6 | import net.sf.jsqlparser.parser.CCJSqlParserUtil; 7 | import net.sf.jsqlparser.schema.Table; 8 | import net.sf.jsqlparser.statement.Statement; 9 | import net.sf.jsqlparser.statement.delete.Delete; 10 | import net.sf.jsqlparser.statement.select.Select; 11 | import net.sf.jsqlparser.statement.update.Update; 12 | import org.jooq.ExecuteContext; 13 | import org.jooq.impl.DefaultExecuteListener; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.stereotype.Component; 18 | 19 | import java.util.List; 20 | import java.util.regex.Matcher; 21 | import java.util.regex.Pattern; 22 | 23 | @Component 24 | public class TenantIDCheckerExecuteListener extends DefaultExecuteListener { 25 | 26 | private final Logger logging = LoggerFactory.getLogger(TenantIDCheckerExecuteListener.class); 27 | private final MultiTenancyProperties multiTenancyProperties; 28 | 29 | @Autowired 30 | public TenantIDCheckerExecuteListener(MultiTenancyProperties multiTenancyProperties) { 31 | this.multiTenancyProperties = multiTenancyProperties; 32 | } 33 | 34 | private static final String SQL_PARSER_ERROR = "SQL parser error!"; 35 | 36 | @Override 37 | public void renderEnd(ExecuteContext ctx) { 38 | String originalSQL = ctx.sql(); 39 | 40 | if (originalSQL == null) { 41 | return; 42 | } 43 | 44 | logging.debug(originalSQL); 45 | 46 | checkSQL(originalSQL); 47 | } 48 | 49 | private void checkSQL(String originalSQL) { 50 | try { 51 | String transformOriginalSQL = transformOriginalSQL(originalSQL); 52 | Statement stmt = CCJSqlParserUtil.parse(transformOriginalSQL); 53 | if (stmt instanceof Select 54 | || stmt instanceof Update 55 | || stmt instanceof Delete) { 56 | checkSelectUpdateDeleteSQL(stmt, transformOriginalSQL); 57 | } 58 | } catch (JSQLParserException e) { 59 | throw new TenantIDException(SQL_PARSER_ERROR); 60 | } 61 | } 62 | 63 | private void checkSelectUpdateDeleteSQL(Statement statement, String originalSQL) { 64 | TablesFinder tablesFinder = new TablesFinder(); 65 | tablesFinder.getTableList(statement); 66 | List
tableList = tablesFinder.getTables(); 67 | 68 | for (Table table : tableList) { 69 | boolean isTableExist = checkTable(table.getName()); 70 | 71 | if (!isTableExist) { 72 | continue; 73 | } 74 | 75 | String tableName = getOriginalOrAliasTableName(table); 76 | 77 | boolean isConditionExist = isConditionExistInSQLRegex(originalSQL); 78 | 79 | if (!isConditionExist) { 80 | throw new TenantIDException("Tenant conditions does not exist in table " + tableName); 81 | } 82 | } 83 | } 84 | 85 | private String getOriginalOrAliasTableName(Table table) { 86 | Alias alias = table.getAlias(); 87 | if (alias != null) { 88 | return alias.getName(); 89 | } 90 | return table.getFullyQualifiedName(); 91 | } 92 | 93 | private boolean isConditionExistInSQLRegex(String sql) { 94 | Pattern p = Pattern.compile(".*(where|and).*" + this.multiTenancyProperties.getTenantIdentifier() + ".*(in|=).*", Pattern.CASE_INSENSITIVE); 95 | Matcher m = p.matcher(sql); 96 | return m.matches(); 97 | } 98 | 99 | private boolean checkTable(String originalTableName) { 100 | boolean isTenantTableExist = false; 101 | for (String tableName : multiTenancyProperties.getTables()) { 102 | String tempTableName = tableName.split("\\.")[1]; 103 | String transformedTempTableName = transformTableName(tempTableName); 104 | if (originalTableName.equalsIgnoreCase(transformedTempTableName) 105 | || tableName.contains(originalTableName)) { 106 | isTenantTableExist = true; 107 | break; 108 | } 109 | } 110 | return isTenantTableExist; 111 | } 112 | 113 | private String transformTableName(String tableName) { 114 | return "\"" + 115 | tableName + 116 | "\""; 117 | } 118 | 119 | private String transformOriginalSQL(String originalSQL) { 120 | if (originalSQL.contains("`")) { 121 | return originalSQL.replace("`", "\""); 122 | } else { 123 | return originalSQL; 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/sql/TenantIDException.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | public class TenantIDException extends RuntimeException { 4 | 5 | public TenantIDException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/java/com/example/multitenancylibrary/sql/TenantIDModifierVisitListener.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.config.MultiTenancyProperties; 4 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 5 | import org.jooq.*; 6 | import org.jooq.impl.DSL; 7 | import org.jooq.impl.DefaultVisitListener; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.util.ReflectionUtils; 11 | 12 | import java.util.*; 13 | 14 | import static java.util.Arrays.asList; 15 | import static org.jooq.Clause.*; 16 | 17 | @Component 18 | public class TenantIDModifierVisitListener extends DefaultVisitListener { 19 | 20 | private MultiTenancyProperties multiTenancyProperties; 21 | 22 | @Autowired 23 | public TenantIDModifierVisitListener(MultiTenancyProperties multiTenancyProperties) { 24 | this.multiTenancyProperties = multiTenancyProperties; 25 | } 26 | 27 | private void pushConditionAndWhereAndOn(VisitContext context) { 28 | getConditionStack(context).push(new LinkedHashSet<>()); 29 | getWhereStack(context).push(false); 30 | getOnStack(context).push(new LinkedHashSet<>()); 31 | } 32 | 33 | private void popConditionAndWhereAndOn(VisitContext context) { 34 | getConditionStack(context).pop(); 35 | getWhereStack(context).pop(); 36 | getOnStack(context).pop(); 37 | } 38 | 39 | private Deque> getConditionStack(VisitContext context) { 40 | String conditions = "conditions"; 41 | Deque> data = (Deque>) context.data(conditions); 42 | 43 | if (data == null) { 44 | data = new ArrayDeque<>(); 45 | context.data(conditions, data); 46 | } 47 | 48 | return data; 49 | } 50 | 51 | private Deque> getOnStack(VisitContext context) { 52 | String conditions = "on"; 53 | Deque> data = (Deque>) context.data(conditions); 54 | 55 | if (data == null) { 56 | data = new ArrayDeque<>(); 57 | context.data(conditions, data); 58 | } 59 | 60 | return data; 61 | } 62 | 63 | private Deque getWhereStack(VisitContext context) { 64 | String predicates = "predicates"; 65 | Deque data = (Deque) context.data(predicates); 66 | 67 | if (data == null) { 68 | data = new ArrayDeque<>(); 69 | context.data(predicates, data); 70 | } 71 | 72 | return data; 73 | } 74 | 75 | private LinkedHashSet peekConditions(VisitContext context) { 76 | return getConditionStack(context).peek(); 77 | } 78 | 79 | private LinkedHashSet peekOns(VisitContext context) { 80 | return getOnStack(context).peek(); 81 | } 82 | 83 | private Boolean peekWheres(VisitContext context) { 84 | return getWhereStack(context).peek(); 85 | } 86 | 87 | private void addWhere(VisitContext context, boolean value) { 88 | getWhereStack(context).pop(); 89 | getWhereStack(context).push(value); 90 | } 91 | 92 | private void addConditions(VisitContext context, Table table, Field field, E... values) { 93 | QueryPart queryPart = context.queryPart(); 94 | 95 | if (queryPart instanceof Table queryTable) { 96 | if (!queryTable.getName().equals(table.getName())) { 97 | return; 98 | } 99 | 100 | List clauses = getClauses(context); 101 | 102 | if (clauses.contains(SELECT_FROM) || 103 | clauses.contains(UPDATE_UPDATE) || 104 | clauses.contains(DELETE_DELETE)) { 105 | field = getTableAlias(context, field, clauses); 106 | peekConditions(context).add(field.in(values)); 107 | } 108 | } 109 | } 110 | 111 | private static Field getTableAlias(VisitContext context, Field field, List clauses) { 112 | if (clauses.contains(TABLE_ALIAS)) { 113 | QueryPart[] parts = context.queryParts(); 114 | 115 | for (int i = parts.length - 2; i >= 0; i--) { 116 | if (parts[i] instanceof Table) { 117 | field = ((Table) parts[i]).field(field); 118 | break; 119 | } 120 | } 121 | } 122 | return field; 123 | } 124 | 125 | List getClauses(VisitContext context) { 126 | List result = asList(context.clauses()); 127 | int index = result.lastIndexOf(SELECT); 128 | 129 | if (index > 0) { 130 | return result.subList(index, result.size() - 1); 131 | } else { 132 | return result; 133 | } 134 | } 135 | 136 | @Override 137 | public void clauseStart(VisitContext context) { 138 | if (context.clause() == SELECT || 139 | context.clause() == UPDATE || 140 | context.clause() == DELETE || 141 | context.clause() == INSERT) { 142 | pushConditionAndWhereAndOn(context); 143 | } 144 | } 145 | 146 | @Override 147 | public void clauseEnd(VisitContext context) { 148 | if (context.clause() == TABLE_JOIN_OUTER_LEFT) { 149 | autoExtendOuterJoin(context, true); 150 | } else if (context.clause() == TABLE_JOIN_OUTER_RIGHT) { 151 | autoExtendOuterJoin(context, false); 152 | } else if (context.clause() == SELECT_WHERE || 153 | context.clause() == UPDATE_WHERE || 154 | context.clause() == DELETE_WHERE) { 155 | autoExtendSelectUpdateDelete(context); 156 | } 157 | 158 | if (context.clause() == SELECT || 159 | context.clause() == UPDATE || 160 | context.clause() == DELETE || 161 | context.clause() == INSERT) { 162 | popConditionAndWhereAndOn(context); 163 | } 164 | } 165 | 166 | private void autoExtendOuterJoin(VisitContext context, boolean isLeftOuterJoin) { 167 | LinkedHashSet conditions = peekConditions(context); 168 | if (conditions == null || conditions.isEmpty()) { 169 | return; 170 | } 171 | 172 | QueryPart[] queryParts = context.queryParts(); 173 | String secondaryTable = null; 174 | for (QueryPart queryPart : queryParts) { 175 | secondaryTable = getOuterJoinSecondaryTableName(queryPart, isLeftOuterJoin); 176 | } 177 | 178 | List finalRTableConditions = new ArrayList<>(); 179 | for (Condition condition : conditions) { 180 | if (secondaryTable != null && condition.toString().contains(secondaryTable)) { 181 | finalRTableConditions.add(condition); 182 | } 183 | } 184 | 185 | if (!finalRTableConditions.isEmpty()) { 186 | peekOns(context).addAll(finalRTableConditions); 187 | 188 | context.context() 189 | .formatSeparator() 190 | .keyword("and") 191 | .sql(' '); 192 | 193 | context.context().visit(DSL.condition(Operator.AND, finalRTableConditions)); 194 | } 195 | } 196 | 197 | private void autoExtendSelectUpdateDelete(VisitContext context) { 198 | LinkedHashSet conditions = peekConditions(context); 199 | if (conditions == null || conditions.isEmpty()) { 200 | return; 201 | } 202 | 203 | LinkedHashSet ons = peekOns(context); 204 | conditions.removeAll(ons); 205 | 206 | if (!conditions.isEmpty()) { 207 | context.context() 208 | .formatSeparator() 209 | .keyword(peekWheres(context) ? "and" : "where") 210 | .sql(' '); 211 | context.context().visit(DSL.condition(Operator.AND, conditions)); 212 | } 213 | } 214 | 215 | private String getOuterJoinSecondaryTableName(QueryPart queryPart, boolean isLeftOuterJoin) { 216 | try { 217 | Class joinTable = Class.forName("org.jooq.impl.JoinTable"); 218 | if (joinTable.isAssignableFrom(queryPart.getClass())) { 219 | Object joinTableObj = joinTable.cast(queryPart); 220 | 221 | java.lang.reflect.Field table = ReflectionUtils.findField(joinTable, isLeftOuterJoin ? "rhs" : "lhs"); 222 | ReflectionUtils.makeAccessible(table); 223 | return ((Table) ReflectionUtils.getField(table, joinTableObj)).getName(); 224 | } 225 | } catch (ClassNotFoundException ignored) { 226 | } 227 | return null; 228 | } 229 | 230 | @Override 231 | public void visitEnd(VisitContext context) { 232 | addTenantInformation(context); 233 | 234 | if (context.queryPart() instanceof Condition) { 235 | List clauses = getClauses(context); 236 | 237 | if (clauses.contains(SELECT_WHERE) || 238 | clauses.contains(UPDATE_WHERE) || 239 | clauses.contains(DELETE_WHERE)) { 240 | addWhere(context, true); 241 | } 242 | } 243 | } 244 | 245 | void addTenantInformation(VisitContext context) { 246 | Integer tenantID = MultiTenancyStorage.getTenantID(); 247 | if (tenantID != null) { 248 | for (String table : multiTenancyProperties.getTables()) { 249 | String schemaName = table.split("\\.")[0]; 250 | String tableName = table.split("\\.")[1]; 251 | addConditions(context, DSL.table(DSL.name(tableName)), 252 | DSL.field(DSL.name(schemaName, tableName, multiTenancyProperties.getTenantIdentifier())), tenantID); 253 | } 254 | } else { 255 | throw new TenantIDException(multiTenancyProperties.getTenantIdentifier() + " value is missing! " + 256 | "Please check MultiTenancyStorage.setTenantID(Integer) has invoked or not!"); 257 | } 258 | } 259 | } -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/resources/META-INF/additional-spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "name": "multi.tenancy.enabled", 5 | "type": "java.lang.Boolean", 6 | "description": "enable multi tenancy" 7 | }, 8 | { 9 | "name": "multi.tenancy.sql-check-filters-exist", 10 | "type": "java.lang.Boolean", 11 | "description": "enable sql check filters exist" 12 | }, 13 | { 14 | "name": "multi.tenancy.sql-auto-add-filters", 15 | "type": "java.lang.Boolean", 16 | "description": "enable sql auto add filters" 17 | }, 18 | { 19 | "name": "multi.tenancy.tenant-identifier", 20 | "type": "java.lang.String", 21 | "description": "tenant table column name. default is tenant_id" 22 | }, 23 | { 24 | "name": "multi.tenancy.tables", 25 | "type": "java.util.List", 26 | "description": "tenant tables array, split by , . for example public.table_a,public.table_b" 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.multitenancylibrary.MultiTenancyAutoConfigure -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | # multi tenancy 2 | multi.tenancy.enabled=true 3 | multi.tenancy.sql-auto-add-filters=true 4 | multi.tenancy.sql-check-filters-exist=true 5 | multi.tenancy.tables=public.t_user, public.t_order, public.t_order_detail, public.t_department, public.v_user 6 | multi.tenancy.tenant-identifier=tenant_id 7 | # h2 8 | spring.datasource.driver-class-name=org.h2.Driver 9 | spring.datasource.url=jdbc:h2:file:./testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false;DATABASE_TO_UPPER=false;DATABASE_TO_LOWER=true;INIT=CREATE SCHEMA IF NOT EXISTS public 10 | spring.datasource.username=sa 11 | spring.datasource.password= 12 | spring.sql.init.mode=always 13 | spring.sql.init.platform=h2 14 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect 15 | spring.jpa.hibernate.ddl-auto=create-drop 16 | spring.jpa.properties.hibernate.default_schema=public 17 | spring.jpa.defer-datasource-initialization=true 18 | # jooq 19 | logging.level.org.jooq.tools.LoggerListener=DEBUG -------------------------------------------------------------------------------- /multi-tenancy-library/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/TestApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class TestApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(TestApplication.class, args); 10 | } 11 | } -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantIDCheckerExecuteListenerTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.config.MultiTenancyProperties; 4 | import org.junit.jupiter.api.Assertions; 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.test.util.ReflectionTestUtils; 7 | 8 | import java.util.List; 9 | 10 | class TenantIDCheckerExecuteListenerTest { 11 | 12 | @Test 13 | void checkSQlTestForMySQL() { 14 | // Normal 15 | String sql = "select `abc_scenario`.`id`, `abc_scenario`.`org_id`, `abc_scenario`.`name`, `abc_scenario`.`name_cn`, `abc_scenario`.`description`, `abc_scenario`.`description_cn`, `abc_scenario`.`installed`, `abc_scenario`.`image`, `abc_scenario`.`parent_scenario_id`, `abc_scenario`.`order`, `abc_scenario`.`created_by`, `abc_scenario`.`created_at`, `abc_scenario`.`updated_by`, `abc_scenario`.`updated_at` from `abc_scenario` where `abc_scenario`.`id` in (4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 1, 1, 1, 1, 1, 1) and `abc_scenario`.`org_id` in (88)"; 16 | 17 | MultiTenancyProperties multiTenancyProperties = new MultiTenancyProperties(); 18 | multiTenancyProperties.setTables(List.of("abc.abc_scenario")); 19 | multiTenancyProperties.setTenantIdentifier("org_id"); 20 | 21 | TenantIDCheckerExecuteListener tenantIDCheckerExecuteListener = new TenantIDCheckerExecuteListener(multiTenancyProperties); 22 | 23 | Assertions.assertDoesNotThrow(() -> ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "checkSQL", sql)); 24 | 25 | // Normal 26 | String sql1 = "select `alias_122582596`.`id`, `alias_122582596`.`org_id`, `alias_122582596`.`name`, `alias_122582596`.`description`, `alias_122582596`.`action_type`, `alias_122582596`.`scenario_id`, `alias_122582596`.`save_path`, `alias_122582596`.`created_by`, `alias_122582596`.`created_at` from (select `abc_action_import`.`id`, `abc_action_import`.`org_id`, `abc_action_import`.`name`, `abc_action_import`.`description`, `abc_action_import`.`action_type`, `abc_action_import`.`scenario_id`, `abc_action_import`.`save_path`, `abc_action_import`.`created_by`, `abc_action_import`.`created_at` from `abc_action_import` where `abc_action_import`.`org_id` in (88)) as `alias_122582596` limit 20"; 27 | 28 | multiTenancyProperties.setTables(List.of("abc.abc_action_import")); 29 | multiTenancyProperties.setTenantIdentifier("org_id"); 30 | 31 | Assertions.assertDoesNotThrow(() -> ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "checkSQL", sql1)); 32 | 33 | // Exception 34 | String sql2 = "select count(*) from (select `abc_action_import`.`id`, `abc_action_import`.`org_id`, `abc_action_import`.`name`, `abc_action_import`.`description`, `abc_action_import`.`action_type`, `abc_action_import`.`scenario_id`, `abc_action_import`.`save_path`, `abc_action_import`.`created_by`, `abc_action_import`.`created_at` from `abc_action_import`) as `alias_122582596`"; 35 | 36 | multiTenancyProperties.setTables(List.of("abc.abc_action_import")); 37 | multiTenancyProperties.setTenantIdentifier("org_id"); 38 | 39 | Assertions.assertThrows(TenantIDException.class, () -> ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "checkSQL", sql2)); 40 | 41 | // Exception 42 | String sql3 = "select count(*) from (select `alias_1`.`id`, `alias_1`.`org_id`, `alias_1`.`name`, `alias_1`.`description`, `alias_1`.`action_type`, `alias_1`.`scenario_id`, `alias_1`.`save_path`, `alias_1`.`created_by`, `alias_1`.`created_at` from `abc_action_import` as `alias_1`) as `alias_122582596`"; 43 | 44 | multiTenancyProperties.setTables(List.of("abc.abc_action_import")); 45 | multiTenancyProperties.setTenantIdentifier("org_id"); 46 | 47 | Assertions.assertThrows(TenantIDException.class, () -> ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "checkSQL", sql3)); 48 | } 49 | 50 | @Test 51 | void checkSQLTestForPostgreSQL() { 52 | String sql = "select \"public\".\"t_user\".\"id\", \"public\".\"t_user\".\"user_id\", \"public\".\"t_user\".\"tenant_id\", \"public\".\"t_user\".\"user_name\" from \"public\".\"t_user\" where \"public\".\"t_user\".\"tenant_id\" in (?)"; 53 | 54 | MultiTenancyProperties multiTenancyProperties = new MultiTenancyProperties(); 55 | multiTenancyProperties.setTables(List.of("public.t_user")); 56 | multiTenancyProperties.setTenantIdentifier("tenant_id"); 57 | 58 | TenantIDCheckerExecuteListener tenantIDCheckerExecuteListener = new TenantIDCheckerExecuteListener(multiTenancyProperties); 59 | 60 | Assertions.assertDoesNotThrow(() -> ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "checkSQL", sql)); 61 | } 62 | 63 | @Test 64 | void checkSQLRegex() { 65 | String sql1 = "select * from t_user where t_user.tenant_id in 1"; 66 | String sql2 = "select * from t_user where t_user.tenant_id = 1"; 67 | String sql3 = "select * from t_user where 1=1 and t_user.tenant_id in 1"; 68 | String sql4 = "select * from t_user where 1=1 and t_user.tenant_id = 1"; 69 | String sql5 = "select * from t_user where 1=1"; 70 | String sql6 = "select * from t_user"; 71 | String sql7 = "update t_user set tenant_id = 1 where 1=1"; 72 | String sql8 = "delete from t_user where 1=1"; 73 | String sql9 = "SELECT FROM t_user WHERE t_user.tenant_id IN 1"; 74 | String sql10 = "SELECT FROM t_user WHERE t_user.tenant_id = 1"; 75 | String sql11 = "SELECT FROM T_USER WHERE T_USER.TENANT_ID IN 1"; 76 | String sql12 = "SELECT FROM T_USER WHERE T_USER.TENANT_ID = 1"; 77 | 78 | MultiTenancyProperties multiTenancyProperties = new MultiTenancyProperties(); 79 | multiTenancyProperties.setTables(List.of("public.t_user")); 80 | multiTenancyProperties.setTenantIdentifier("tenant_id"); 81 | 82 | TenantIDCheckerExecuteListener tenantIDCheckerExecuteListener = new TenantIDCheckerExecuteListener(multiTenancyProperties); 83 | 84 | Boolean b1 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql1); 85 | Boolean b2 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql2); 86 | Boolean b3 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql3); 87 | Boolean b4 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql4); 88 | Boolean b5 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql5); 89 | Boolean b6 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql6); 90 | Boolean b7 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql7); 91 | Boolean b8 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql8); 92 | Boolean b9 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql9); 93 | Boolean b10 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql10); 94 | Boolean b11 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql11); 95 | Boolean b12 = ReflectionTestUtils.invokeMethod(tenantIDCheckerExecuteListener, "isConditionExistInSQLRegex", sql12); 96 | Assertions.assertAll( 97 | () -> Assertions.assertEquals(Boolean.TRUE, b1), 98 | () -> Assertions.assertEquals(Boolean.TRUE, b2), 99 | () -> Assertions.assertEquals(Boolean.TRUE, b3), 100 | () -> Assertions.assertEquals(Boolean.TRUE, b4), 101 | () -> Assertions.assertEquals(Boolean.FALSE, b5), 102 | () -> Assertions.assertEquals(Boolean.FALSE, b6), 103 | () -> Assertions.assertEquals(Boolean.FALSE, b7), 104 | () -> Assertions.assertEquals(Boolean.FALSE, b8), 105 | () -> Assertions.assertEquals(Boolean.TRUE, b9), 106 | () -> Assertions.assertEquals(Boolean.TRUE, b10), 107 | () -> Assertions.assertEquals(Boolean.TRUE, b11), 108 | () -> Assertions.assertEquals(Boolean.TRUE, b12) 109 | ); 110 | } 111 | } -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLDeleteTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Result; 7 | import org.jooq.Table; 8 | import org.junit.jupiter.api.Assertions; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.test.context.ActiveProfiles; 14 | 15 | import java.util.List; 16 | 17 | @SpringBootTest 18 | @ActiveProfiles("test") 19 | class TenantSQLDeleteTest { 20 | 21 | @Autowired 22 | private DSLContext dslContext; 23 | 24 | private Table userTable; 25 | 26 | @BeforeEach 27 | public void beforeEach() { 28 | List> tables = dslContext.meta().getTables("t_user"); 29 | userTable = tables.get(0); 30 | } 31 | 32 | @Test 33 | void testUserTableDelete() { 34 | MultiTenancyStorage.setTenantID(101); 35 | 36 | int execute = dslContext 37 | .insertInto(userTable, 38 | userTable.field("user_id"), 39 | userTable.field("tenant_id"), 40 | userTable.field("user_name")) 41 | .values("uid101", 101, "uname101") 42 | .execute(); 43 | Assertions.assertEquals(1, execute); 44 | 45 | Result fetch = dslContext 46 | .select() 47 | .from(userTable) 48 | .fetch(); 49 | Assertions.assertEquals("uname101", fetch.getValues("user_name").get(0)); 50 | 51 | int execute1 = dslContext 52 | .deleteFrom(userTable) 53 | .where(userTable.field("user_id").eq("uid101")) 54 | .execute(); 55 | Assertions.assertEquals(1, execute1); 56 | 57 | Result fetch1 = dslContext 58 | .select() 59 | .from(userTable) 60 | .fetch(); 61 | Assertions.assertEquals(0, fetch1.size()); 62 | 63 | MultiTenancyStorage.setTenantID(null); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLQuerySingleTableTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Record1; 7 | import org.jooq.Result; 8 | import org.jooq.Table; 9 | import org.junit.jupiter.api.Assertions; 10 | import org.junit.jupiter.api.BeforeEach; 11 | import org.junit.jupiter.api.DisplayName; 12 | import org.junit.jupiter.api.Nested; 13 | import org.junit.jupiter.api.Test; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.test.context.ActiveProfiles; 17 | 18 | import java.util.List; 19 | 20 | @SpringBootTest 21 | @ActiveProfiles("test") 22 | class TenantSQLQuerySingleTableTest { 23 | 24 | @Autowired 25 | private DSLContext dslContext; 26 | 27 | private Table userTable; 28 | 29 | @BeforeEach 30 | public void beforeEach() { 31 | List> tables = dslContext.meta().getTables("t_user"); 32 | userTable = tables.get(0); 33 | } 34 | 35 | @Nested 36 | @DisplayName("DSL SQL") 37 | class DSLSQLTest { 38 | @Test 39 | void testUserTableQuery() { 40 | MultiTenancyStorage.setTenantID(4); 41 | 42 | Result fetch = dslContext 43 | .select() 44 | .from(userTable) 45 | .fetch(); 46 | 47 | MultiTenancyStorage.setTenantID(null); 48 | 49 | Assertions.assertEquals(2, fetch.size()); 50 | } 51 | 52 | @Test 53 | void testUserTableQueryWithWhere() { 54 | MultiTenancyStorage.setTenantID(4); 55 | 56 | Result fetch = dslContext 57 | .select() 58 | .from(userTable) 59 | .where(userTable.field("tenant_id", Integer.class).eq(4)) 60 | .fetch(); 61 | 62 | MultiTenancyStorage.setTenantID(null); 63 | 64 | Assertions.assertEquals(2, fetch.size()); 65 | } 66 | 67 | @Test 68 | void testUserTableQueryWithAlias() { 69 | MultiTenancyStorage.setTenantID(4); 70 | 71 | Table tUserAlias = userTable.as("t_user_alias"); 72 | 73 | Result fetch = dslContext 74 | .select() 75 | .from(tUserAlias) 76 | .fetch(); 77 | 78 | MultiTenancyStorage.setTenantID(null); 79 | 80 | Assertions.assertEquals(2, fetch.size()); 81 | } 82 | 83 | @Test 84 | void testUserTableQueryDistinct() { 85 | MultiTenancyStorage.setTenantID(1); 86 | 87 | Result> userId = dslContext 88 | .selectDistinct(userTable.field("user_id")) 89 | .from(userTable) 90 | .fetch(); 91 | 92 | MultiTenancyStorage.setTenantID(null); 93 | 94 | Assertions.assertEquals(2, userId.size()); 95 | } 96 | 97 | @Test 98 | void testUserTableQueryCount() { 99 | MultiTenancyStorage.setTenantID(1); 100 | 101 | int count = dslContext 102 | .selectCount() 103 | .from(userTable) 104 | .fetchOne(0, int.class); 105 | 106 | MultiTenancyStorage.setTenantID(null); 107 | 108 | Assertions.assertEquals(3, count); 109 | } 110 | } 111 | 112 | @Nested 113 | @DisplayName("Plain SQL") 114 | class PlainSQLTest { 115 | @Test 116 | void testUserTablePlainQueryThrowsException() { 117 | Assertions.assertThrows(TenantIDException.class, () -> { 118 | MultiTenancyStorage.setTenantID(1); 119 | 120 | dslContext.fetch("select * from t_user"); 121 | 122 | MultiTenancyStorage.setTenantID(null); 123 | }); 124 | } 125 | 126 | @Test 127 | void testUserTablePlainQueryWithWhereThrowsException() { 128 | Assertions.assertThrows(TenantIDException.class, () -> { 129 | MultiTenancyStorage.setTenantID(1); 130 | 131 | dslContext.fetch("select * from t_user where 1 = 1"); 132 | 133 | MultiTenancyStorage.setTenantID(null); 134 | }); 135 | } 136 | 137 | @Test 138 | void testUserTablePlainQueryWithSchemaThrowsException() { 139 | Assertions.assertThrows(TenantIDException.class, () -> { 140 | MultiTenancyStorage.setTenantID(1); 141 | 142 | dslContext.fetch("select * from public.t_user"); 143 | 144 | MultiTenancyStorage.setTenantID(null); 145 | }); 146 | } 147 | 148 | @Test 149 | void testUserTablePlainQuery() { 150 | MultiTenancyStorage.setTenantID(2); 151 | 152 | Result fetch = dslContext.fetch("select * from t_user where tenant_id = 1"); 153 | Assertions.assertEquals(3, fetch.size()); 154 | 155 | Result fetch1 = dslContext.fetch("select * from public.t_user where t_user.tenant_id = 1"); 156 | Assertions.assertEquals(3, fetch1.size()); 157 | 158 | Result fetch2 = dslContext.fetch("select * from public.t_user where public.t_user.tenant_id = 1"); 159 | Assertions.assertEquals(3, fetch2.size()); 160 | 161 | Result fetch3 = dslContext.fetch("select * from public.t_user where public.t_user.tenant_id = 1"); 162 | Assertions.assertEquals(3, fetch3.size()); 163 | 164 | Result fetch4 = dslContext.fetch("select * from public.t_user where 1=1 and public.t_user.tenant_id = 1"); 165 | Assertions.assertEquals(3, fetch4.size()); 166 | 167 | MultiTenancyStorage.setTenantID(null); 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLQueryThreeTableTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Result; 7 | import org.jooq.Table; 8 | import org.junit.jupiter.api.*; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.ActiveProfiles; 12 | 13 | import java.util.List; 14 | 15 | import static org.jooq.impl.DSL.name; 16 | 17 | @SpringBootTest 18 | @ActiveProfiles("test") 19 | class TenantSQLQueryThreeTableTest { 20 | 21 | @Autowired 22 | private DSLContext dslContext; 23 | 24 | private Table userTable; 25 | 26 | private Table orderTable; 27 | 28 | private Table orderDetailTable; 29 | 30 | @BeforeEach 31 | public void beforeEach() { 32 | List> tables = dslContext.meta().getTables("t_user"); 33 | userTable = tables.get(0); 34 | 35 | List> tables1 = dslContext.meta().getTables("t_order"); 36 | orderTable = tables1.get(0); 37 | 38 | List> tables2 = dslContext.meta().getTables("t_order_detail"); 39 | orderDetailTable = tables2.get(0); 40 | } 41 | 42 | @Nested 43 | @DisplayName("Left Outer Join || Right Outer Join") 44 | class LeftOrRightOuterJoinTest { 45 | @Test 46 | void testLeftOuterJoinThreeTables() { 47 | MultiTenancyStorage.setTenantID(4); 48 | 49 | Result fetch = dslContext 50 | .select(userTable.fields()) 51 | .select(orderTable.fields()) 52 | .select(orderDetailTable.fields()) 53 | .from(userTable) 54 | .leftOuterJoin(orderTable) 55 | .on(userTable.field("user_id") 56 | .eq(orderTable.field("user_id"))) 57 | .leftOuterJoin(orderDetailTable) 58 | .on(orderTable.field("order_id") 59 | .eq(orderDetailTable.field("order_id"))) 60 | .fetch(); 61 | 62 | MultiTenancyStorage.setTenantID(null); 63 | 64 | Assertions.assertEquals(2, fetch.size()); 65 | } 66 | 67 | @Test 68 | void testRightOuterJoinThreeTables() { 69 | MultiTenancyStorage.setTenantID(9); 70 | 71 | Result fetch = dslContext 72 | .select(userTable.fields()) 73 | .select(orderTable.fields()) 74 | .select(orderDetailTable.fields()) 75 | .from(userTable) 76 | .rightOuterJoin(orderTable) 77 | .on(userTable.field("user_id") 78 | .eq(orderTable.field("user_id"))) 79 | .rightOuterJoin(orderDetailTable) 80 | .on(orderTable.field("order_id") 81 | .eq(orderDetailTable.field("order_id"))) 82 | .fetch(); 83 | 84 | MultiTenancyStorage.setTenantID(null); 85 | 86 | Assertions.assertEquals(6, fetch.size()); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLQueryTwoTableTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Result; 7 | import org.jooq.Table; 8 | import org.junit.jupiter.api.*; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.ActiveProfiles; 12 | 13 | import java.util.List; 14 | 15 | import static org.jooq.impl.DSL.select; 16 | 17 | @SpringBootTest 18 | @ActiveProfiles("test") 19 | class TenantSQLQueryTwoTableTest { 20 | 21 | @Autowired 22 | private DSLContext dslContext; 23 | 24 | private Table userTable; 25 | 26 | private Table orderTable; 27 | 28 | @BeforeEach 29 | public void beforeEach() { 30 | List> tables = dslContext.meta().getTables("t_user"); 31 | userTable = tables.get(0); 32 | 33 | List> tables1 = dslContext.meta().getTables("t_order"); 34 | orderTable = tables1.get(0); 35 | } 36 | 37 | @Test 38 | void testUserAndOrderUnion() { 39 | MultiTenancyStorage.setTenantID(2); 40 | 41 | Result fetch = dslContext 42 | .select() 43 | .from(userTable) 44 | .union(select() 45 | .from(orderTable)) 46 | .fetch(); 47 | 48 | MultiTenancyStorage.setTenantID(null); 49 | 50 | Assertions.assertEquals(4, fetch.size()); 51 | } 52 | 53 | @Test 54 | void testUserAndOrderInnerJoin() { 55 | MultiTenancyStorage.setTenantID(2); 56 | 57 | Result fetch = dslContext 58 | .select() 59 | .from(userTable) 60 | .innerJoin(orderTable) 61 | .on(userTable.field("user_id") 62 | .eq(orderTable.field("user_id"))) 63 | .fetch(); 64 | 65 | MultiTenancyStorage.setTenantID(null); 66 | 67 | Assertions.assertEquals(2, fetch.size()); 68 | } 69 | 70 | @Test 71 | void testUserAndOrderNestedQuery() { 72 | MultiTenancyStorage.setTenantID(2); 73 | 74 | Result fetch = dslContext 75 | .select() 76 | .from(userTable) 77 | .where(userTable.field("user_id") 78 | .in(select(orderTable.field("user_id")) 79 | .from(orderTable))) 80 | .fetch(); 81 | 82 | MultiTenancyStorage.setTenantID(null); 83 | 84 | Assertions.assertEquals(2, fetch.size()); 85 | } 86 | 87 | 88 | @Nested 89 | @DisplayName("Left Outer Join || Right Outer Join") 90 | class LeftOrRightOuterJoinTest { 91 | @Test 92 | void testLeftOuterJoinTwoTables() { 93 | MultiTenancyStorage.setTenantID(4); 94 | 95 | Result fetch = dslContext 96 | .select(userTable.fields()) 97 | .select(orderTable.fields()) 98 | .from(userTable) 99 | .leftOuterJoin(orderTable) 100 | .on(userTable.field("user_id") 101 | .eq(orderTable.field("user_id"))) 102 | .fetch(); 103 | 104 | MultiTenancyStorage.setTenantID(null); 105 | 106 | Assertions.assertEquals(2, fetch.size()); 107 | } 108 | 109 | @Test 110 | void testRightOuterJoinTwoTables() { 111 | MultiTenancyStorage.setTenantID(9); 112 | 113 | Result fetch = dslContext 114 | .select(userTable.fields()) 115 | .select(orderTable.fields()) 116 | .from(userTable) 117 | .rightOuterJoin(orderTable) 118 | .on(orderTable.field("user_id") 119 | .eq(userTable.field("user_id"))) 120 | .fetch(); 121 | 122 | MultiTenancyStorage.setTenantID(null); 123 | 124 | Assertions.assertEquals(3, fetch.size()); 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLQueryViewTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Result; 7 | import org.jooq.Table; 8 | import org.junit.jupiter.api.Assertions; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.test.context.ActiveProfiles; 14 | 15 | import java.util.List; 16 | 17 | @SpringBootTest 18 | @ActiveProfiles("test") 19 | class TenantSQLQueryViewTest { 20 | 21 | @Autowired 22 | private DSLContext dslContext; 23 | 24 | private Table userView; 25 | 26 | @BeforeEach 27 | public void beforeEach() { 28 | List> tables = dslContext.meta().getTables("v_user"); 29 | userView = tables.get(0); 30 | } 31 | 32 | @Test 33 | void testUserViewQuery() { 34 | MultiTenancyStorage.setTenantID(4); 35 | 36 | Result fetch = dslContext 37 | .select() 38 | .from(userView) 39 | .fetch(); 40 | 41 | MultiTenancyStorage.setTenantID(null); 42 | 43 | Assertions.assertEquals(2, fetch.size()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLSelfJoinTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Result; 7 | import org.jooq.Table; 8 | import org.junit.jupiter.api.*; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.ActiveProfiles; 12 | 13 | import java.util.List; 14 | 15 | @SpringBootTest 16 | @ActiveProfiles("test") 17 | public class TenantSQLSelfJoinTest { 18 | 19 | @Autowired 20 | private DSLContext dslContext; 21 | 22 | private Table departmentTable; 23 | 24 | @BeforeEach 25 | public void beforeEach() { 26 | List> tables = dslContext.meta().getTables("t_department"); 27 | departmentTable = tables.get(0); 28 | } 29 | 30 | @Test 31 | void testSelfInnerJoin() { 32 | MultiTenancyStorage.setTenantID(1); 33 | 34 | Table c = departmentTable.as("c"); 35 | Result fetch = dslContext 36 | .select(c.field("id"), 37 | c.field("department_id"), 38 | c.field("department_name"), 39 | c.field("parent_department_id"), 40 | c.field("tenant_id")) 41 | .from(c) 42 | .innerJoin(departmentTable) 43 | .on(c.field("parent_department_id").eq(departmentTable.field("department_id"))) 44 | .fetch(); 45 | 46 | MultiTenancyStorage.setTenantID(null); 47 | 48 | Assertions.assertEquals(6, fetch.size()); 49 | } 50 | 51 | @Nested 52 | @DisplayName("Left Outer Join || Right Outer Join") 53 | class LeftOrRightOuterJoinTest { 54 | @Test 55 | void testSelfLeftJoin() { 56 | MultiTenancyStorage.setTenantID(1); 57 | 58 | Table c = departmentTable.as("c"); 59 | Result fetch = dslContext 60 | .select(c.field("id"), 61 | c.field("department_id"), 62 | c.field("department_name"), 63 | c.field("parent_department_id"), 64 | c.field("tenant_id"), 65 | departmentTable.field("department_name").as("parent_department_name")) 66 | .from(c) 67 | .leftOuterJoin(departmentTable) 68 | .on(c.field("parent_department_id").eq(departmentTable.field("department_id"))) 69 | .fetch(); 70 | 71 | MultiTenancyStorage.setTenantID(null); 72 | 73 | Assertions.assertEquals(7, fetch.size()); 74 | } 75 | 76 | @Test 77 | void testSelfRightJoin() { 78 | MultiTenancyStorage.setTenantID(1); 79 | 80 | Table c = departmentTable.as("c"); 81 | Result fetch = dslContext 82 | .select(departmentTable.field("id"), 83 | departmentTable.field("department_id"), 84 | departmentTable.field("department_name"), 85 | departmentTable.field("parent_department_id"), 86 | departmentTable.field("tenant_id"), 87 | c.field("department_name").as("parent_department_name")) 88 | .from(c) 89 | .rightOuterJoin(departmentTable) 90 | .on(departmentTable.field("parent_department_id").eq(c.field("department_id"))) 91 | .fetch(); 92 | 93 | MultiTenancyStorage.setTenantID(null); 94 | 95 | Assertions.assertEquals(7, fetch.size()); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/java/com/example/multitenancylibrary/sql/TenantSQLUpdateTest.java: -------------------------------------------------------------------------------- 1 | package com.example.multitenancylibrary.sql; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.jooq.DSLContext; 5 | import org.jooq.Record; 6 | import org.jooq.Result; 7 | import org.jooq.Table; 8 | import org.junit.jupiter.api.Assertions; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.test.context.ActiveProfiles; 14 | 15 | import java.util.List; 16 | import java.util.UUID; 17 | 18 | import static org.jooq.impl.DSL.row; 19 | 20 | @SpringBootTest 21 | @ActiveProfiles("test") 22 | class TenantSQLUpdateTest { 23 | 24 | @Autowired 25 | private DSLContext dslContext; 26 | 27 | private Table userTable; 28 | 29 | @BeforeEach 30 | public void beforeEach() { 31 | List> tables = dslContext.meta().getTables("t_user"); 32 | userTable = tables.get(0); 33 | } 34 | 35 | @Test 36 | void testUserTableUpdate() { 37 | MultiTenancyStorage.setTenantID(100); 38 | 39 | String updatedValue = UUID.randomUUID().toString(); 40 | 41 | int execute = dslContext 42 | .update(userTable) 43 | .set(row(userTable.field("user_name")), row(updatedValue)) 44 | .where(userTable.field("user_id").eq("uid100")) 45 | .execute(); 46 | Assertions.assertEquals(1, execute); 47 | 48 | Result fetch = dslContext 49 | .select() 50 | .from(userTable) 51 | .fetch(); 52 | Assertions.assertEquals(updatedValue, fetch.getValues("user_name").get(0)); 53 | MultiTenancyStorage.setTenantID(null); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/resources/data-h2.sql: -------------------------------------------------------------------------------- 1 | -- t_user 2 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 3 | VALUES ('uid0', 1, 'uname0'); 4 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 5 | VALUES ('uid1', 1, 'uname1'); 6 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 7 | VALUES ('uid1', 1, 'uname1'); 8 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 9 | VALUES ('uid2', 2, 'uname2'); 10 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 11 | VALUES ('uid3', 2, 'uname3'); 12 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 13 | VALUES ('uid4', 4, 'uname4'); 14 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 15 | VALUES ('uid5', 4, 'uname5'); 16 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 17 | VALUES ('uid6', 5, 'uname6'); 18 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 19 | VALUES ('uid9', 9, 'uname9'); 20 | INSERT INTO t_user ("user_id", "tenant_id", "user_name") 21 | VALUES ('uid100', 100, 'uname100'); 22 | 23 | -- t_order 24 | INSERT INTO t_order ("user_id", "order_id", "tenant_id") 25 | VALUES ('uid1', 'ord1', 1); 26 | INSERT INTO t_order ("user_id", "order_id", "tenant_id") 27 | VALUES ('uid2', 'ord1', 2); 28 | INSERT INTO t_order ("user_id", "order_id", "tenant_id") 29 | VALUES ('uid3', 'ord1', 2); 30 | INSERT INTO t_order ("user_id", "order_id", "tenant_id") 31 | VALUES ('uid9', 'ord1', 9); 32 | INSERT INTO t_order ("user_id", "order_id", "tenant_id") 33 | VALUES ('uid9', 'ord2', 9); 34 | INSERT INTO t_order ("user_id", "order_id", "tenant_id") 35 | VALUES ('uid10', 'ord1', 9); 36 | 37 | -- t_order_detail 38 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 39 | VALUES ('ord1', 1, 1); 40 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 41 | VALUES ('ord2', 2, 2); 42 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 43 | VALUES ('ord3', 3, 3); 44 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 45 | VALUES ('ord4', 4, 4); 46 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 47 | VALUES ('ord9', 4, 9); 48 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 49 | VALUES ('ord1', 4, 9); 50 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 51 | VALUES ('ord1', 4, 9); 52 | INSERT INTO t_order_detail ("order_id", "quantity", "tenant_id") 53 | VALUES ('ord1', 4, 9); 54 | 55 | -- t_department 56 | INSERT INTO t_department ("department_id", "department_name", "tenant_id") 57 | VALUES (1, 'aaa', 1); 58 | INSERT INTO t_department ("department_id", "department_name", "parent_department_id", "tenant_id") 59 | VALUES (2, 'bbb', 1, 1); 60 | INSERT INTO t_department ("department_id", "department_name", "parent_department_id", "tenant_id") 61 | VALUES (3, 'ccc', 1, 1); 62 | INSERT INTO t_department ("department_id", "department_name", "parent_department_id", "tenant_id") 63 | VALUES (4, 'ddd', 1, 1); 64 | INSERT INTO t_department ("department_id", "department_name", "parent_department_id", "tenant_id") 65 | VALUES (5, 'bbb', 2, 1); 66 | INSERT INTO t_department ("department_id", "department_name", "parent_department_id", "tenant_id") 67 | VALUES (6, 'ccc', 2, 1); 68 | INSERT INTO t_department ("department_id", "department_name", "parent_department_id", "tenant_id") 69 | VALUES (7, 'ddd', 2, 1); -------------------------------------------------------------------------------- /multi-tenancy-library/src/test/resources/schema-h2.sql: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA IF NOT EXISTS public; 2 | 3 | DROP VIEW IF EXISTS v_user; 4 | DROP TABLE IF EXISTS t_user; 5 | DROP TABLE IF EXISTS t_order; 6 | DROP TABLE IF EXISTS t_order_detail; 7 | DROP TABLE IF EXISTS t_department; 8 | 9 | -- t_user 10 | CREATE TABLE t_user 11 | ( 12 | id INT AUTO_INCREMENT PRIMARY KEY, 13 | user_id VARCHAR(255) NOT NULL, 14 | user_name VARCHAR(255), 15 | tenant_id INT NOT NULL 16 | ); 17 | -- t_order 18 | CREATE TABLE t_order 19 | ( 20 | id INT AUTO_INCREMENT PRIMARY KEY, 21 | user_id VARCHAR(255) NOT NULL, 22 | order_id VARCHAR(255) NOT NULL, 23 | tenant_id INT NOT NULL 24 | ); 25 | -- t_order_detail 26 | CREATE TABLE t_order_detail 27 | ( 28 | id INT AUTO_INCREMENT PRIMARY KEY, 29 | order_id VARCHAR(255) NOT NULL, 30 | quantity INT NOT NULL, 31 | tenant_id INT NOT NULL 32 | ); 33 | -- t_department 34 | CREATE TABLE t_department 35 | ( 36 | id INT AUTO_INCREMENT PRIMARY KEY, 37 | department_id INT NOT NULL, 38 | department_name VARCHAR(255) NOT NULL, 39 | parent_department_id INT, 40 | tenant_id INT NOT NULL 41 | ); 42 | -- v_user 43 | CREATE VIEW v_user AS 44 | SELECT * 45 | FROM t_user; -------------------------------------------------------------------------------- /rls/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /rls/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'nu.studer.jooq' 2 | 3 | repositories { 4 | mavenLocal() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | jooqGenerator 'org.postgresql:postgresql:42.5.0' 10 | runtimeOnly 'org.postgresql:postgresql' 11 | implementation 'org.springframework.boot:spring-boot-starter-jooq' 12 | implementation 'org.springframework.boot:spring-boot-starter-web' 13 | } 14 | 15 | jooq { 16 | // use jOOQ version defined in Spring Boot 17 | version = dependencyManagement.importedProperties['jooq.version'] 18 | // edition = JooqEdition.OSS 19 | 20 | configurations { 21 | main { 22 | generationTool { 23 | logging = org.jooq.meta.jaxb.Logging.WARN 24 | jdbc { 25 | driver = 'org.postgresql.Driver' 26 | url = 'jdbc:postgresql://127.0.0.1:5432/postgres' 27 | user = 'postgres' 28 | password = '123456' 29 | properties { 30 | property { 31 | key = 'PAGE_SIZE' 32 | value = 2048 33 | } 34 | } 35 | } 36 | generator { 37 | database { 38 | name = 'org.jooq.meta.postgres.PostgresDatabase' 39 | inputSchema = 'rls' 40 | includes = '.*' 41 | excludes = '' 42 | } 43 | generate { 44 | deprecated = false 45 | records = true 46 | immutablePojos = true 47 | fluentSetters = true 48 | } 49 | target { 50 | packageName = 'com.khch.jooq' 51 | } 52 | strategy.name = "org.jooq.codegen.DefaultGeneratorStrategy" 53 | } 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /rls/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springmonster/multi-tenancy/6e7e3cefc9c61522915de8dbc01b8ecb9576039d/rls/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /rls/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /rls/rest-api.http: -------------------------------------------------------------------------------- 1 | ### 0 create user 2 | POST http://localhost:8082/user/create 3 | Content-Type: application/json 4 | X-TenantID: 4 5 | 6 | { 7 | "userId": "uid5", 8 | "tenantId": 4, 9 | "userName": "uname5" 10 | } 11 | 12 | ### 1 get all users 13 | GET http://localhost:8082/users 14 | Content-Type: application/json 15 | X-TenantID: 2 16 | 17 | ### 2 get all orders 18 | GET http://localhost:8082/orders 19 | Content-Type: application/json 20 | X-TenantID: 1 21 | 22 | ### 3 get users and orders 23 | GET http://localhost:8082/users-orders 24 | Content-Type: application/json 25 | X-TenantID: 1 26 | 27 | ### 4 update user 28 | PUT http://localhost:8082/user/uid5?username=james bond 29 | Content-Type: application/json 30 | X-TenantID: 4 31 | 32 | ### 5 delete user 33 | DELETE http://localhost:8082/user/uid5 34 | Content-Type: application/json 35 | X-TenantID: 4 -------------------------------------------------------------------------------- /rls/sql/ddl.sql: -------------------------------------------------------------------------------- 1 | --- CREATE USER TABLE --- 2 | CREATE TABLE rls.t_user 3 | ( 4 | id serial4 NOT NULL, 5 | user_id varchar NOT NULL, 6 | tenant_id varchar NOT NULL, 7 | user_name varchar NOT NULL, 8 | CONSTRAINT t_user_pk PRIMARY KEY (id) 9 | ); 10 | 11 | --- INSERT USER DATA --- 12 | INSERT INTO rls.t_user 13 | (user_id, tenant_id, user_name) 14 | VALUES ('uid1', 1, 'uname1'); 15 | 16 | INSERT INTO rls.t_user 17 | (user_id, tenant_id, user_name) 18 | VALUES ('uid2', 1, 'uname2'); 19 | 20 | INSERT INTO rls.t_user 21 | (user_id, tenant_id, user_name) 22 | VALUES ('uid3', 2, 'uname3'); 23 | 24 | INSERT INTO rls.t_user 25 | (user_id, tenant_id, user_name) 26 | VALUES ('uid4', 3, 'uname4'); 27 | -------------------------------------------------------------------------------- /rls/sql/policies.sql: -------------------------------------------------------------------------------- 1 | -- CREATE POSTGRES USER 2 | CREATE ROLE app_user LOGIN PASSWORD 'app_user'; 3 | 4 | -- GRANT PERMISSIONS TO APP_USER 5 | GRANT 6 | ALL 7 | ON SCHEMA rls TO app_user; 8 | 9 | GRANT 10 | ALL 11 | ON SEQUENCE rls.t_user_id_seq TO app_user; 12 | 13 | GRANT ALL 14 | ON TABLE rls.t_user TO app_user; 15 | 16 | -- ENABLE ROW LEVEL SECURITY 17 | ALTER TABLE rls.t_user ENABLE ROW LEVEL SECURITY; 18 | 19 | -- CREATE POLICIES 20 | CREATE 21 | POLICY select_tenant_isolation_policy ON rls.t_user 22 | FOR 23 | SELECT 24 | USING (tenant_id = current_setting('app.current_tenant'):: VARCHAR); 25 | 26 | CREATE 27 | POLICY update_tenant_isolation_policy ON rls.t_user 28 | FOR 29 | UPDATE 30 | USING (tenant_id = current_setting('app.current_tenant'):: VARCHAR); 31 | 32 | CREATE 33 | POLICY delete_tenant_isolation_policy ON rls.t_user 34 | FOR DELETE 35 | USING (tenant_id = current_setting('app.current_tenant')::VARCHAR); 36 | 37 | CREATE 38 | POLICY insert_tenant_isolation_policy ON rls.t_user 39 | FOR INSERT 40 | WITH CHECK(true); 41 | 42 | -- CHECK ALL POLICIES 43 | select * 44 | from pg_policies; -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/SpringbootPostgresJooqApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootPostgresJooqApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootPostgresJooqApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.controller; 2 | 3 | import com.example.springbootpostgresjooq.model.UserInput; 4 | import com.khch.jooq.Tables; 5 | import com.khch.jooq.tables.pojos.TUser; 6 | import org.jooq.DSLContext; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.util.List; 11 | 12 | 13 | @RestController 14 | public class UserController { 15 | 16 | @Autowired 17 | private DSLContext dslContext; 18 | 19 | @GetMapping("/users") 20 | public List getUsers() { 21 | return dslContext.selectFrom(Tables.T_USER) 22 | .fetchInto(TUser.class); 23 | } 24 | 25 | @PostMapping("/user/create") 26 | public TUser createUser(@RequestBody UserInput userInput) { 27 | dslContext.insertInto(Tables.T_USER) 28 | .set(Tables.T_USER.USER_ID, userInput.getUserId()) 29 | .set(Tables.T_USER.TENANT_ID, userInput.getTenantId()) 30 | .set(Tables.T_USER.USER_NAME, userInput.getUserName()) 31 | .execute(); 32 | 33 | return dslContext.selectFrom(Tables.T_USER) 34 | .where(Tables.T_USER.USER_ID.eq(userInput.getUserId())) 35 | .fetchOneInto(TUser.class); 36 | } 37 | 38 | @PutMapping("/user/{id}") 39 | public TUser updateUser(@PathVariable("id") String userId, @RequestParam("username") String userName) { 40 | dslContext.update(Tables.T_USER) 41 | .set(Tables.T_USER.USER_NAME, userName) 42 | .where(Tables.T_USER.USER_ID.eq(userId)) 43 | .execute(); 44 | 45 | return dslContext.selectFrom(Tables.T_USER) 46 | .where(Tables.T_USER.USER_ID.eq(userId)) 47 | .fetchOneInto(TUser.class); 48 | } 49 | 50 | @DeleteMapping("/user/{id}") 51 | public TUser deleteUser(@PathVariable("id") String userId) { 52 | dslContext.deleteFrom(Tables.T_USER) 53 | .where(Tables.T_USER.USER_ID.eq(userId)) 54 | .execute(); 55 | 56 | return dslContext.selectFrom(Tables.T_USER) 57 | .where(Tables.T_USER.USER_ID.eq(userId)) 58 | .fetchOneInto(TUser.class); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/model/UserInput.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.model; 2 | 3 | public class UserInput { 4 | private String userId; 5 | private String tenantId; 6 | private String userName; 7 | 8 | public String getUserId() { 9 | return userId; 10 | } 11 | 12 | public void setUserId(String userId) { 13 | this.userId = userId; 14 | } 15 | 16 | public String getTenantId() { 17 | return tenantId; 18 | } 19 | 20 | public void setTenantId(String tenantId) { 21 | this.tenantId = tenantId; 22 | } 23 | 24 | public String getUserName() { 25 | return userName; 26 | } 27 | 28 | public void setUserName(String userName) { 29 | this.userName = userName; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/tenant/Configuration.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.tenant; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class Configuration { 8 | @Bean 9 | public RlsConnectionProvider connectionProvider() { 10 | return new RlsConnectionProvider(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/tenant/RlsConnectionProvider.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.tenant; 2 | 3 | import org.jooq.ConnectionProvider; 4 | import org.jooq.exception.DataAccessException; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import javax.sql.DataSource; 8 | import java.sql.Connection; 9 | import java.sql.SQLException; 10 | import java.sql.Statement; 11 | 12 | public class RlsConnectionProvider implements ConnectionProvider { 13 | 14 | @Autowired 15 | DataSource ds; 16 | 17 | @Override 18 | public Connection acquire() { 19 | try { 20 | Connection connection = ds.getConnection(); 21 | try (Statement sql = connection.createStatement()) { 22 | sql.execute("SET app.current_tenant = '" + ThreadLocalStorage.getTenantID() + "'"); 23 | } 24 | return connection; 25 | } catch (SQLException e) { 26 | throw new DataAccessException("Something failed", e); 27 | } 28 | } 29 | 30 | @Override 31 | public void release(Connection c) { 32 | try { 33 | c.close(); 34 | } catch (SQLException e) { 35 | throw new DataAccessException("Something failed", e); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/tenant/TenantNameInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.tenant; 2 | 3 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | public class TenantNameInterceptor extends HandlerInterceptorAdapter { 9 | 10 | @Override 11 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 12 | 13 | String tenantID = request.getHeader("X-TenantID"); 14 | ThreadLocalStorage.setTenantID(tenantID); 15 | 16 | return true; 17 | } 18 | 19 | @Override 20 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 21 | ThreadLocalStorage.setTenantID(null); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/tenant/ThreadLocalStorage.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.tenant; 2 | 3 | public class ThreadLocalStorage { 4 | 5 | private static final ThreadLocal tenant = new InheritableThreadLocal<>(); 6 | 7 | public static void setTenantID(String tenantName) { 8 | tenant.set(tenantName); 9 | } 10 | 11 | public static String getTenantID() { 12 | return tenant.get(); 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /rls/src/main/java/com/example/springbootpostgresjooq/tenant/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.tenant; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | @Configuration 8 | public class WebMvcConfig implements WebMvcConfigurer { 9 | 10 | @Override 11 | public void addInterceptors(InterceptorRegistry registry) { 12 | registry.addInterceptor(new TenantNameInterceptor()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /rls/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | datasource: 6 | url: jdbc:postgresql://127.0.0.1:5432/postgres 7 | username: app_user 8 | password: app_user 9 | driver-class-name: org.postgresql.Driver -------------------------------------------------------------------------------- /rls/src/test/java/com/example/springbootpostgresjooq/SpringbootPostgresJooqApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringbootPostgresJooqApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'MultiTenancy' 2 | 3 | include 'multi-tenancy-library' 4 | include 'springboot-postgres-jooq' 5 | include 'springboot-mysql-jooq' 6 | include 'rls' -------------------------------------------------------------------------------- /springboot-mysql-jooq/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'nu.studer.jooq' 2 | 3 | repositories { 4 | mavenLocal() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | implementation 'com.multi:tenancy:0.0.2-SNAPSHOT' 10 | implementation 'org.springframework.boot:spring-boot-starter-jooq' 11 | implementation 'org.springframework.boot:spring-boot-starter-web' 12 | jooqGenerator 'com.mysql:mysql-connector-j' 13 | runtimeOnly 'com.mysql:mysql-connector-j' 14 | } 15 | 16 | jooq { 17 | // use jOOQ version defined in Spring Boot 18 | version = dependencyManagement.importedProperties['jooq.version'] 19 | // edition = JooqEdition.OSS 20 | 21 | configurations { 22 | main { 23 | generationTool { 24 | logging = org.jooq.meta.jaxb.Logging.WARN 25 | jdbc { 26 | driver = 'com.mysql.cj.jdbc.Driver' 27 | url = 'jdbc:mysql://127.0.0.1:3306/multi_tenancy' 28 | user = 'root' 29 | password = '123456' 30 | properties { 31 | property { 32 | key = 'PAGE_SIZE' 33 | value = 2048 34 | } 35 | } 36 | } 37 | generator { 38 | database { 39 | name = 'org.jooq.meta.mysql.MySQLDatabase' 40 | inputSchema = 'multi_tenancy' 41 | includes = '.*' 42 | excludes = '' 43 | } 44 | generate { 45 | deprecated = false 46 | records = true 47 | immutablePojos = true 48 | fluentSetters = true 49 | } 50 | target { 51 | packageName = 'com.khch.jooq' 52 | } 53 | strategy.name = "org.jooq.codegen.DefaultGeneratorStrategy" 54 | } 55 | } 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /springboot-mysql-jooq/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springmonster/multi-tenancy/6e7e3cefc9c61522915de8dbc01b8ecb9576039d/springboot-mysql-jooq/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /springboot-mysql-jooq/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/rest-api.http: -------------------------------------------------------------------------------- 1 | ### 0 create user 2 | POST http://localhost:8082/user/create 3 | Content-Type: application/json 4 | X-TenantID: 4 5 | 6 | { 7 | "userId": "uid5", 8 | "tenantId": 4, 9 | "userName": "uname5" 10 | } 11 | 12 | ### 1 get all users 13 | GET http://localhost:8082/users 14 | Content-Type: application/json 15 | X-TenantID: 1 16 | 17 | ### 2 get all orders 18 | GET http://localhost:8082/orders 19 | Content-Type: application/json 20 | X-TenantID: 1 21 | 22 | ### 3 get users and orders 23 | GET http://localhost:8082/users-orders 24 | Content-Type: application/json 25 | X-TenantID: 1 26 | 27 | ### 4 update user 28 | PUT http://localhost:8082/user/uid5?username=james bond 29 | Content-Type: application/json 30 | X-TenantID: 4 31 | 32 | ### 5 delete user 33 | DELETE http://localhost:8082/user/uid5 34 | Content-Type: application/json 35 | X-TenantID: 4 -------------------------------------------------------------------------------- /springboot-mysql-jooq/sql/ddl.sql: -------------------------------------------------------------------------------- 1 | --- CREATE DATABASE --- 2 | CREATE DATABASE `multi_tenancy`; 3 | 4 | --- CREATE USER TABLE --- 5 | CREATE TABLE multi_tenancy.t_user 6 | ( 7 | id int auto_increment NOT NULL, 8 | user_id varchar(100) NOT NULL, 9 | tenant_id int NOT NULL, 10 | user_name varchar(100) NOT NULL, 11 | CONSTRAINT t_user_pk PRIMARY KEY (id) 12 | ) ENGINE=InnoDB 13 | DEFAULT CHARSET=utf8 14 | COLLATE=utf8_general_ci; 15 | 16 | --- CREATE ORDER TABLE --- 17 | CREATE TABLE multi_tenancy.t_order 18 | ( 19 | id int auto_increment NOT NULL, 20 | user_id varchar(100) NOT NULL, 21 | order_id varchar(100) NOT NULL, 22 | tenant_id int NOT NULL, 23 | CONSTRAINT t_order_pk PRIMARY KEY (id) 24 | ) ENGINE=InnoDB 25 | DEFAULT CHARSET=utf8 26 | COLLATE=utf8_general_ci; 27 | 28 | --- INSERT USER DATA --- 29 | INSERT INTO multi_tenancy.t_user 30 | (user_id, tenant_id, user_name) 31 | VALUES ('uid1', 1, 'uname1'); 32 | 33 | INSERT INTO multi_tenancy.t_user 34 | (user_id, tenant_id, user_name) 35 | VALUES ('uid2', 1, 'uname2'); 36 | 37 | INSERT INTO multi_tenancy.t_user 38 | (user_id, tenant_id, user_name) 39 | VALUES ('uid3', 2, 'uname3'); 40 | 41 | INSERT INTO multi_tenancy.t_user 42 | (user_id, tenant_id, user_name) 43 | VALUES ('uid4', 3, 'uname4'); 44 | 45 | --- INSERT ORDER DATA --- 46 | INSERT INTO multi_tenancy.t_order 47 | (user_id, order_id, tenant_id) 48 | VALUES ('uid1', 'ord1', 1); 49 | 50 | INSERT INTO multi_tenancy.t_order 51 | (user_id, order_id, tenant_id) 52 | VALUES ('uid1', 'ord2', 1); 53 | 54 | INSERT INTO multi_tenancy.t_order 55 | (user_id, order_id, tenant_id) 56 | VALUES ('uid3', 'ord1', 3); 57 | 58 | INSERT INTO multi_tenancy.t_order 59 | (user_id, order_id, tenant_id) 60 | VALUES ('uid4', 'ord1', 4); 61 | 62 | INSERT INTO multi_tenancy.t_order 63 | (user_id, order_id, tenant_id) 64 | VALUES ('uid2', 'ord1', 1); 65 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/SpringbootMysqlJooqApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootMysqlJooqApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootMysqlJooqApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/config/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq.config; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.HandlerInterceptor; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | @Configuration 13 | public class WebMvcConfig implements WebMvcConfigurer { 14 | 15 | @Override 16 | public void addInterceptors(InterceptorRegistry registry) { 17 | registry.addInterceptor(new HandlerInterceptor() { 18 | @Override 19 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 20 | String tenantID = request.getHeader("X-TenantID"); 21 | if (null == tenantID) { 22 | throw new RuntimeException("Tenant ID must not be null!"); 23 | } 24 | MultiTenancyStorage.setTenantID(Integer.valueOf(tenantID)); 25 | return true; 26 | } 27 | 28 | @Override 29 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 30 | MultiTenancyStorage.setTenantID(null); 31 | } 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq.controller; 2 | 3 | import com.khch.jooq.Tables; 4 | import com.khch.jooq.tables.pojos.TOrder; 5 | import org.jooq.DSLContext; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import java.util.List; 11 | 12 | @RestController 13 | public class OrderController { 14 | 15 | @Autowired 16 | private DSLContext dslContext; 17 | 18 | @GetMapping("/orders") 19 | public List getOrders() { 20 | return dslContext.selectFrom(Tables.T_ORDER) 21 | .fetchInto(TOrder.class); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq.controller; 2 | 3 | import com.example.springbootmysqljooq.model.UserInput; 4 | import com.khch.jooq.Tables; 5 | import com.khch.jooq.tables.pojos.TOrder; 6 | import com.khch.jooq.tables.pojos.TUser; 7 | import org.jooq.DSLContext; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import static com.khch.jooq.tables.TOrder.T_ORDER; 15 | import static com.khch.jooq.tables.TUser.T_USER; 16 | 17 | @RestController 18 | public class UserController { 19 | 20 | @Autowired 21 | private DSLContext dslContext; 22 | 23 | @GetMapping("/users") 24 | public List getUsers() { 25 | return dslContext.selectFrom(Tables.T_USER) 26 | .fetchInto(TUser.class); 27 | } 28 | 29 | @GetMapping("/users-orders") 30 | public Map> getUsersOrders() { 31 | return dslContext.select(T_USER.fields()) 32 | .select(T_ORDER.fields()) 33 | .from(T_USER) 34 | .join(T_ORDER) 35 | .on(T_USER.USER_ID.eq(T_ORDER.USER_ID)) 36 | .fetchGroups( 37 | r -> r.into(T_USER).into(TUser.class), 38 | r -> r.into(T_ORDER).into(TOrder.class) 39 | ); 40 | } 41 | 42 | @PostMapping("/user/create") 43 | public TUser createUser(@RequestBody UserInput userInput) { 44 | dslContext.insertInto(Tables.T_USER) 45 | .set(Tables.T_USER.USER_ID, userInput.getUserId()) 46 | .set(Tables.T_USER.TENANT_ID, userInput.getTenantId()) 47 | .set(Tables.T_USER.USER_NAME, userInput.getUserName()) 48 | .execute(); 49 | 50 | return dslContext.selectFrom(Tables.T_USER) 51 | .where(Tables.T_USER.USER_ID.eq(userInput.getUserId())) 52 | .fetchOneInto(TUser.class); 53 | } 54 | 55 | @PutMapping("/user/{id}") 56 | public TUser updateUser(@PathVariable("id") String userId, @RequestParam("username") String userName) { 57 | dslContext.update(Tables.T_USER) 58 | .set(Tables.T_USER.USER_NAME, userName) 59 | .where(Tables.T_USER.USER_ID.eq(userId)) 60 | .execute(); 61 | 62 | return dslContext.selectFrom(Tables.T_USER) 63 | .where(Tables.T_USER.USER_ID.eq(userId)) 64 | .fetchOneInto(TUser.class); 65 | } 66 | 67 | @DeleteMapping("/user/{id}") 68 | public TUser deleteUser(@PathVariable("id") String userId) { 69 | dslContext.deleteFrom(Tables.T_USER) 70 | .where(Tables.T_USER.USER_ID.eq(userId)) 71 | .execute(); 72 | 73 | return dslContext.selectFrom(Tables.T_USER) 74 | .where(Tables.T_USER.USER_ID.eq(userId)) 75 | .fetchOneInto(TUser.class); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/job/ScheduledJob.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq.job; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import com.khch.jooq.Tables; 5 | import com.khch.jooq.tables.pojos.TUser; 6 | import org.jooq.DSLContext; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | 10 | import java.util.List; 11 | 12 | @Component 13 | public class ScheduledJob { 14 | 15 | @Autowired 16 | private DSLContext dslContext; 17 | 18 | // @Scheduled(cron = "0/10 0/1 * * * ? ") 19 | public void schedule() { 20 | MultiTenancyStorage.setTenantID(1); 21 | 22 | List tUsers = dslContext.selectFrom(Tables.T_USER) 23 | .fetchInto(TUser.class); 24 | 25 | System.out.println(tUsers); 26 | 27 | MultiTenancyStorage.setTenantID(null); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/java/com/example/springbootmysqljooq/model/UserInput.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq.model; 2 | 3 | public class UserInput { 4 | private String userId; 5 | private int tenantId; 6 | private String userName; 7 | 8 | public String getUserId() { 9 | return userId; 10 | } 11 | 12 | public void setUserId(String userId) { 13 | this.userId = userId; 14 | } 15 | 16 | public int getTenantId() { 17 | return tenantId; 18 | } 19 | 20 | public void setTenantId(int tenantId) { 21 | this.tenantId = tenantId; 22 | } 23 | 24 | public String getUserName() { 25 | return userName; 26 | } 27 | 28 | public void setUserName(String userName) { 29 | this.userName = userName; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | multi: 5 | tenancy: 6 | enabled: true 7 | tenant-identifier: tenant_id 8 | tables: 9 | - multi_tenancy.t_user 10 | - multi_tenancy.t_order 11 | sql-check-filters-exist: true 12 | sql-auto-add-filters: true 13 | 14 | logging: 15 | level: 16 | com.example.multitenancylibrary: DEBUG 17 | 18 | spring: 19 | datasource: 20 | url: jdbc:mysql://127.0.0.1:3306/multi_tenancy 21 | username: root 22 | password: 123456 23 | driver-class-name: com.mysql.cj.jdbc.Driver 24 | -------------------------------------------------------------------------------- /springboot-mysql-jooq/src/test/java/com/example/springbootmysqljooq/SpringbootMysqlJooqApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootmysqljooq; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringbootMysqlJooqApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'nu.studer.jooq' 2 | 3 | repositories { 4 | mavenLocal() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | // implementation 'com.multi:tenancy:0.0.2-SNAPSHOT' 10 | implementation project(':multi-tenancy-library') 11 | jooqGenerator 'org.postgresql:postgresql:42.5.0' 12 | runtimeOnly 'org.postgresql:postgresql' 13 | implementation 'org.springframework.boot:spring-boot-starter-jooq' 14 | implementation 'org.springframework.boot:spring-boot-starter-web' 15 | } 16 | 17 | jooq { 18 | // use jOOQ version defined in Spring Boot 19 | version = dependencyManagement.importedProperties['jooq.version'] 20 | // edition = JooqEdition.OSS 21 | 22 | configurations { 23 | main { 24 | generationTool { 25 | logging = org.jooq.meta.jaxb.Logging.WARN 26 | jdbc { 27 | driver = 'org.postgresql.Driver' 28 | url = 'jdbc:postgresql://127.0.0.1:5432/postgres' 29 | user = 'postgres' 30 | password = '123456' 31 | properties { 32 | property { 33 | key = 'PAGE_SIZE' 34 | value = 2048 35 | } 36 | } 37 | } 38 | generator { 39 | database { 40 | name = 'org.jooq.meta.postgres.PostgresDatabase' 41 | inputSchema = 'public' 42 | includes = '.*' 43 | excludes = '' 44 | } 45 | generate { 46 | deprecated = false 47 | records = true 48 | immutablePojos = true 49 | fluentSetters = true 50 | } 51 | target { 52 | packageName = 'com.khch.jooq' 53 | } 54 | strategy.name = "org.jooq.codegen.DefaultGeneratorStrategy" 55 | } 56 | } 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /springboot-postgres-jooq/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springmonster/multi-tenancy/6e7e3cefc9c61522915de8dbc01b8ecb9576039d/springboot-postgres-jooq/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /springboot-postgres-jooq/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/rest-api.http: -------------------------------------------------------------------------------- 1 | ### 0 create user 2 | POST http://localhost:8081/user/create 3 | Content-Type: application/json 4 | X-TenantID: 4 5 | 6 | { 7 | "userId": "uid5", 8 | "tenantId": 4, 9 | "userName": "uname5" 10 | } 11 | 12 | ### 1 get all users 13 | GET http://localhost:8081/users 14 | Content-Type: application/json 15 | X-TenantID: 1 16 | 17 | ### 1.1 get all users alias 18 | GET http://localhost:8081/users-alias 19 | Content-Type: application/json 20 | X-TenantID: 1 21 | 22 | ### 2 get all orders 23 | GET http://localhost:8081/orders 24 | Content-Type: application/json 25 | X-TenantID: 1 26 | 27 | ### 3 get users and orders 28 | GET http://localhost:8081/users-orders 29 | Content-Type: application/json 30 | X-TenantID: 1 31 | 32 | ### 4 update user 33 | PUT http://localhost:8081/user/uid5?username=james bond 34 | Content-Type: application/json 35 | X-TenantID: 4 36 | 37 | ### 5 delete user 38 | DELETE http://localhost:8081/user/uid5 39 | Content-Type: application/json 40 | X-TenantID: 4 -------------------------------------------------------------------------------- /springboot-postgres-jooq/sql/ddl.sql: -------------------------------------------------------------------------------- 1 | --- CREATE USER TABLE --- 2 | CREATE TABLE public.t_user 3 | ( 4 | id serial4 NOT NULL, 5 | user_id varchar NOT NULL, 6 | tenant_id int4 NOT NULL, 7 | user_name varchar NOT NULL, 8 | CONSTRAINT t_user_pk PRIMARY KEY (id) 9 | ); 10 | 11 | --- CREATE ORDER TABLE --- 12 | CREATE TABLE public.t_order 13 | ( 14 | id serial4 NOT NULL, 15 | user_id varchar NOT NULL, 16 | order_id varchar NOT NULL, 17 | tenant_id int4 NOT NULL, 18 | CONSTRAINT t_order_pk PRIMARY KEY (id) 19 | ); 20 | 21 | --- INSERT USER DATA --- 22 | INSERT INTO public.t_user 23 | (user_id, tenant_id, user_name) 24 | VALUES ('uid1', 1, 'uname1'); 25 | 26 | INSERT INTO public.t_user 27 | (user_id, tenant_id, user_name) 28 | VALUES ('uid2', 1, 'uname2'); 29 | 30 | INSERT INTO public.t_user 31 | (user_id, tenant_id, user_name) 32 | VALUES ('uid3', 2, 'uname3'); 33 | 34 | INSERT INTO public.t_user 35 | (user_id, tenant_id, user_name) 36 | VALUES ('uid4', 3, 'uname4'); 37 | 38 | --- INSERT ORDER DATA --- 39 | INSERT INTO public.t_order 40 | (user_id, order_id, tenant_id) 41 | VALUES ('uid1', 'ord1', 1); 42 | 43 | INSERT INTO public.t_order 44 | (user_id, order_id, tenant_id) 45 | VALUES ('uid1', 'ord2', 1); 46 | 47 | INSERT INTO public.t_order 48 | (user_id, order_id, tenant_id) 49 | VALUES ('uid3', 'ord1', 3); 50 | 51 | INSERT INTO public.t_order 52 | (user_id, order_id, tenant_id) 53 | VALUES ('uid4', 'ord1', 4); 54 | 55 | INSERT INTO public.t_order 56 | (user_id, order_id, tenant_id) 57 | VALUES ('uid2', 'ord1', 1); 58 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/SpringbootPostgresJooqApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.scheduling.annotation.EnableScheduling; 6 | 7 | @EnableScheduling 8 | @SpringBootApplication 9 | public class SpringbootPostgresJooqApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringbootPostgresJooqApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/config/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.config; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.HandlerInterceptor; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 | 9 | import javax.servlet.http.HttpServletRequest; 10 | import javax.servlet.http.HttpServletResponse; 11 | 12 | @Configuration 13 | public class WebMvcConfig implements WebMvcConfigurer { 14 | 15 | @Override 16 | public void addInterceptors(InterceptorRegistry registry) { 17 | registry.addInterceptor(new HandlerInterceptor() { 18 | @Override 19 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 20 | String tenantID = request.getHeader("X-TenantID"); 21 | if (null == tenantID) { 22 | throw new RuntimeException("Tenant ID must not be null!"); 23 | } 24 | MultiTenancyStorage.setTenantID(Integer.valueOf(tenantID)); 25 | return true; 26 | } 27 | 28 | @Override 29 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 30 | MultiTenancyStorage.setTenantID(null); 31 | } 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.controller; 2 | 3 | import com.khch.jooq.Tables; 4 | import com.khch.jooq.tables.pojos.TOrder; 5 | import org.jooq.DSLContext; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import java.util.List; 11 | 12 | @RestController 13 | public class OrderController { 14 | 15 | @Autowired 16 | private DSLContext dslContext; 17 | 18 | @GetMapping("/orders") 19 | public List getOrders() { 20 | return dslContext.selectFrom(Tables.T_ORDER) 21 | .fetchInto(TOrder.class); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.controller; 2 | 3 | import com.example.springbootpostgresjooq.model.UserInput; 4 | import com.khch.jooq.Tables; 5 | import com.khch.jooq.tables.pojos.TOrder; 6 | import com.khch.jooq.tables.pojos.TUser; 7 | import org.jooq.DSLContext; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import static com.khch.jooq.tables.TOrder.T_ORDER; 15 | import static com.khch.jooq.tables.TUser.T_USER; 16 | 17 | @RestController 18 | public class UserController { 19 | 20 | @Autowired 21 | private DSLContext dslContext; 22 | 23 | @GetMapping("/users") 24 | public List getUsers() { 25 | return dslContext.selectFrom(Tables.T_USER) 26 | .fetchInto(TUser.class); 27 | } 28 | 29 | @GetMapping("/users-alias") 30 | public List getUsersAlias() { 31 | return dslContext.selectFrom(Tables.T_USER.as("t_alias_user")) 32 | .fetchInto(TUser.class); 33 | } 34 | 35 | @GetMapping("/users-orders") 36 | public Map> getUsersOrders() { 37 | return dslContext.select(T_USER.fields()) 38 | .select(T_ORDER.fields()) 39 | .from(T_USER) 40 | .rightJoin(T_ORDER) 41 | .on(T_USER.USER_ID.eq(T_ORDER.USER_ID)) 42 | .fetchGroups( 43 | r -> r.into(T_USER).into(TUser.class), 44 | r -> r.into(T_ORDER).into(TOrder.class) 45 | ); 46 | } 47 | 48 | @PostMapping("/user/create") 49 | public TUser createUser(@RequestBody UserInput userInput) { 50 | dslContext.insertInto(Tables.T_USER) 51 | .set(Tables.T_USER.USER_ID, userInput.getUserId()) 52 | .set(Tables.T_USER.TENANT_ID, userInput.getTenantId()) 53 | .set(Tables.T_USER.USER_NAME, userInput.getUserName()) 54 | .execute(); 55 | 56 | return dslContext.selectFrom(Tables.T_USER) 57 | .where(Tables.T_USER.USER_ID.eq(userInput.getUserId())) 58 | .fetchOneInto(TUser.class); 59 | } 60 | 61 | @PutMapping("/user/{id}") 62 | public TUser updateUser(@PathVariable("id") String userId, @RequestParam("username") String userName) { 63 | dslContext.update(Tables.T_USER) 64 | .set(Tables.T_USER.USER_NAME, userName) 65 | .where(Tables.T_USER.USER_ID.eq(userId)) 66 | .execute(); 67 | 68 | return dslContext.selectFrom(Tables.T_USER) 69 | .where(Tables.T_USER.USER_ID.eq(userId)) 70 | .fetchOneInto(TUser.class); 71 | } 72 | 73 | @DeleteMapping("/user/{id}") 74 | public TUser deleteUser(@PathVariable("id") String userId) { 75 | dslContext.deleteFrom(Tables.T_USER) 76 | .where(Tables.T_USER.USER_ID.eq(userId)) 77 | .execute(); 78 | 79 | return dslContext.selectFrom(Tables.T_USER) 80 | .where(Tables.T_USER.USER_ID.eq(userId)) 81 | .fetchOneInto(TUser.class); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/job/ScheduledJob.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.job; 2 | 3 | import com.example.multitenancylibrary.network.MultiTenancyStorage; 4 | import com.khch.jooq.Tables; 5 | import com.khch.jooq.tables.pojos.TUser; 6 | import org.jooq.DSLContext; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | 10 | import java.util.List; 11 | 12 | @Component 13 | public class ScheduledJob { 14 | 15 | @Autowired 16 | private DSLContext dslContext; 17 | 18 | // @Scheduled(cron = "0/10 0/1 * * * ? ") 19 | public void schedule() { 20 | MultiTenancyStorage.setTenantID(1); 21 | 22 | List tUsers = dslContext.selectFrom(Tables.T_USER) 23 | .fetchInto(TUser.class); 24 | 25 | System.out.println(tUsers); 26 | 27 | MultiTenancyStorage.setTenantID(null); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/java/com/example/springbootpostgresjooq/model/UserInput.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq.model; 2 | 3 | public class UserInput { 4 | private String userId; 5 | private int tenantId; 6 | private String userName; 7 | 8 | public String getUserId() { 9 | return userId; 10 | } 11 | 12 | public void setUserId(String userId) { 13 | this.userId = userId; 14 | } 15 | 16 | public int getTenantId() { 17 | return tenantId; 18 | } 19 | 20 | public void setTenantId(int tenantId) { 21 | this.tenantId = tenantId; 22 | } 23 | 24 | public String getUserName() { 25 | return userName; 26 | } 27 | 28 | public void setUserName(String userName) { 29 | this.userName = userName; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8081 3 | 4 | multi: 5 | tenancy: 6 | enabled: true 7 | tenant-identifier: tenant_id 8 | tables: 9 | - public.t_user 10 | - public.t_order 11 | sql-check-filters-exist: true 12 | sql-auto-add-filters: true 13 | 14 | logging: 15 | level: 16 | com.example.multitenancylibrary: DEBUG 17 | 18 | spring: 19 | datasource: 20 | url: jdbc:postgresql://127.0.0.1:5432/postgres 21 | username: postgres 22 | password: 123456 23 | driver-class-name: org.postgresql.Driver -------------------------------------------------------------------------------- /springboot-postgres-jooq/src/test/java/com/example/springbootpostgresjooq/SpringbootPostgresJooqApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootpostgresjooq; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringbootPostgresJooqApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------