66 Commits
2.1.0 ... 2.2.0

Author SHA1 Message Date
72a7aa7273 Merge pull request #32 from flecomte/minor_fix 2022-10-15 00:41:25 +02:00
8da69d1288 clean syntax 2022-10-15 00:38:55 +02:00
dab7358e39 typo 2022-10-15 00:38:54 +02:00
a2b8483967 clean RequesterTest.kt 2022-10-15 00:38:53 +02:00
f835685c30 clean ConnectionTest.kt 2022-10-15 00:38:53 +02:00
18e9bddff5 clean Migrations.kt 2022-10-15 00:38:52 +02:00
0491a444aa Fix enum class Status() 2022-10-15 00:38:51 +02:00
6522818cde Merge pull request #31 from flecomte/update 2022-10-15 00:38:13 +02:00
4392f1ff8f optimise regex 2022-10-15 00:35:18 +02:00
927eff7172 remove jcenter 2022-10-15 00:35:17 +02:00
f06bdd732e Update tests libraries 2022-10-15 00:35:16 +02:00
1b3616df59 Update ktlint 2022-10-15 00:35:15 +02:00
38170246dd Update com.avast.gradle.docker-compose 2022-10-15 00:35:15 +02:00
c5c271506f Update jasync 2022-10-15 00:35:14 +02:00
c5a9efe8df Update fasterxml 2022-10-15 00:35:13 +02:00
0f10b6308e Update logback 2022-10-15 00:35:12 +02:00
d6d79ab4d7 Update kotlin 1.7.20 2022-10-15 00:35:06 +02:00
29986895cf Update Badge 2021-09-28 23:03:37 +02:00
b94a9ec5a7 Update gradle & jdk 2021-09-28 01:42:10 +02:00
4e4816eb77 Update documentation 2021-09-28 01:39:21 +02:00
ac2afbcf93 Merge pull request #28 from flecomte/improve-tests
improve-tests and clean library
2021-07-20 02:24:22 +02:00
2b89fee027 fix doc link 2021-07-20 02:06:18 +02:00
7b962a779d Add transaction test 2021-07-20 02:02:05 +02:00
a970a5b885 Add more test 2021-07-20 01:26:26 +02:00
5ebcba73f4 Add more test 2021-07-19 02:57:05 +02:00
05759c9b47 Add more test and fix some incoherence
remove useless "perform" method
2021-07-19 02:21:46 +02:00
bd88e7938d apply "replaceNamedArgByQuestionMark" on exec() function 2021-07-18 04:01:21 +02:00
0288a57ed9 Add more tests 2021-07-18 02:54:35 +02:00
11cff350ed clean code 2021-07-18 02:42:09 +02:00
ab1422ec16 Escape SQL argument for sendQuery 2021-07-18 02:41:44 +02:00
a4a4ef5f6f Add more tests
remove "sendQuery" on function
sendQuery now return QueryResult
remove null on queryError message
2021-07-18 01:19:27 +02:00
35d43abc4b Add documentation on methods 2021-07-17 23:42:55 +02:00
71742c0c4f remove default parameter for sendQuery 2021-07-17 19:06:01 +02:00
6e9175d84f create Exception QueryError
test select paginated without total
2021-07-17 18:55:39 +02:00
7a0ef83211 test call request return nothing 2021-07-17 16:32:49 +02:00
23b4a17505 Add arguments to gradle test 2021-07-17 16:32:18 +02:00
fa66114d01 test call request without args 2021-07-17 15:52:03 +02:00
a2f265d227 Test connexion update Entity 2021-07-17 15:18:12 +02:00
aa70ea9170 add extention "toTypeReference" 2021-07-17 15:17:49 +02:00
fdc6681f27 Add gradle argument to stay on the pg container 2021-07-17 15:15:59 +02:00
95e7a32747 Extract Reified method of connection to Extension
Add update method
2021-07-17 14:05:50 +02:00
69f85b5bf5 Extract Reified method to Extension
Add update method
2021-07-16 04:32:08 +02:00
eb3a732440 Rename select to selectOne 2021-07-15 03:10:18 +02:00
8a5697cd31 Add tests 2021-07-14 23:51:42 +02:00
b70230fd4c remove useless Migration.status() 2021-07-14 23:45:10 +02:00
682fd5caba clean Requester 2021-07-14 23:30:29 +02:00
486b038ad2 remove RequesterFactory 2021-07-14 22:51:31 +02:00
4ad69238c7 Add tests 2021-07-14 21:31:47 +02:00
4ff30e1201 Remove update object by deserialize 2021-07-14 20:18:45 +02:00
8a848fd3dc Add documentation for paginated and multi level request 2021-07-14 03:32:46 +02:00
414dec1f98 Create documentation 2021-07-11 19:07:29 +02:00
b8331e7420 increase gradle memory 2021-07-01 01:44:02 +02:00
6957a325fe Add Readme 2021-07-01 01:18:50 +02:00
9804bf5246 Merge pull request #27 from flecomte/update-project
Update project
2021-07-01 01:11:11 +02:00
58bb85ff1a update kotlin 2021-07-01 01:06:57 +02:00
f98b26b22c remove useless default argument in RequesterFactory 2021-07-01 01:01:18 +02:00
b06a92209c update postgresql version 2021-07-01 01:01:18 +02:00
6aa7f5568b update gradle 2021-07-01 01:01:18 +02:00
a839370b27 Send analysis to sonarqube 2021-07-01 01:01:17 +02:00
6b5323f70d Publish on CI 2021-06-30 23:57:59 +02:00
0de6f13eee change domain 2021-06-30 23:57:30 +02:00
c6da94a6e5 Merge pull request #26
action
2021-03-20 15:01:30 +01:00
93ce3831f4 init github action 2021-03-20 14:42:38 +01:00
4b28f64c43 Sort sql files on walk 2021-03-20 14:33:18 +01:00
35a8712eef fix select on query with no result 2021-02-27 01:29:21 +01:00
b200b3579a Improve gradle tasks 2021-02-27 00:19:30 +01:00
64 changed files with 2236 additions and 779 deletions

76
.github/workflows/gradle.yml vendored Normal file
View File

@@ -0,0 +1,76 @@
name: Tests
on:
push:
branches:
- 'master'
pull_request:
branches:
- 'master'
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11
- name: Cache Gradle packages
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Build
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: build -x test -x ktlintKotlinScriptCheck -x ktlintTestSourceSetCheck -x ktlintMainSourceSetCheck
- name: Cleanup Gradle Cache
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions.
# Restoring these files from a GitHub Actions cache might cause problems for future builds.
run: |
rm -f ~/.gradle/caches/modules-2/modules-2.lock
rm -f ~/.gradle/caches/modules-2/gc.properties
- name: Lint
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: ktlintCheck
- name: Test
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: test
- name: Coverage
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: jacocoTestReport
- name: Cache SonarCloud packages
uses: actions/cache@v1
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Push analyse to sonarqube
uses: eskatos/gradle-command-action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
gradle-version: '7.1'
arguments: sonarqube --info

53
.github/workflows/publish.yml vendored Normal file
View File

@@ -0,0 +1,53 @@
name: Publish
on:
release:
types: [ published ]
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
uses: actions/setup-java@v1
with:
java-version: 11
- name: Cache Gradle packages
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Build
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: build -x test -x ktlintKotlinScriptCheck -x ktlintTestSourceSetCheck -x ktlintMainSourceSetCheck
- name: Cleanup Gradle Cache
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions.
# Restoring these files from a GitHub Actions cache might cause problems for future builds.
run: |
rm -f ~/.gradle/caches/modules-2/modules-2.lock
rm -f ~/.gradle/caches/modules-2/gc.properties
- name: Test
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: test
- name: Publish
uses: eskatos/gradle-command-action@v1
with:
gradle-version: '7.1'
arguments: publish
env:
GITHUB_ACTOR: ${{ secrets.GITHUB_ACTOR }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

1
.idea/.gitignore generated vendored
View File

@@ -5,6 +5,5 @@
/dataSources.local.xml /dataSources.local.xml
/compiler.xml /compiler.xml
/uiDesigner.xml /uiDesigner.xml
/dataSources.xml
/sonarlint/ /sonarlint/
/jarRepositories.xml /jarRepositories.xml

View File

@@ -2,12 +2,18 @@
<code_scheme name="Project" version="173"> <code_scheme name="Project" version="173">
<JetCodeStyleSettings> <JetCodeStyleSettings>
<option name="PACKAGES_TO_USE_STAR_IMPORTS"> <option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value />
</option>
<option name="PACKAGES_IMPORT_LAYOUT">
<value> <value>
<package name="java.util" withSubpackages="true" static="false" /> <package name="" alias="false" withSubpackages="true" />
<package name="" alias="true" withSubpackages="true" />
</value> </value>
</option> </option>
<option name="SPACE_BEFORE_EXTEND_COLON" value="false" /> <option name="SPACE_BEFORE_EXTEND_COLON" value="false" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="2147483647" /> <option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="2147483647" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="2147483647" />
<option name="IMPORT_NESTED_CLASSES" value="true" />
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" /> <option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings> </JetCodeStyleSettings>
<codeStyleSettings language="kotlin"> <codeStyleSettings language="kotlin">

12
.idea/dataSources.xml generated Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="json_test@localhost" uuid="1191ff9a-6823-4b18-af90-483ddf0e4b69">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://localhost:5555/json_test</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

3
.idea/kotlinc.xml generated
View File

@@ -3,4 +3,7 @@
<component name="Kotlin2JvmCompilerArguments"> <component name="Kotlin2JvmCompilerArguments">
<option name="jvmTarget" value="11" /> <option name="jvmTarget" value="11" />
</component> </component>
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.7.20" />
</component>
</project> </project>

2
.idea/misc.xml generated
View File

@@ -3,7 +3,7 @@
<component name="FrameworkDetectionExcludesConfiguration"> <component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" /> <file type="web" url="file://$PROJECT_DIR$" />
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="corretto-11" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="openjdk-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
<component name="TaskProjectConfiguration"> <component name="TaskProjectConfiguration">

View File

@@ -1,34 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Test and Publish To MavenLocal" type="GradleRunConfiguration" factoryName="Gradle" singleton="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="publishToMavenLocal" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<extension name="net.ashald.envfile">
<option name="IS_ENABLED" value="false" />
<option name="IS_SUBST" value="false" />
<option name="IS_PATH_MACRO_SUPPORTED" value="false" />
<option name="IS_IGNORE_MISSING_FILES" value="false" />
<option name="IS_ENABLE_EXPERIMENTAL_INTEGRATIONS" value="false" />
<ENTRIES>
<ENTRY IS_ENABLED="true" PARSER="runconfig" />
</ENTRIES>
</extension>
<GradleScriptDebugEnabled>true</GradleScriptDebugEnabled>
<method v="2">
<option name="RunConfigurationTask" enabled="true" run_configuration_name="Lint" run_configuration_type="GradleRunConfiguration" />
<option name="RunConfigurationTask" enabled="true" run_configuration_name="tests" run_configuration_type="JUnit" />
</method>
</configuration>
</component>

View File

@@ -2,6 +2,12 @@
<configuration default="false" name="tests" type="JUnit" factoryName="JUnit" singleton="false"> <configuration default="false" name="tests" type="JUnit" factoryName="JUnit" singleton="false">
<module name="postgres-json.test" /> <module name="postgres-json.test" />
<useClassPathOnly /> <useClassPathOnly />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="fr.postgresjson.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<extension name="net.ashald.envfile"> <extension name="net.ashald.envfile">
<option name="IS_ENABLED" value="false" /> <option name="IS_ENABLED" value="false" />
<option name="IS_SUBST" value="false" /> <option name="IS_SUBST" value="false" />

39
README.md Normal file
View File

@@ -0,0 +1,39 @@
PostgresJson
============
_Kotlin library to request postgres with native SQL queries_
[![Tests](https://github.com/flecomte/postgres-json/actions/workflows/gradle.yml/badge.svg)](https://github.com/flecomte/postgres-json/actions/workflows/gradle.yml)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=postgres-json&metric=coverage)](https://sonarcloud.io/dashboard?id=postgres-json)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=postgres-json&metric=alert_status)](https://sonarcloud.io/dashboard?id=postgres-json)
[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=postgres-json&metric=ncloc)](https://sonarcloud.io/dashboard?id=postgres-json)
---
## What is this lib for?
This library allows you to make sql requests and return the result in json format, then deserialize it into an entity.
It also allows you to save an entity (INSERT) by serializing it and sending the json to the database, allowing you to insert several entities with their children, in a single request.
It also manages the migrations of the schema of tables and stored procedures.
All sql requests are handled manually for full control over what you do.
---
## The best benefits
* Total control of all Postgresql features and SQL language
* More speed and flexible than an ORM
* [Multi level request](./docs/usage/multi-level.md) (Can return multiple tables and these children in a single request)
* Queries are written in separate native `.sql` files
* Unit testing of SQL queries
* Migrations are written in separate native `.sql` files
* Automatic tested database migration and rollback
---
## Documentation: Table of Contents
* [Installation](./docs/installation.md)
* [Migrations](./docs/migrations/migrations.md)
* [Usage](./docs/usage/usage.md)
* [How that works](./docs/call%20function.png) (Diagram)
* [How to begin](./docs/checklist.md)

View File

@@ -1,45 +1,80 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
val containerAlwaysOn: String by project
val disableLint: String by project
plugins { plugins {
jacoco jacoco
id("maven-publish") id("maven-publish")
kotlin("jvm") version "1.4.30" kotlin("jvm") version "1.7.20"
id("org.jlleitschuh.gradle.ktlint") version "10.0.0" id("org.jlleitschuh.gradle.ktlint") version "11.0.0"
id("org.owasp.dependencycheck") version "6.1.1" id("org.owasp.dependencycheck") version "7.2.0"
id("fr.coppernic.versioning") version "3.2.1" id("fr.coppernic.versioning") version "3.2.1"
id("com.avast.gradle.docker-compose") version "0.16.9"
id("org.sonarqube") version "+"
} }
group = "com.github.flecomte" group = "io.github.flecomte"
version = versioning.info.tag version = versioning.info.tag
repositories { repositories {
mavenCentral() mavenCentral()
jcenter()
} }
tasks.withType<KotlinCompile> { tasks.withType<KotlinCompile> {
kotlinOptions { kotlinOptions {
jvmTarget = "11" jvmTarget = "11"
sourceCompatibility = "11"
targetCompatibility = "11"
} }
} }
dependencies { val compileKotlin: KotlinCompile by tasks
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") compileKotlin.kotlinOptions {
implementation("org.jetbrains.kotlin:kotlin-reflect:1.4.31") jvmTarget = "11"
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1") }
implementation("com.fasterxml.jackson.datatype:jackson-datatype-joda:2.12.1") val compileTestKotlin: KotlinCompile by tasks
implementation("com.github.jasync-sql:jasync-postgresql:1.1.7") compileTestKotlin.kotlinOptions {
implementation("org.slf4j:slf4j-api:1.7.30") jvmTarget = "11"
}
testImplementation("ch.qos.logback:logback-classic:1.2.3") tasks.test {
testImplementation("ch.qos.logback:logback-core:1.2.3") useJUnit()
testImplementation("io.mockk:mockk:1.10.6") useJUnitPlatform()
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1") systemProperty("junit.jupiter.execution.parallel.enabled", true)
testImplementation("org.amshove.kluent:kluent:1.65") if (!disableLint.toBoolean()) {
finalizedBy(tasks.ktlintCheck)
}
}
tasks.jacocoTestReport {
dependsOn(tasks.test)
reports {
xml.required.set(true)
}
}
tasks.sonarqube.configure {
dependsOn(tasks.jacocoTestReport)
}
tasks.publishToMavenLocal {
dependsOn(tasks.test)
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.20")
implementation("org.jetbrains.kotlin:kotlin-reflect:1.7.20")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.14.0-rc1")
implementation("com.fasterxml.jackson.datatype:jackson-datatype-joda:2.14.0-rc1")
implementation("com.github.jasync-sql:jasync-postgresql:2.1.7")
implementation("org.slf4j:slf4j-api:2.0.3")
testImplementation("ch.qos.logback:logback-classic:1.4.3")
testImplementation("ch.qos.logback:logback-core:1.4.3")
testImplementation("io.mockk:mockk:1.13.2")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.0")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:1.7.20")
testImplementation("org.amshove.kluent:kluent:1.68")
} }
val sourcesJar by tasks.creating(Jar::class) { val sourcesJar by tasks.creating(Jar::class) {
@@ -47,6 +82,14 @@ val sourcesJar by tasks.creating(Jar::class) {
from(sourceSets.getByName("main").allSource) from(sourceSets.getByName("main").allSource)
} }
apply(plugin = "docker-compose")
dockerCompose {
setProjectName("postgres-json")
setProperty("useComposeFiles", listOf("docker-compose.yml"))
setProperty("stopContainers", !containerAlwaysOn.toBoolean())
isRequiredBy(project.tasks.test)
}
publishing { publishing {
repositories { repositories {
maven { maven {
@@ -66,3 +109,13 @@ publishing {
} }
} }
} }
tasks.withType<PublishToMavenRepository>().configureEach {
onlyIf {
versioning.info.run {
!dirty && tag != null && tag.matches("""[0-9]+\.[0-9]+\.[0-9]+""".toRegex())
}
}
dependsOn(tasks.test)
}

View File

@@ -1,6 +1,6 @@
# To execute this docker-compose yml file use docker-compose -f <file_name> up # To execute this docker-compose yml file use docker-compose -f <file_name> up
# Add the "-d" flag at the end for detached execution # Add the "-d" flag at the end for detached execution
version: '3.7' version: '3.8'
services: services:
db: db:
container_name: postgres_json container_name: postgres_json
@@ -8,7 +8,7 @@ services:
context: docker/postgresql context: docker/postgresql
restart: always restart: always
ports: ports:
- 5555:5432 - "5555:5432"
environment: environment:
POSTGRES_DB: json_test POSTGRES_DB: json_test
POSTGRES_USER: test POSTGRES_USER: test

View File

@@ -1,4 +1,4 @@
FROM postgres:11 FROM postgres:13
COPY postgresql.conf /tmp/postgresql.conf COPY postgresql.conf /tmp/postgresql.conf
COPY extension.sh /docker-entrypoint-initdb.d/000-extension.sh COPY extension.sh /docker-entrypoint-initdb.d/000-extension.sh

View File

@@ -664,5 +664,3 @@ log_rotation_size = 100MB
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Add settings for extensions here # Add settings for extensions here
zdb.default_elasticsearch_url = 'http://elasticsearch:9200/'

BIN
docs/call function.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

52
docs/call function.puml Normal file
View File

@@ -0,0 +1,52 @@
@startuml
participant Gradle
participant App
control Migration
control Repository
control Requester
control Function
control Connection
database Database
== Migration ==
[-> Gradle++ : run gradle
Gradle -> Migration** : Init Migration
Migration -> Migration : Read Schemas
Migration -> Migration : Read SQL Function
Gradle -> Migration++ : Run Migrations
Migration -> Migration : Run Migrations
return
Gradle -> Migration!!
return
== Application ==
[-> App : run app
App -> Connection** : Create Connection
Connection -> Database : Connect to the database
App -> Requester** : Create Requester
Requester -> Requester: Read all Function file
Requester -> Function** : Create Function object
Function -> Function : Parse function
Function -> Function : Store parameters and function name
App -> Repository** : Create Repository
... wait request ...
[-> Repository++ : call repository with args
Repository -> Repository : Define function name
Repository -> Requester++ : get function
Requester -> Function++ : select()
Function -> Function : Compile args
Function -> Function : Compile SQL
Function -> Connection++ : select()
Connection -> Database++ : Send Prepared Statement
return
Connection -> Connection : Convert json to Entity
return entity
return entity
return entity
return entity
@enduml

9
docs/checklist.md Normal file
View File

@@ -0,0 +1,9 @@
# Checklist
- [ ] Define schemas with migrations files (*.up.sql & *.down.sql)
- [ ] Define query with sql function (*.sql)
- [ ] Create Entity (*.kt)
- [ ] Create repository (*.kt)
- [ ] Configure migrations in gradle
- [ ] Execute migrations functions
- [ ] Call Repository

9
docs/installation.md Normal file
View File

@@ -0,0 +1,9 @@
# Installation
## Gradle
```kotlin
// build.gradle.kts
dependencies {
implementation("com.github.flecomte:postgres-json:+")
}
```

View File

@@ -0,0 +1,16 @@
# Execute migration in application
```kotlin
import fr.postgresjson.migration.Migrations
import fr.postgresjson.connexion.Connection
val conn: Connection = TODO()
val migrations = Migrations(
conn,
this::class.java.getResource("/sql/migrations")?.toURI() ?: error("No migrations found"),
this::class.java.getResource("/sql/functions")?.toURI() ?: error("No sql function found")
)
migrations.status() // Show executed and not executed migrations
migrations.runDry() // Execute migration in transaction and rollback at the end
migrations.run() // Execute migration in transaction and commit if no error
```

View File

@@ -0,0 +1,37 @@
# Execute Migrations with Gradle
You can execute migration with a Gradle task like this:
```kotlin
// build.gradle.kts
import fr.postgresjson.connexion.Connection
import fr.postgresjson.connexion.Requester
import fr.postgresjson.migration.Migrations
buildscript {
dependencies {
classpath("com.github.flecomte:postgres-json:+")
}
}
val migration by tasks.registering {
doLast {
val connection = Connection(
host = "localhost",
port = 5432,
database = "database",
username = "username",
password = "password"
)
Migrations(
connection,
file("$buildDir/resources/main/sql/migrations").toURI(),
file("$buildDir/resources/main/sql/functions").toURI()
).run()
}
}
```
```shell
$ gradle migration
```

View File

@@ -0,0 +1,71 @@
# Migration
## Schemas migration
Migrations are just manually written `*.sql` files that represent the database schemas.
Each file is executed one after the other in alphabetical order.
Each execution is stored in the `migration.history` table.
A migration contains a `*.up.sql` file and a `*.down.sql` file to rollback the migration.
The content of the `*.down.sql` file is also stored in the database.
This allows the `*.down.sql` to be executed even if the code is already rollback.
Example:
```postgresql
-- resources/sql/migrations/0000-init_schema.up.sql
create table "user"
(
id uuid default uuid_generate_v4() not null primary key,
created_at timestamptz default now() not null,
blocked_at timestamptz default null null,
username varchar(64) not null check ( username != '' and lower(username) = username) unique,
password text not null check ( password != '' ),
roles text[] default '{}' not null
);
```
```postgresql
-- resources/sql/migrations/0000-init_schema.down.sql
drop table if exists "user";
```
## Stored procedure migrations
Migrations are also stored procedures and other functions.
Each function is updated with each migration.
Example:
```postgresql
-- resources/sql/functions/insert_user.sql
create or replace function insert_user(inout resource json) language plpgsql as
$$
declare
new_id uuid;
begin
insert into "user" (id, username, password, blocked_at, roles)
select
coalesce(t.id, uuid_generate_v4()),
t.username,
crypt(resource->>'password', gen_salt('bf', 8)),
case when t.blocked_at is not null then now() else null end,
t.roles
from json_populate_record(null::"user", resource) t
returning id into new_id;
select find_user_by_id(new_id) into resource;
end;
$$;
```
```postgresql
-- resources/sql/functions/find_user_by_id.sql
create or replace function find_user_by_id(in _id uuid, out resource json) language plpgsql as
$$
begin
select to_jsonb(u) - 'password' into resource
from "user" as u
where u.id = _id;
end;
$$;
```
* [Execute migrations in application](./migrations-application.md)
* [Execute migrations with gradle](./migrations-gradle.md)

View File

@@ -0,0 +1,14 @@
# Init connection
Before execute any query you must instantiate the connection.
```kotlin
import fr.postgresjson.connexion.Connection
val connection = Connection(
host = "localhost",
port = 5432,
database = "mydb",
username = "john",
password = "azerty"
)
```

93
docs/usage/multi-level.md Normal file
View File

@@ -0,0 +1,93 @@
Multi Level Queries
===================
## Define schema, query and kotlin object
1. Schema
```postgresql
create table parent (
id uuid primary key,
name text not null
);
create table child (
id uuid primary key,
name text not null,
parent_id uuid not null references parent
)
```
2. Insert some data for tests
```postgresql
insert into parent (id, name) VALUES ('379e0687-9e4a-4781-b0e9-d94a62e4261f', 'Bernard');
insert into child (id, name, parent_id) VALUES (uuid_generate_v4(), 'Noé', '379e0687-9e4a-4781-b0e9-d94a62e4261f');
insert into child (id, name, parent_id) VALUES (uuid_generate_v4(), 'John', '379e0687-9e4a-4781-b0e9-d94a62e4261f');
```
3. Define Model
```kotlin
import java.util.UUID
class Parent(val id: UUID, val name: String, val children: List<Child>)
class Child(val id: UUID, val name: String)
```
4. Define request function
```postgresql
-- resource/sql/functions/find_parent_by_id.sql
create or replace function find_parent_by_id(in _id uuid, out resource json) language plpgsql as
$$
begin
select to_json(t) into resource
from (
select
p.*,
json_agg(to_jsonb(c) - 'parent_id') as children
from parent p
join child c on c.parent_id = p.id
where p.id = _id
group by p.id
) t;
end;
$$;
```
## Execute the function
You just to use `Requester` and set the sql function name, then pass arguments.
If you need to return more than one entry, use `.select()` instead of `.selecteOne()`
See the [Paginated example](./paginated.md)
```kotlin
import fr.postgresjson.connexion.Requester
val requester: Requester = TODO()
val result: Parent = requester
.getFunction("find_parent_by_id")
.selectOne("id" to "379e0687-9e4a-4781-b0e9-d94a62e4261f")
```
The requester create dynamically this request
```postgresql
select * from find_parent_by_id(_id => '379e0687-9e4a-4781-b0e9-d94a62e4261f');
```
*Watch the underscore as prefix is added if necessary.
The requester known the parameters because it parses all SQL functions and reads the names of the parameters from them.*
And the SQL return is a JSON like follow:
```json
{
"id": "379e0687-9e4a-4781-b0e9-d94a62e4261f",
"name": "Bernard",
"child": [
{
"id": "c2d0ec81-7cac-4689-8086-2644a3b309b5",
"name": "Noé"
},
{
"id": "255d911a-0cbc-4156-bf8c-0204e89494d9",
"name": "John"
}
]
}
```
But the requester deserialize the result automatically into a Kotlin object with their children objects. **And do that in only one request**.

19
docs/usage/paginated.md Normal file
View File

@@ -0,0 +1,19 @@
Paginated request
=================
```kotlin
import fr.postgresjson.connexion.Paginated
import fr.postgresjson.connexion.Requester
import java.util.UUID
class Article(val id: UUID, val name: String)
val request: Requester = TODO()
val article: Paginated<Article> = requester
.getFunction("find_articles")
.select(
page = 1,
limit = 10,
"id" to "4a04820e-f880-4d80-b1c9-aeacccb24977"
)
```

86
docs/usage/raw-request.md Normal file
View File

@@ -0,0 +1,86 @@
# Raw request
You can execute query directly from the code like this:
(*see [Init connection](./init-connection.md) before*)
```kotlin
import fr.postgresjson.connexion.Connection
val connection: Connection = TODO()
val result: QueryResult = connection.exec(
"SELECT id FROM inventor WHERE name = :name",
mapOf("name" to "Nikola Tesla")
)
val id: String = result.rows[0].getString(0)
```
And if you must map the query result with an entity, you can do it like this:
```kotlin
import java.util.UUID
import fr.postgresjson.entity.Serializable
import fr.postgresjson.connexion.Connection
val connection: Connection = TODO()
data class Inventor(
val id: UUID = UUID.randomUUID(),
val name: String,
val roles: List<String> = listOf(),
): Serializable
// Select one entity
val result: Inventor? = connection.selectOne(
"""
SELECT json_build_object(
'id', '9e65de49-712e-47ce-8bf2-dfffae53a82e',
'name', :name
)
""",
mapOf("name" to "Nikola Tesla")
)
// Select multiple entities
val result = connection.select<List<Inventor>>(
"""
SELECT json_build_array(
json_build_object(
'id', '9e65de49-712e-47ce-8bf2-dfffae53a82e',
'name', :name
),
json_build_object(
'id', '32f67ed3-af6d-403b-a3b9-5fe3540c3412',
'name', :name2
)
)
""",
mapOf(
"name" to "Nikola Tesla",
"name2" to "Albert Einstein",
)
)
// Select multiple with real query
val result: List<Inventor> = connection.select(
"""
select json_agg(i)
from inventor i
where roles @> ARRAY[:role];
""",
mapOf("role" to "ADMIN")
)
// Select multiple with only some rows
val result: List<Inventor> = connection.select(
"""
select json_agg(i)
from (
select id, name
from inventor
) i;
"""
)
```
See [ConnectionTest.kt](/src/test/kotlin/fr/postgresjson/ConnectionTest.kt) for more examples.

View File

@@ -0,0 +1,85 @@
# Stored Procedure
*Execute stored procedure with requester*
You can execute a stored procedure (previously defined in a migration) via the Requester
To do that:
1. First, instantiate the requester
```kotlin
import fr.postgresjson.connexion.Requester
import fr.postgresjson.connexion.Connection
val connection: Connection = TODO()
val requester = Requester(
connection = connection,
functionsDirectory = this::class.java.getResource("/sql/functions")?.toURI() ?: error("No sql function found")
).createRequester()
```
2. then, define Entities
```kotlin
import java.util.UUID
import org.joda.time.DateTime
import fr.postgresjson.entity.Serializable
enum class Roles { ROLE_USER, ROLE_ADMIN }
class User(
id: UUID = UUID.randomUUID(),
override var username: String,
var blockedAt: DateTime? = null,
var roles: List<Roles> = emptyList()
): Serializable
class UserForCreate(
id: UUID = UUID.randomUUID(),
username: String,
val password: String,
blockedAt: DateTime? = null,
roles: List<Roles> = emptyList()
): Serializable
```
3. and, define Repositories
[See SQL function](../migrations/migrations.md)
```kotlin
import fr.postgresjson.connexion.Requester
import fr.postgresjson.repository.RepositoryI
import java.util.UUID
class UserRepository(override var requester: Requester): RepositoryI {
fun findById(id: UUID): User {
return requester
.getFunction("find_user_by_id") // Use the name of the function
.selectOne(
"id" to id // You can pass parameters by their names. The underscore prefix on parameters is not required to be mapped.
) ?: throw UserNotFound(id) // Throw exception if user not found
}
fun insert(user: UserForCreate): User {
return requester
.getFunction("insert_user")
.selectOne("resource" to user)
}
class UserNotFound(override val message: String?, override val cause: Throwable?): Throwable(message, cause) {
constructor(id: UUID): this("No User with ID $id", null)
}
}
```
4. And at last, execute queries
```kotlin
import fr.postgresjson.connexion.Requester
import java.util.UUID
val requester: Requester = TODO()
val userRepo = UserRepository(requester)
val user: User = userRepo.findById(UUID.fromString(id))
val newUser: UserForCreate = TODO()
val userInserted: User = userRepo.insert(newUser)
```

7
docs/usage/usage.md Normal file
View File

@@ -0,0 +1,7 @@
## Usage
1. [Init connection](./init-connection.md)
2. [Raw request](./raw-request.md)
3. [Stored Procedure](./stored-procedure.md)
4. [Paginated request](./paginated.md)
5. [Multi level request](./multi-level.md)

View File

@@ -1,2 +1,10 @@
kotlin.code.style=official kotlin.code.style=official
kotlin_version=1.3.31 systemProp.sonar.host.url=https://sonarcloud.io
systemProp.sonar.projectKey=postgres-json
systemProp.sonar.projectName=PostgresJson
systemProp.sonar.organization=flecomte
systemProp.sonar.java.coveragePlugin=jacoco
systemProp.sonar.coverage.jacoco.xmlReportPaths=build/reports/jacoco/test/jacocoTestReport.xml
org.gradle.jvmargs=-Xmx4096M
containerAlwaysOn=false
disableLint=false

View File

@@ -1,4 +1,4 @@
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

View File

@@ -1,8 +1,9 @@
package fr.postgresjson.connexion package fr.postgresjson.connexion
import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.core.type.TypeReference
import com.github.jasync.sql.db.Connection
import com.github.jasync.sql.db.QueryResult import com.github.jasync.sql.db.QueryResult
import com.github.jasync.sql.db.ResultSet
import com.github.jasync.sql.db.general.ArrayRowData
import com.github.jasync.sql.db.pool.ConnectionPool import com.github.jasync.sql.db.pool.ConnectionPool
import com.github.jasync.sql.db.postgresql.PostgreSQLConnection import com.github.jasync.sql.db.postgresql.PostgreSQLConnection
import com.github.jasync.sql.db.postgresql.PostgreSQLConnectionBuilder import com.github.jasync.sql.db.postgresql.PostgreSQLConnectionBuilder
@@ -12,7 +13,7 @@ import fr.postgresjson.entity.Serializable
import fr.postgresjson.serializer.Serializer import fr.postgresjson.serializer.Serializer
import fr.postgresjson.utils.LoggerDelegate import fr.postgresjson.utils.LoggerDelegate
import org.slf4j.Logger import org.slf4j.Logger
import java.util.concurrent.* import kotlin.random.Random
typealias SelectOneCallback<T> = QueryResult.(T?) -> Unit typealias SelectOneCallback<T> = QueryResult.(T?) -> Unit
typealias SelectCallback<T> = QueryResult.(List<T>) -> Unit typealias SelectCallback<T> = QueryResult.(List<T>) -> Unit
@@ -44,70 +45,68 @@ class Connection(
} }
fun disconnect() { fun disconnect() {
connection?.run { disconnect() } connection?.disconnect()
} }
fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>) = connect().inTransaction(f) fun <A> inTransaction(block: Connection.() -> A?): A? = connect().run {
sendQuery("BEGIN")
try {
block().apply { sendQuery("COMMIT") }
} catch (e: Throwable) {
sendQuery("ROLLBACK")
throw e
}
}
override fun <R : EntityI> select( /**
* Select One [EntityI] with [List] of parameters
*/
override fun <R : EntityI> selectOne(
sql: String, sql: String,
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: List<Any?>, values: List<Any?>,
block: (QueryResult, R?) -> Unit block: (QueryResult, R?) -> Unit
): R? { ): R? {
val primaryObject = values.firstOrNull {
it is EntityI && typeReference.type.typeName == it::class.java.name
} as R?
val result = exec(sql, compileArgs(values)) val result = exec(sql, compileArgs(values))
val json = result.rows[0].getString(0) val json = result.rows.firstOrNull()?.getString(0)
return if (json === null) { return if (json === null) {
null null
} else {
if (primaryObject != null) {
serializer.deserialize(json, primaryObject)
} else { } else {
serializer.deserialize(json, typeReference) serializer.deserialize(json, typeReference)
}
}.also { }.also {
block(result, it) block(result, it)
} }
} }
inline fun <reified R : EntityI> selectOne( /**
sql: String, * Select One [EntityI] with named parameters
values: List<Any?> = emptyList(), */
noinline block: SelectOneCallback<R> = {} override fun <R : EntityI> selectOne(
): R? =
select(sql, object : TypeReference<R>() {}, values, block)
override fun <R : EntityI> select(
sql: String, sql: String,
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, R?) -> Unit block: (QueryResult, R?) -> Unit
): R? { ): R? {
return replaceArgs(sql, values) { return replaceArgs(sql, values) {
select(this.sql, typeReference, this.parameters, block) selectOne(this.sql, typeReference, parameters, block)
} }
} }
inline fun <reified R : EntityI> selectOne( /* Select Multiples */
sql: String,
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
select(sql, object : TypeReference<R>() {}, values, block)
/**
* Select multiple [EntityI] with [List] of parameters
*/
override fun <R : EntityI> select( override fun <R : EntityI> select(
sql: String, sql: String,
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: List<Any?>, values: List<Any?>,
block: (QueryResult, List<R>) -> Unit block: QueryResult.(List<R>) -> Unit
): List<R> { ): List<R> {
val result = exec(sql, compileArgs(values)) val result = exec(sql, values)
val json = result.rows[0].getString(0) val json = result.rows[0].getString(0)
return if (json === null) { return if (json === null) {
listOf<EntityI>() as List<R> emptyList()
} else { } else {
serializer.deserializeList(json, typeReference) serializer.deserializeList(json, typeReference)
}.also { }.also {
@@ -115,20 +114,32 @@ class Connection(
} }
} }
inline fun <reified R : EntityI> select( /**
* Select multiple [EntityI] with [Map] of parameters
*/
override fun <R : EntityI> select(
sql: String, sql: String,
values: List<Any?> = emptyList(), typeReference: TypeReference<List<R>>,
noinline block: SelectCallback<R> = {} values: Map<String, Any?>,
): List<R> = block: QueryResult.(List<R>) -> Unit
select(sql, object : TypeReference<List<R>>() {}, values, block) ): List<R> {
return replaceArgs(sql, values) {
select(this.sql, typeReference, this.parameters, block)
}
}
/* Select Paginated */
/**
* Select Multiple [EntityI] with pagination
*/
override fun <R : EntityI> select( override fun <R : EntityI> select(
sql: String, sql: String,
page: Int, page: Int,
limit: Int, limit: Int,
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, Paginated<R>) -> Unit block: QueryResult.(Paginated<R>) -> Unit
): Paginated<R> { ): Paginated<R> {
val offset = (page - 1) * limit val offset = (page - 1) * limit
val newValues = values val newValues = values
@@ -140,9 +151,16 @@ class Connection(
} }
return line.run { return line.run {
val json = rows[0].getString(0) val firstLine = rows.firstOrNull() ?: queryError("The query has no return", sql, newValues)
val entities = if (json === null) { if (!(firstLine as ArrayRowData).mapping.keys.contains("total")) queryError("""The query not return the "total" column""", sql, newValues, rows)
listOf<EntityI>() as List<R> val total = try {
firstLine.getInt("total") ?: queryError("The query return \"total\" must not be null", sql, newValues, rows)
} catch (e: ClassCastException) {
queryError("""Column "total" must be an integer""", sql, newValues, rows)
}
val json = firstLine.getString(0)
val entities = if (json == null) {
emptyList()
} else { } else {
serializer.deserializeList(json, typeReference) serializer.deserializeList(json, typeReference)
} }
@@ -150,44 +168,17 @@ class Connection(
entities, entities,
offset, offset,
limit, limit,
rows[0].getInt("total") ?: error("The query not return total") total
) )
}.also { }.also {
block(line, it) block(line, it)
} }
} }
inline fun <reified R : EntityI> select(
sql: String,
page: Int,
limit: Int,
values: Map<String, Any?> = emptyMap(),
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(sql, page, limit, object : TypeReference<List<R>>() {}, values, block)
override fun <R : EntityI> select(
sql: String,
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: (QueryResult, List<R>) -> Unit
): List<R> {
return replaceArgs(sql, values) {
select(this.sql, typeReference, this.parameters, block)
}
}
inline fun <reified R : EntityI> select(
sql: String,
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(sql, object : TypeReference<List<R>>() {}, values, block)
override fun exec(sql: String, values: List<Any?>): QueryResult { override fun exec(sql: String, values: List<Any?>): QueryResult {
val compiledValues = compileArgs(values) val compiledValues = compileArgs(values)
return stopwatchQuery(sql, compiledValues) { return stopwatchQuery(sql, compiledValues) {
connect().sendPreparedStatement(sql, compiledValues).join() connect().sendPreparedStatement(replaceNamedArgByQuestionMark(sql), compiledValues).join()
} }
} }
@@ -197,16 +188,22 @@ class Connection(
} }
} }
override fun sendQuery(sql: String, values: List<Any?>): Int { /**
* Warning: this method not use prepared statement
*/
override fun sendQuery(sql: String, values: List<Any?>): QueryResult {
val compiledValues = compileArgs(values) val compiledValues = compileArgs(values)
return stopwatchQuery(sql, compiledValues) { return stopwatchQuery(sql, compiledValues) {
replaceArgsIntoSql(sql, compiledValues) { replaceArgsIntoSql(sql, compiledValues) {
connect().sendQuery(it).join().rowsAffected.toInt() connect().sendQuery(it).join()
} }
} }
} }
override fun sendQuery(sql: String, values: Map<String, Any?>): Int { /**
* Warning: this method not use prepared statement
*/
override fun sendQuery(sql: String, values: Map<String, Any?>): QueryResult {
return replaceArgs(sql, values) { return replaceArgs(sql, values) {
sendQuery(this.sql, this.parameters) sendQuery(this.sql, this.parameters)
} }
@@ -223,36 +220,64 @@ class Connection(
} }
private fun <T> replaceArgs(sql: String, values: Map<String, Any?>, block: ParametersQuery.() -> T): T { private fun <T> replaceArgs(sql: String, values: Map<String, Any?>, block: ParametersQuery.() -> T): T {
val paramRegex = "(?<!:):([a-zA-Z0-9_-]+)".toRegex(RegexOption.IGNORE_CASE) val paramRegex = "(?<!:):([a-z0-9_-]+)".toRegex(RegexOption.IGNORE_CASE)
val newArgs = paramRegex.findAll(sql).map { match -> val orderedArgs = paramRegex.findAll(sql).map { match ->
val name = match.groups[1]!!.value val name = match.groups[1]!!.value
values[name] ?: values[name.trimStart('_')] ?: error("Parameter $name missing") values[name] ?: values[name.trimStart('_')] ?: queryError("""Parameter "$name" missing""", sql, values)
}.toList() }.toList()
var newSql = sql return block(ParametersQuery(replaceNamedArgByQuestionMark(sql), orderedArgs))
values.forEach { (key, _) ->
val regex = ":_?$key".toRegex()
newSql = newSql.replace(regex, "?")
} }
return block(ParametersQuery(newSql, newArgs)) private fun replaceNamedArgByQuestionMark(sql: String): String =
"(?<!:):([a-z0-9_-]+)"
.toRegex(RegexOption.IGNORE_CASE)
.replace(sql, "?")
private fun insertArgsValuesIntoSql(sql: String, values: List<Any?>): String {
var i = 0
/* The regular expression matches a question mark "?" alone, not preceded or followed by another question mark */
return """(?<!\?)(\?)(?!\?)"""
.toRegex(RegexOption.IGNORE_CASE)
.replace(sql) {
values.getOrNull(i)
?.toString()
?.also { ++i }
?.let(this::escapeParameter)
?: queryError("Parameter $i missing", sql, values)
}
} }
private fun <T> replaceArgsIntoSql(sql: String, values: List<Any?>, block: (String) -> T): T { private fun <T> replaceArgsIntoSql(sql: String, values: List<Any?>, block: (String) -> T): T {
val paramRegex = "(?<!\\?)(\\?)(?!\\?)".toRegex(RegexOption.IGNORE_CASE) return if (values.isNotEmpty()) {
var i = 0 sql
if (values.isNotEmpty()) { .let(this::replaceNamedArgByQuestionMark)
val newSql = paramRegex.replace(sql) { .let { insertArgsValuesIntoSql(it, values) }
values[i] ?: error("Parameter $i missing") .let(block)
val valToReplace = values[i].toString() } else block(sql)
++i
"'$valToReplace'"
} }
return block(newSql) /**
* Escape parameter by generate a random tag to prevent SQL injection
*/
private fun escapeParameter(parameter: String): String {
val escapeTag = escapeTag().let {
if (parameter.indexOf(it) >= 0) escapeParameter(parameter) else it
}
return """$escapeTag$parameter$escapeTag"""
} }
return block(sql) /**
* Generate a random alphaNum tag of 8 characters
*/
private fun escapeTag(): String {
val charPool: List<Char> = ('a'..'z') + ('A'..'Z')
val tagName = (1..8)
.map { _ -> Random.nextInt(0, charPool.size) }
.map(charPool::get)
.joinToString("")
return "\$$tagName\$"
} }
data class ParametersQuery(val sql: String, val parameters: List<Any?>) data class ParametersQuery(val sql: String, val parameters: List<Any?>)
@@ -280,12 +305,51 @@ class Connection(
logger?.debug("Query executed in $duration ms \n{}", args) logger?.debug("Query executed in $duration ms \n{}", args)
return result return result
} catch (e: Throwable) { } catch (e: Throwable) {
logger?.info(""" logger?.info(
"""
Query Error: Query Error:
${sql.prependIndent()}, ${sql.prependIndent()},
${values.joinToString(", ").prependIndent()} ${values.joinToString(", ").prependIndent()}
""".trimIndent(), e) """.trimIndent(),
e
)
throw e throw e
} }
} }
class QueryError(msg: String) : Exception(msg)
private fun queryError(
msg: String,
sql: String,
parameters: List<Any?>,
result: ResultSet? = null
): Nothing = throw QueryError(
"""
|$msg
|
|${parameters.joinToString(", ") { it.toString() }.prependIndent(" > ")}
|${sql.prependIndent(" > ")}
|${result?.let { "-----" }?.prependIndent(" > ") ?: ""}
|${result?.columnNames()?.joinToString(" | ")?.prependIndent(" > ") ?: ""}
|${result?.map { it.joinToString(" | ") }?.joinToString("\n")?.prependIndent(" > ") ?: ""}
""".trimMargin().trim(' ', '\n')
)
private fun queryError(
msg: String,
sql: String,
parameters: Map<String, Any?>,
result: ResultSet? = null
): Nothing = throw QueryError(
"""
|$msg
|
|${parameters.map { ":" + it.key + " = " + it.value }.joinToString(", ").prependIndent(" > ")}
|${sql.prependIndent(" > ")}
|${result?.let { "-----" }?.prependIndent(" > ") ?: ""}
|${result?.columnNames()?.joinToString(" | ")?.prependIndent(" > ") ?: ""}
|${result?.map { it.joinToString(" | ") }?.joinToString("\n")?.prependIndent(" > ") ?: ""}
""".trimMargin().trim(' ', '\n')
)
} }

View File

@@ -4,41 +4,86 @@ import com.fasterxml.jackson.core.type.TypeReference
import com.github.jasync.sql.db.QueryResult import com.github.jasync.sql.db.QueryResult
import fr.postgresjson.entity.EntityI import fr.postgresjson.entity.EntityI
interface EmbedExecutable { sealed interface EmbedExecutable {
val connection: Connection val connection: Connection
override fun toString(): String override fun toString(): String
val name: String val name: String
/* Select One */ /* Select One */
/** /**
* Select One entity with list of parameters * Update [EntityI] with one entity as argument
*/
fun <R : EntityI> update(
typeReference: TypeReference<R>,
value: R,
block: SelectOneCallback<R> = {}
): R? =
selectOne(typeReference, listOf(value), block)
/**
* Select One [EntityI] with [List] of parameters
*/
fun <R : EntityI> selectOne(
typeReference: TypeReference<R>,
values: List<Any?>,
block: SelectOneCallback<R> = {}
): R?
/**
* Select One [EntityI] with [Map] of parameters
*/
fun <R : EntityI> selectOne(
typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: SelectOneCallback<R> = {}
): R?
/**
* Select One [EntityI] with multiple [Pair] of parameters
*/
fun <R : EntityI> selectOne(
typeReference: TypeReference<R>,
vararg values: Pair<String, Any?>,
block: SelectOneCallback<R> = {}
): R? =
selectOne(typeReference, values.toMap(), block)
/* Select Multiples */
/**
* Select Multiple [EntityI] with [List] of parameters
*/ */
fun <R : EntityI> select(
typeReference: TypeReference<R>,
values: List<Any?> = emptyList(),
block: SelectOneCallback<R> = {}
): R?
fun <R : EntityI> select(
typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: SelectOneCallback<R> = {}
): R?
/* Select Miltiples */
fun <R : EntityI> select( fun <R : EntityI> select(
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: List<Any?> = emptyList(), values: List<Any?>,
block: SelectCallback<R> = {} block: SelectCallback<R> = {}
): List<R> ): List<R>
/**
* Select Multiple [EntityI] with [Map] of parameters
*/
fun <R : EntityI> select( fun <R : EntityI> select(
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: SelectCallback<R> = {} block: SelectCallback<R> = {}
): List<R> ): List<R>
/**
* Select Multiple [EntityI] with multiple [Pair] of parameters
*/
fun <R : EntityI> select(
typeReference: TypeReference<List<R>>,
vararg values: Pair<String, Any?>,
block: SelectCallback<R> = {}
): List<R> =
select(typeReference, values.toMap(), block)
/* Select Paginated */ /* Select Paginated */
/**
* Select Paginated [EntityI] with [Map] of parameters
*/
fun <R : EntityI> select( fun <R : EntityI> select(
page: Int, page: Int,
limit: Int, limit: Int,
@@ -47,16 +92,19 @@ interface EmbedExecutable {
block: SelectPaginatedCallback<R> = {} block: SelectPaginatedCallback<R> = {}
): Paginated<R> ): Paginated<R>
fun exec(values: List<Any?> = emptyList()): QueryResult /**
* Select Paginated [EntityI] with multiple [Pair] of parameters
*/
fun <R : EntityI> select(
page: Int,
limit: Int,
typeReference: TypeReference<List<R>>,
vararg values: Pair<String, Any?>,
block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(page, limit, typeReference, values.toMap(), block)
fun exec(values: List<Any?>): QueryResult
fun exec(values: Map<String, Any?>): QueryResult fun exec(values: Map<String, Any?>): QueryResult
fun exec(vararg values: Pair<String, Any?>): QueryResult = exec(values.toMap()) fun exec(vararg values: Pair<String, Any?>): QueryResult = exec(values.toMap())
fun perform(values: List<Any?>) { exec(values) }
fun perform(values: Map<String, Any?>) { exec(values) }
fun perform(vararg values: Pair<String, Any?>) = perform(values.toMap())
fun sendQuery(values: List<Any?> = emptyList()): Int
fun sendQuery(values: Map<String, Any?>): Int
fun sendQuery(vararg values: Pair<String, Any?>): Int =
sendQuery(values.toMap())
} }

View File

@@ -0,0 +1,68 @@
package fr.postgresjson.connexion
import com.fasterxml.jackson.core.type.TypeReference
import fr.postgresjson.entity.EntityI
/* Select One */
inline fun <reified R : EntityI> EmbedExecutable.update(
value: R,
noinline block: SelectOneCallback<R> = {}
): R? =
update(object : TypeReference<R>() {}, value, block)
inline fun <reified R : EntityI> EmbedExecutable.selectOne(
values: List<Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(object : TypeReference<R>() {}, values, block)
inline fun <reified R : EntityI> EmbedExecutable.selectOne(
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(object : TypeReference<R>() {}, values, block)
inline fun <reified R : EntityI> EmbedExecutable.selectOne(
vararg values: Pair<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(object : TypeReference<R>() {}, values = values, block)
/* Select Multiples */
inline fun <reified R : EntityI> EmbedExecutable.select(
values: List<Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(object : TypeReference<List<R>>() {}, values, block)
inline fun <reified R : EntityI> EmbedExecutable.select(
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(object : TypeReference<List<R>>() {}, values, block)
inline fun <reified R : EntityI> EmbedExecutable.select(
vararg values: Pair<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(object : TypeReference<List<R>>() {}, values = values, block)
/* Select Paginated */
inline fun <reified R : EntityI> EmbedExecutable.select(
page: Int,
limit: Int,
values: Map<String, Any?> = emptyMap(),
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(page, limit, object : TypeReference<List<R>>() {}, values, block)
inline fun <reified R : EntityI> EmbedExecutable.select(
page: Int,
limit: Int,
vararg values: Pair<String, Any?>,
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(page, limit, object : TypeReference<List<R>>() {}, values = values, block)

View File

@@ -5,24 +5,58 @@ import com.github.jasync.sql.db.QueryResult
import fr.postgresjson.entity.EntityI import fr.postgresjson.entity.EntityI
interface Executable { interface Executable {
/* Update */
/**
* Update [EntityI] with one entity as argument
*/
fun <R : EntityI> update(
sql: String,
typeReference: TypeReference<R>,
value: R,
block: SelectOneCallback<R> = {}
): R? =
selectOne(sql, typeReference, listOf(value), block)
/* Select One */ /* Select One */
fun <R : EntityI> select( /**
* Select One [EntityI] with [List] of parameters
*/
fun <R : EntityI> selectOne(
sql: String, sql: String,
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: List<Any?> = emptyList(), values: List<Any?>,
block: SelectOneCallback<R> = {} block: SelectOneCallback<R> = {}
): R? ): R?
fun <R : EntityI> select( /**
* Select One [EntityI] with [Map] of parameters
*/
fun <R : EntityI> selectOne(
sql: String, sql: String,
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: SelectOneCallback<R> = {} block: SelectOneCallback<R> = {}
): R? ): R?
/* Select Miltiples */ /**
* Select One [EntityI] with multiple [Pair] of parameters
*/
fun <R : EntityI> selectOne(
sql: String,
typeReference: TypeReference<R>,
vararg values: Pair<String, Any?>,
block: SelectOneCallback<R> = {}
): R? =
selectOne(sql, typeReference, values.toMap(), block)
/* Select Multiples */
/**
* Select Multiple [EntityI] with [List] of parameters
*/
fun <R : EntityI> select( fun <R : EntityI> select(
sql: String, sql: String,
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
@@ -30,6 +64,9 @@ interface Executable {
block: SelectCallback<R> = {} block: SelectCallback<R> = {}
): List<R> ): List<R>
/**
* Select Multiple [EntityI] with [Map] of parameters
*/
fun <R : EntityI> select( fun <R : EntityI> select(
sql: String, sql: String,
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
@@ -37,8 +74,22 @@ interface Executable {
block: SelectCallback<R> = {} block: SelectCallback<R> = {}
): List<R> ): List<R>
/**
* Select Multiple [EntityI] with multiple [Pair] of parameters
*/
fun <R : EntityI> select(
sql: String,
typeReference: TypeReference<List<R>>,
vararg values: Pair<String, Any?>,
block: SelectCallback<R> = {}
): List<R> =
select(sql, typeReference, values.toMap(), block)
/* Select Paginated */ /* Select Paginated */
/**
* Select Paginated [EntityI] with [Map] of parameters
*/
fun <R : EntityI> select( fun <R : EntityI> select(
sql: String, sql: String,
page: Int, page: Int,
@@ -48,8 +99,38 @@ interface Executable {
block: SelectPaginatedCallback<R> = {} block: SelectPaginatedCallback<R> = {}
): Paginated<R> ): Paginated<R>
fun exec(sql: String, values: List<Any?> = emptyList()): QueryResult /**
* Select Paginated [EntityI] with multiple [Pair] of parameters
*/
fun <R : EntityI> select(
sql: String,
page: Int,
limit: Int,
typeReference: TypeReference<List<R>>,
vararg values: Pair<String, Any?>,
block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(sql, page, limit, typeReference, values.toMap(), block)
fun <R : EntityI> exec(sql: String, value: R): QueryResult = exec(sql, listOf(value))
fun exec(sql: String, values: List<Any?>): QueryResult
fun exec(sql: String, values: Map<String, Any?>): QueryResult fun exec(sql: String, values: Map<String, Any?>): QueryResult
fun sendQuery(sql: String, values: List<Any?> = emptyList()): Int fun exec(sql: String, vararg values: Pair<String, Any?>): QueryResult = exec(sql, values.toMap())
fun sendQuery(sql: String, values: Map<String, Any?>): Int
/**
* Warning: this method not use prepared statement
*/
fun <R : EntityI> sendQuery(sql: String, value: R): QueryResult = sendQuery(sql, listOf(value))
/**
* Warning: this method not use prepared statement
*/
fun sendQuery(sql: String, values: List<Any?>): QueryResult
/**
* Warning: this method not use prepared statement
*/
fun sendQuery(sql: String, values: Map<String, Any?>): QueryResult
/**
* Warning: this method not use prepared statement
*/
fun sendQuery(sql: String, vararg values: Pair<String, Any?>): QueryResult = sendQuery(sql, values.toMap())
} }

View File

@@ -0,0 +1,106 @@
package fr.postgresjson.connexion
import com.fasterxml.jackson.core.type.TypeReference
import fr.postgresjson.entity.EntityI
/* Update */
/**
* Update [EntityI] with one entity as argument
*/
inline fun <reified R : EntityI> Executable.update(
sql: String,
value: R,
noinline block: SelectOneCallback<R> = {}
): R? =
update(sql, object : TypeReference<R>() {}, value, block)
/* Select One */
/**
* Select One [EntityI] with [List] of parameters
*/
inline fun <reified R : EntityI> Executable.selectOne(
sql: String,
values: List<Any?> = emptyList(),
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(sql, object : TypeReference<R>() {}, values, block)
/**
* Select One [EntityI] with [Map] of parameters
*/
inline fun <reified R : EntityI> Executable.selectOne(
sql: String,
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(sql, object : TypeReference<R>() {}, values, block)
/**
* Select One [EntityI] with multiple [Pair] of parameters
*/
inline fun <reified R : EntityI> Executable.selectOne(
sql: String,
vararg values: Pair<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(sql, object : TypeReference<R>() {}, values = values, block)
/* Select Multiples */
/**
* Select Multiple [EntityI] with [List] of parameters
*/
inline fun <reified R : EntityI> Executable.select(
sql: String,
values: List<Any?> = emptyList(),
noinline block: SelectCallback<R> = {}
): List<R> =
select(sql, object : TypeReference<List<R>>() {}, values, block)
/**
* Select Multiple [EntityI] with [Map] of parameters
*/
inline fun <reified R : EntityI> Executable.select(
sql: String,
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(sql, object : TypeReference<List<R>>() {}, values, block)
/**
* Select Multiple [EntityI] with multiple [Pair] of parameters
*/
inline fun <reified R : EntityI> Executable.select(
sql: String,
vararg values: Pair<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(sql, object : TypeReference<List<R>>() {}, values = values, block)
/* Select Paginated */
/**
* Select Paginated [EntityI] with [Map] of parameters
*/
inline fun <reified R : EntityI> Executable.select(
sql: String,
page: Int,
limit: Int,
values: Map<String, Any?> = emptyMap(),
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(sql, page, limit, object : TypeReference<List<R>>() {}, values, block)
/**
* Select Paginated [EntityI] with multiple [Pair] of parameters
*/
inline fun <reified R : EntityI> Executable.select(
sql: String,
page: Int,
limit: Int,
vararg values: Pair<String, Any?>,
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(sql, page, limit, object : TypeReference<List<R>>() {}, values = values, block)

View File

@@ -15,109 +15,51 @@ class Function(val definition: Function, override val connection: Connection) :
/* Select One */ /* Select One */
/** /**
* Select One entity with list of parameters * Select One [EntityI] with [List] of parameters
*/ */
override fun <R : EntityI> select( override fun <R : EntityI> selectOne(
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: List<Any?>, values: List<Any?>,
block: (QueryResult, R?) -> Unit block: (QueryResult, R?) -> Unit
): R? {
val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block)
}
inline fun <reified R : EntityI> selectOne(
values: List<Any?> = emptyList(),
noinline block: SelectOneCallback<R> = {}
): R? = ): R? =
select(object : TypeReference<R>() {}, values, block) connection.selectOne(compileSql(values), typeReference, values, block)
inline fun <reified R : EntityI> selectOne(
value: R,
noinline block: SelectOneCallback<R> = {}
): R? =
select(object : TypeReference<R>() {}, listOf(value), block)
/** /**
* Select One entity with named parameters * Select One [EntityI] with named parameters
*/ */
override fun <R : EntityI> select( override fun <R : EntityI> selectOne(
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, R?) -> Unit block: (QueryResult, R?) -> Unit
): R? {
val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block)
}
inline fun <reified R : EntityI> selectOne(
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? = ): R? =
select(object : TypeReference<R>() {}, values, block) connection.selectOne(compileSql(values), typeReference, values, block)
inline fun <reified R : EntityI> selectOne(
vararg values: Pair<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
selectOne(values.toMap(), block)
/* Select Multiples */ /* Select Multiples */
/** /**
* Select list of entities with list of parameters * Select multiple [EntityI] with [List] of parameters
*/ */
override fun <R : EntityI> select( override fun <R : EntityI> select(
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: List<Any?>, values: List<Any?>,
block: (QueryResult, List<R>) -> Unit block: (QueryResult, List<R>) -> Unit
): List<R> {
val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block)
}
inline fun <reified R : EntityI> select(
values: List<Any?> = emptyList(),
noinline block: SelectCallback<R> = {}
): List<R> = ): List<R> =
select(object : TypeReference<List<R>>() {}, values, block) connection.select(compileSql(values), typeReference, values, block)
/** /**
* Select list of entities with named parameters * Select multiple [EntityI] with named parameters
*/ */
override fun <R : EntityI> select( override fun <R : EntityI> select(
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, List<R>) -> Unit block: (QueryResult, List<R>) -> Unit
): List<R> {
val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block)
}
inline fun <reified R : EntityI> select(
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> = ): List<R> =
select(object : TypeReference<List<R>>() {}, values, block) connection.select(compileSql(values), typeReference, values, block)
inline fun <reified R : EntityI> select(
vararg values: Pair<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(values.toMap(), block)
/* Select Paginated */ /* Select Paginated */
/** /**
* Select Multiple with pagination * Select Multiple [EntityI] with pagination
*/ */
override fun <R : EntityI> select( override fun <R : EntityI> select(
page: Int, page: Int,
@@ -131,53 +73,16 @@ class Function(val definition: Function, override val connection: Connection) :
.plus("offset" to offset) .plus("offset" to offset)
.plus("limit" to limit) .plus("limit" to limit)
val args = compileArgs(newValues) return connection.select(compileSql(newValues), page, limit, typeReference, values, block)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, page, limit, typeReference, values, block)
} }
inline fun <reified R : EntityI> select( /* Execute function without treatments */
page: Int,
limit: Int,
values: Map<String, Any?> = emptyMap(),
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(page, limit, object : TypeReference<List<R>>() {}, values, block)
inline fun <reified R : EntityI> select( override fun exec(values: List<Any?>): QueryResult = connection.exec(compileSql(values), values)
page: Int,
limit: Int,
vararg values: Pair<String, Any?>,
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> =
select(page, limit, object : TypeReference<List<R>>() {}, values.toMap(), block)
/* Execute function without traitements */ override fun exec(values: Map<String, Any?>): QueryResult = connection.exec(compileSql(values), values)
override fun exec(values: List<Any?>): QueryResult { private fun <R : EntityI> compileArgs(value: R): String = compileArgs(listOf(value))
val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.exec(sql, values)
}
override fun exec(values: Map<String, Any?>): QueryResult {
val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.exec(sql, values)
}
override fun sendQuery(values: List<Any?>): Int {
exec(values)
return 0
}
override fun sendQuery(values: Map<String, Any?>): Int {
exec(values)
return 0
}
private fun compileArgs(values: List<Any?>): String { private fun compileArgs(values: List<Any?>): String {
val placeholders = values val placeholders = values
@@ -205,4 +110,8 @@ class Function(val definition: Function, override val connection: Connection) :
return placeholders.joinToString(separator = ", ") return placeholders.joinToString(separator = ", ")
} }
private fun <R : EntityI> compileSql(value: R): String = "SELECT * FROM ${definition.name} (${compileArgs(value)})"
private fun compileSql(values: List<Any?>): String = "SELECT * FROM ${definition.name} (${compileArgs(values)})"
private fun compileSql(values: Map<String, Any?>): String = "SELECT * FROM ${definition.name} (${compileArgs(values)})"
} }

View File

@@ -0,0 +1,16 @@
package fr.postgresjson.connexion
import fr.postgresjson.utils.searchSqlFiles
import java.net.URI
import fr.postgresjson.definition.Function as DefinitionFunction
fun DefinitionFunction.toRunnable(connection: Connection): Function = Function(this, connection)
fun Sequence<DefinitionFunction>.toRunnable(connection: Connection): Sequence<Function> = map { it.toRunnable(connection) }
fun Sequence<Function>.toMutableMap(): MutableMap<String, Function> = map { it.name to it }.toMap().toMutableMap()
internal fun URI.toFunction(connection: Connection): MutableMap<String, Function> = searchSqlFiles()
.filterIsInstance(DefinitionFunction::class.java)
.toRunnable(connection)
.toMutableMap()

View File

@@ -14,9 +14,9 @@ data class Paginated<T : EntityI>(
val totalPages: Int = (total.toDouble() / limit.toDouble()).ceil() val totalPages: Int = (total.toDouble() / limit.toDouble()).ceil()
init { init {
if (offset < 0) error("offset must be greather or equal than 0") if (offset < 0) error("offset must be greater or equal than 0")
if (limit < 1) error("limit must be greather or equal than 1") if (limit < 1) error("limit must be greater or equal than 1")
if (total < 0) error("total must be greather or equal than 0") if (total < 0) error("total must be greater or equal than 0")
} }
fun isLastPage(): Boolean = currentPage >= totalPages fun isLastPage(): Boolean = currentPage >= totalPages

View File

@@ -11,99 +11,79 @@ class Query(override val name: String, private val sql: String, override val con
/* Select One */ /* Select One */
override fun <R : EntityI> select( /**
* Select One [EntityI] with [List] of parameters
*/
override fun <R : EntityI> selectOne(
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: List<Any?>, values: List<Any?>,
block: (QueryResult, R?) -> Unit block: SelectOneCallback<R>
): R? {
return connection.select(this.toString(), typeReference, values, block)
}
inline fun <reified R : EntityI> selectOne(
values: List<Any?> = emptyList(),
noinline block: SelectOneCallback<R> = {}
): R? = ): R? =
select(object : TypeReference<R>() {}, values, block) connection.selectOne(sql, typeReference, values, block)
override fun <R : EntityI> select( /**
* Select One [EntityI] with named parameters
*/
override fun <R : EntityI> selectOne(
typeReference: TypeReference<R>, typeReference: TypeReference<R>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, R?) -> Unit block: SelectOneCallback<R>
): R? {
return connection.select(this.toString(), typeReference, values, block)
}
inline fun <reified R : EntityI> selectOne(
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? = ): R? =
select(object : TypeReference<R>() {}, values, block) connection.selectOne(sql, typeReference, values, block)
/* Select Multiples */ /* Select Multiples */
/**
* Select multiple [EntityI] with [List] of parameters
*/
override fun <R : EntityI> select( override fun <R : EntityI> select(
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: List<Any?>, values: List<Any?>,
block: (QueryResult, List<R>) -> Unit block: SelectCallback<R>
): List<R> {
return connection.select(this.toString(), typeReference, values, block)
}
inline fun <reified R : EntityI> select(
values: List<Any?> = emptyList(),
noinline block: SelectCallback<R> = {}
): List<R> = ): List<R> =
select(object : TypeReference<List<R>>() {}, values, block) connection.select(sql, typeReference, values, block)
/**
* Select multiple [EntityI] with [Map] of parameters
*/
override fun <R : EntityI> select( override fun <R : EntityI> select(
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, List<R>) -> Unit block: SelectCallback<R>
): List<R> {
return connection.select(this.toString(), typeReference, values, block)
}
inline fun <reified R : EntityI> select(
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> = ): List<R> =
select(object : TypeReference<List<R>>() {}, values, block) connection.select(sql, typeReference, values, block)
/* Select Paginated */
/**
* Select Multiple [EntityI] with pagination
*/
override fun <R : EntityI> select( override fun <R : EntityI> select(
page: Int, page: Int,
limit: Int, limit: Int,
typeReference: TypeReference<List<R>>, typeReference: TypeReference<List<R>>,
values: Map<String, Any?>, values: Map<String, Any?>,
block: (QueryResult, Paginated<R>) -> Unit block: (QueryResult, Paginated<R>) -> Unit
): Paginated<R> {
return connection.select(this.toString(), page, limit, typeReference, values, block)
}
/* Select Paginated */
inline fun <reified R : EntityI> select(
page: Int,
limit: Int,
values: Map<String, Any?> = emptyMap(),
noinline block: SelectPaginatedCallback<R> = {}
): Paginated<R> = ): Paginated<R> =
select(page, limit, object : TypeReference<List<R>>() {}, values, block) connection.select(sql, page, limit, typeReference, values, block)
/* Execute function without traitements */ /* Execute function without treatments */
override fun exec(values: List<Any?>): QueryResult { override fun exec(values: List<Any?>): QueryResult = connection.exec(sql, values)
return connection.exec(sql, values)
}
override fun exec(values: Map<String, Any?>): QueryResult { override fun exec(values: Map<String, Any?>): QueryResult = connection.exec(sql, values)
return connection.exec(sql, values)
}
override fun sendQuery(values: List<Any?>): Int { /**
return connection.sendQuery(sql, values) * Warning: this method not use prepared statement
} */
fun sendQuery(values: List<Any?>): QueryResult = connection.sendQuery(sql, values)
override fun sendQuery(values: Map<String, Any?>): Int { /**
return connection.sendQuery(sql, values) * Warning: this method not use prepared statement
} */
fun sendQuery(values: Map<String, Any?>): QueryResult = connection.sendQuery(sql, values)
/**
* Warning: this method not use prepared statement
*/
fun sendQuery(vararg values: Pair<String, Any?>): QueryResult = sendQuery(values.toMap())
} }

View File

@@ -0,0 +1,16 @@
package fr.postgresjson.connexion
import fr.postgresjson.utils.searchSqlFiles
import java.net.URI
import fr.postgresjson.definition.Query as QueryDefinition
fun QueryDefinition.toRunnable(connection: Connection): Query = Query(name, script, connection)
fun Sequence<QueryDefinition>.toRunnable(connection: Connection): Sequence<Query> = map { it.toRunnable(connection) }
fun Sequence<Query>.toMutableMap(): MutableMap<String, Query> = map { it.name to it }.toMap().toMutableMap()
internal fun URI.toQuery(connection: Connection): MutableMap<String, Query> = searchSqlFiles()
.filterIsInstance(QueryDefinition::class.java)
.toRunnable(connection)
.toMutableMap()

View File

@@ -3,7 +3,6 @@ package fr.postgresjson.connexion
import fr.postgresjson.utils.searchSqlFiles import fr.postgresjson.utils.searchSqlFiles
import java.net.URI import java.net.URI
import fr.postgresjson.definition.Function as DefinitionFunction import fr.postgresjson.definition.Function as DefinitionFunction
import fr.postgresjson.definition.Function as FunctionDefinition
import fr.postgresjson.definition.Query as QueryDefinition import fr.postgresjson.definition.Query as QueryDefinition
class Requester( class Requester(
@@ -11,101 +10,59 @@ class Requester(
private val queries: MutableMap<String, Query> = mutableMapOf(), private val queries: MutableMap<String, Query> = mutableMapOf(),
private val functions: MutableMap<String, Function> = mutableMapOf() private val functions: MutableMap<String, Function> = mutableMapOf()
) { ) {
fun addQuery(query: Query): Requester { constructor(connection: Connection) : this(connection, mutableMapOf(), mutableMapOf())
queries[query.name] = query
return this
}
fun addQuery(query: QueryDefinition): Requester = addQuery(query.name, query.script)
fun addQuery(name: String, sql: String): Requester {
addQuery(Query(name, sql, connection))
return this
}
fun addQuery(queriesDirectory: URI): Requester {
queriesDirectory.searchSqlFiles()
.forEach {
if (it is QueryDefinition) {
addQuery(it)
}
}
return this
}
fun getQueries(): List<Query> {
return queries.map { it.value }
}
fun addFunction(definition: DefinitionFunction): Requester {
functions[definition.name] = Function(definition, connection)
return this
}
fun addFunction(sql: String): Requester {
DefinitionFunction(sql).let {
functions[it.name] = Function(it, connection)
}
return this
}
fun addFunction(functionsDirectory: URI): Requester {
functionsDirectory.searchSqlFiles()
.forEach {
if (it is FunctionDefinition) {
addFunction(it)
}
}
return this
}
fun getFunction(name: String): Function {
if (functions[name] === null) {
throw Exception("No function defined for $name")
}
return functions[name]!!
}
fun getQuery(path: String): Query {
if (queries[path] === null) {
throw Exception("No query defined in $path")
}
return queries[path]!!
}
class RequesterFactory(
private val connection: Connection,
private val queriesDirectory: URI? = null,
private val functionsDirectory: URI? = null
) {
constructor( constructor(
host: String = "localhost", connection: Connection,
port: Int = 5432,
database: String = "dc-project",
username: String = "dc-project",
password: String = "dc-project",
queriesDirectory: URI? = null, queriesDirectory: URI? = null,
functionsDirectory: URI? = null functionsDirectory: URI? = null
) : this( ) : this(
Connection(host = host, port = port, database = database, username = username, password = password), connection = connection,
queriesDirectory, queries = queriesDirectory?.toQuery(connection) ?: mutableMapOf(),
functionsDirectory functions = functionsDirectory?.toFunction(connection) ?: mutableMapOf(),
) )
fun createRequester(): Requester { fun addQuery(query: Query) {
return initRequester(Requester(connection)) queries[query.name] = query
} }
private fun initRequester(req: Requester): Requester { fun addQuery(query: QueryDefinition) = addQuery(query.toRunnable(connection))
if (queriesDirectory !== null) {
req.addQuery(queriesDirectory) fun addQuery(name: String, sql: String) {
addQuery(Query(name, sql, connection))
} }
if (functionsDirectory !== null) { fun addQuery(queriesDirectory: URI) {
req.addFunction(functionsDirectory) queriesDirectory
.searchSqlFiles()
.filterIsInstance(QueryDefinition::class.java)
.forEach(this::addQuery)
} }
return req fun getQueries(): List<Query> = queries.map { it.value }
fun addFunction(definition: DefinitionFunction) {
definition
.run { toRunnable(connection) }
.run { functions[name] = this }
} }
fun addFunction(sql: String) {
DefinitionFunction(sql)
.run { toRunnable(connection) }
.run { functions[name] = this }
} }
fun addFunctions(functionsDirectory: URI) {
functionsDirectory.searchSqlFiles()
.filterIsInstance(DefinitionFunction::class.java)
.forEach(this::addFunction)
}
fun getFunction(name: String): Function = functions[name] ?: throw NoFunctionDefined(name)
fun getQuery(path: String): Query = queries[path] ?: throw NoQueryDefined(path)
class NoFunctionDefined(name: String) : Exception("No function defined for $name")
class NoQueryDefined(path: String) : Exception("No query defined in $path")
} }

View File

@@ -1,11 +1,10 @@
package fr.postgresjson.definition package fr.postgresjson.definition
import java.io.File
import java.nio.file.Path import java.nio.file.Path
class Function( class Function(
override val script: String, override val script: String,
override var source: Path? = null override val source: Path? = null
) : Resource, ParametersInterface { ) : Resource, ParametersInterface {
val returns: String val returns: String
override val name: String override val name: String
@@ -22,7 +21,7 @@ class Function(
val queryMatch = functionRegex.find(script) val queryMatch = functionRegex.find(script)
if (queryMatch !== null) { if (queryMatch !== null) {
val functionName = queryMatch.groups.get("name")?.value?.trim() ?: error("Function name not found") val functionName = queryMatch.groups["name"]?.value?.trim() ?: error("Function name not found")
val functionParameters = queryMatch.groups["params"]?.value?.trim() val functionParameters = queryMatch.groups["params"]?.value?.trim()
this.returns = queryMatch.groups["return"]?.value?.trim() ?: "" this.returns = queryMatch.groups["return"]?.value?.trim() ?: ""
@@ -52,15 +51,12 @@ class Function(
fun getDefinition(): String { fun getDefinition(): String {
return parameters return parameters
.filter { it.direction == Parameter.Direction.IN } .filter { it.direction == Parameter.Direction.IN }
.joinToString(", ") { "${it.name} ${it.type}" }.let { .joinToString(", ") { "${it.name} ${it.type}" }
"$name ($it)" .let { "$name ($it)" }
}
} }
fun getParametersIndexedByName(): Map<String, Parameter> { fun getParametersIndexedByName(): Map<String, Parameter> {
return parameters.map { return parameters.associateBy { it.name }
it.name to it
}.toMap()
} }
infix fun `has same definition`(other: Function): Boolean { infix fun `has same definition`(other: Function): Boolean {
@@ -70,21 +66,4 @@ class Function(
infix fun `is different from`(other: Function): Boolean { infix fun `is different from`(other: Function): Boolean {
return other.script != this.script return other.script != this.script
} }
companion object {
fun build(source: File): List<Function> {
return source.readText()
.split(
"CREATE +(OR REPLACE +)?(PROCEDURE|FUNCTION)".toRegex(
setOf(
RegexOption.IGNORE_CASE,
RegexOption.MULTILINE
)
)
)
.map {
Function("CREATE OR REPLACE FUNCTION $it")
}
}
}
} }

View File

@@ -4,14 +4,12 @@ import java.nio.file.Path
class Migration( class Migration(
override val script: String, override val script: String,
source: Path override var source: Path
) : Resource { ) : Resource {
override val name: String override val name: String
val direction: Direction val direction: Direction
override var source: Path? = null
init { init {
this.source = source
this.direction = source.fileName.toString() this.direction = source.fileName.toString()
.let { .let {
when { when {

View File

@@ -1,5 +1,7 @@
package fr.postgresjson.definition package fr.postgresjson.definition
import java.util.Locale
interface ParameterI { interface ParameterI {
val name: String val name: String
val type: String val type: String
@@ -21,7 +23,7 @@ class Parameter(val name: String, val type: String, direction: Direction? = Dire
constructor(name: String, type: String, direction: String? = "IN", default: Any? = null) : this( constructor(name: String, type: String, direction: String? = "IN", default: Any? = null) : this(
name = name, name = name,
type = type, type = type,
direction = direction?.let { Direction.valueOf(direction.toUpperCase()) }, direction = direction?.let { Direction.valueOf(direction.uppercase(Locale.getDefault())) },
default = default default = default
) )

View File

@@ -4,9 +4,8 @@ import java.nio.file.Path
class Query( class Query(
override val script: String, override val script: String,
source: Path override var source: Path
) : Resource { ) : Resource {
override var source: Path? = source
override val name: String = getNameFromComment(script) ?: getNameFromFile(source) override val name: String = getNameFromComment(script) ?: getNameFromFile(source)
/** Try to get name from comment in file */ /** Try to get name from comment in file */

View File

@@ -4,10 +4,10 @@ import java.io.File
import java.net.URL import java.net.URL
import java.nio.file.Path import java.nio.file.Path
interface Resource { sealed interface Resource {
val name: String val name: String
val script: String val script: String
var source: Path? val source: Path?
open class ParseException(message: String, cause: Throwable? = null) : Exception(message, cause) open class ParseException(message: String, cause: Throwable? = null) : Exception(message, cause)
@@ -34,7 +34,3 @@ interface Resource {
} }
} }
} }
interface ResourceCollection {
val parameters: List<Parameter>
}

View File

@@ -1,7 +1,7 @@
package fr.postgresjson.entity package fr.postgresjson.entity
import org.joda.time.DateTime import org.joda.time.DateTime
import java.util.* import java.util.UUID
interface EntityRefI<T> : EntityI { interface EntityRefI<T> : EntityI {
val id: T val id: T

View File

@@ -2,10 +2,11 @@ package fr.postgresjson.migration
import com.github.jasync.sql.db.postgresql.exceptions.GenericDatabaseException import com.github.jasync.sql.db.postgresql.exceptions.GenericDatabaseException
import fr.postgresjson.connexion.Connection import fr.postgresjson.connexion.Connection
import fr.postgresjson.connexion.selectOne
import fr.postgresjson.migration.Migration.Action import fr.postgresjson.migration.Migration.Action
import fr.postgresjson.migration.Migration.Status import fr.postgresjson.migration.Migration.Status
import java.util.* import java.util.Date
import java.util.concurrent.* import java.util.concurrent.CompletionException
import fr.postgresjson.definition.Function as DefinitionFunction import fr.postgresjson.definition.Function as DefinitionFunction
data class Function( data class Function(
@@ -36,6 +37,7 @@ data class Function(
) )
override fun up(): Status { override fun up(): Status {
return try {
try { try {
connection.sendQuery(up.script) connection.sendQuery(up.script)
} catch (e: CompletionException) { } catch (e: CompletionException) {
@@ -46,51 +48,48 @@ data class Function(
} }
} }
this::class.java.classLoader.getResource("sql/migration/insertFunction.sql")!!.readText().let { this::class.java.classLoader
connection.selectOne<MigrationEntity>(it, listOf(up.name, up.getDefinition(), up.script, down.script))?.let { function -> .getResource("sql/migration/insertFunction.sql")!!.readText()
.let { connection.selectOne<MigrationEntity>(it, listOf(up.name, up.getDefinition(), up.script, down.script)) }
?.let { function ->
executedAt = function.executedAt executedAt = function.executedAt
doExecute = Action.OK doExecute = Action.OK
} }
Status.OK
} catch (e: Throwable) {
Status.UP_FAIL
} }
return Status.OK
} }
override fun down(): Status { override fun down(): Status {
return try {
connection.sendQuery(down.script) connection.sendQuery(down.script)
this::class.java.classLoader.getResource("sql/migration/deleteFunction.sql")!!.readText().let { this::class.java.classLoader
connection.sendQuery(it, listOf(down.name)) .getResource("sql/migration/deleteFunction.sql")!!
.readText()
.let { connection.sendQuery(it, listOf(down.name)) }
Status.OK
} catch (e: Throwable) {
Status.DOWN_FAIL
} }
return Status.OK
} }
override fun test(): Status { override fun test(): Status {
connection.inTransaction { connection.inTransaction {
up() up()
down() down()
it.sendQuery("ROLLBACK") sendQuery("ROLLBACK")
}.join()
return Status.OK // TODO
} }
override fun status(): Status { return Status.OK
connection.inTransaction {
up()
down()
it.sendQuery("ROLLBACK")
}.join()
return Status.OK // TODO
} }
fun copy(): Function { fun copy(): Function = this
return this.copy(up = up, down = down, connection = connection, executedAt = executedAt).also { .copy(up = up, down = down, connection = connection, executedAt = executedAt)
it.doExecute = this.doExecute .also { it.doExecute = this.doExecute }
}
}
infix fun `is different from`(other: DefinitionFunction): Boolean { infix fun `is different from`(other: DefinitionFunction): Boolean = other.script != this.up.script
return other.script != this.up.script
}
} }

View File

@@ -1,9 +1,10 @@
package fr.postgresjson.migration package fr.postgresjson.migration
import fr.postgresjson.connexion.Connection import fr.postgresjson.connexion.Connection
import fr.postgresjson.connexion.selectOne
import fr.postgresjson.entity.Entity import fr.postgresjson.entity.Entity
import fr.postgresjson.migration.Migration.Action import fr.postgresjson.migration.Migration.Action
import java.util.* import java.util.Date
data class MigrationScript( data class MigrationScript(
val name: String, val name: String,
@@ -41,20 +42,10 @@ data class MigrationScript(
connection.inTransaction { connection.inTransaction {
up() up()
down() down()
it.sendQuery("ROLLBACK") sendQuery("ROLLBACK")
}.join()
return Migration.Status.OK // TODO
} }
override fun status(): Migration.Status { return Migration.Status.OK
connection.inTransaction {
up()
down()
it.sendQuery("ROLLBACK")
}.join()
return Migration.Status.OK // TODO
} }
fun copy(): MigrationScript { fun copy(): MigrationScript {

View File

@@ -2,7 +2,6 @@ package fr.postgresjson.migration
import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.core.type.TypeReference
import fr.postgresjson.connexion.Connection import fr.postgresjson.connexion.Connection
import fr.postgresjson.definition.Migration as DefinitionMigration
import fr.postgresjson.entity.Entity import fr.postgresjson.entity.Entity
import fr.postgresjson.migration.Migration.Action import fr.postgresjson.migration.Migration.Action
import fr.postgresjson.migration.Migration.Status import fr.postgresjson.migration.Migration.Status
@@ -11,8 +10,9 @@ import fr.postgresjson.utils.searchSqlFiles
import org.slf4j.Logger import org.slf4j.Logger
import java.io.FileNotFoundException import java.io.FileNotFoundException
import java.net.URI import java.net.URI
import java.util.* import java.util.Date
import fr.postgresjson.definition.Function as DefinitionFunction import fr.postgresjson.definition.Function as DefinitionFunction
import fr.postgresjson.definition.Migration as DefinitionMigration
class MigrationEntity( class MigrationEntity(
val filename: String, val filename: String,
@@ -28,13 +28,12 @@ interface Migration {
fun up(): Status fun up(): Status
fun down(): Status fun down(): Status
fun test(): Status fun test(): Status
fun status(): Status
enum class Status(i: Int) { OK(2), UP_FAIL(0), DOWN_FAIL(1) } enum class Status(val i: Int) { OK(2), UP_FAIL(0), DOWN_FAIL(1) }
enum class Action { OK, UP, DOWN } enum class Action { OK, UP, DOWN }
} }
data class Migrations private constructor( class Migrations private constructor(
private val connection: Connection, private val connection: Connection,
private val migrationsScripts: MutableMap<String, MigrationScript> = mutableMapOf(), private val migrationsScripts: MutableMap<String, MigrationScript> = mutableMapOf(),
private val functions: MutableMap<String, Function> = mutableMapOf() private val functions: MutableMap<String, Function> = mutableMapOf()
@@ -50,7 +49,7 @@ data class Migrations private constructor(
reset() reset()
} }
fun reset() { private fun reset() {
migrationsScripts.clear() migrationsScripts.clear()
functions.clear() functions.clear()
@@ -77,14 +76,14 @@ data class Migrations private constructor(
*/ */
private fun getMigrationFromDB() { private fun getMigrationFromDB() {
this::class.java.classLoader.getResource("sql/migration/findAllFunction.sql")!!.readText().let { this::class.java.classLoader.getResource("sql/migration/findAllFunction.sql")!!.readText().let {
connection.select<MigrationEntity>(it, object : TypeReference<List<MigrationEntity>>() {}) connection.select(it, object : TypeReference<List<MigrationEntity>>() {})
.map { function -> .map { function ->
functions[function.filename] = Function(function.up, function.down, connection, function.executedAt) functions[function.filename] = Function(function.up, function.down, connection, function.executedAt)
} }
} }
this::class.java.classLoader.getResource("sql/migration/findAllHistory.sql")!!.readText().let { this::class.java.classLoader.getResource("sql/migration/findAllHistory.sql")!!.readText().let {
connection.select<MigrationEntity>(it, object : TypeReference<List<MigrationEntity>>() {}) connection.select(it, object : TypeReference<List<MigrationEntity>>() {})
.map { query -> .map { query ->
migrationsScripts[query.filename] = MigrationScript(query.filename, query.up, query.down, connection, query.executedAt) migrationsScripts[query.filename] = MigrationScript(query.filename, query.up, query.down, connection, query.executedAt)
} }
@@ -131,7 +130,7 @@ data class Migrations private constructor(
enum class Direction { UP, DOWN } enum class Direction { UP, DOWN }
internal class DownMigrationNotDefined(path: String, cause: FileNotFoundException? = null) : internal class DownMigrationNotDefined(path: String, cause: FileNotFoundException? = null) :
Throwable("The file $path whas not found", cause) Throwable("The file $path was not found", cause)
fun addFunction(newDefinition: DefinitionFunction, callback: (Function) -> Unit = {}): Migrations { fun addFunction(newDefinition: DefinitionFunction, callback: (Function) -> Unit = {}): Migrations {
val currentFunction = functions[newDefinition.name] val currentFunction = functions[newDefinition.name]
@@ -175,10 +174,10 @@ data class Migrations private constructor(
private fun initDB() { private fun initDB() {
if (!initialized) { if (!initialized) {
this::class.java.classLoader.getResource("sql/migration/createHistoryShema.sql")!!.readText().let { this::class.java.classLoader.getResource("sql/migration/createHistorySchema.sql")!!.readText().let {
connection.sendQuery(it) connection.sendQuery(it)
} }
this::class.java.classLoader.getResource("sql/migration/createFunctionShema.sql")!!.readText().let { this::class.java.classLoader.getResource("sql/migration/createFunctionSchema.sql")!!.readText().let {
connection.sendQuery(it) connection.sendQuery(it)
} }
initialized = true initialized = true
@@ -298,7 +297,7 @@ data class Migrations private constructor(
return list.toMap() return list.toMap()
} }
fun copy(): Migrations { private fun copy(): Migrations {
val queriesCopy = migrationsScripts.map { val queriesCopy = migrationsScripts.map {
it.key to it.value.copy() it.key to it.value.copy()
}.toMap().toMutableMap() }.toMap().toMutableMap()

View File

@@ -3,7 +3,7 @@ package fr.postgresjson.serializer
import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.PropertyNamingStrategies
import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.datatype.joda.JodaModule import com.fasterxml.jackson.datatype.joda.JodaModule
@@ -15,7 +15,7 @@ class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
init { init {
val module = SimpleModule() val module = SimpleModule()
mapper.registerModule(module) mapper.registerModule(module)
mapper.propertyNamingStrategy = PropertyNamingStrategy.SNAKE_CASE mapper.propertyNamingStrategy = PropertyNamingStrategies.SNAKE_CASE
mapper.registerModule(JodaModule()) mapper.registerModule(JodaModule())
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
@@ -42,13 +42,10 @@ class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
inline fun <reified E> deserializeList(json: String): E { inline fun <reified E> deserializeList(json: String): E {
return deserializeList(json, object : TypeReference<E>() {}) return deserializeList(json, object : TypeReference<E>() {})
} }
fun <E> deserialize(json: String, target: E): E {
return mapper.readerForUpdating(target).readValue<E>(json)
}
} }
fun Serializable.serialize(pretty: Boolean = false) = Serializer().serialize(this, pretty) fun Serializable.serialize(pretty: Boolean = false) = Serializer().serialize(this, pretty)
fun List<Serializable>.serialize(pretty: Boolean = false) = Serializer().serialize(this, pretty) fun List<Serializable>.serialize(pretty: Boolean = false) = Serializer().serialize(this, pretty)
inline fun <reified E : Serializable> E.deserialize(json: String) = Serializer().deserialize(json, this)
inline fun <reified E : Serializable> String.deserialize() = Serializer().deserialize<E>(this) inline fun <reified E : Serializable> String.deserialize() = Serializer().deserialize<E>(this)
inline fun <reified T : Serializable> T.toTypeReference(): TypeReference<T> = object : TypeReference<T>() {}

View File

@@ -6,5 +6,5 @@ import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty import kotlin.reflect.KProperty
internal class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> { internal class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>) = LoggerFactory.getLogger(thisRef.javaClass.packageName) override fun getValue(thisRef: R, property: KProperty<*>): Logger = LoggerFactory.getLogger(thisRef.javaClass.packageName)
} }

View File

@@ -14,7 +14,7 @@ import kotlin.streams.asSequence
fun URL.searchSqlFiles() = this.toURI().searchSqlFiles() fun URL.searchSqlFiles() = this.toURI().searchSqlFiles()
fun URI.searchSqlFiles() = sequence<Resource> { fun URI.searchSqlFiles() = sequence {
val logger: Logger = LoggerFactory.getLogger("sqlFilesSearch") val logger: Logger = LoggerFactory.getLogger("sqlFilesSearch")
val uri: URI = this@searchSqlFiles val uri: URI = this@searchSqlFiles
logger.debug("""SQL files found in "${uri.toString().substringAfter('!')}" :""") logger.debug("""SQL files found in "${uri.toString().substringAfter('!')}" :""")
@@ -47,5 +47,5 @@ fun URI.searchSqlFiles() = sequence<Resource> {
} }
} }
private fun Path.walk(maxDepth: Int = 2147483647, vararg options: FileVisitOption) = Files.walk(this, maxDepth, *options) private fun Path.walk(maxDepth: Int = 2147483647, vararg options: FileVisitOption) = Files.walk(this, maxDepth, *options).sorted()
private fun URI.walk(maxDepth: Int = 2147483647, vararg options: FileVisitOption) = Files.walk(Path.of(this), maxDepth, *options) private fun URI.walk(maxDepth: Int = 2147483647, vararg options: FileVisitOption) = Files.walk(Path.of(this), maxDepth, *options).sorted()

View File

@@ -1,32 +1,43 @@
package fr.postgresjson package fr.postgresjson
import com.fasterxml.jackson.core.type.TypeReference
import fr.postgresjson.connexion.Connection.QueryError
import fr.postgresjson.connexion.Paginated import fr.postgresjson.connexion.Paginated
import fr.postgresjson.entity.UuidEntity import fr.postgresjson.connexion.select
import fr.postgresjson.connexion.selectOne
import fr.postgresjson.entity.Parameter import fr.postgresjson.entity.Parameter
import org.junit.Assert.* import fr.postgresjson.entity.UuidEntity
import org.junit.jupiter.api.Assertions import fr.postgresjson.serializer.deserialize
import fr.postgresjson.serializer.toTypeReference
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance
import java.util.* import org.junit.jupiter.api.assertThrows
import java.util.UUID
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ConnectionTest() : TestAbstract() { class ConnectionTest : TestAbstract() {
private class ObjTest(val name: String, id: UUID = UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00")) : UuidEntity(id) private class ObjTest(val name: String, id: UUID = UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00")) : UuidEntity(id)
private class ObjTest2(val title: String, var test: ObjTest?) : UuidEntity() private class ObjTest2(val title: String, var test: ObjTest?) : UuidEntity()
private class ObjTest3(val first: String, var seconde: String, var third: Int) : UuidEntity() private class ObjTest3(val first: String, var second: String, var third: Int) : UuidEntity()
private class ObjTestWithParameterObject(var first: ParameterObject, var seconde: ParameterObject) : UuidEntity() private class ObjTestWithParameterObject(var first: ParameterObject, var second: ParameterObject) : UuidEntity()
private class ParameterObject(var third: String) : Parameter private class ParameterObject(var third: String) : Parameter
@Test @Test
fun getObject() { fun getObject() {
val obj: ObjTest? = connection.selectOne("select to_json(a) from test a limit 1") val obj: ObjTest? = connection.selectOne("select to_json(a) from test a limit 1")
assertTrue(obj is ObjTest) assertTrue(obj is ObjTest)
assertTrue(obj!!.id == UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96")) assertEquals(UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"), obj.id)
} }
@Test @Test
fun getExistingObject() { fun getExistingObject() {
val objs: List<ObjTest2> = connection.select(""" val objs: List<ObjTest2> = connection.select(
"""
select select
json_agg(j) json_agg(j)
FROM ( FROM (
@@ -45,10 +56,31 @@ class ConnectionTest() : TestAbstract() {
} }
@Test @Test
fun callRequestWithArgs() { fun `test call request with args`() {
val result: ObjTest? = connection.selectOne("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', ?::text)", listOf("myName")) val result: ObjTest? = connection.selectOne("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', ?::text)", listOf("myName"))
assertNotNull(result) assertNotNull(result)
assertEquals("myName", result!!.name) assertEquals("myName", result.name)
}
@Test
fun `test call request without args`() {
val result: ObjTest? = connection.selectOne("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', 'myName')", object : TypeReference<ObjTest>() {}) {
assertEquals("myName", this.rows[0].getString(0)?.deserialize<ObjTest>()?.name)
}
assertNotNull(result)
assertEquals("myName", result.name)
}
@Test
fun `test call request return null`() {
val result: ObjTest? = connection.selectOne("select null;", object : TypeReference<ObjTest>() {})
assertNull(result)
}
@Test
fun `test call request return nothing`() {
val result: ObjTest? = connection.selectOne("select * from test where false;", object : TypeReference<ObjTest>() {})
assertNull(result)
} }
@Test @Test
@@ -56,84 +88,92 @@ class ConnectionTest() : TestAbstract() {
val o = ObjTest("myName", id = UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00")) val o = ObjTest("myName", id = UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00"))
val obj: ObjTest? = connection.selectOne("select json_build_object('id', id, 'name', name) FROM json_to_record(?::json) as o(id uuid, name text);", listOf(o)) val obj: ObjTest? = connection.selectOne("select json_build_object('id', id, 'name', name) FROM json_to_record(?::json) as o(id uuid, name text);", listOf(o))
assertNotNull(obj) assertNotNull(obj)
assertTrue(obj is ObjTest) assertEquals(UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00"), obj.id)
assertEquals(obj!!.id, UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00")) assertEquals("myName", obj.name)
assertEquals(obj.name, "myName") }
@Test
fun `test update Entity`() {
val obj = ObjTest("before", id = UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"))
val objUpdated: ObjTest? = connection.update("select ?::jsonb || jsonb_build_object('name', 'after');", obj.toTypeReference(), obj)
assertTrue(objUpdated is ObjTest)
assertEquals(UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"), objUpdated.id)
assertEquals("after", objUpdated.name)
} }
@Test @Test
fun callExec() { fun callExec() {
val o = ObjTest("myName") val o = ObjTest("myName")
val result = connection.exec("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', ?::json->>'name')", listOf(o)) val result = connection.exec("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', ?::json->>'name')", listOf(o))
Assertions.assertEquals(1, result.rowsAffected) assertEquals(1, result.rowsAffected)
} }
@Test @Test
fun `select one with named parameters`() { fun `select one with named parameters`() {
val result: ObjTest3? = connection.selectOne( val result: ObjTest3? = connection.selectOne(
"SELECT json_build_object('first', :first::text, 'seconde', :seconde::text, 'third', :third::int)", "SELECT json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int)",
mapOf( mapOf(
"first" to "ff", "first" to "ff",
"seconde" to "sec", "second" to "sec",
"third" to 123 "third" to 123
) )
) )
assertEquals(result!!.first, "ff") assertNotNull(result)
assertEquals(result.seconde, "sec") assertEquals("ff", result.first)
assertEquals(result.third, 123) assertEquals("sec", result.second)
assertEquals(123, result.third)
} }
@Test @Test
fun `select one with named parameters object`() { fun `select one with named parameters object`() {
val result: ObjTestWithParameterObject? = connection.selectOne( val result: ObjTestWithParameterObject? = connection.selectOne(
"SELECT json_build_object('first', :first::json, 'seconde', :seconde::json)", "SELECT json_build_object('first', :first::json, 'second', :second::json)",
mapOf( mapOf(
"first" to ParameterObject("one"), "first" to ParameterObject("one"),
"seconde" to ParameterObject("two") "second" to ParameterObject("two")
) )
) )
assertEquals("one", result!!.first.third) assertNotNull(result)
assertEquals("two", result.seconde.third) assertEquals("one", result.first.third)
assertEquals("two", result.second.third)
} }
@Test @Test
fun `select with named parameters`() { fun `select with named parameters`() {
val params: Map<String, Any?> = mapOf(
"first" to "ff",
"third" to 123,
"seconde" to "sec"
)
val result: List<ObjTest3> = connection.select( val result: List<ObjTest3> = connection.select(
""" """
SELECT json_build_array( SELECT json_build_array(
json_build_object('first', :first::text, 'seconde', :seconde::text, 'third', :third::int), json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int),
json_build_object('first', :first::text, 'seconde', :seconde::text, 'third', :third::int) json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int)
) )
""".trimIndent(), """.trimIndent(),
params mapOf(
"first" to "ff",
"third" to 123,
"second" to "sec"
) )
assertEquals(result[0].first, "ff") )
assertEquals(result[0].seconde, "sec") assertEquals("ff", result[0].first)
assertEquals(result[0].third, 123) assertEquals("sec", result[0].second)
assertEquals(123, result[0].third)
} }
@Test @Test
fun `selectOne with named parameters`() { fun `select with named parameters as vararg of Pair`() {
val params: Map<String, Any?> = mapOf( val result: List<ObjTest3> = connection.select(
"""
SELECT json_build_array(
json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int),
json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int)
)
""".trimIndent(),
"first" to "ff", "first" to "ff",
"third" to 123, "third" to 123,
"seconde" to "sec" "second" to "sec"
) )
val result: ObjTest3? = connection.selectOne( assertEquals("ff", result[0].first)
""" assertEquals("sec", result[0].second)
SELECT json_build_object('first', :first::text, 'seconde', :seconde::text, 'third', :third::int) assertEquals(123, result[0].third)
""".trimIndent(),
params
)
assertNotNull(result)
assertEquals(result!!.first, "ff")
assertEquals(result.seconde, "sec")
assertEquals(result.third, 123)
} }
@Test @Test
@@ -152,10 +192,135 @@ class ConnectionTest() : TestAbstract() {
) )
assertNotNull(result) assertNotNull(result)
assertEquals(result.result[0].name, "ff") assertEquals("ff", result.result[0].name)
assertEquals(result.result[1].name, "ff-2") assertEquals("ff-2", result.result[1].name)
assertEquals(result.total, 10) assertEquals(10, result.total)
assertEquals(result.offset, 0) assertEquals(0, result.offset)
}
@Test
fun `test select paginated without result`() {
val result: Paginated<ObjTest> = connection.select(
"""
SELECT null,
10 as total
LIMIT :limit
OFFSET :offset
""".trimIndent(),
1,
2,
object : TypeReference<List<ObjTest>>() {}
)
assertNotNull(result)
assertTrue(result.result.isEmpty())
assertEquals(0, result.result.size)
assertEquals(10, result.total)
assertEquals(0, result.offset)
}
@Test
fun `test select paginated`() {
val result: Paginated<ObjTest> = connection.select(
"""
SELECT json_build_array(
jsonb_build_object(
'name', :name::text,
'id', 'e9f9a0f0-237c-47cf-98c5-be353f2f2ce3'
)
),
10 as total
LIMIT :limit
OFFSET :offset
""".trimIndent(),
1,
2,
object : TypeReference<List<ObjTest>>() {},
mapOf(
"name" to "myName"
)
)
assertNotNull(result)
assertEquals("myName", result.result[0].name)
assertEquals(1, result.result.size)
assertEquals(10, result.total)
assertEquals(0, result.offset)
}
@Test
fun `test select paginated with no result`() {
assertThrows<QueryError> {
connection.select(
"""
SELECT :name as name,
10 as total
LIMIT :limit
OFFSET :offset
""".trimIndent(),
100,
10,
object : TypeReference<List<ObjTest>>() {},
mapOf(
"name" to "myName"
)
)
}.run {
assertNotNull(message)
assertContains(message!!, "The query has no return")
}
}
@Test
fun `test select paginated with total was not integer`() {
assertThrows<QueryError> {
connection.select(
"""
SELECT :name as name,
'plop' as total
LIMIT :limit
OFFSET :offset
""".trimIndent(),
1,
10,
object : TypeReference<List<ObjTest>>() {},
mapOf(
"name" to "myName"
)
)
}.run {
assertNotNull(message)
assertContains(message!!, """Column "total" must be an integer""")
}
}
@Test
fun `test select paginated without total`() {
val exception = assertThrows<QueryError> {
val result: Paginated<ObjTest> = connection.select(
"""
SELECT null
LIMIT :limit
OFFSET :offset
""".trimIndent(),
1,
2,
object : TypeReference<List<ObjTest>>() {}
)
}
assertEquals(
"""
The query not return the "total" column
> :offset = 0, :limit = 2
> SELECT null
> LIMIT :limit
> OFFSET :offset
> -----
> ?column?
> null
""".trimIndent(),
exception.message
)
} }
@Test @Test
@@ -163,20 +328,54 @@ class ConnectionTest() : TestAbstract() {
val params: Map<String, Any?> = mapOf( val params: Map<String, Any?> = mapOf(
"first" to "ff", "first" to "ff",
"third" to 123, "third" to 123,
"seconde" to "sec" "second" to "sec"
) )
val result: ObjTest3? = connection.selectOne( val result: ObjTest3? = connection.selectOne(
""" """
SELECT json_build_object('first', :first::text, 'seconde', :seconde::text, 'third', :third::int), 'plop'::text as other SELECT json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int), 'plop'::text as other
""".trimIndent(), """.trimIndent(),
params params
) { ) {
assertEquals("ff", it!!.first) assertNotNull(it)
assertEquals("ff", it.first)
assertEquals("plop", rows[0].getString("other")) assertEquals("plop", rows[0].getString("other"))
} }
assertNotNull(result) assertNotNull(result)
assertEquals("ff", result!!.first) assertEquals("ff", result.first)
assertEquals("sec", result.seconde) assertEquals("sec", result.second)
assertEquals(123, result.third) assertEquals(123, result.third)
} }
@Test
fun `test exec without parameters`() {
connection.exec("select 42, 'hello';").run {
assertEquals(42, rows[0].getInt(0))
assertEquals("hello", rows[0].getString(1))
}
}
@Test
fun `test exec with one object as parameter`() {
val obj = ObjTest("myName", UUID.fromString("c606e216-53b3-43c8-a900-e727cb4a017c"))
connection.exec("select ?::jsonb->>'name'", obj).run {
assertEquals("myName", rows[0].getString(0))
}
}
@Test
fun `select one in transaction`() {
connection.inTransaction {
selectOne<ObjTestWithParameterObject>(
"SELECT json_build_object('first', :first::json, 'second', :second::json)",
mapOf(
"first" to ParameterObject("one"),
"second" to ParameterObject("two")
)
).let { result ->
assertNotNull(result)
assertEquals("one", result.first.third)
assertEquals("two", result.second.third)
}
}
}
} }

View File

@@ -1,19 +1,26 @@
package fr.postgresjson package fr.postgresjson
import fr.postgresjson.entity.* import fr.postgresjson.entity.Entity
import fr.postgresjson.entity.EntityCreatedAt
import fr.postgresjson.entity.EntityCreatedBy
import fr.postgresjson.entity.EntityI
import fr.postgresjson.entity.EntityUpdatedAt
import fr.postgresjson.entity.EntityUpdatedBy
import fr.postgresjson.entity.Published
import fr.postgresjson.entity.UuidEntityExtended
import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance
import java.util.* import java.util.UUID
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class EntityTest() { class EntityTest() {
private class User(id: UUID = UUID.randomUUID()) : Entity<UUID>(id) private class User(id: UUID = UUID.randomUUID()) : Entity<UUID>(id)
private class ObjTest(var name: String) : UuidEntityExtended<Int?, User>(User(), User()) private class ObjTest(val name: String) : UuidEntityExtended<Int?, User>(User(), User())
@Test @Test
fun getObject() { fun getObject() {
val obj: ObjTest? = ObjTest("plop") val obj = ObjTest("plop")
assertTrue(obj is ObjTest) assertTrue(obj is ObjTest)
assertTrue(obj is UuidEntityExtended<Int?, User>) assertTrue(obj is UuidEntityExtended<Int?, User>)
assertTrue(obj is EntityI) assertTrue(obj is EntityI)

View File

@@ -1,22 +1,23 @@
package fr.postgresjson package fr.postgresjson
import fr.postgresjson.connexion.Requester import fr.postgresjson.connexion.Requester
import fr.postgresjson.connexion.selectOne
import fr.postgresjson.migration.Migration import fr.postgresjson.migration.Migration
import fr.postgresjson.migration.Migrations import fr.postgresjson.migration.Migrations
import org.amshove.kluent.invoking
import org.amshove.kluent.`should be equal to` import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should contain` import org.amshove.kluent.`should contain`
import org.amshove.kluent.invoking
import org.amshove.kluent.shouldThrow import org.amshove.kluent.shouldThrow
import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance
import java.util.* import java.util.UUID
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MigrationTest() : TestAbstract() { class MigrationTest : TestAbstract() {
@Test @Test
fun `run up query`() { fun `run up query`() {
val resources = this::class.java.getResource("/sql/migrations").toURI() val resources = this::class.java.getResource("/sql/migrations")!!.toURI()
val m = Migrations(connection, resources) val m = Migrations(connection, resources)
m.up().apply { m.up().apply {
this `should contain` Pair("1", Migration.Status.OK) this `should contain` Pair("1", Migration.Status.OK)
@@ -28,7 +29,7 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `migration up Query should throw error if no down`() { fun `migration up Query should throw error if no down`() {
val resources = this::class.java.getResource("/sql/migration_without_down").toURI() val resources = this::class.java.getResource("/sql/migration_without_down")!!.toURI()
invoking { invoking {
Migrations(resources, connection) Migrations(resources, connection)
} shouldThrow Migrations.DownMigrationNotDefined::class } shouldThrow Migrations.DownMigrationNotDefined::class
@@ -36,7 +37,7 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run forced down query`() { fun `run forced down query`() {
val resources = this::class.java.getResource("/sql/migrations").toURI() val resources = this::class.java.getResource("/sql/migrations")!!.toURI()
val m = Migrations(resources, connection) val m = Migrations(resources, connection)
repeat(3) { repeat(3) {
m.down(true).apply { m.down(true).apply {
@@ -48,7 +49,7 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run dry migrations`() { fun `run dry migrations`() {
val resources = this::class.java.getResource("/sql/real_migrations").toURI() val resources = this::class.java.getResource("/sql/real_migrations")!!.toURI()
Migrations(resources, connection).apply { Migrations(resources, connection).apply {
runDry().size `should be equal to` 2 runDry().size `should be equal to` 2
} }
@@ -59,7 +60,7 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run dry migrations launch twice`() { fun `run dry migrations launch twice`() {
val resources = this::class.java.getResource("/sql/real_migrations").toURI() val resources = this::class.java.getResource("/sql/real_migrations")!!.toURI()
Migrations(resources, connection).apply { Migrations(resources, connection).apply {
runDry().size `should be equal to` 2 runDry().size `should be equal to` 2
runDry().size `should be equal to` 2 runDry().size `should be equal to` 2
@@ -68,7 +69,7 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run migrations`() { fun `run migrations`() {
val resources = this::class.java.getResource("/sql/real_migrations").toURI() val resources = this::class.java.getResource("/sql/real_migrations")!!.toURI()
Migrations(resources, connection).apply { Migrations(resources, connection).apply {
run().apply { run().apply {
size `should be equal to` 1 size `should be equal to` 1
@@ -78,8 +79,8 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run migrations force down`() { fun `run migrations force down`() {
val resources = this::class.java.getResource("/sql/real_migrations").toURI() val resources = this::class.java.getResource("/sql/real_migrations")!!.toURI()
val resourcesFunctions = this::class.java.getResource("/sql/function/Test").toURI() val resourcesFunctions = this::class.java.getResource("/sql/function/Test")!!.toURI()
Migrations(listOf(resources, resourcesFunctions), connection).apply { Migrations(listOf(resources, resourcesFunctions), connection).apply {
up().apply { up().apply {
size `should be equal to` 6 size `should be equal to` 6
@@ -94,13 +95,12 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run functions migrations`() { fun `run functions migrations`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/function/Test")!!.toURI()
Migrations(resources, connection).apply { Migrations(resources, connection).apply {
run().size `should be equal to` 5 run().size `should be equal to` 5
} }
val objTest: RequesterTest.ObjTest? = Requester(connection) val objTest: RequesterTest.ObjTest? = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function") .getFunction("test_function")
.selectOne(listOf("test", "plip")) .selectOne(listOf("test", "plip"))
@@ -110,20 +110,19 @@ class MigrationTest() : TestAbstract() {
@Test @Test
fun `run functions migrations and drop if exist`() { fun `run functions migrations and drop if exist`() {
val resources = this::class.java.getResource("/sql/function/Test1").toURI() val resources = this::class.java.getResource("/sql/function/Test1")!!.toURI()
Migrations(resources, connection).apply { Migrations(resources, connection).apply {
run().size `should be equal to` 1 run().size `should be equal to` 1
} }
val objTest: RequesterTest.ObjTest? = Requester(connection) val objTest: RequesterTest.ObjTest? = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function_duplicate") .getFunction("test_function_duplicate")
.selectOne(listOf("test")) .selectOne(listOf("test"))
Assertions.assertEquals(objTest!!.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d")) Assertions.assertEquals(objTest!!.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d"))
Assertions.assertEquals(objTest.name, "test") Assertions.assertEquals(objTest.name, "test")
val resources2 = this::class.java.getResource("/sql/function/Test2").toURI() val resources2 = this::class.java.getResource("/sql/function/Test2")!!.toURI()
Migrations(resources2, connection).apply { Migrations(resources2, connection).apply {
run().size `should be equal to` 1 run().size `should be equal to` 1
} }

View File

@@ -1,56 +1,174 @@
package fr.postgresjson package fr.postgresjson
import com.fasterxml.jackson.core.type.TypeReference
import fr.postgresjson.connexion.Connection.QueryError
import fr.postgresjson.connexion.Paginated import fr.postgresjson.connexion.Paginated
import fr.postgresjson.connexion.Requester import fr.postgresjson.connexion.Requester
import fr.postgresjson.connexion.Requester.NoFunctionDefined
import fr.postgresjson.connexion.Requester.NoQueryDefined
import fr.postgresjson.connexion.select
import fr.postgresjson.connexion.selectOne
import fr.postgresjson.connexion.update
import fr.postgresjson.entity.UuidEntity import fr.postgresjson.entity.UuidEntity
import org.junit.Assert import fr.postgresjson.serializer.deserialize
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import java.util.* import java.util.UUID
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class RequesterTest : TestAbstract() { class RequesterTest : TestAbstract() {
class ObjTest(var name: String, id: UUID = UUID.fromString("5623d902-3067-42f3-bfd9-095dbb12c29f")) : UuidEntity(id) class ObjTest(val name: String, id: UUID = UUID.fromString("5623d902-3067-42f3-bfd9-095dbb12c29f")) : UuidEntity(id)
@Test
fun `requester constructor empty`() {
val resources = this::class.java.getResource("/sql/function/Test")!!.toURI()
val name: String = Requester(connection)
.apply { addFunctions(resources) }
.getFunction("test_function")
.name
assertEquals("test_function", name)
}
@Test
fun `requester constructor function directory`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val name: String = Requester(connection, functionsDirectory = resources)
.getFunction("test_function")
.name
assertEquals("test_function", name)
}
@Test
fun `requester constructor query directory`() {
val resources = this::class.java.getResource("/sql/query/Test")?.toURI()
val name: String = Requester(connection, queriesDirectory = resources)
.getQuery("DeleteTest")
.name
assertEquals("DeleteTest", name)
}
@Test
fun `function toString`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val name: String = Requester(connection, functionsDirectory = resources)
.getFunction("test_function")
.toString()
assertEquals("test_function", name)
}
@Test
fun `add function as string`() {
val sql = """
CREATE OR REPLACE FUNCTION test_function (name text default 'plop', IN hi text default 'hello', out result json)
LANGUAGE plpgsql
AS
$$
BEGIN
result = json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', name);
END;
$$
""".trimIndent()
val name: String = Requester(connection)
.apply { addFunction(sql) }
.getFunction("test_function")
.name
assertEquals("test_function", name)
}
@Test
fun `add query from string`() {
val result: Int? = Requester(connection)
.apply { addQuery("simpleTest", "select 42;") }
.getQuery("simpleTest")
.exec()
.rows[0].getInt(0)
assertNotNull(result)
assertEquals(42, result)
}
@Test @Test
fun `get query from file`() { fun `get query from file`() {
val resources = this::class.java.getResource("/sql/query").toURI() val resources = this::class.java.getResource("/sql/query")!!.toURI()
val objTest: ObjTest? = Requester(connection) val objTest: ObjTest? = Requester(connection)
.addQuery(resources) .apply { addQuery(resources) }
.getQuery("selectOne") .getQuery("selectOne")
.selectOne() .selectOne()
assertEquals(objTest!!.id, UUID.fromString("829b1a29-5db8-47f9-9562-961c561ac528")) assertNotNull(objTest)
assertEquals(objTest.name, "test") assertEquals(objTest.id, UUID.fromString("829b1a29-5db8-47f9-9562-961c561ac528"))
assertEquals("test", objTest.name)
}
@Test
fun `get query from file with wrong name throw exception`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
assertThrows(NoQueryDefined::class.java) {
Requester(connection, queriesDirectory = resources)
.getQuery("wrongName")
}
}
@Test
fun `get queries from file`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
val name: String = Requester(connection, queriesDirectory = resources)
.getQueries()[0].name
assertEquals(name, "DeleteTest")
}
@Test
fun `get function from file with wrong name throw exception`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
assertThrows(NoFunctionDefined::class.java) {
Requester(connection, functionsDirectory = resources)
.getFunction("wrongName")
}
} }
@Test @Test
fun `get function from file`() { fun `get function from file`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val objTest: ObjTest? = Requester(connection) val objTest: ObjTest? = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function") .getFunction("test_function")
.selectOne(listOf("test", "plip")) .selectOne(listOf("test", "plip"))
assertEquals(objTest!!.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d")) assertNotNull(objTest)
assertEquals(objTest.name, "test") assertEquals(objTest.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d"))
assertEquals("test", objTest.name)
} }
@Test @Test
fun `call exec on query`() { fun `call exec on query`() {
val resources = this::class.java.getResource("/sql/query").toURI() val resources = this::class.java.getResource("/sql/query")?.toURI()
val result = Requester(connection) val result = Requester(connection, queriesDirectory = resources)
.addQuery(resources)
.getQuery("selectOne") .getQuery("selectOne")
.exec() .exec()
assertEquals(1, result.rowsAffected) assertEquals(1, result.rowsAffected)
} }
@Test
fun `call exec on query with a list of arguments`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
val result = Requester(connection, queriesDirectory = resources)
.getQuery("selectOneWithParameters")
.exec(listOf("myName"))
assertEquals("myName", result.rows[0].getString(0)?.deserialize<ObjTest>()?.name)
}
@Test @Test
fun `call exec on function`() { fun `call exec on function`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val result = Requester(connection) val result = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function") .getFunction("test_function")
.exec(listOf("test", "plip")) .exec(listOf("test", "plip"))
@@ -58,112 +176,332 @@ class RequesterTest : TestAbstract() {
} }
@Test @Test
fun `call sendQuery on query with name`() { fun `call exec on query with name`() {
val resources = this::class.java.getResource("/sql/query").toURI() val resources = this::class.java.getResource("/sql/query")?.toURI()
val result = Requester(connection) val result = Requester(connection, queriesDirectory = resources)
.addQuery(resources)
.getQuery("DeleteTest") .getQuery("DeleteTest")
.sendQuery() .exec()
assertEquals(0, result) assertEquals(0, result.rowsAffected)
} }
@Test @Test
fun `call sendQuery on function`() { fun `call sendQuery with same name of arguments`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/query")?.toURI()
val result = Requester(connection) Requester(connection, queriesDirectory = resources)
.addFunction(resources) .getQuery("selectMultipleWithSameArgs")
.getFunction("function_void") .sendQuery("name" to "myName").run {
.sendQuery(listOf("test")) assertEquals("myName", rows[0].getString("firstName"))
assertEquals("myName", rows[0].getString("secondName"))
}
}
assertEquals(0, result) @Test
fun `call sendQuery with same name of arguments as list`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleWithSameArgs")
.sendQuery(listOf("myName", "myName2")).run {
assertEquals("myName", rows[0].getString("firstName"))
assertEquals("myName2", rows[0].getString("secondName"))
}
}
@Test
fun `call sendQuery with arguments on not same orders`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleDifferentArgs")
.sendQuery("first" to "firstName", "second" to "secondName").run {
assertEquals("firstName", rows[0].getString("firstName"))
assertEquals("secondName", rows[0].getString("secondName"))
}
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleDifferentArgs")
.sendQuery("second" to "secondName", "first" to "firstName").run {
assertEquals("firstName", rows[0].getString("firstName"))
assertEquals("secondName", rows[0].getString("secondName"))
}
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleDifferentArgs")
.sendQuery("second" to "secondName", "first" to "firstName").run {
assertEquals("firstName", rows[0].getString(0))
assertEquals("secondName", rows[0].getString(1))
}
}
@Test
fun `call sendQuery with wrong number of arguments`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
assertThrows(QueryError::class.java) {
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleDifferentArgs")
.sendQuery("first" to "firstName")
}.let {
assertEquals(
"""
Parameter "second" missing
> :first = firstName
> SELECT :first::text as "firstName", :second::text as "secondName";
""".trimIndent(),
it.message
)
}
}
@Test
fun `call sendQuery with wrong number of arguments as list`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
assertThrows(QueryError::class.java) {
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleDifferentArgs")
.sendQuery(listOf("firstName"))
}.let {
assertEquals(
"""
Parameter 1 missing
> firstName
> SELECT ?::text as "firstName", ?::text as "secondName";
""".trimIndent(),
it.message
)
}
}
@Test
fun `call exec on function with pair as arguments`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val result = Requester(connection, functionsDirectory = resources)
.getFunction("function_void")
.exec("name" to "test")
assertEquals(1, result.rowsAffected)
} }
@Test @Test
fun `call selectOne on function`() { fun `call selectOne on function`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val obj: ObjTest = Requester(connection) val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function") .getFunction("test_function")
.selectOne(mapOf("name" to "myName"))!! .selectOne(mapOf("name" to "myName"))
assertNotNull(obj)
assertEquals("myName", obj.name) assertEquals("myName", obj.name)
} }
@Test
fun `call selectOne on function with object and named argument`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val obj2 = ObjTest("original")
val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
.getFunction("test_function_object")
.selectOne("resource" to obj2)
assertNotNull(obj)
assertEquals("changedName", obj.name)
assertEquals("original", obj2.name)
}
@Test @Test
fun `call selectOne on function with object`() { fun `call selectOne on function with object`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val obj2 = ObjTest("original") val obj2 = ObjTest("original")
val obj: ObjTest = Requester(connection) val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function_object") .getFunction("test_function_object")
.selectOne("resource" to obj2)!! .update(obj2)
assertNotNull(obj)
assertEquals("changedName", obj.name) assertEquals("changedName", obj.name)
assertEquals("changedName", obj2.name) assertEquals("original", obj2.name)
}
@Test
fun `call selectOne on function with object and no arguments`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
.getFunction("test_function")
.selectOne()
assertNotNull(obj)
assertEquals("plop", obj.name)
} }
@Test @Test
fun `call selectOne on query`() { fun `call selectOne on query`() {
val resources = this::class.java.getResource("/sql/query").toURI() val resources = this::class.java.getResource("/sql/query")?.toURI()
val obj: ObjTest = Requester(connection) val obj: ObjTest? = Requester(connection, queriesDirectory = resources)
.addQuery(resources)
.getQuery("selectOneWithParameters") .getQuery("selectOneWithParameters")
.selectOne(mapOf("name" to "myName"))!! .selectOne(mapOf("name" to "myName"))
assertNotNull(obj)
assertEquals("myName", obj.name) assertEquals("myName", obj.name)
} }
@Test @Test
fun `call select (multiple) on function`() { fun `call select (multiple) on function with named argument`() {
val resources = this::class.java.getResource("/sql/function/Test").toURI() val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val obj: List<ObjTest>? = Requester(connection) val obj: List<ObjTest> = Requester(connection, functionsDirectory = resources)
.addFunction(resources)
.getFunction("test_function_multiple") .getFunction("test_function_multiple")
.select(mapOf("name" to "myName")) .select(mapOf("name" to "myName"))
assertEquals("myName", obj!![0].name) assertNotNull(obj[0])
assertEquals("myName", obj[0].name)
assertEquals("myName", obj[0].name)
}
@Test
fun `call select (multiple) on function with ordered arguments`() {
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
val obj: List<ObjTest> = Requester(connection, functionsDirectory = resources)
.getFunction("test_function_multiple")
.select(listOf("myName"))
assertEquals("myName", obj[0].name)
}
@Test
fun `call select multiple (named arguments)`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultiple").apply {
select<ObjTest>(mapOf("name" to "ff")).let { result ->
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
}
}.apply {
select(object : TypeReference<List<ObjTest>>() {}, mapOf("name" to "ff")).let { result ->
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
}
}
}
@Test
fun `call select multiple (named arguments as pair)`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultiple").apply {
select<ObjTest>("name" to "ff").let { result ->
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
}
}.apply {
select(object : TypeReference<List<ObjTest>>() {}, "name" to "ff").let { result ->
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
}
}
}
@Test
fun `call select multiple (ordered argument)`() {
val resources = this::class.java.getResource("/sql/query")?.toURI()
Requester(connection, queriesDirectory = resources)
.getQuery("selectMultipleOrderedArgs").apply {
select<ObjTest>(listOf("ff", "aa")).let { result ->
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("aa-2", result[1].name)
}
}.apply {
select(object : TypeReference<List<ObjTest>>() {}, listOf("ff", "aa")).let { result ->
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("aa-2", result[1].name)
}
}
} }
@Test @Test
fun `call select paginated on query`() { fun `call select paginated on query`() {
val resources = this::class.java.getResource("/sql/query").toURI() val resources = this::class.java.getResource("/sql/query")?.toURI()
val result: Paginated<ObjTest> = Requester(connection) val result: Paginated<ObjTest> = Requester(connection, queriesDirectory = resources)
.addQuery(resources)
.getQuery("selectPaginated") .getQuery("selectPaginated")
.select(1, 2, mapOf("name" to "ff")) .select(1, 2, mapOf("name" to "ff"))
Assert.assertNotNull(result) assertNotNull(result)
Assert.assertEquals("ff", result.result[0].name) assertEquals("ff", result.result[0].name)
Assert.assertEquals("ff-2", result.result[1].name) assertEquals("ff-2", result.result[1].name)
Assert.assertEquals(10, result.total) assertEquals(10, result.total)
Assert.assertEquals(0, result.offset) assertEquals(0, result.offset)
} }
@Test @Test
fun `call select paginated on function`() { fun `call select paginated on function`() {
val resources = this::class.java.getResource("/sql/function").toURI() val resources = this::class.java.getResource("/sql/function")?.toURI()
val result: Paginated<ObjTest> = Requester(connection) Requester(connection, functionsDirectory = resources)
.addFunction(resources) .getFunction("test_function_paginated").apply {
select<ObjTest>(1, 2, mapOf("name" to "ff")).run {
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
assertEquals(10, total)
assertEquals(0, offset)
}
}.apply {
select(1, 2, object : TypeReference<List<ObjTest>>() {}, mapOf("name" to "ff")).run {
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
assertEquals(10, total)
assertEquals(0, offset)
}
}
}
@Test
fun `call select paginated on function with vararg`() {
val resources = this::class.java.getResource("/sql/function")?.toURI()
Requester(connection, functionsDirectory = resources)
.getFunction("test_function_paginated") .getFunction("test_function_paginated")
.select(1, 2, mapOf("name" to "ff")) .select<ObjTest>(1, 2, "name" to "ff").run {
Assert.assertNotNull(result) assertNotNull(result)
Assert.assertEquals("ff", result.result[0].name) assertEquals("ff", result[0].name)
Assert.assertEquals("ff-2", result.result[1].name) assertEquals("ff-2", result[1].name)
Assert.assertEquals(10, result.total) assertEquals(10, total)
Assert.assertEquals(0, result.offset) assertEquals(0, offset)
}
Requester(connection, functionsDirectory = resources)
.getFunction("test_function_paginated")
.select(1, 2, object : TypeReference<List<ObjTest>>() {}, "name" to "ff").run {
assertNotNull(result)
assertEquals("ff", result[0].name)
assertEquals("ff-2", result[1].name)
assertEquals(10, total)
assertEquals(0, offset)
}
} }
@Test @Test
fun `call selectOne on query with extra parameter`() { fun `call selectOne on query with extra parameter`() {
val resources = this::class.java.getResource("/sql/query").toURI() val resources = this::class.java.getResource("/sql/query")?.toURI()
val obj: ObjTest = Requester(connection) Requester(connection, queriesDirectory = resources)
.addQuery(resources) .getQuery("selectOneWithParameters").apply {
.getQuery("selectOneWithParameters") selectOne<ObjTest>(mapOf("name" to "myName")) {
.selectOne(mapOf("name" to "myName")) { assertNotNull(it)
assertEquals("myName", it!!.name) assertEquals("myName", it.name)
Assert.assertEquals("plop", rows[0].getString("other")) assertEquals("plop", rows[0].getString("other"))
}!! }.run {
assertEquals("selectOneWithParameters", name)
assertEquals("myName", obj.name) }
}.apply {
selectOne(typeReference = object : TypeReference<ObjTest>() {}, values = mapOf("name" to "myName")) {
assertNotNull(it)
assertEquals("myName", it.name)
assertEquals("plop", rows[0].getString("other"))
}.run {
assertEquals("selectOneWithParameters", name)
}
}
} }
} }

View File

@@ -2,7 +2,6 @@ package fr.postgresjson
import fr.postgresjson.entity.UuidEntity import fr.postgresjson.entity.UuidEntity
import fr.postgresjson.serializer.Serializer import fr.postgresjson.serializer.Serializer
import fr.postgresjson.serializer.deserialize
import fr.postgresjson.serializer.serialize import fr.postgresjson.serializer.serialize
import org.joda.time.DateTime import org.joda.time.DateTime
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertEquals
@@ -10,7 +9,7 @@ import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.TestInstance
import java.util.* import java.util.UUID
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class SerializerTest { internal class SerializerTest {
@@ -21,7 +20,6 @@ internal class SerializerTest {
private val objSerialized: String = """{"val1":"plop","val2":123,"id":"829b1a29-5db8-47f9-9562-961c561ac528"}""" private val objSerialized: String = """{"val1":"plop","val2":123,"id":"829b1a29-5db8-47f9-9562-961c561ac528"}"""
private val objSerializedWithExtra: String = """{"val1":"plop","val2":123,"id":"829b1a29-5db8-47f9-9562-961c561ac528","toto":"tata"}""" private val objSerializedWithExtra: String = """{"val1":"plop","val2":123,"id":"829b1a29-5db8-47f9-9562-961c561ac528","toto":"tata"}"""
private val objSerializedUpdate = """{"val1":"update","val2":123}"""
private lateinit var obj: ObjTest private lateinit var obj: ObjTest
@BeforeEach @BeforeEach
@@ -69,20 +67,4 @@ internal class SerializerTest {
assertEquals(obj.val1, objDeserialized!!.val1) assertEquals(obj.val1, objDeserialized!!.val1)
assertEquals(obj.val2, objDeserialized.val2) assertEquals(obj.val2, objDeserialized.val2)
} }
@Test
fun deserializeUpdate() {
val objDeserialized: ObjTest = serializer.deserialize(objSerializedUpdate, obj)
assertTrue(obj === objDeserialized)
assertEquals("update", objDeserialized.val1)
assertEquals(123, objDeserialized.val2)
}
@Test
fun deserializeUpdate2() {
val objDeserialized = obj.deserialize(objSerializedUpdate)
assertTrue(obj === objDeserialized)
assertEquals("update", objDeserialized.val1)
assertEquals(123, objDeserialized.val2)
}
} }

View File

@@ -13,7 +13,7 @@ abstract class TestAbstract {
@BeforeEach @BeforeEach
fun beforeAll() { fun beforeAll() {
val initSQL = File(this::class.java.getResource("/fixtures/init.sql").toURI()) val initSQL = File(this::class.java.getResource("/fixtures/init.sql")!!.toURI())
connection connection
.connect() .connect()
.sendQuery(initSQL.readText()) .sendQuery(initSQL.readText())
@@ -22,9 +22,9 @@ abstract class TestAbstract {
@AfterEach @AfterEach
fun afterAll() { fun afterAll() {
val downSQL = File(this::class.java.getResource("/fixtures/down.sql").toURI()) val downSQL = File(this::class.java.getResource("/fixtures/down.sql")!!.toURI())
connection.connect().apply { connection
sendQuery(downSQL.readText()).join() .apply { connect().sendQuery(downSQL.readText()).join() }
}.disconnect() .disconnect()
} }
} }

View File

@@ -0,0 +1,4 @@
SELECT json_build_array(
json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', :name::text),
json_build_object('id', '6085c12e-e94d-4ae1-b7ad-23acc7a82a98', 'name', :name::text || '-2')
)

View File

@@ -0,0 +1 @@
SELECT :first::text as "firstName", :second::text as "secondName";

View File

@@ -0,0 +1,4 @@
SELECT json_build_array(
json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', ?::text),
json_build_object('id', '6085c12e-e94d-4ae1-b7ad-23acc7a82a98', 'name', ?::text || '-2')
)

View File

@@ -0,0 +1 @@
SELECT :name::text as "firstName", :name::text as "secondName";