Compare commits
37 Commits
2.2.0
...
compiled_s
| Author | SHA1 | Date | |
|---|---|---|---|
| 817912dd5b | |||
| 96aaa1ada9 | |||
| 3e3a72306b | |||
| f4e88d385b | |||
| 5c37481368 | |||
| f228ec8da2 | |||
| 7c26670a1b | |||
| aa3ca82b39 | |||
| 67fae02cb3 | |||
| 88d79b9609 | |||
| 0702e7dca8 | |||
| 9cba119337 | |||
| 1def5ae095 | |||
| ad657a6136 | |||
| aa1435bb4e | |||
| 691fd888f5 | |||
| 6f6e9f6560 | |||
| 9f6c32375e | |||
| eac77d7419 | |||
| 75066d977c | |||
| 9fc6a23ac1 | |||
| c268efb44f | |||
| f8f3273f18 | |||
| b31c8c87f1 | |||
| 56c67981db | |||
| bd473daa6c | |||
| 1af34366fc | |||
| a7e66ab8b5 | |||
| 7d39dcf248 | |||
| b96ffcc5ea | |||
| 074228807e | |||
| ee89ffcb1d | |||
| d5b8472304 | |||
| 2cd69d4501 | |||
| 79d2e52978 | |||
| 90d5f6e0d7 | |||
| 39bae86307 |
10
.idea/codeStyles/Project.xml
generated
10
.idea/codeStyles/Project.xml
generated
@@ -14,8 +14,18 @@
|
|||||||
<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="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="2147483647" />
|
||||||
<option name="IMPORT_NESTED_CLASSES" value="true" />
|
<option name="IMPORT_NESTED_CLASSES" value="true" />
|
||||||
|
<option name="ALLOW_TRAILING_COMMA" value="true" />
|
||||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||||
</JetCodeStyleSettings>
|
</JetCodeStyleSettings>
|
||||||
|
<SqlCodeStyleSettings version="6">
|
||||||
|
<option name="KEYWORD_CASE" value="1" />
|
||||||
|
<option name="IDENTIFIER_CASE" value="1" />
|
||||||
|
<option name="TYPE_CASE" value="1" />
|
||||||
|
<option name="CUSTOM_TYPE_CASE" value="1" />
|
||||||
|
<option name="ALIAS_CASE" value="1" />
|
||||||
|
<option name="BUILT_IN_CASE" value="1" />
|
||||||
|
<option name="QUOTE_IDENTIFIER" value="1" />
|
||||||
|
</SqlCodeStyleSettings>
|
||||||
<codeStyleSettings language="kotlin">
|
<codeStyleSettings language="kotlin">
|
||||||
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
|
||||||
<indentOptions>
|
<indentOptions>
|
||||||
|
|||||||
4
.idea/dataSources.xml
generated
4
.idea/dataSources.xml
generated
@@ -1,11 +1,11 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project version="4">
|
<project version="4">
|
||||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||||
<data-source source="LOCAL" name="json_test@localhost" uuid="1191ff9a-6823-4b18-af90-483ddf0e4b69">
|
<data-source source="LOCAL" name="PostgreSQL - json_test@localhost" uuid="1191ff9a-6823-4b18-af90-483ddf0e4b69">
|
||||||
<driver-ref>postgresql</driver-ref>
|
<driver-ref>postgresql</driver-ref>
|
||||||
<synchronize>true</synchronize>
|
<synchronize>true</synchronize>
|
||||||
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
||||||
<jdbc-url>jdbc:postgresql://localhost:5555/json_test</jdbc-url>
|
<jdbc-url>jdbc:postgresql://localhost:35555/json_test</jdbc-url>
|
||||||
<working-dir>$ProjectFileDir$</working-dir>
|
<working-dir>$ProjectFileDir$</working-dir>
|
||||||
</data-source>
|
</data-source>
|
||||||
</component>
|
</component>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||||
val containerAlwaysOn: String by project
|
val containerAlwaysOn: String by project
|
||||||
val disableLint: String by project
|
val disableLint: String by project
|
||||||
|
val projectName: String by project
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
jacoco
|
jacoco
|
||||||
@@ -75,6 +76,8 @@ dependencies {
|
|||||||
testImplementation("org.junit.jupiter:junit-jupiter:5.9.0")
|
testImplementation("org.junit.jupiter:junit-jupiter:5.9.0")
|
||||||
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:1.7.20")
|
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:1.7.20")
|
||||||
testImplementation("org.amshove.kluent:kluent:1.68")
|
testImplementation("org.amshove.kluent:kluent:1.68")
|
||||||
|
testImplementation("io.kotest:kotest-runner-junit5:5.5.5")
|
||||||
|
testImplementation("io.kotest:kotest-property:5.5.5")
|
||||||
}
|
}
|
||||||
|
|
||||||
val sourcesJar by tasks.creating(Jar::class) {
|
val sourcesJar by tasks.creating(Jar::class) {
|
||||||
@@ -84,7 +87,7 @@ val sourcesJar by tasks.creating(Jar::class) {
|
|||||||
|
|
||||||
apply(plugin = "docker-compose")
|
apply(plugin = "docker-compose")
|
||||||
dockerCompose {
|
dockerCompose {
|
||||||
setProjectName("postgres-json")
|
setProjectName(projectName.toString())
|
||||||
setProperty("useComposeFiles", listOf("docker-compose.yml"))
|
setProperty("useComposeFiles", listOf("docker-compose.yml"))
|
||||||
setProperty("stopContainers", !containerAlwaysOn.toBoolean())
|
setProperty("stopContainers", !containerAlwaysOn.toBoolean())
|
||||||
isRequiredBy(project.tasks.test)
|
isRequiredBy(project.tasks.test)
|
||||||
@@ -93,7 +96,7 @@ dockerCompose {
|
|||||||
publishing {
|
publishing {
|
||||||
repositories {
|
repositories {
|
||||||
maven {
|
maven {
|
||||||
name = "postgres-json"
|
name = projectName.toString()
|
||||||
url = uri("https://maven.pkg.github.com/flecomte/postgres-json")
|
url = uri("https://maven.pkg.github.com/flecomte/postgres-json")
|
||||||
credentials {
|
credentials {
|
||||||
username = System.getenv("GITHUB_USERNAME")
|
username = System.getenv("GITHUB_USERNAME")
|
||||||
@@ -103,7 +106,7 @@ publishing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
publications {
|
publications {
|
||||||
create<MavenPublication>("postgres-json") {
|
create<MavenPublication>(projectName.toString()) {
|
||||||
from(components["java"])
|
from(components["java"])
|
||||||
artifact(sourcesJar)
|
artifact(sourcesJar)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ services:
|
|||||||
context: docker/postgresql
|
context: docker/postgresql
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
- "5555:5432"
|
- "35555:5432"
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_DB: json_test
|
POSTGRES_DB: json_test
|
||||||
POSTGRES_USER: test
|
POSTGRES_USER: test
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM postgres:13
|
FROM postgres:15
|
||||||
|
|
||||||
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
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ import fr.postgresjson.connexion.Requester
|
|||||||
val requester: Requester = TODO()
|
val requester: Requester = TODO()
|
||||||
val result: Parent = requester
|
val result: Parent = requester
|
||||||
.getFunction("find_parent_by_id")
|
.getFunction("find_parent_by_id")
|
||||||
.selectOne("id" to "379e0687-9e4a-4781-b0e9-d94a62e4261f")
|
.execute("id" to "379e0687-9e4a-4781-b0e9-d94a62e4261f")
|
||||||
```
|
```
|
||||||
|
|
||||||
The requester create dynamically this request
|
The requester create dynamically this request
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
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"
|
|
||||||
)
|
|
||||||
```
|
|
||||||
@@ -26,10 +26,10 @@ data class Inventor(
|
|||||||
val id: UUID = UUID.randomUUID(),
|
val id: UUID = UUID.randomUUID(),
|
||||||
val name: String,
|
val name: String,
|
||||||
val roles: List<String> = listOf(),
|
val roles: List<String> = listOf(),
|
||||||
): Serializable
|
)
|
||||||
|
|
||||||
// Select one entity
|
// Select one entity
|
||||||
val result: Inventor? = connection.selectOne(
|
val result: Inventor = connection.execute(
|
||||||
"""
|
"""
|
||||||
SELECT json_build_object(
|
SELECT json_build_object(
|
||||||
'id', '9e65de49-712e-47ce-8bf2-dfffae53a82e',
|
'id', '9e65de49-712e-47ce-8bf2-dfffae53a82e',
|
||||||
@@ -40,7 +40,7 @@ val result: Inventor? = connection.selectOne(
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Select multiple entities
|
// Select multiple entities
|
||||||
val result = connection.select<List<Inventor>>(
|
val result = connection.execute<List<Inventor>>(
|
||||||
"""
|
"""
|
||||||
SELECT json_build_array(
|
SELECT json_build_array(
|
||||||
json_build_object(
|
json_build_object(
|
||||||
@@ -60,7 +60,7 @@ val result = connection.select<List<Inventor>>(
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Select multiple with real query
|
// Select multiple with real query
|
||||||
val result: List<Inventor> = connection.select(
|
val result: List<Inventor> = connection.execute(
|
||||||
"""
|
"""
|
||||||
select json_agg(i)
|
select json_agg(i)
|
||||||
from inventor i
|
from inventor i
|
||||||
@@ -71,7 +71,7 @@ val result: List<Inventor> = connection.select(
|
|||||||
|
|
||||||
|
|
||||||
// Select multiple with only some rows
|
// Select multiple with only some rows
|
||||||
val result: List<Inventor> = connection.select(
|
val result: List<Inventor> = connection.execute(
|
||||||
"""
|
"""
|
||||||
select json_agg(i)
|
select json_agg(i)
|
||||||
from (
|
from (
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ val requester = Requester(
|
|||||||
```kotlin
|
```kotlin
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import org.joda.time.DateTime
|
import org.joda.time.DateTime
|
||||||
import fr.postgresjson.entity.Serializable
|
|
||||||
|
|
||||||
enum class Roles { ROLE_USER, ROLE_ADMIN }
|
enum class Roles { ROLE_USER, ROLE_ADMIN }
|
||||||
|
|
||||||
@@ -31,15 +30,16 @@ class User(
|
|||||||
override var username: String,
|
override var username: String,
|
||||||
var blockedAt: DateTime? = null,
|
var blockedAt: DateTime? = null,
|
||||||
var roles: List<Roles> = emptyList()
|
var roles: List<Roles> = emptyList()
|
||||||
): Serializable
|
)
|
||||||
|
|
||||||
|
@SqlSerializable
|
||||||
class UserForCreate(
|
class UserForCreate(
|
||||||
id: UUID = UUID.randomUUID(),
|
id: UUID = UUID.randomUUID(),
|
||||||
username: String,
|
username: String,
|
||||||
val password: String,
|
val password: String,
|
||||||
blockedAt: DateTime? = null,
|
blockedAt: DateTime? = null,
|
||||||
roles: List<Roles> = emptyList()
|
roles: List<Roles> = emptyList()
|
||||||
): Serializable
|
)
|
||||||
```
|
```
|
||||||
3. and, define Repositories
|
3. and, define Repositories
|
||||||
[See SQL function](../migrations/migrations.md)
|
[See SQL function](../migrations/migrations.md)
|
||||||
@@ -53,19 +53,14 @@ class UserRepository(override var requester: Requester): RepositoryI {
|
|||||||
fun findById(id: UUID): User {
|
fun findById(id: UUID): User {
|
||||||
return requester
|
return requester
|
||||||
.getFunction("find_user_by_id") // Use the name of the function
|
.getFunction("find_user_by_id") // Use the name of the function
|
||||||
.selectOne(
|
.execute("id" to id) // You can pass parameters by their names. The underscore prefix on parameters is not required to be mapped.
|
||||||
"id" to id // You can pass parameters by their names. The underscore prefix on parameters is not required to be mapped.
|
// Throw exception if user not found
|
||||||
) ?: throw UserNotFound(id) // Throw exception if user not found
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun insert(user: UserForCreate): User {
|
fun insert(user: UserForCreate): User {
|
||||||
return requester
|
return requester
|
||||||
.getFunction("insert_user")
|
.getFunction("insert_user")
|
||||||
.selectOne("resource" to user)
|
.execute("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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -3,5 +3,4 @@
|
|||||||
1. [Init connection](./init-connection.md)
|
1. [Init connection](./init-connection.md)
|
||||||
2. [Raw request](./raw-request.md)
|
2. [Raw request](./raw-request.md)
|
||||||
3. [Stored Procedure](./stored-procedure.md)
|
3. [Stored Procedure](./stored-procedure.md)
|
||||||
4. [Paginated request](./paginated.md)
|
4. [Multi level request](./multi-level.md)
|
||||||
5. [Multi level request](./multi-level.md)
|
|
||||||
@@ -8,3 +8,4 @@ systemProp.sonar.coverage.jacoco.xmlReportPaths=build/reports/jacoco/test/jacoco
|
|||||||
org.gradle.jvmargs=-Xmx4096M
|
org.gradle.jvmargs=-Xmx4096M
|
||||||
containerAlwaysOn=false
|
containerAlwaysOn=false
|
||||||
disableLint=false
|
disableLint=false
|
||||||
|
projectName=postgres-json
|
||||||
9
src/.editorconfig
Normal file
9
src/.editorconfig
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
indent_size = 4
|
||||||
|
indent_style = space
|
||||||
|
insert_final_newline = true
|
||||||
|
tab_width = 4
|
||||||
@@ -3,21 +3,16 @@ package fr.postgresjson.connexion
|
|||||||
import com.fasterxml.jackson.core.type.TypeReference
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
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.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
|
||||||
import com.github.jasync.sql.db.util.length
|
import com.github.jasync.sql.db.util.length
|
||||||
import fr.postgresjson.entity.EntityI
|
|
||||||
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 kotlin.jvm.Throws
|
||||||
import kotlin.random.Random
|
import kotlin.random.Random
|
||||||
|
import kotlin.reflect.full.hasAnnotation
|
||||||
typealias SelectOneCallback<T> = QueryResult.(T?) -> Unit
|
|
||||||
typealias SelectCallback<T> = QueryResult.(List<T>) -> Unit
|
|
||||||
typealias SelectPaginatedCallback<T> = QueryResult.(Paginated<T>) -> Unit
|
|
||||||
|
|
||||||
class Connection(
|
class Connection(
|
||||||
private val database: String,
|
private val database: String,
|
||||||
@@ -25,18 +20,18 @@ class Connection(
|
|||||||
private val password: String,
|
private val password: String,
|
||||||
private val host: String = "localhost",
|
private val host: String = "localhost",
|
||||||
private val port: Int = 5432
|
private val port: Int = 5432
|
||||||
) : Executable {
|
) : ExecutableRaw {
|
||||||
private var connection: ConnectionPool<PostgreSQLConnection>? = null
|
private var connectionPool: ConnectionPool<PostgreSQLConnection>? = null
|
||||||
private val serializer = Serializer()
|
private val serializer = Serializer()
|
||||||
private val logger: Logger? by LoggerDelegate()
|
private val logger: Logger? by LoggerDelegate()
|
||||||
|
|
||||||
internal fun connect(): ConnectionPool<PostgreSQLConnection> {
|
internal fun connect(): ConnectionPool<PostgreSQLConnection> {
|
||||||
return connection.let { connectionPool ->
|
return connectionPool.let { connectionPool ->
|
||||||
if (connectionPool == null || !connectionPool.isConnected()) {
|
if (connectionPool == null || !connectionPool.isConnected()) {
|
||||||
PostgreSQLConnectionBuilder.createConnectionPool(
|
PostgreSQLConnectionBuilder.createConnectionPool(
|
||||||
"jdbc:postgresql://$host:$port/$database?user=$username&password=$password"
|
"jdbc:postgresql://$host:$port/$database?user=$username&password=$password"
|
||||||
).also {
|
).also {
|
||||||
connection = it
|
this.connectionPool = it
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
connectionPool
|
connectionPool
|
||||||
@@ -45,7 +40,7 @@ class Connection(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun disconnect() {
|
fun disconnect() {
|
||||||
connection?.disconnect()
|
connectionPool?.disconnect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <A> inTransaction(block: Connection.() -> A?): A? = connect().run {
|
fun <A> inTransaction(block: Connection.() -> A?): A? = connect().run {
|
||||||
@@ -59,16 +54,19 @@ class Connection(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with [List] of parameters
|
* Select with unnamed parameters
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> selectOne(
|
@Throws(DataNotFoundException::class)
|
||||||
|
override fun <R : Any> execute(
|
||||||
sql: String,
|
sql: String,
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: List<Any?>,
|
values: List<Any?>,
|
||||||
block: (QueryResult, R?) -> Unit
|
block: SelectCallback<R>
|
||||||
): R? {
|
): R? {
|
||||||
val result = exec(sql, compileArgs(values))
|
val result: QueryResult = exec(sql, compileArgs(values))
|
||||||
val json = result.rows.firstOrNull()?.getString(0)
|
if (result.rows.size == 0) throw DataNotFoundException(sql)
|
||||||
|
|
||||||
|
val json: String? = result.rows.firstOrNull()?.getString(0)
|
||||||
return if (json === null) {
|
return if (json === null) {
|
||||||
null
|
null
|
||||||
} else {
|
} else {
|
||||||
@@ -79,99 +77,16 @@ class Connection(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with named parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> selectOne(
|
override fun <R : Any> execute(
|
||||||
sql: String,
|
sql: String,
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: Map<String, Any?>,
|
values: Map<String, Any?>,
|
||||||
block: (QueryResult, R?) -> Unit
|
block: SelectCallback<R>
|
||||||
): R? {
|
): R? {
|
||||||
return replaceArgs(sql, values) {
|
return replaceArgs(sql, values) {
|
||||||
selectOne(this.sql, typeReference, parameters, block)
|
execute(this.sql, typeReference, parameters, block)
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Select Multiples */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select multiple [EntityI] with [List] of parameters
|
|
||||||
*/
|
|
||||||
override fun <R : EntityI> select(
|
|
||||||
sql: String,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: List<Any?>,
|
|
||||||
block: QueryResult.(List<R>) -> Unit
|
|
||||||
): List<R> {
|
|
||||||
val result = exec(sql, values)
|
|
||||||
val json = result.rows[0].getString(0)
|
|
||||||
return if (json === null) {
|
|
||||||
emptyList()
|
|
||||||
} else {
|
|
||||||
serializer.deserializeList(json, typeReference)
|
|
||||||
}.also {
|
|
||||||
block(result, it)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select multiple [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Select Paginated */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select Multiple [EntityI] with pagination
|
|
||||||
*/
|
|
||||||
override fun <R : EntityI> select(
|
|
||||||
sql: String,
|
|
||||||
page: Int,
|
|
||||||
limit: Int,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: QueryResult.(Paginated<R>) -> Unit
|
|
||||||
): Paginated<R> {
|
|
||||||
val offset = (page - 1) * limit
|
|
||||||
val newValues = values
|
|
||||||
.plus("offset" to offset)
|
|
||||||
.plus("limit" to limit)
|
|
||||||
|
|
||||||
val line = replaceArgs(sql, newValues) {
|
|
||||||
exec(this.sql, this.parameters)
|
|
||||||
}
|
|
||||||
|
|
||||||
return line.run {
|
|
||||||
val firstLine = rows.firstOrNull() ?: queryError("The query has no return", sql, newValues)
|
|
||||||
if (!(firstLine as ArrayRowData).mapping.keys.contains("total")) queryError("""The query not return the "total" column""", sql, newValues, rows)
|
|
||||||
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 {
|
|
||||||
serializer.deserializeList(json, typeReference)
|
|
||||||
}
|
|
||||||
Paginated(
|
|
||||||
entities,
|
|
||||||
offset,
|
|
||||||
limit,
|
|
||||||
total
|
|
||||||
)
|
|
||||||
}.also {
|
|
||||||
block(line, it)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,10 +126,12 @@ class Connection(
|
|||||||
|
|
||||||
private fun compileArgs(values: List<Any?>): List<Any?> {
|
private fun compileArgs(values: List<Any?>): List<Any?> {
|
||||||
return values.map {
|
return values.map {
|
||||||
if (it is Serializable || (it is List<*> && it.firstOrNull() is Serializable)) {
|
when {
|
||||||
serializer.serialize(it)
|
it == null -> it
|
||||||
} else {
|
it is List<*> && it.isEmpty() -> it
|
||||||
it
|
it is List<*> && it.first()!!::class.hasAnnotation<SqlSerializable>() -> serializer.serialize(it)
|
||||||
|
it::class.hasAnnotation<SqlSerializable>() -> serializer.serialize(it)
|
||||||
|
else -> it
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -307,10 +224,11 @@ class Connection(
|
|||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
logger?.info(
|
logger?.info(
|
||||||
"""
|
"""
|
||||||
Query Error:
|
|Query Error:
|
||||||
${sql.prependIndent()},
|
|$sql,
|
||||||
${values.joinToString(", ").prependIndent()}
|
|Arguments (${values.length}):
|
||||||
""".trimIndent(),
|
|${values.joinToString(", ").ifBlank { "No arguments" }.prependIndent()}
|
||||||
|
""".trimMargin().prependIndent(" > "),
|
||||||
e
|
e
|
||||||
)
|
)
|
||||||
throw e
|
throw e
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
|
class DataNotFoundException(val queryExecuted: String) : Exception() {
|
||||||
|
override val message: String
|
||||||
|
get() = "No data return for the query"
|
||||||
|
}
|
||||||
@@ -2,107 +2,43 @@ package fr.postgresjson.connexion
|
|||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
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 kotlin.jvm.Throws
|
||||||
|
|
||||||
sealed interface EmbedExecutable {
|
sealed interface EmbedExecutable : Executable {
|
||||||
val connection: Connection
|
val connection: Connection
|
||||||
override fun toString(): String
|
override fun toString(): String
|
||||||
val name: String
|
val name: String
|
||||||
|
|
||||||
/* Select One */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update [EntityI] with one entity as argument
|
* Select with unnamed parameters
|
||||||
*/
|
*/
|
||||||
fun <R : EntityI> update(
|
@Throws(DataNotFoundException::class)
|
||||||
typeReference: TypeReference<R>,
|
fun <R : Any> execute(
|
||||||
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>,
|
typeReference: TypeReference<R>,
|
||||||
values: List<Any?>,
|
values: List<Any?>,
|
||||||
block: SelectOneCallback<R> = {}
|
block: SelectCallback<R> = {}
|
||||||
): R?
|
): R?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with [Map] of parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
fun <R : EntityI> selectOne(
|
@Throws(DataNotFoundException::class)
|
||||||
|
fun <R : Any> execute(
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: Map<String, Any?>,
|
values: Map<String, Any?>,
|
||||||
block: SelectOneCallback<R> = {}
|
block: SelectCallback<R> = {}
|
||||||
): R?
|
): R?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with multiple [Pair] of parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
fun <R : EntityI> selectOne(
|
@Throws(DataNotFoundException::class)
|
||||||
|
fun <R : Any> execute(
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
vararg values: Pair<String, Any?>,
|
vararg values: Pair<String, Any?>,
|
||||||
block: SelectOneCallback<R> = {}
|
block: SelectCallback<R> = {}
|
||||||
): R? =
|
): R? =
|
||||||
selectOne(typeReference, values.toMap(), block)
|
execute(typeReference, values.toMap(), block)
|
||||||
|
|
||||||
/* Select Multiples */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select Multiple [EntityI] with [List] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> select(
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: List<Any?>,
|
|
||||||
block: SelectCallback<R> = {}
|
|
||||||
): List<R>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select Multiple [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> select(
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: SelectCallback<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 [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> select(
|
|
||||||
page: Int,
|
|
||||||
limit: Int,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: SelectPaginatedCallback<R> = {}
|
|
||||||
): Paginated<R>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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: List<Any?>): QueryResult
|
||||||
fun exec(values: Map<String, Any?>): QueryResult
|
fun exec(values: Map<String, Any?>): QueryResult
|
||||||
|
|||||||
@@ -1,68 +1,25 @@
|
|||||||
package fr.postgresjson.connexion
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
import fr.postgresjson.entity.EntityI
|
import kotlin.jvm.Throws
|
||||||
|
|
||||||
/* Select One */
|
@Throws(DataNotFoundException::class)
|
||||||
|
inline fun <reified R : Any> EmbedExecutable.execute(
|
||||||
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?>,
|
values: List<Any?>,
|
||||||
noinline block: SelectCallback<R> = {}
|
noinline block: SelectCallback<R> = {}
|
||||||
): List<R> =
|
): R? =
|
||||||
select(object : TypeReference<List<R>>() {}, values, block)
|
execute(object : TypeReference<R>() {}, values, block)
|
||||||
|
|
||||||
inline fun <reified R : EntityI> EmbedExecutable.select(
|
@Throws(DataNotFoundException::class)
|
||||||
|
inline fun <reified R : Any> EmbedExecutable.execute(
|
||||||
values: Map<String, Any?>,
|
values: Map<String, Any?>,
|
||||||
noinline block: SelectCallback<R> = {}
|
noinline block: SelectCallback<R> = {}
|
||||||
): List<R> =
|
): R? =
|
||||||
select(object : TypeReference<List<R>>() {}, values, block)
|
execute(object : TypeReference<R>() {}, values, block)
|
||||||
|
|
||||||
inline fun <reified R : EntityI> EmbedExecutable.select(
|
@Throws(DataNotFoundException::class)
|
||||||
|
inline fun <reified R : Any> EmbedExecutable.execute(
|
||||||
vararg values: Pair<String, Any?>,
|
vararg values: Pair<String, Any?>,
|
||||||
noinline block: SelectCallback<R> = {}
|
noinline block: SelectCallback<R> = {}
|
||||||
): List<R> =
|
): R? =
|
||||||
select(object : TypeReference<List<R>>() {}, values = values, block)
|
execute(object : TypeReference<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)
|
|
||||||
|
|||||||
@@ -1,136 +1,3 @@
|
|||||||
package fr.postgresjson.connexion
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
sealed interface Executable
|
||||||
import com.github.jasync.sql.db.QueryResult
|
|
||||||
import fr.postgresjson.entity.EntityI
|
|
||||||
|
|
||||||
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 [EntityI] with [List] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> selectOne(
|
|
||||||
sql: String,
|
|
||||||
typeReference: TypeReference<R>,
|
|
||||||
values: List<Any?>,
|
|
||||||
block: SelectOneCallback<R> = {}
|
|
||||||
): R?
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select One [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> selectOne(
|
|
||||||
sql: String,
|
|
||||||
typeReference: TypeReference<R>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: SelectOneCallback<R> = {}
|
|
||||||
): R?
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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(
|
|
||||||
sql: String,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: List<Any?> = emptyList(),
|
|
||||||
block: SelectCallback<R> = {}
|
|
||||||
): List<R>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select Multiple [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> select(
|
|
||||||
sql: String,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: SelectCallback<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 [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
fun <R : EntityI> select(
|
|
||||||
sql: String,
|
|
||||||
page: Int,
|
|
||||||
limit: Int,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: SelectPaginatedCallback<R> = {}
|
|
||||||
): Paginated<R>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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, vararg values: Pair<String, Any?>): QueryResult = exec(sql, values.toMap())
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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())
|
|
||||||
}
|
|
||||||
|
|||||||
64
src/main/kotlin/fr/postgresjson/connexion/ExecutableRaw.kt
Normal file
64
src/main/kotlin/fr/postgresjson/connexion/ExecutableRaw.kt
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
|
import com.github.jasync.sql.db.QueryResult
|
||||||
|
import kotlin.jvm.Throws
|
||||||
|
|
||||||
|
typealias SelectCallback<R> = QueryResult.(R?) -> Unit
|
||||||
|
|
||||||
|
sealed interface ExecutableRaw : Executable {
|
||||||
|
/**
|
||||||
|
* Select with [List] of parameters
|
||||||
|
*/
|
||||||
|
@Throws(DataNotFoundException::class)
|
||||||
|
fun <R : Any> execute(
|
||||||
|
sql: String,
|
||||||
|
typeReference: TypeReference<R>,
|
||||||
|
values: List<Any?> = emptyList(),
|
||||||
|
block: SelectCallback<R> = {}
|
||||||
|
): R?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select with [Map] of parameters
|
||||||
|
*/
|
||||||
|
@Throws(DataNotFoundException::class)
|
||||||
|
fun <R : Any> execute(
|
||||||
|
sql: String,
|
||||||
|
typeReference: TypeReference<R>,
|
||||||
|
values: Map<String, Any?>,
|
||||||
|
block: SelectCallback<R> = {}
|
||||||
|
): R?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select with multiple [Pair] of parameters
|
||||||
|
*/
|
||||||
|
@Throws(DataNotFoundException::class)
|
||||||
|
fun <R : Any> execute(
|
||||||
|
sql: String,
|
||||||
|
typeReference: TypeReference<R>,
|
||||||
|
vararg values: Pair<String, Any?>,
|
||||||
|
block: SelectCallback<R> = {}
|
||||||
|
): R? = execute(sql, typeReference, values.toMap(), block)
|
||||||
|
|
||||||
|
fun <R : Any?> 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, vararg values: Pair<String, Any?>): QueryResult = exec(sql, values.toMap())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Warning: this method not use prepared statement
|
||||||
|
*/
|
||||||
|
fun <R : Any?> 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())
|
||||||
|
}
|
||||||
@@ -1,106 +1,37 @@
|
|||||||
package fr.postgresjson.connexion
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
import fr.postgresjson.entity.EntityI
|
import kotlin.jvm.Throws
|
||||||
|
|
||||||
/* Update */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update [EntityI] with one entity as argument
|
* Select with unnamed parameters
|
||||||
*/
|
*/
|
||||||
inline fun <reified R : EntityI> Executable.update(
|
@Throws(DataNotFoundException::class)
|
||||||
sql: String,
|
inline fun <reified R : Any> ExecutableRaw.execute(
|
||||||
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,
|
sql: String,
|
||||||
values: List<Any?> = emptyList(),
|
values: List<Any?> = emptyList(),
|
||||||
noinline block: SelectCallback<R> = {}
|
noinline block: SelectCallback<R> = {}
|
||||||
): List<R> =
|
): R? =
|
||||||
select(sql, object : TypeReference<List<R>>() {}, values, block)
|
execute(sql, object : TypeReference<R>() {}, values, block)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select Multiple [EntityI] with [Map] of parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
inline fun <reified R : EntityI> Executable.select(
|
@Throws(DataNotFoundException::class)
|
||||||
|
inline fun <reified R : Any> ExecutableRaw.execute(
|
||||||
sql: String,
|
sql: String,
|
||||||
values: Map<String, Any?>,
|
values: Map<String, Any?>,
|
||||||
noinline block: SelectCallback<R> = {}
|
noinline block: SelectCallback<R> = {}
|
||||||
): List<R> =
|
): R? =
|
||||||
select(sql, object : TypeReference<List<R>>() {}, values, block)
|
execute(sql, object : TypeReference<R>() {}, values, block)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select Multiple [EntityI] with multiple [Pair] of parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
inline fun <reified R : EntityI> Executable.select(
|
@Throws(DataNotFoundException::class)
|
||||||
|
inline fun <reified R : Any> ExecutableRaw.execute(
|
||||||
sql: String,
|
sql: String,
|
||||||
vararg values: Pair<String, Any?>,
|
vararg values: Pair<String, Any?>,
|
||||||
noinline block: SelectCallback<R> = {}
|
noinline block: SelectCallback<R> = {}
|
||||||
): List<R> =
|
): R? =
|
||||||
select(sql, object : TypeReference<List<R>>() {}, values = values, block)
|
execute(sql, object : TypeReference<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)
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package fr.postgresjson.connexion
|
|||||||
import com.fasterxml.jackson.core.type.TypeReference
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
import com.github.jasync.sql.db.QueryResult
|
import com.github.jasync.sql.db.QueryResult
|
||||||
import fr.postgresjson.definition.Function
|
import fr.postgresjson.definition.Function
|
||||||
import fr.postgresjson.entity.EntityI
|
|
||||||
|
|
||||||
class Function(val definition: Function, override val connection: Connection) : EmbedExecutable {
|
class Function(val definition: Function, override val connection: Connection) : EmbedExecutable {
|
||||||
override fun toString(): String {
|
override fun toString(): String {
|
||||||
@@ -12,79 +11,42 @@ class Function(val definition: Function, override val connection: Connection) :
|
|||||||
|
|
||||||
override val name: String = definition.name
|
override val name: String = definition.name
|
||||||
|
|
||||||
/* Select One */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with [List] of parameters
|
* Select with [List] of parameters
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> selectOne(
|
override fun <R : Any> execute(
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: List<Any?>,
|
values: List<Any?>,
|
||||||
block: (QueryResult, R?) -> Unit
|
block: SelectCallback<R>
|
||||||
): R? =
|
): R? =
|
||||||
connection.selectOne(compileSql(values), typeReference, values, block)
|
connection.execute(compileSql(values), typeReference, values, block)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with named parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> selectOne(
|
override fun <R : Any> execute(
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: Map<String, Any?>,
|
values: Map<String, Any?>,
|
||||||
block: (QueryResult, R?) -> Unit
|
block: SelectCallback<R>
|
||||||
): R? =
|
): R? =
|
||||||
connection.selectOne(compileSql(values), typeReference, values, block)
|
connection.execute(compileSql(values), typeReference, values, block)
|
||||||
|
|
||||||
/* Select Multiples */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select multiple [EntityI] with [List] of parameters
|
* Execute function without treatments
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> select(
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: List<Any?>,
|
|
||||||
block: (QueryResult, List<R>) -> Unit
|
|
||||||
): List<R> =
|
|
||||||
connection.select(compileSql(values), typeReference, values, block)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select multiple [EntityI] with named parameters
|
|
||||||
*/
|
|
||||||
override fun <R : EntityI> select(
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: (QueryResult, List<R>) -> Unit
|
|
||||||
): List<R> =
|
|
||||||
connection.select(compileSql(values), typeReference, values, block)
|
|
||||||
|
|
||||||
/* Select Paginated */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select Multiple [EntityI] with pagination
|
|
||||||
*/
|
|
||||||
override fun <R : EntityI> select(
|
|
||||||
page: Int,
|
|
||||||
limit: Int,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: (QueryResult, Paginated<R>) -> Unit
|
|
||||||
): Paginated<R> {
|
|
||||||
val offset = (page - 1) * limit
|
|
||||||
val newValues = values
|
|
||||||
.plus("offset" to offset)
|
|
||||||
.plus("limit" to limit)
|
|
||||||
|
|
||||||
return connection.select(compileSql(newValues), page, limit, typeReference, values, block)
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Execute function without treatments */
|
|
||||||
|
|
||||||
override fun exec(values: List<Any?>): QueryResult = connection.exec(compileSql(values), values)
|
override fun exec(values: List<Any?>): QueryResult = connection.exec(compileSql(values), values)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute function without treatments
|
||||||
|
*/
|
||||||
override fun exec(values: Map<String, Any?>): QueryResult = connection.exec(compileSql(values), values)
|
override fun exec(values: Map<String, Any?>): QueryResult = connection.exec(compileSql(values), values)
|
||||||
|
|
||||||
private fun <R : EntityI> compileArgs(value: R): String = compileArgs(listOf(value))
|
private fun <A : Any?> compileParameters(value: A): String = compileParameters(listOf(value))
|
||||||
|
|
||||||
private fun compileArgs(values: List<Any?>): String {
|
/**
|
||||||
|
* Add cast to all parameters
|
||||||
|
*/
|
||||||
|
private fun compileParameters(values: List<Any?>): String {
|
||||||
val placeholders = values
|
val placeholders = values
|
||||||
.filterIndexed { index, value ->
|
.filterIndexed { index, value ->
|
||||||
definition.parameters[index].default === null || value != null
|
definition.parameters[index].default === null || value != null
|
||||||
@@ -96,7 +58,10 @@ class Function(val definition: Function, override val connection: Connection) :
|
|||||||
return placeholders.joinToString(separator = ", ")
|
return placeholders.joinToString(separator = ", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun compileArgs(values: Map<String, Any?>): String {
|
/**
|
||||||
|
* Cast and add named parameters
|
||||||
|
*/
|
||||||
|
private fun compileParameters(values: Map<String, Any?>): String {
|
||||||
val parameters = definition.getParametersIndexedByName()
|
val parameters = definition.getParametersIndexedByName()
|
||||||
val placeholders = values
|
val placeholders = values
|
||||||
.filter { entry ->
|
.filter { entry ->
|
||||||
@@ -111,7 +76,16 @@ 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)})"
|
* Create SQL to call the function
|
||||||
private fun compileSql(values: Map<String, Any?>): String = "SELECT * FROM ${definition.name} (${compileArgs(values)})"
|
*/
|
||||||
|
private fun <A : Any?> compileSql(value: A): String = "SELECT * FROM ${definition.name} (${compileParameters(value)})"
|
||||||
|
/**
|
||||||
|
* Create SQL to call the function
|
||||||
|
*/
|
||||||
|
private fun compileSql(values: List<Any?>): String = "SELECT * FROM ${definition.name} (${compileParameters(values)})"
|
||||||
|
/**
|
||||||
|
* Create SQL to call the function
|
||||||
|
*/
|
||||||
|
private fun compileSql(values: Map<String, Any?>): String = "SELECT * FROM ${definition.name} (${compileParameters(values)})"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
package fr.postgresjson.connexion
|
|
||||||
|
|
||||||
import fr.postgresjson.entity.EntityI
|
|
||||||
import kotlin.math.ceil
|
|
||||||
|
|
||||||
data class Paginated<T : EntityI>(
|
|
||||||
val result: List<T>,
|
|
||||||
val offset: Int,
|
|
||||||
val limit: Int,
|
|
||||||
val total: Int
|
|
||||||
) {
|
|
||||||
val currentPage: Int = (offset / limit) + 1
|
|
||||||
val count: Int = result.size
|
|
||||||
val totalPages: Int = (total.toDouble() / limit.toDouble()).ceil()
|
|
||||||
|
|
||||||
init {
|
|
||||||
if (offset < 0) error("offset must be greater or equal than 0")
|
|
||||||
if (limit < 1) error("limit must be greater or equal than 1")
|
|
||||||
if (total < 0) error("total must be greater or equal than 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isLastPage(): Boolean = currentPage >= totalPages
|
|
||||||
|
|
||||||
private fun Double.ceil(): Int = ceil(this).toInt()
|
|
||||||
}
|
|
||||||
@@ -2,75 +2,40 @@ package fr.postgresjson.connexion
|
|||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
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
|
|
||||||
|
|
||||||
class Query(override val name: String, private val sql: String, override val connection: Connection) : EmbedExecutable {
|
class Query(override val name: String, private val sql: String, override val connection: Connection) : EmbedExecutable {
|
||||||
override fun toString(): String {
|
override fun toString(): String {
|
||||||
return sql
|
return sql
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Select One */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with [List] of parameters
|
* Select with unnamed of parameters
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> selectOne(
|
override fun <R : Any> execute(
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: List<Any?>,
|
values: List<Any?>,
|
||||||
block: SelectOneCallback<R>
|
block: SelectCallback<R>
|
||||||
): R? =
|
): R? =
|
||||||
connection.selectOne(sql, typeReference, values, block)
|
connection.execute(sql, typeReference, values, block)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select One [EntityI] with named parameters
|
* Select with named parameters
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> selectOne(
|
override fun <R : Any> execute(
|
||||||
typeReference: TypeReference<R>,
|
typeReference: TypeReference<R>,
|
||||||
values: Map<String, Any?>,
|
values: Map<String, Any?>,
|
||||||
block: SelectOneCallback<R>
|
block: SelectCallback<R>
|
||||||
): R? =
|
): R? =
|
||||||
connection.selectOne(sql, typeReference, values, block)
|
connection.execute(sql, typeReference, values, block)
|
||||||
|
|
||||||
/* Select Multiples */
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Select multiple [EntityI] with [List] of parameters
|
* Execute function without treatments
|
||||||
*/
|
*/
|
||||||
override fun <R : EntityI> select(
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: List<Any?>,
|
|
||||||
block: SelectCallback<R>
|
|
||||||
): List<R> =
|
|
||||||
connection.select(sql, typeReference, values, block)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select multiple [EntityI] with [Map] of parameters
|
|
||||||
*/
|
|
||||||
override fun <R : EntityI> select(
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: SelectCallback<R>
|
|
||||||
): List<R> =
|
|
||||||
connection.select(sql, typeReference, values, block)
|
|
||||||
|
|
||||||
/* Select Paginated */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select Multiple [EntityI] with pagination
|
|
||||||
*/
|
|
||||||
override fun <R : EntityI> select(
|
|
||||||
page: Int,
|
|
||||||
limit: Int,
|
|
||||||
typeReference: TypeReference<List<R>>,
|
|
||||||
values: Map<String, Any?>,
|
|
||||||
block: (QueryResult, Paginated<R>) -> Unit
|
|
||||||
): Paginated<R> =
|
|
||||||
connection.select(sql, page, limit, typeReference, values, block)
|
|
||||||
|
|
||||||
/* Execute function without treatments */
|
|
||||||
|
|
||||||
override fun exec(values: List<Any?>): QueryResult = connection.exec(sql, values)
|
override fun exec(values: List<Any?>): QueryResult = connection.exec(sql, values)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute function without treatments
|
||||||
|
*/
|
||||||
override fun exec(values: Map<String, Any?>): QueryResult = connection.exec(sql, values)
|
override fun exec(values: Map<String, Any?>): QueryResult = connection.exec(sql, values)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,6 +47,7 @@ class Query(override val name: String, private val sql: String, override val con
|
|||||||
* Warning: this method not use prepared statement
|
* Warning: this method not use prepared statement
|
||||||
*/
|
*/
|
||||||
fun sendQuery(values: Map<String, Any?>): QueryResult = connection.sendQuery(sql, values)
|
fun sendQuery(values: Map<String, Any?>): QueryResult = connection.sendQuery(sql, values)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Warning: this method not use prepared statement
|
* Warning: this method not use prepared statement
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,12 +4,24 @@ import fr.postgresjson.utils.searchSqlFiles
|
|||||||
import java.net.URI
|
import java.net.URI
|
||||||
import fr.postgresjson.definition.Query as QueryDefinition
|
import fr.postgresjson.definition.Query as QueryDefinition
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert [QueryDefinition], to runnable [Query]
|
||||||
|
*/
|
||||||
fun QueryDefinition.toRunnable(connection: Connection): Query = Query(name, script, connection)
|
fun QueryDefinition.toRunnable(connection: Connection): Query = Query(name, script, connection)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Sequence of [QueryDefinition], to runnable Sequence of [Query]
|
||||||
|
*/
|
||||||
fun Sequence<QueryDefinition>.toRunnable(connection: Connection): Sequence<Query> = map { it.toRunnable(connection) }
|
fun Sequence<QueryDefinition>.toRunnable(connection: Connection): Sequence<Query> = map { it.toRunnable(connection) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Sequence of [Query], to [Map] of [Query] with name as key
|
||||||
|
*/
|
||||||
fun Sequence<Query>.toMutableMap(): MutableMap<String, Query> = map { it.name to it }.toMap().toMutableMap()
|
fun Sequence<Query>.toMutableMap(): MutableMap<String, Query> = map { it.name to it }.toMap().toMutableMap()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a [Map] of [Query] from a [URI] pointing to the queries folder
|
||||||
|
*/
|
||||||
internal fun URI.toQuery(connection: Connection): MutableMap<String, Query> = searchSqlFiles()
|
internal fun URI.toQuery(connection: Connection): MutableMap<String, Query> = searchSqlFiles()
|
||||||
.filterIsInstance(QueryDefinition::class.java)
|
.filterIsInstance(QueryDefinition::class.java)
|
||||||
.toRunnable(connection)
|
.toRunnable(connection)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package fr.postgresjson.connexion
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.parse.parseFunction
|
||||||
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
|
||||||
@@ -48,7 +49,7 @@ class Requester(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun addFunction(sql: String) {
|
fun addFunction(sql: String) {
|
||||||
DefinitionFunction(sql)
|
parseFunction(sql)
|
||||||
.run { toRunnable(connection) }
|
.run { toRunnable(connection) }
|
||||||
.run { functions[name] = this }
|
.run { functions[name] = this }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package fr.postgresjson.connexion
|
||||||
|
|
||||||
|
@Target(AnnotationTarget.CLASS)
|
||||||
|
annotation class SqlSerializable
|
||||||
@@ -1,63 +1,26 @@
|
|||||||
package fr.postgresjson.definition
|
package fr.postgresjson.definition
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.IN
|
||||||
import java.nio.file.Path
|
import java.nio.file.Path
|
||||||
|
|
||||||
class Function(
|
class Function(
|
||||||
|
override val name: String,
|
||||||
|
override val parameters: List<Parameter>,
|
||||||
|
val returns: Returns,
|
||||||
override val script: String,
|
override val script: String,
|
||||||
override val source: Path? = null
|
override val source: Path? = null,
|
||||||
) : Resource, ParametersInterface {
|
) : Resource, ParametersInterface {
|
||||||
val returns: String
|
|
||||||
override val name: String
|
|
||||||
override val parameters: List<Parameter>
|
|
||||||
|
|
||||||
init {
|
fun getDefinition(): String = parameters
|
||||||
val functionRegex =
|
.filter { it.direction == IN }
|
||||||
"""create (or replace )?(procedure|function) *(?<name>[^(\s]+)\s*\((?<params>(\s*((IN|OUT|INOUT|VARIADIC)?\s+)?([^\s,)]+\s+)?([^\s,)]+)(\s+(?:default\s|=)\s*[^\s,)]+)?\s*(,|(?=\))))*)\) *(?<return>RETURNS *[^ \n]+)?"""
|
.joinToString(", ") { it.type.toString() }
|
||||||
.toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE))
|
|
||||||
|
|
||||||
val paramsRegex =
|
|
||||||
"""\s*(?<param>((?<direction>IN|OUT|INOUT|VARIADIC)?\s+)?("?(?<name>[^\s,")]+)"?\s+)?(?<type>[^\s,)]+)(\s+(?<default>default\s|=)\s*[^\s,)]+)?)\s*(,|$)"""
|
|
||||||
.toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE))
|
|
||||||
|
|
||||||
val queryMatch = functionRegex.find(script)
|
|
||||||
if (queryMatch !== null) {
|
|
||||||
val functionName = queryMatch.groups["name"]?.value?.trim() ?: error("Function name not found")
|
|
||||||
val functionParameters = queryMatch.groups["params"]?.value?.trim()
|
|
||||||
this.returns = queryMatch.groups["return"]?.value?.trim() ?: ""
|
|
||||||
|
|
||||||
/* Create parameters definition */
|
|
||||||
val parameters = if (functionParameters !== null) {
|
|
||||||
val matchesParams = paramsRegex.findAll(functionParameters)
|
|
||||||
matchesParams.map { paramsMatch ->
|
|
||||||
Parameter(
|
|
||||||
paramsMatch.groups["name"]!!.value.trim(),
|
|
||||||
paramsMatch.groups["type"]!!.value.trim(),
|
|
||||||
paramsMatch.groups["direction"]?.value?.trim(),
|
|
||||||
paramsMatch.groups["default"]?.value?.trim()
|
|
||||||
)
|
|
||||||
}.toList()
|
|
||||||
} else {
|
|
||||||
listOf()
|
|
||||||
}
|
|
||||||
this.name = functionName
|
|
||||||
this.parameters = parameters
|
|
||||||
} else {
|
|
||||||
throw FunctionNotFound()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class FunctionNotFound(cause: Throwable? = null) : Resource.ParseException("Function not found in script", cause)
|
|
||||||
|
|
||||||
fun getDefinition(): String {
|
|
||||||
return parameters
|
|
||||||
.filter { it.direction == Parameter.Direction.IN }
|
|
||||||
.joinToString(", ") { "${it.name} ${it.type}" }
|
|
||||||
.let { "$name ($it)" }
|
.let { "$name ($it)" }
|
||||||
}
|
|
||||||
|
|
||||||
fun getParametersIndexedByName(): Map<String, Parameter> {
|
fun getParametersIndexedByName(): Map<String, Parameter> = parameters
|
||||||
return parameters.associateBy { it.name }
|
.withIndex()
|
||||||
}
|
.associate { (key, param) -> Pair(param.name ?: "${key + 1}", param) }
|
||||||
|
|
||||||
|
operator fun get(name: String): Parameter? = parameters.firstOrNull { it.name == name }
|
||||||
|
|
||||||
infix fun `has same definition`(other: Function): Boolean {
|
infix fun `has same definition`(other: Function): Boolean {
|
||||||
return other.getDefinition() == this.getDefinition()
|
return other.getDefinition() == this.getDefinition()
|
||||||
|
|||||||
@@ -2,32 +2,63 @@ package fr.postgresjson.definition
|
|||||||
|
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
interface ParameterI {
|
class ParameterType(
|
||||||
val name: String
|
val name: String,
|
||||||
val type: String
|
val precision: Int? = null,
|
||||||
val direction: Parameter.Direction
|
val scale: Int? = null,
|
||||||
val default: String
|
val array: String? = null,
|
||||||
}
|
) {
|
||||||
|
val isArray: Boolean
|
||||||
|
get() = array != null
|
||||||
|
|
||||||
class Parameter(val name: String, val type: String, direction: Direction? = Direction.IN, val default: Any? = null) {
|
override fun toString(): String {
|
||||||
val direction: Direction
|
val type = if (precision == null && scale == null) {
|
||||||
|
name
|
||||||
init {
|
} else if (scale == null) {
|
||||||
if (direction === null) {
|
"""$name($precision)"""
|
||||||
this.direction = Direction.IN
|
|
||||||
} else {
|
} else {
|
||||||
this.direction = direction
|
"""$name($precision, $scale)"""
|
||||||
|
}
|
||||||
|
|
||||||
|
return type+array
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(name: String, type: String, direction: String? = "IN", default: Any? = null) : this(
|
interface ParameterSimpleI {
|
||||||
|
val name: String?
|
||||||
|
val type: ParameterType
|
||||||
|
}
|
||||||
|
|
||||||
|
class Parameter(
|
||||||
|
override val name: String?,
|
||||||
|
override val type: ParameterType,
|
||||||
|
val direction: Direction = Direction.IN,
|
||||||
|
val default: String? = null,
|
||||||
|
) : ParameterSimpleI {
|
||||||
|
constructor(name: String?, type: ParameterType, direction: String = "IN", default: String? = null) : this(
|
||||||
name = name,
|
name = name,
|
||||||
type = type,
|
type = type,
|
||||||
direction = direction?.let { Direction.valueOf(direction.uppercase(Locale.getDefault())) },
|
direction = direction.let { Direction.valueOf(direction.uppercase(Locale.getDefault())) },
|
||||||
default = default
|
default = default
|
||||||
)
|
)
|
||||||
|
|
||||||
enum class Direction { IN, OUT, INOUT }
|
enum class Direction { IN, OUT, INOUT }
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return buildString {
|
||||||
|
append(direction.name.lowercase())
|
||||||
|
if (name?.isNotBlank() == true) {
|
||||||
|
append(" ")
|
||||||
|
append(name)
|
||||||
|
}
|
||||||
|
append(" ")
|
||||||
|
append(type.toString())
|
||||||
|
if (default?.isNotBlank() == true) {
|
||||||
|
append(" ")
|
||||||
|
append(default)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ParametersInterface {
|
interface ParametersInterface {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package fr.postgresjson.definition
|
package fr.postgresjson.definition
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.parse.parseFunction
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.net.URL
|
import java.net.URL
|
||||||
import java.nio.file.Path
|
import java.nio.file.Path
|
||||||
@@ -23,7 +24,7 @@ sealed interface Resource {
|
|||||||
Migration(resource, path)
|
Migration(resource, path)
|
||||||
} catch (e: ParseException) {
|
} catch (e: ParseException) {
|
||||||
try {
|
try {
|
||||||
Function(resource, path)
|
parseFunction(resource, path)
|
||||||
} catch (e: ParseException) {
|
} catch (e: ParseException) {
|
||||||
try {
|
try {
|
||||||
Query(resource, path)
|
Query(resource, path)
|
||||||
|
|||||||
45
src/main/kotlin/fr/postgresjson/definition/Returns.kt
Normal file
45
src/main/kotlin/fr/postgresjson/definition/Returns.kt
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package fr.postgresjson.definition
|
||||||
|
|
||||||
|
sealed class Returns(
|
||||||
|
val definition: String,
|
||||||
|
val isSetOf: Boolean,
|
||||||
|
) {
|
||||||
|
class Primitive(
|
||||||
|
definition: String,
|
||||||
|
isSetOf: Boolean,
|
||||||
|
) : Returns(definition, isSetOf) {
|
||||||
|
val name = definition
|
||||||
|
.trim('"')
|
||||||
|
}
|
||||||
|
|
||||||
|
class PrimitiveList(
|
||||||
|
definition: String,
|
||||||
|
isSetOf: Boolean,
|
||||||
|
) : Returns(definition, isSetOf) {
|
||||||
|
val name = definition
|
||||||
|
.drop(2)
|
||||||
|
.trim('"')
|
||||||
|
}
|
||||||
|
|
||||||
|
class Table(
|
||||||
|
definition: String,
|
||||||
|
isSetOf: Boolean,
|
||||||
|
val parameters: List<ParameterTable>,
|
||||||
|
) : Returns(definition, isSetOf) {
|
||||||
|
class ParameterTable(
|
||||||
|
override val name: String,
|
||||||
|
override val type: ParameterType,
|
||||||
|
) : ParameterSimpleI
|
||||||
|
}
|
||||||
|
|
||||||
|
class Any(
|
||||||
|
isSetOf: Boolean,
|
||||||
|
) : Returns("any", isSetOf)
|
||||||
|
|
||||||
|
class Unknown(
|
||||||
|
definition: String,
|
||||||
|
isSetOf: Boolean,
|
||||||
|
) : Returns(definition, isSetOf)
|
||||||
|
|
||||||
|
class Void : Returns("void", false)
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package fr.postgresjson.definition.parse
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.Function
|
||||||
|
import fr.postgresjson.definition.Parameter
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.IN
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.INOUT
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.OUT
|
||||||
|
import fr.postgresjson.definition.ParameterType
|
||||||
|
import fr.postgresjson.definition.Resource.ParseException
|
||||||
|
import fr.postgresjson.definition.Returns
|
||||||
|
import fr.postgresjson.definition.Returns.Primitive
|
||||||
|
import fr.postgresjson.definition.Returns.Unknown
|
||||||
|
import fr.postgresjson.definition.Returns.Void
|
||||||
|
import java.nio.file.Path
|
||||||
|
import kotlin.text.RegexOption.IGNORE_CASE
|
||||||
|
|
||||||
|
internal fun parseFunction(script: String, source: Path? = null): Function {
|
||||||
|
val name: String
|
||||||
|
val parameters: List<Parameter>
|
||||||
|
val returns: Returns
|
||||||
|
ScriptPart(script)
|
||||||
|
.getFunctionOrProcedure().trimSpace().nextScriptPart
|
||||||
|
.getFunctionName().apply { name = value }.nextScriptPart
|
||||||
|
.getParameters().apply { parameters = value }.nextScriptPart
|
||||||
|
.getReturns().apply { returns = value }
|
||||||
|
|
||||||
|
return Function(name, parameters, returns, script, source)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Throws(FunctionNameMalformed::class)
|
||||||
|
internal fun ScriptPart.getFunctionName(): NextScript<String> {
|
||||||
|
try {
|
||||||
|
return getNextScript { status.isNotEscaped() && afterBeginBy("(", " ", "\n") }
|
||||||
|
.changeValue(String::unescapeOrLowercase)
|
||||||
|
} catch (e: ParseException) {
|
||||||
|
throw FunctionNameMalformed(this, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class FunctionNameMalformed(val script: ScriptPart, cause: Throwable? = null) :
|
||||||
|
ParseException("Function name is malformed", cause)
|
||||||
|
|
||||||
|
@Throws(FunctionNotFound::class)
|
||||||
|
internal fun ScriptPart.getFunctionOrProcedure(): NextScript<String> {
|
||||||
|
val result = """create\s+(?:or\s+replace\s+)?(procedure|function)\s+"""
|
||||||
|
.toRegex()
|
||||||
|
.find(restOfScript)
|
||||||
|
?: throw FunctionNotFound(this)
|
||||||
|
|
||||||
|
val rest = result.range.last
|
||||||
|
.let { cursor -> restOfScript.drop(cursor + 1) }
|
||||||
|
|
||||||
|
return NextScript(
|
||||||
|
result.groups[1]!!.value,
|
||||||
|
rest
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class FunctionNotFound(val script: ScriptPart) :
|
||||||
|
ParseException("Function not found in script")
|
||||||
|
|
||||||
|
internal fun ScriptPart.getParameters(): NextScript<List<Parameter>> {
|
||||||
|
val allParametersScript = this.getNextScript {
|
||||||
|
currentChar == ')' && status.isNotEscaped()
|
||||||
|
}
|
||||||
|
val parameterList: List<Parameter> = allParametersScript
|
||||||
|
.valueAsScriptPart()
|
||||||
|
.removeParentheses()
|
||||||
|
.split(",")
|
||||||
|
.map { it.toParameter() }
|
||||||
|
|
||||||
|
return NextScript(parameterList, allParametersScript.restOfScript)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ScriptPart.toParameter(): Parameter {
|
||||||
|
var script: ScriptPart = this.trimSpace()
|
||||||
|
return Parameter(
|
||||||
|
direction = script.getParameterMode().apply { script = nextScriptPart }.value,
|
||||||
|
name = script.getParameterName().trimSpace().apply { script = nextScriptPart }.value.trim(),
|
||||||
|
type = script.getParameterType().trimSpace().apply { script = nextScriptPart }.value,
|
||||||
|
default = script.getParameterDefault().trimSpace().apply { script = nextScriptPart }.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ScriptPart.getParameterMode(): NextScript<Direction> {
|
||||||
|
return when {
|
||||||
|
restOfScript.startsWith("inout ", true) -> NextScript(INOUT, restOfScript.drop("inout ".length))
|
||||||
|
restOfScript.startsWith("in ", true) -> NextScript(IN, restOfScript.drop("in ".length))
|
||||||
|
restOfScript.startsWith("out ", true) -> NextScript(OUT, restOfScript.drop("out ".length))
|
||||||
|
else -> NextScript(IN, restOfScript)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Throws(ParameterNameMalformed::class)
|
||||||
|
private fun ScriptPart.getParameterName(): NextScript<String> {
|
||||||
|
try {
|
||||||
|
return getNextScript { afterBeginBy(" ", "\n") && status.isNotEscaped() }
|
||||||
|
.changeValue(String::unescapeOrLowercase)
|
||||||
|
} catch (e: ParseException) {
|
||||||
|
throw ParameterNameMalformed(this, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ParameterNameMalformed(val script: ScriptPart, cause: Throwable) :
|
||||||
|
ParseException("Parameter name is malformed", cause)
|
||||||
|
|
||||||
|
@Throws(ParameterTypeMalformed::class)
|
||||||
|
private fun ScriptPart.getParameterType(): NextScript<ParameterType> {
|
||||||
|
val fullType = try {
|
||||||
|
val endTextList = arrayOf(" default ", "=")
|
||||||
|
getNextScript { afterBeginBy(texts = endTextList) }
|
||||||
|
} catch (e: ParseError) {
|
||||||
|
throw ParameterTypeMalformed(this, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
var rest: ScriptPart = fullType.valueAsScriptPart()
|
||||||
|
|
||||||
|
val name = rest
|
||||||
|
.getNextScript { afterBeginBy("(", "[") }
|
||||||
|
.apply { rest = nextScriptPart }
|
||||||
|
rest = rest.trimStart(' ', '\n', '\t', ',', '(')
|
||||||
|
val precision = rest
|
||||||
|
.getNextInteger()
|
||||||
|
.apply { rest = nextScriptPart }
|
||||||
|
rest = rest.trimStart(' ', '\n', '\t', ',')
|
||||||
|
val scale = rest
|
||||||
|
.getNextInteger()
|
||||||
|
.apply { rest = nextScriptPart }
|
||||||
|
rest = rest.trimStart(' ', '\n', '\t', ')')
|
||||||
|
|
||||||
|
val arrayDef = rest.restOfScript.trim().takeIf(String::isNotBlank)
|
||||||
|
|
||||||
|
return NextScript(
|
||||||
|
ParameterType(
|
||||||
|
name = name.value.trim().trim('[', ']'),
|
||||||
|
precision = precision.value,
|
||||||
|
scale = scale.value,
|
||||||
|
array = arrayDef
|
||||||
|
),
|
||||||
|
fullType.nextScriptPart.restOfScript
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class ParameterTypeMalformed(val script: ScriptPart, cause: Throwable) :
|
||||||
|
ParseException("Parameter type is malformed", cause)
|
||||||
|
|
||||||
|
@Throws(ParameterDefaultMalformed::class)
|
||||||
|
private fun ScriptPart.getParameterDefault(): NextScript<String?> {
|
||||||
|
return if (this.isEmpty() || this.restOfScript == ")") {
|
||||||
|
NextScript(null, "")
|
||||||
|
} else {
|
||||||
|
"""^(\s*=\s*|\s+default\s+)(.+)\s*$"""
|
||||||
|
.toRegex(IGNORE_CASE)
|
||||||
|
.find(restOfScript)
|
||||||
|
.let { it ?: throw ParameterDefaultMalformed(this) }
|
||||||
|
.let { it.groups[2]!!.value }
|
||||||
|
.let { NextScript(it.trim(), "") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ParameterDefaultMalformed(val script: ScriptPart) :
|
||||||
|
ParseException("Parameter default is malformed")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TODO Finalize this
|
||||||
|
*/
|
||||||
|
internal fun ScriptPart.getReturns(): NextScript<Returns> {
|
||||||
|
val rest = this.trimSpace()
|
||||||
|
if (!rest.restOfScript.startsWith("returns")) {
|
||||||
|
return NextScript(Void(), "")
|
||||||
|
}
|
||||||
|
var returns = ScriptPart(rest.restOfScript.drop("returns".length))
|
||||||
|
.getNextScript { this.afterBeginBy(Regex("\\s+language\\s+", IGNORE_CASE), Regex("\\s+as\\s+", IGNORE_CASE)) }
|
||||||
|
.trimSpace()
|
||||||
|
.value
|
||||||
|
.trimStart()
|
||||||
|
|
||||||
|
val isSetOf = returns.startsWith("SETOF", ignoreCase = true)
|
||||||
|
|
||||||
|
if (isSetOf) {
|
||||||
|
returns = returns.drop("SETOF".length).trimStart()
|
||||||
|
}
|
||||||
|
|
||||||
|
val returnsClass = if (returns.isBlank()) {
|
||||||
|
Void()
|
||||||
|
} else if (primitiveList.contains(ScriptPart(returns).getParameterType().value.name)) {
|
||||||
|
Primitive(returns, isSetOf)
|
||||||
|
} else {
|
||||||
|
Unknown(returns, isSetOf)
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextScript(returnsClass, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
private val primitiveList = listOf(
|
||||||
|
"text",
|
||||||
|
"varchar",
|
||||||
|
"character varying",
|
||||||
|
"character",
|
||||||
|
"char",
|
||||||
|
"int",
|
||||||
|
"smallint",
|
||||||
|
"integer",
|
||||||
|
"bigint",
|
||||||
|
"decimal",
|
||||||
|
"real",
|
||||||
|
"double precision",
|
||||||
|
"float",
|
||||||
|
"numeric",
|
||||||
|
"boolean",
|
||||||
|
"json",
|
||||||
|
"jsonb",
|
||||||
|
)
|
||||||
|
|
||||||
|
class ParseError(message: String? = null, cause: Throwable? = null) :
|
||||||
|
ParseException(message ?: "Parsing fail", cause)
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
package fr.postgresjson.definition.parse
|
||||||
|
|
||||||
|
import kotlin.contracts.ExperimentalContracts
|
||||||
|
import kotlin.contracts.InvocationKind.EXACTLY_ONCE
|
||||||
|
import kotlin.contracts.contract
|
||||||
|
|
||||||
|
@JvmInline
|
||||||
|
internal value class ScriptPart(val restOfScript: String) {
|
||||||
|
fun copy(block: (String) -> String): ScriptPart {
|
||||||
|
return ScriptPart(block(restOfScript))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isEmpty() = restOfScript.isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class NextScript<T>(val value: T, val restOfScript: String) {
|
||||||
|
val nextScriptPart: ScriptPart = ScriptPart(restOfScript)
|
||||||
|
fun isLast() = restOfScript == ""
|
||||||
|
fun isEmptyValue() = value == "" || value == null
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.removeParentheses(): ScriptPart {
|
||||||
|
return if (restOfScript.take(1) == "(" && restOfScript.takeLast(1) == ")") {
|
||||||
|
this.copy {
|
||||||
|
it.drop(1).dropLast(1)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get next part of script.
|
||||||
|
* You can define a list of characters that end the part of script. Like `(` or space.
|
||||||
|
*/
|
||||||
|
@Throws(ParseError::class)
|
||||||
|
internal fun ScriptPart.getNextScript(isEnd: Context.() -> Boolean = { false }): NextScript<String> {
|
||||||
|
val status = Status()
|
||||||
|
|
||||||
|
for ((index, c) in restOfScript.withIndex()) {
|
||||||
|
val prevChar = restOfScript.getOrNull(index - 1)
|
||||||
|
val nextChar = restOfScript.getOrNull(index + 1)
|
||||||
|
val nestedChars = listOf(prevChar, nextChar)
|
||||||
|
|
||||||
|
if (c == '"' && nestedChars.none { c == it }) {
|
||||||
|
status.doubleQuoted = !status.doubleQuoted
|
||||||
|
} else if (c == '\'' && nestedChars.none { c == it }) {
|
||||||
|
status.simpleQuoted = !status.simpleQuoted
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status.isNotQuoted()) {
|
||||||
|
when (c) {
|
||||||
|
'(' -> status.parentheses++
|
||||||
|
')' -> status.parentheses--
|
||||||
|
'[' -> status.brackets++
|
||||||
|
']' -> status.brackets--
|
||||||
|
'{' -> status.braces++
|
||||||
|
'}' -> status.braces--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEnd(Context(index, c, status.copy(), restOfScript))) {
|
||||||
|
return NextScript(
|
||||||
|
restOfScript.take(index + 1),
|
||||||
|
restOfScript.drop(index + 1),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status.isNotEscaped()) {
|
||||||
|
return NextScript(
|
||||||
|
restOfScript.trim(),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
throw ParseError()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.unescapeOrLowercase(): ScriptPart = restOfScript
|
||||||
|
.run(String::unescapeOrLowercase)
|
||||||
|
.let(::ScriptPart)
|
||||||
|
|
||||||
|
internal fun String.unescapeOrLowercase(): String {
|
||||||
|
val first = take(1)
|
||||||
|
val last = takeLast(1)
|
||||||
|
return if (first == last && first == "'") {
|
||||||
|
drop(1).dropLast(1).replace("$first$first", first).lowercase()
|
||||||
|
} else if (first == last && first == "\"") {
|
||||||
|
drop(1).dropLast(1).replace("$first$first", first)
|
||||||
|
} else {
|
||||||
|
this.lowercase()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <T> NextScript<T>.trimSpace(): NextScript<T> {
|
||||||
|
val spaces = charArrayOf(' ', '\n', '\t')
|
||||||
|
return trim(chars = spaces)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.trimSpace(): ScriptPart {
|
||||||
|
for ((n, char) in restOfScript.withIndex()) {
|
||||||
|
if (char !in listOf(' ', '\n', '\t')) {
|
||||||
|
return ScriptPart(
|
||||||
|
restOfScript.drop(n)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ScriptPart(restOfScript)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <T> NextScript<T>.trim(vararg chars: Char): NextScript<T> {
|
||||||
|
return NextScript(value, restOfScript.apply { dropWhile { it in chars } })
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.trimStart(vararg chars: Char): ScriptPart {
|
||||||
|
return this.change { dropWhile { it in chars } }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.trimEnd(vararg chars: Char): ScriptPart {
|
||||||
|
return this.change { dropLastWhile { it in chars } }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.split(delimiter: String): List<ScriptPart> {
|
||||||
|
val parts: MutableList<ScriptPart> = mutableListOf()
|
||||||
|
var rest: ScriptPart = this
|
||||||
|
do {
|
||||||
|
rest = rest.trimSpace()
|
||||||
|
.getNextScript { status.isNotEscaped() && currentChar.toString() == delimiter }
|
||||||
|
.trimSpace()
|
||||||
|
.also { parts.add(it.valueAsScriptPart().trimSpace().trimEnd(',')) }
|
||||||
|
.nextScriptPart
|
||||||
|
} while (!rest.isEmpty())
|
||||||
|
|
||||||
|
return parts
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the value as ScriptPart
|
||||||
|
*/
|
||||||
|
internal fun NextScript<String>.valueAsScriptPart(): ScriptPart = ScriptPart(value)
|
||||||
|
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
internal inline fun ScriptPart.change(block: String.() -> String): ScriptPart {
|
||||||
|
contract {
|
||||||
|
callsInPlace(block, EXACTLY_ONCE)
|
||||||
|
}
|
||||||
|
return ScriptPart(restOfScript.run(block))
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
internal inline fun <T> NextScript<T>.changeValue(block: (T) -> T): NextScript<T> {
|
||||||
|
contract {
|
||||||
|
callsInPlace(block, EXACTLY_ONCE)
|
||||||
|
}
|
||||||
|
return NextScript(value.run(block), nextScriptPart.restOfScript)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <T> NextScript<T>.changeScript(block: (String) -> String): NextScript<T> {
|
||||||
|
return NextScript(value, block(restOfScript))
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <T> NextScript<T>.dropOneOf(vararg endTextList: String): NextScript<T> {
|
||||||
|
return changeScript { script ->
|
||||||
|
endTextList
|
||||||
|
.filter { script.startsWith(it) }
|
||||||
|
.let { script.drop(it.size) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ScriptPart.getNextInteger(): NextScript<Int?> {
|
||||||
|
val digits = restOfScript.takeWhile { it.isDigit() }
|
||||||
|
val restOfScript = restOfScript.trimStart { it.isDigit() }
|
||||||
|
return NextScript(digits.toIntOrNull(), restOfScript).trimSpace()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal data class Status(
|
||||||
|
var doubleQuoted: Boolean = false, // "
|
||||||
|
var simpleQuoted: Boolean = false, // '
|
||||||
|
var parentheses: Int = 0, // ()
|
||||||
|
var brackets: Int = 0, // []
|
||||||
|
var braces: Int = 0, // {}
|
||||||
|
) {
|
||||||
|
fun isQuoted(): Boolean = doubleQuoted || simpleQuoted
|
||||||
|
fun isNotQuoted(): Boolean = !isQuoted()
|
||||||
|
fun isNotEscaped(): Boolean = isNotQuoted() && parentheses == 0 && brackets == 0 && braces == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
internal data class Context(
|
||||||
|
val index: Int,
|
||||||
|
val currentChar: Char,
|
||||||
|
val status: Status,
|
||||||
|
val script: String,
|
||||||
|
) {
|
||||||
|
fun afterBeginBy(vararg texts: String): Boolean = texts.any {
|
||||||
|
script.drop(index + 1).take(it.length).lowercase() == it.lowercase()
|
||||||
|
}
|
||||||
|
fun afterBeginBy(vararg texts: Regex): Boolean = texts.any {
|
||||||
|
it.matchAt(script, index + 1) != null
|
||||||
|
}
|
||||||
|
|
||||||
|
val nextChar: Char? get() = script.substring(index + 1).getOrNull(0)
|
||||||
|
}
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
package fr.postgresjson.entity
|
|
||||||
|
|
||||||
import org.joda.time.DateTime
|
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
interface EntityRefI<T> : EntityI {
|
|
||||||
val id: T
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UuidEntityI : EntityRefI<UUID> {
|
|
||||||
override val id: UUID
|
|
||||||
}
|
|
||||||
|
|
||||||
abstract class Entity<T>(override val id: T) : EntityRefI<T>
|
|
||||||
open class UuidEntity(id: UUID? = null) : UuidEntityI, Entity<UUID>(id ?: UUID.randomUUID())
|
|
||||||
|
|
||||||
/* Version */
|
|
||||||
interface EntityVersioning<ID, NUMBER> {
|
|
||||||
val versionNumber: NUMBER
|
|
||||||
val versionId: ID
|
|
||||||
}
|
|
||||||
|
|
||||||
class UuidEntityVersioning(
|
|
||||||
override val versionNumber: Int,
|
|
||||||
versionId: UUID? = null
|
|
||||||
) : EntityVersioning<UUID, Int> {
|
|
||||||
override val versionId: UUID = versionId ?: UUID.randomUUID()
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Dates */
|
|
||||||
interface EntityCreatedAt {
|
|
||||||
val createdAt: DateTime
|
|
||||||
}
|
|
||||||
interface EntityUpdatedAt {
|
|
||||||
val updatedAt: DateTime
|
|
||||||
}
|
|
||||||
|
|
||||||
interface EntityDeletedAt {
|
|
||||||
val deletedAt: DateTime?
|
|
||||||
fun isDeleted(): Boolean {
|
|
||||||
return deletedAt?.let {
|
|
||||||
it < DateTime.now()
|
|
||||||
} ?: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class EntityCreatedAtImp(
|
|
||||||
override val createdAt: DateTime = DateTime.now()
|
|
||||||
) : EntityCreatedAt
|
|
||||||
|
|
||||||
class EntityUpdatedAtImp(
|
|
||||||
override val updatedAt: DateTime = DateTime.now()
|
|
||||||
) : EntityUpdatedAt
|
|
||||||
|
|
||||||
class EntityDeletedAtImp(
|
|
||||||
override val deletedAt: DateTime? = null
|
|
||||||
) : EntityDeletedAt
|
|
||||||
|
|
||||||
/* Author */
|
|
||||||
interface EntityCreatedBy<T : EntityI> {
|
|
||||||
val createdBy: T
|
|
||||||
}
|
|
||||||
interface EntityUpdatedBy<T : EntityI> {
|
|
||||||
val updatedBy: T
|
|
||||||
}
|
|
||||||
|
|
||||||
interface EntityDeletedBy<T : EntityI> {
|
|
||||||
val deletedBy: T?
|
|
||||||
}
|
|
||||||
|
|
||||||
class EntityCreatedByImp<UserT : EntityI>(
|
|
||||||
override val createdBy: UserT
|
|
||||||
) : EntityCreatedBy<UserT>
|
|
||||||
|
|
||||||
class EntityUpdatedByImp<UserT : EntityI>(
|
|
||||||
override val updatedBy: UserT
|
|
||||||
) : EntityUpdatedBy<UserT>
|
|
||||||
|
|
||||||
class EntityDeletedByImp<UserT : EntityI>(
|
|
||||||
override val deletedBy: UserT?
|
|
||||||
) : EntityDeletedBy<UserT>
|
|
||||||
|
|
||||||
/* Mixed */
|
|
||||||
class EntityCreatedImp<UserT : EntityI>(
|
|
||||||
override val createdAt: DateTime = DateTime.now(),
|
|
||||||
createdBy: UserT
|
|
||||||
) : EntityCreatedBy<UserT> by EntityCreatedByImp(createdBy),
|
|
||||||
EntityCreatedAt by EntityCreatedAtImp()
|
|
||||||
|
|
||||||
class EntityUpdatedImp<UserT : EntityI>(
|
|
||||||
updatedAt: DateTime = DateTime.now(),
|
|
||||||
override val updatedBy: UserT
|
|
||||||
) : EntityUpdatedBy<UserT>,
|
|
||||||
EntityUpdatedAt by EntityUpdatedAtImp(updatedAt)
|
|
||||||
|
|
||||||
/* Published */
|
|
||||||
interface Published<UserT : EntityI> {
|
|
||||||
val publishedAt: DateTime?
|
|
||||||
val publishedBy: UserT?
|
|
||||||
}
|
|
||||||
|
|
||||||
class EntityPublishedImp<UserT : EntityI>(
|
|
||||||
override val publishedBy: UserT?
|
|
||||||
) : Published<UserT> {
|
|
||||||
override val publishedAt: DateTime? = null
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Implementation */
|
|
||||||
abstract class EntityImp<T, UserT : EntityI>(
|
|
||||||
updatedBy: UserT,
|
|
||||||
updatedAt: DateTime = DateTime.now()
|
|
||||||
) : UuidEntity(),
|
|
||||||
EntityCreatedAt by EntityCreatedAtImp(updatedAt),
|
|
||||||
EntityUpdatedAt by EntityUpdatedAtImp(updatedAt),
|
|
||||||
EntityDeletedAt by EntityDeletedAtImp(),
|
|
||||||
EntityCreatedBy<UserT> by EntityCreatedByImp(updatedBy),
|
|
||||||
EntityUpdatedBy<UserT> by EntityUpdatedByImp(updatedBy),
|
|
||||||
EntityDeletedBy<UserT> by EntityDeletedByImp(updatedBy)
|
|
||||||
|
|
||||||
abstract class UuidEntityExtended<T, UserT : EntityI>(
|
|
||||||
updatedBy: UserT,
|
|
||||||
publishedBy: UserT?
|
|
||||||
) :
|
|
||||||
EntityImp<T, UserT>(updatedBy),
|
|
||||||
EntityVersioning<UUID, Int> by UuidEntityVersioning(0),
|
|
||||||
Published<UserT> by EntityPublishedImp(publishedBy)
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package fr.postgresjson.entity
|
|
||||||
|
|
||||||
interface Serializable
|
|
||||||
interface EntityI : Serializable
|
|
||||||
interface Parameter : Serializable
|
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package fr.postgresjson.functionGenerator
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.Function
|
||||||
|
import fr.postgresjson.definition.Parameter
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.IN
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.INOUT
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.OUT
|
||||||
|
import fr.postgresjson.definition.Returns
|
||||||
|
import fr.postgresjson.utils.searchSqlFiles
|
||||||
|
import fr.postgresjson.utils.toCamelCase
|
||||||
|
import org.slf4j.Logger
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
|
import java.io.File
|
||||||
|
import java.net.URI
|
||||||
|
|
||||||
|
class FunctionGenerator(private val functionsDirectories: List<URI>) {
|
||||||
|
constructor(functionsDirectories: URI) : this(listOf(functionsDirectories))
|
||||||
|
|
||||||
|
private val logger: Logger = LoggerFactory.getLogger("sqlFilesSearch")
|
||||||
|
|
||||||
|
private fun List<Parameter>.toKotlinArgs(): String {
|
||||||
|
return filter { it.direction == IN || it.direction == INOUT }
|
||||||
|
.mapIndexed { index, parameter -> index to parameter }
|
||||||
|
.joinToString(", ") { (idx, param) ->
|
||||||
|
val base = """${param.kotlinName ?: "arg$idx"}: ${param.kotlinType}"""
|
||||||
|
val default = if (param.default == null) {
|
||||||
|
""
|
||||||
|
} else {
|
||||||
|
when (param.kotlinType) {
|
||||||
|
"String" -> """ = "${param.default.trim('\'')}""""
|
||||||
|
"Int" -> """ = ${param.default}"""
|
||||||
|
"Boolean" -> """ = ${param.default.lowercase()}"""
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
base + default
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun List<Parameter>.toMapOf(): String {
|
||||||
|
return filter { it.direction == IN || it.direction == INOUT }
|
||||||
|
.joinToString(", ", prefix = "mapOf(", postfix = ")") { """"${it.kotlinName}" to ${it.kotlinName}""" }
|
||||||
|
}
|
||||||
|
|
||||||
|
private val Parameter.kotlinType: String
|
||||||
|
get() {
|
||||||
|
return when (type.name.lowercase()) {
|
||||||
|
"text" -> "String"
|
||||||
|
"varchar" -> "String"
|
||||||
|
"character varying" -> "String"
|
||||||
|
"character" -> "String"
|
||||||
|
"char" -> "String"
|
||||||
|
"int" -> "Int"
|
||||||
|
"smallint" -> "Int"
|
||||||
|
"integer" -> "Int"
|
||||||
|
"bigint" -> "Int"
|
||||||
|
"decimal" -> "Float"
|
||||||
|
"real" -> "Float"
|
||||||
|
"double precision" -> "Float"
|
||||||
|
"float" -> "Float"
|
||||||
|
"numeric" -> "Number"
|
||||||
|
"boolean" -> "Boolean"
|
||||||
|
"json" -> "S"
|
||||||
|
"jsonb" -> "S"
|
||||||
|
"any" -> "Any"
|
||||||
|
"anyelement" -> "Any"
|
||||||
|
"anyarray" -> "List<*>"
|
||||||
|
else -> "String"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val Parameter.kotlinName: String?
|
||||||
|
get() {
|
||||||
|
return name?.toCamelCase()?.trimStart('_')
|
||||||
|
}
|
||||||
|
|
||||||
|
private val Function.kotlinName: String
|
||||||
|
get() {
|
||||||
|
return name.toCamelCase().trimStart('_')
|
||||||
|
}
|
||||||
|
|
||||||
|
private val functions: List<Function>
|
||||||
|
get() = functionsDirectories
|
||||||
|
.flatMap { it.searchSqlFiles() }
|
||||||
|
.filterIsInstance<Function>()
|
||||||
|
|
||||||
|
fun generate(outputDirectory: URI) {
|
||||||
|
File(outputDirectory.path).apply {
|
||||||
|
logger.debug("Create Directory: $absolutePath")
|
||||||
|
mkdirs()
|
||||||
|
}
|
||||||
|
|
||||||
|
functions
|
||||||
|
.map { function ->
|
||||||
|
File("${outputDirectory.path}${function.kotlinName}.kt").apply {
|
||||||
|
writeText(generate(function))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun generate(functionName: String): String {
|
||||||
|
return functions
|
||||||
|
.first { it.name == functionName }
|
||||||
|
.let { generate(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun generate(function: Function): String = function.run {
|
||||||
|
val args = parameters.toKotlinArgs()
|
||||||
|
|
||||||
|
val hasInputArgs: Boolean = parameters.filter { it.direction != OUT }.any { it.kotlinType == "S" }
|
||||||
|
val hasReturn: Boolean = parameters.any { it.direction != IN } || (returns !is Returns.Void)
|
||||||
|
|
||||||
|
val generics = mutableListOf<String>()
|
||||||
|
if (hasReturn) generics.add("reified E: Any")
|
||||||
|
if (hasInputArgs) generics.add("S: Any?")
|
||||||
|
|
||||||
|
val functionDecl = if (generics.isNotEmpty()) "inline fun <${generics.joinToString(", ")}>" else "fun"
|
||||||
|
|
||||||
|
return if (hasReturn) {
|
||||||
|
"""
|
||||||
|
|package fr.postgresjson.functionGenerator.generated
|
||||||
|
|
|
||||||
|
|import com.fasterxml.jackson.core.type.TypeReference
|
||||||
|
|import fr.postgresjson.connexion.Requester
|
||||||
|
|
|
||||||
|
|$functionDecl Requester.$kotlinName($args): E? {
|
||||||
|
| return getFunction("$name")
|
||||||
|
| .execute<E>(object : TypeReference<E>() {}, ${parameters.toMapOf()})
|
||||||
|
|}
|
||||||
|
""".trimMargin()
|
||||||
|
} else {
|
||||||
|
"""
|
||||||
|
|package fr.postgresjson.functionGenerator.generated
|
||||||
|
|
|
||||||
|
|import fr.postgresjson.connexion.Requester
|
||||||
|
|
|
||||||
|
|$functionDecl Requester.$kotlinName($args): Unit {
|
||||||
|
| getFunction("$name")
|
||||||
|
| .exec(${parameters.toMapOf()})
|
||||||
|
|}
|
||||||
|
""".trimMargin()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,8 @@ 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.connexion.execute
|
||||||
|
import fr.postgresjson.definition.parse.parseFunction
|
||||||
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.Date
|
import java.util.Date
|
||||||
@@ -30,8 +31,8 @@ data class Function(
|
|||||||
connection: Connection,
|
connection: Connection,
|
||||||
executedAt: Date? = null
|
executedAt: Date? = null
|
||||||
) : this(
|
) : this(
|
||||||
DefinitionFunction(up),
|
parseFunction(up),
|
||||||
DefinitionFunction(down),
|
parseFunction(down),
|
||||||
connection,
|
connection,
|
||||||
executedAt
|
executedAt
|
||||||
)
|
)
|
||||||
@@ -50,11 +51,11 @@ data class Function(
|
|||||||
|
|
||||||
this::class.java.classLoader
|
this::class.java.classLoader
|
||||||
.getResource("sql/migration/insertFunction.sql")!!.readText()
|
.getResource("sql/migration/insertFunction.sql")!!.readText()
|
||||||
.let { connection.selectOne<MigrationEntity>(it, listOf(up.name, up.getDefinition(), up.script, down.script)) }
|
.let { connection.execute<MigrationEntity>(it, listOf(up.name, up.getDefinition(), up.script, down.script)) }
|
||||||
?.let { function ->
|
?.let { migration: MigrationEntity ->
|
||||||
executedAt = function.executedAt
|
executedAt = migration.executedAt
|
||||||
doExecute = Action.OK
|
doExecute = Action.OK
|
||||||
}
|
} ?: error("No migration executed")
|
||||||
|
|
||||||
Status.OK
|
Status.OK
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
@@ -77,16 +78,6 @@ data class Function(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun test(): Status {
|
|
||||||
connection.inTransaction {
|
|
||||||
up()
|
|
||||||
down()
|
|
||||||
sendQuery("ROLLBACK")
|
|
||||||
}
|
|
||||||
|
|
||||||
return Status.OK
|
|
||||||
}
|
|
||||||
|
|
||||||
fun copy(): Function = this
|
fun copy(): Function = this
|
||||||
.copy(up = up, down = down, connection = connection, executedAt = executedAt)
|
.copy(up = up, down = down, connection = connection, executedAt = executedAt)
|
||||||
.also { it.doExecute = this.doExecute }
|
.also { it.doExecute = this.doExecute }
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ 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.entity.Entity
|
import fr.postgresjson.definition.parse.parseFunction
|
||||||
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 fr.postgresjson.utils.LoggerDelegate
|
import fr.postgresjson.utils.LoggerDelegate
|
||||||
@@ -20,20 +20,19 @@ class MigrationEntity(
|
|||||||
val up: String,
|
val up: String,
|
||||||
val down: String,
|
val down: String,
|
||||||
val version: Int
|
val version: Int
|
||||||
) : Entity<String?>(filename)
|
)
|
||||||
|
|
||||||
interface Migration {
|
interface Migration {
|
||||||
var executedAt: Date?
|
var executedAt: Date?
|
||||||
var doExecute: Action?
|
var doExecute: Action?
|
||||||
fun up(): Status
|
fun up(): Status
|
||||||
fun down(): Status
|
fun down(): Status
|
||||||
fun test(): Status
|
|
||||||
|
|
||||||
enum class Status(val 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 }
|
||||||
}
|
}
|
||||||
|
|
||||||
class Migrations private constructor(
|
class MigrationExecutor 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()
|
||||||
@@ -53,8 +52,8 @@ class Migrations private constructor(
|
|||||||
migrationsScripts.clear()
|
migrationsScripts.clear()
|
||||||
functions.clear()
|
functions.clear()
|
||||||
|
|
||||||
getMigrationFromDB()
|
addMigrationFromDB()
|
||||||
getMigrationFromDirectory(directories)
|
addMigrationFromDirectory(directories)
|
||||||
|
|
||||||
migrationsScripts.forEach { (_, query) ->
|
migrationsScripts.forEach { (_, query) ->
|
||||||
if (query.doExecute === null) {
|
if (query.doExecute === null) {
|
||||||
@@ -74,17 +73,17 @@ class Migrations private constructor(
|
|||||||
/**
|
/**
|
||||||
* Get all migration from DB
|
* Get all migration from DB
|
||||||
*/
|
*/
|
||||||
private fun getMigrationFromDB() {
|
private fun addMigrationFromDB() {
|
||||||
this::class.java.classLoader.getResource("sql/migration/findAllFunction.sql")!!.readText().let {
|
this::class.java.classLoader.getResource("sql/migration/findAllFunction.sql")!!.readText().let {
|
||||||
connection.select(it, object : TypeReference<List<MigrationEntity>>() {})
|
connection.execute(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(it, object : TypeReference<List<MigrationEntity>>() {})
|
connection.execute(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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,16 +92,16 @@ class Migrations private constructor(
|
|||||||
/**
|
/**
|
||||||
* Get all migration from multiples Directories
|
* Get all migration from multiples Directories
|
||||||
*/
|
*/
|
||||||
private fun getMigrationFromDirectory(directory: List<URI>) {
|
private fun addMigrationFromDirectory(directories: List<URI>) {
|
||||||
directory.forEach {
|
directories.forEach {
|
||||||
getMigrationFromDirectory(it)
|
addMigrationFromDirectory(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all migration from Directory
|
* Get all migration from Directory
|
||||||
*/
|
*/
|
||||||
private fun getMigrationFromDirectory(directory: URI) {
|
private fun addMigrationFromDirectory(directory: URI) {
|
||||||
val downs: MutableMap<String, DefinitionMigration> = mutableMapOf()
|
val downs: MutableMap<String, DefinitionMigration> = mutableMapOf()
|
||||||
|
|
||||||
directory.searchSqlFiles().apply {
|
directory.searchSqlFiles().apply {
|
||||||
@@ -132,7 +131,7 @@ class Migrations private constructor(
|
|||||||
internal class DownMigrationNotDefined(path: String, cause: FileNotFoundException? = null) :
|
internal class DownMigrationNotDefined(path: String, cause: FileNotFoundException? = null) :
|
||||||
Throwable("The file $path was 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 = {}): MigrationExecutor {
|
||||||
val currentFunction = functions[newDefinition.name]
|
val currentFunction = functions[newDefinition.name]
|
||||||
if (currentFunction === null || currentFunction `is different from` newDefinition) {
|
if (currentFunction === null || currentFunction `is different from` newDefinition) {
|
||||||
val oldDefinition = functions[newDefinition.name]?.up ?: newDefinition
|
val oldDefinition = functions[newDefinition.name]?.up ?: newDefinition
|
||||||
@@ -148,15 +147,15 @@ class Migrations private constructor(
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addFunction(sql: String): Migrations {
|
fun addFunction(sql: String): MigrationExecutor {
|
||||||
addFunction(DefinitionFunction(sql))
|
addFunction(parseFunction(sql))
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addMigrationScript(up: DefinitionMigration, down: DefinitionMigration, callback: (MigrationScript) -> Unit = {}): Migrations =
|
fun addMigrationScript(up: DefinitionMigration, down: DefinitionMigration, callback: (MigrationScript) -> Unit = {}): MigrationExecutor =
|
||||||
addMigrationScript(up.name, up.script, down.script, callback)
|
addMigrationScript(up.name, up.script, down.script, callback)
|
||||||
|
|
||||||
fun addMigrationScript(name: String, up: String, down: String, callback: (MigrationScript) -> Unit = {}): Migrations {
|
fun addMigrationScript(name: String, up: String, down: String, callback: (MigrationScript) -> Unit = {}): MigrationExecutor {
|
||||||
if (migrationsScripts[name] === null) {
|
if (migrationsScripts[name] === null) {
|
||||||
migrationsScripts[name] = MigrationScript(name, up, down, connection).apply {
|
migrationsScripts[name] = MigrationScript(name, up, down, connection).apply {
|
||||||
doExecute = Action.UP
|
doExecute = Action.UP
|
||||||
@@ -297,7 +296,7 @@ class Migrations private constructor(
|
|||||||
return list.toMap()
|
return list.toMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun copy(): Migrations {
|
private fun copy(): MigrationExecutor {
|
||||||
val queriesCopy = migrationsScripts.map {
|
val queriesCopy = migrationsScripts.map {
|
||||||
it.key to it.value.copy()
|
it.key to it.value.copy()
|
||||||
}.toMap().toMutableMap()
|
}.toMap().toMutableMap()
|
||||||
@@ -306,10 +305,6 @@ class Migrations private constructor(
|
|||||||
it.key to it.value.copy()
|
it.key to it.value.copy()
|
||||||
}.toMap().toMutableMap()
|
}.toMap().toMutableMap()
|
||||||
|
|
||||||
return Migrations(connection, queriesCopy, functionsCopy)
|
return MigrationExecutor(connection, queriesCopy, functionsCopy)
|
||||||
}
|
|
||||||
|
|
||||||
fun status(): Map<String, Int> {
|
|
||||||
TODO("not implemented")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
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.connexion.execute
|
||||||
import fr.postgresjson.entity.Entity
|
|
||||||
import fr.postgresjson.migration.Migration.Action
|
import fr.postgresjson.migration.Migration.Action
|
||||||
|
import fr.postgresjson.migration.Migration.Status
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
|
||||||
data class MigrationScript(
|
data class MigrationScript(
|
||||||
@@ -12,40 +12,34 @@ data class MigrationScript(
|
|||||||
val down: String,
|
val down: String,
|
||||||
private val connection: Connection,
|
private val connection: Connection,
|
||||||
override var executedAt: Date? = null
|
override var executedAt: Date? = null
|
||||||
) : Migration, Entity<String?>(name) {
|
) : Migration {
|
||||||
override var doExecute: Action? = null
|
override var doExecute: Action? = null
|
||||||
|
|
||||||
override fun up(): Migration.Status {
|
override fun up(): Status {
|
||||||
|
return try {
|
||||||
connection.sendQuery(up)
|
connection.sendQuery(up)
|
||||||
|
|
||||||
this::class.java.classLoader.getResource("sql/migration/insertHistory.sql")!!.readText().let {
|
this::class.java.classLoader.getResource("sql/migration/insertHistory.sql")!!.readText().let { sqlScript ->
|
||||||
connection.selectOne<MigrationEntity>(it, listOf(name, up, down))?.let { query ->
|
connection.execute<MigrationEntity>(sqlScript, listOf(name, up, down))?.let { query ->
|
||||||
executedAt = query.executedAt
|
executedAt = query.executedAt
|
||||||
doExecute = Action.OK
|
doExecute = Action.OK
|
||||||
|
} ?: error("No migration executed")
|
||||||
|
}
|
||||||
|
|
||||||
|
Status.OK
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
Status.UP_FAIL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Migration.Status.OK
|
override fun down(): Status {
|
||||||
}
|
|
||||||
|
|
||||||
override fun down(): Migration.Status {
|
|
||||||
connection.sendQuery(down)
|
connection.sendQuery(down)
|
||||||
|
|
||||||
this::class.java.classLoader.getResource("sql/migration/deleteHistory.sql")!!.readText().let {
|
this::class.java.classLoader.getResource("sql/migration/deleteHistory.sql")!!.readText().let {
|
||||||
connection.exec(it, listOf(name))
|
connection.exec(it, listOf(name))
|
||||||
}
|
}
|
||||||
|
|
||||||
return Migration.Status.OK
|
return Status.OK
|
||||||
}
|
|
||||||
|
|
||||||
override fun test(): Migration.Status {
|
|
||||||
connection.inTransaction {
|
|
||||||
up()
|
|
||||||
down()
|
|
||||||
sendQuery("ROLLBACK")
|
|
||||||
}
|
|
||||||
|
|
||||||
return Migration.Status.OK
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun copy(): MigrationScript {
|
fun copy(): MigrationScript {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import com.fasterxml.jackson.databind.module.SimpleModule
|
|||||||
import com.fasterxml.jackson.datatype.joda.JodaModule
|
import com.fasterxml.jackson.datatype.joda.JodaModule
|
||||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||||
import com.fasterxml.jackson.module.kotlin.readValue
|
import com.fasterxml.jackson.module.kotlin.readValue
|
||||||
import fr.postgresjson.entity.Serializable
|
import com.github.jasync.sql.db.QueryResult
|
||||||
|
|
||||||
class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
|
class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
|
||||||
init {
|
init {
|
||||||
@@ -28,24 +28,21 @@ class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun <E> deserialize(json: String, valueTypeRef: TypeReference<E>): E {
|
fun <E> deserialize(json: String, valueTypeRef: TypeReference<E>): E {
|
||||||
return this.mapper.readValue(json, valueTypeRef)
|
return mapper.readValue(json, valueTypeRef)
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified E> deserialize(json: String): E? {
|
inline fun <reified E> deserialize(json: String): E? {
|
||||||
return this.mapper.readValue(json)
|
return this.mapper.readValue(json)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <E> deserializeList(json: String, valueTypeRef: TypeReference<E>): E {
|
|
||||||
return mapper.readValue(json, valueTypeRef)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified E> deserializeList(json: String): E {
|
inline fun <reified E : Any?> QueryResult.deserialize(): E? {
|
||||||
return deserializeList(json, object : TypeReference<E>() {})
|
val value = this.rows.firstOrNull()?.getString(0)
|
||||||
|
return if (value == null) {
|
||||||
|
null
|
||||||
|
} else {
|
||||||
|
Serializer().deserialize<E>(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Serializable.serialize(pretty: Boolean = false) = Serializer().serialize(this, pretty)
|
inline fun <reified T : Any> T.toTypeReference(): TypeReference<T> = object : TypeReference<T>() {}
|
||||||
fun List<Serializable>.serialize(pretty: Boolean = false) = Serializer().serialize(this, pretty)
|
|
||||||
inline fun <reified E : Serializable> String.deserialize() = Serializer().deserialize<E>(this)
|
|
||||||
|
|
||||||
inline fun <reified T : Serializable> T.toTypeReference(): TypeReference<T> = object : TypeReference<T>() {}
|
|
||||||
|
|||||||
7
src/main/kotlin/fr/postgresjson/utils/caseChange.kt
Normal file
7
src/main/kotlin/fr/postgresjson/utils/caseChange.kt
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package fr.postgresjson.utils
|
||||||
|
|
||||||
|
fun String.toCamelCase(): String {
|
||||||
|
return "_[a-zA-Z]".toRegex().replace(this) {
|
||||||
|
it.value.replace("_", "").uppercase()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ import kotlin.streams.asSequence
|
|||||||
|
|
||||||
fun URL.searchSqlFiles() = this.toURI().searchSqlFiles()
|
fun URL.searchSqlFiles() = this.toURI().searchSqlFiles()
|
||||||
|
|
||||||
fun URI.searchSqlFiles() = sequence {
|
fun URI.searchSqlFiles(): Sequence<Resource> = 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('!')}" :""")
|
||||||
|
|||||||
@@ -1,117 +1,208 @@
|
|||||||
package fr.postgresjson
|
package fr.postgresjson
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
import fr.postgresjson.connexion.Connection.QueryError
|
import fr.postgresjson.connexion.DataNotFoundException
|
||||||
import fr.postgresjson.connexion.Paginated
|
import fr.postgresjson.connexion.SqlSerializable
|
||||||
import fr.postgresjson.connexion.select
|
import fr.postgresjson.connexion.execute
|
||||||
import fr.postgresjson.connexion.selectOne
|
|
||||||
import fr.postgresjson.entity.Parameter
|
|
||||||
import fr.postgresjson.entity.UuidEntity
|
|
||||||
import fr.postgresjson.serializer.deserialize
|
import fr.postgresjson.serializer.deserialize
|
||||||
import fr.postgresjson.serializer.toTypeReference
|
import fr.postgresjson.serializer.toTypeReference
|
||||||
import org.junit.jupiter.api.Test
|
import io.kotest.core.spec.style.StringSpec
|
||||||
import org.junit.jupiter.api.TestInstance
|
import io.kotest.matchers.nulls.shouldBeNull
|
||||||
|
import io.kotest.matchers.nulls.shouldNotBeNull
|
||||||
|
import org.amshove.kluent.`should be equal to`
|
||||||
import org.junit.jupiter.api.assertThrows
|
import org.junit.jupiter.api.assertThrows
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import kotlin.test.assertContains
|
import kotlin.reflect.full.hasAnnotation
|
||||||
import kotlin.test.assertEquals
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFalse
|
||||||
import kotlin.test.assertNotNull
|
import kotlin.test.assertNotNull
|
||||||
import kotlin.test.assertNull
|
|
||||||
import kotlin.test.assertTrue
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
class ConnectionTest : StringSpec({
|
||||||
class ConnectionTest : TestAbstract() {
|
val connection = TestConnection()
|
||||||
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 ObjTest3(val first: String, var second: String, var third: Int) : UuidEntity()
|
|
||||||
private class ObjTestWithParameterObject(var first: ParameterObject, var second: ParameterObject) : UuidEntity()
|
|
||||||
private class ParameterObject(var third: String) : Parameter
|
|
||||||
|
|
||||||
@Test
|
@SqlSerializable
|
||||||
fun getObject() {
|
class ObjTest(val name: String, val id: UUID = UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00"))
|
||||||
val obj: ObjTest? = connection.selectOne("select to_json(a) from test a limit 1")
|
|
||||||
assertTrue(obj is ObjTest)
|
@SqlSerializable
|
||||||
|
class ObjTest2(val id: UUID, val title: String, var test: ObjTest?)
|
||||||
|
|
||||||
|
@SqlSerializable
|
||||||
|
class ObjTest3(val id: UUID, val first: String, var second: String, var third: Int)
|
||||||
|
|
||||||
|
@SqlSerializable
|
||||||
|
class ParameterObject(var third: String)
|
||||||
|
|
||||||
|
@SqlSerializable
|
||||||
|
class ObjTestWithParameterObject(val id: UUID, var first: ParameterObject, var second: ParameterObject)
|
||||||
|
class ObjTest4
|
||||||
|
|
||||||
|
"serializable" {
|
||||||
|
assertTrue(ObjTest("plop")::class.hasAnnotation<SqlSerializable>())
|
||||||
|
assertFalse(ObjTest4()::class.hasAnnotation<SqlSerializable>())
|
||||||
|
}
|
||||||
|
|
||||||
|
"getObject" {
|
||||||
|
val obj: ObjTest? = connection.rollbackAfter {
|
||||||
|
sendQuery(
|
||||||
|
"""
|
||||||
|
create table test(
|
||||||
|
id UUID primary key,
|
||||||
|
name text
|
||||||
|
);
|
||||||
|
INSERT INTO test (id, name) VALUES ('1e5f5d41-6d14-4007-897b-0ed2616bec96', 'one');
|
||||||
|
INSERT INTO test (id, name) VALUES ('26fa76cf-7688-4a1d-b611-e3060b38bf58', 'two');
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
execute("select to_json(a) from test a limit 1")
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNotNull(obj)
|
||||||
assertEquals(UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"), obj.id)
|
assertEquals(UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"), obj.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"getExistingObject" {
|
||||||
fun getExistingObject() {
|
val objs: List<ObjTest2>? = connection.rollbackAfter {
|
||||||
val objs: List<ObjTest2> = connection.select(
|
sendQuery(
|
||||||
"""
|
"""
|
||||||
|
create table test(
|
||||||
|
id uuid primary key,
|
||||||
|
name text
|
||||||
|
);
|
||||||
|
create table test2(
|
||||||
|
id uuid primary key,
|
||||||
|
title text,
|
||||||
|
test_id uuid
|
||||||
|
);
|
||||||
|
INSERT INTO test VALUES ('1e5f5d41-6d14-4007-897b-0ed2616bec96', 'one');
|
||||||
|
INSERT INTO test2 VALUES ('a0214677-7332-4eec-8e9b-af0658ea72a6', 'two', '1e5f5d41-6d14-4007-897b-0ed2616bec96');
|
||||||
|
INSERT INTO test2 VALUES ('8545577e-2785-421f-bb7e-1ec3faa1d79a', 'three', null);
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
execute<List<ObjTest2>>(
|
||||||
|
"""
|
||||||
|
select json_agg(j)
|
||||||
|
from (
|
||||||
select
|
select
|
||||||
json_agg(j)
|
t.id,
|
||||||
FROM (
|
t.title,
|
||||||
SELECT
|
|
||||||
t.id, t.title,
|
|
||||||
t2 as test
|
t2 as test
|
||||||
from test2 t
|
from test2 t
|
||||||
JOIN test t2 ON t.test_id = t2.id
|
join test t2 ON t.test_id = t2.id
|
||||||
) j;
|
) j;
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
)
|
)
|
||||||
assertNotNull(objs)
|
|
||||||
assertEquals(objs.size, 2)
|
|
||||||
assertEquals(objs[0].id, UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"))
|
|
||||||
assertEquals(objs[0].test!!.id, UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
objs.shouldNotBeNull()
|
||||||
fun `test call request with args`() {
|
objs.size `should be equal to` 1
|
||||||
val result: ObjTest? = connection.selectOne("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', ?::text)", listOf("myName"))
|
objs.first().id `should be equal to` UUID.fromString("a0214677-7332-4eec-8e9b-af0658ea72a6")
|
||||||
assertNotNull(result)
|
objs.first().title `should be equal to` "two"
|
||||||
assertEquals("myName", result.name)
|
objs.first().test!!.id `should be equal to` UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96")
|
||||||
|
objs.first().test!!.name `should be equal to` "one"
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test call request with args" {
|
||||||
fun `test call request without args`() {
|
val result: ObjTest? = connection.execute(
|
||||||
val result: ObjTest? = connection.selectOne("select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', 'myName')", object : TypeReference<ObjTest>() {}) {
|
"select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', ?::text)",
|
||||||
assertEquals("myName", this.rows[0].getString(0)?.deserialize<ObjTest>()?.name)
|
listOf("myName")
|
||||||
}
|
)
|
||||||
assertNotNull(result)
|
result.shouldNotBeNull()
|
||||||
assertEquals("myName", result.name)
|
result.name `should be equal to` "myName"
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test call request without args" {
|
||||||
fun `test call request return null`() {
|
val result: ObjTest? = connection.execute(
|
||||||
val result: ObjTest? = connection.selectOne("select null;", object : TypeReference<ObjTest>() {})
|
"select json_build_object('id', '2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00', 'name', 'myName')",
|
||||||
assertNull(result)
|
object : TypeReference<ObjTest>() {}
|
||||||
|
) {
|
||||||
|
assertEquals("myName", this.deserialize<ObjTest>()?.name)
|
||||||
|
}
|
||||||
|
result.shouldNotBeNull()
|
||||||
|
result.name `should be equal to` "myName"
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test call request return null" {
|
||||||
fun `test call request return nothing`() {
|
val result: ObjTest? = connection.execute("select null;", object : TypeReference<ObjTest>() {})
|
||||||
val result: ObjTest? = connection.selectOne("select * from test where false;", object : TypeReference<ObjTest>() {})
|
result.shouldBeNull()
|
||||||
assertNull(result)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test call request return nothing" {
|
||||||
fun callRequestWithArgsEntity() {
|
val e = connection.rollbackAfter {
|
||||||
|
sendQuery(
|
||||||
|
"""
|
||||||
|
create table test(
|
||||||
|
id UUID primary key,
|
||||||
|
name text
|
||||||
|
);
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
assertThrows<DataNotFoundException> {
|
||||||
|
execute("select * from test where false;", object : TypeReference<ObjTest>() {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
e.shouldNotBeNull()
|
||||||
|
e.message `should be equal to` "No data return for the query"
|
||||||
|
e.queryExecuted `should be equal to` "select * from test where false;"
|
||||||
|
}
|
||||||
|
|
||||||
|
"callRequestWithArgsEntity" {
|
||||||
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.execute(
|
||||||
assertNotNull(obj)
|
"select json_build_object('id', id, 'name', name) FROM json_to_record(?::json) as o(id uuid, name text);",
|
||||||
assertEquals(UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00"), obj.id)
|
listOf(o)
|
||||||
assertEquals("myName", obj.name)
|
)
|
||||||
|
obj.shouldNotBeNull()
|
||||||
|
obj.id `should be equal to` UUID.fromString("2c0243ed-ff4d-4b9f-a52b-e38c71b0ed00")
|
||||||
|
obj.name `should be equal to` "myName"
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test update Entity" {
|
||||||
fun `test update Entity`() {
|
|
||||||
val obj = ObjTest("before", id = UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"))
|
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)
|
val objUpdated: ObjTest? = connection.execute(
|
||||||
assertTrue(objUpdated is ObjTest)
|
"select ?::jsonb || jsonb_build_object('name', 'after');",
|
||||||
|
obj.toTypeReference(), listOf(obj)
|
||||||
|
)
|
||||||
|
objUpdated.shouldNotBeNull()
|
||||||
|
objUpdated.id `should be equal to` UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96")
|
||||||
|
objUpdated.name `should be equal to` "after"
|
||||||
|
}
|
||||||
|
|
||||||
|
"test update Entity with vararg" {
|
||||||
|
val obj = ObjTest("before", id = UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"))
|
||||||
|
val objUpdated: ObjTest? = connection.execute(
|
||||||
|
"select :obj::jsonb || jsonb_build_object('name', 'after');",
|
||||||
|
obj.toTypeReference(),
|
||||||
|
"obj" to obj
|
||||||
|
)
|
||||||
|
assertNotNull(objUpdated)
|
||||||
assertEquals(UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"), objUpdated.id)
|
assertEquals(UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"), objUpdated.id)
|
||||||
assertEquals("after", objUpdated.name)
|
assertEquals("after", objUpdated.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"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)
|
||||||
|
)
|
||||||
assertEquals(1, result.rowsAffected)
|
assertEquals(1, result.rowsAffected)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"select one with named parameters" {
|
||||||
fun `select one with named parameters`() {
|
val result: ObjTest3? = connection.execute(
|
||||||
val result: ObjTest3? = connection.selectOne(
|
"""
|
||||||
"SELECT json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int)",
|
SELECT json_build_object(
|
||||||
|
'id', 'bf0e5605-3a8f-4db9-8b98-c8e0691dd576',
|
||||||
|
'first', :first::text,
|
||||||
|
'second', :second::text,
|
||||||
|
'third', :third::int
|
||||||
|
)
|
||||||
|
""".trimIndent(),
|
||||||
mapOf(
|
mapOf(
|
||||||
"first" to "ff",
|
"first" to "ff",
|
||||||
"second" to "sec",
|
"second" to "sec",
|
||||||
@@ -124,219 +215,95 @@ class ConnectionTest : TestAbstract() {
|
|||||||
assertEquals(123, result.third)
|
assertEquals(123, result.third)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"select one with named parameters object" {
|
||||||
fun `select one with named parameters object`() {
|
val result: ObjTestWithParameterObject? = connection.execute(
|
||||||
val result: ObjTestWithParameterObject? = connection.selectOne(
|
"""
|
||||||
"SELECT json_build_object('first', :first::json, 'second', :second::json)",
|
SELECT json_build_object(
|
||||||
|
'id', 'bf0e5605-3a8f-4db9-8b98-c8e0691dd576',
|
||||||
|
'first', :first::json,
|
||||||
|
'second', :second::json
|
||||||
|
)
|
||||||
|
""".trimIndent(),
|
||||||
mapOf(
|
mapOf(
|
||||||
"first" to ParameterObject("one"),
|
"first" to ParameterObject("one"),
|
||||||
"second" to ParameterObject("two")
|
"second" to ParameterObject("two")
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
|
assertEquals("bf0e5605-3a8f-4db9-8b98-c8e0691dd576", result.id.toString())
|
||||||
assertEquals("one", result.first.third)
|
assertEquals("one", result.first.third)
|
||||||
assertEquals("two", result.second.third)
|
assertEquals("two", result.second.third)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"select with named parameters" {
|
||||||
fun `select with named parameters`() {
|
val result: List<ObjTest3>? = connection.execute(
|
||||||
val result: List<ObjTest3> = connection.select(
|
|
||||||
"""
|
"""
|
||||||
SELECT json_build_array(
|
SELECT json_build_array(
|
||||||
json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int),
|
json_build_object(
|
||||||
json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int)
|
'id', 'bf0e5605-3a8f-4db9-8b98-c8e0691dd576',
|
||||||
)
|
'first', :first::text,
|
||||||
""".trimIndent(),
|
'second', :second::text,
|
||||||
mapOf(
|
'third', :third::int
|
||||||
"first" to "ff",
|
|
||||||
"third" to 123,
|
|
||||||
"second" to "sec"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
assertEquals("ff", result[0].first)
|
|
||||||
assertEquals("sec", result[0].second)
|
|
||||||
assertEquals(123, result[0].third)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `select with named parameters as vararg of Pair`() {
|
|
||||||
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",
|
|
||||||
"third" to 123,
|
|
||||||
"second" to "sec"
|
|
||||||
)
|
|
||||||
assertEquals("ff", result[0].first)
|
|
||||||
assertEquals("sec", result[0].second)
|
|
||||||
assertEquals(123, result[0].third)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `select paginated`() {
|
|
||||||
val result: Paginated<ObjTest> = connection.select(
|
|
||||||
"""
|
|
||||||
SELECT json_build_array(
|
|
||||||
json_build_object('id', '417aaa7e-7bc6-49b7-9fe8-6c8433b3f430', 'name', :name::text),
|
|
||||||
json_build_object('id', 'abd46e7a-e749-4ce4-8361-e7b64da89da6', 'name', :name::text || '-2')
|
|
||||||
), 10 as total
|
|
||||||
LIMIT :limit OFFSET :offset
|
|
||||||
""".trimIndent(),
|
|
||||||
1,
|
|
||||||
2,
|
|
||||||
mapOf("name" to "ff")
|
|
||||||
|
|
||||||
)
|
|
||||||
assertNotNull(result)
|
|
||||||
assertEquals("ff", result.result[0].name)
|
|
||||||
assertEquals("ff-2", result.result[1].name)
|
|
||||||
assertEquals(10, result.total)
|
|
||||||
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
|
json_build_object(
|
||||||
LIMIT :limit
|
'id', 'ce9ae3c9-dc0e-4561-a168-811b996d913e',
|
||||||
OFFSET :offset
|
'first', :first::text,
|
||||||
|
'second', :second::text,
|
||||||
|
'third', :third::int
|
||||||
|
)
|
||||||
|
)
|
||||||
""".trimIndent(),
|
""".trimIndent(),
|
||||||
1,
|
|
||||||
2,
|
|
||||||
object : TypeReference<List<ObjTest>>() {},
|
|
||||||
mapOf(
|
mapOf(
|
||||||
"name" to "myName"
|
"first" to "ff",
|
||||||
|
"third" to 123,
|
||||||
|
"second" to "sec"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("myName", result.result[0].name)
|
assertEquals("bf0e5605-3a8f-4db9-8b98-c8e0691dd576", result[0].id.toString())
|
||||||
assertEquals(1, result.result.size)
|
assertEquals("ff", result[0].first)
|
||||||
assertEquals(10, result.total)
|
assertEquals("sec", result[0].second)
|
||||||
assertEquals(0, result.offset)
|
assertEquals(123, result[0].third)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"select with named parameters as vararg of Pair" {
|
||||||
fun `test select paginated with no result`() {
|
val result: List<ObjTest3>? = connection.execute(
|
||||||
assertThrows<QueryError> {
|
|
||||||
connection.select(
|
|
||||||
"""
|
"""
|
||||||
SELECT :name as name,
|
SELECT json_build_array(
|
||||||
10 as total
|
json_build_object('id', 'bf0e5605-3a8f-4db9-8b98-c8e0691dd576', 'first', :first::text, 'second', :second::text, 'third', :third::int),
|
||||||
LIMIT :limit
|
json_build_object('id', '0c9d55d2-f69a-4750-a278-fac821774276', 'first', :first::text, 'second', :second::text, 'third', :third::int)
|
||||||
OFFSET :offset
|
)
|
||||||
""".trimIndent(),
|
""".trimIndent(),
|
||||||
100,
|
"first" to "ff",
|
||||||
10,
|
"third" to 123,
|
||||||
object : TypeReference<List<ObjTest>>() {},
|
"second" to "sec"
|
||||||
mapOf(
|
|
||||||
"name" to "myName"
|
|
||||||
)
|
)
|
||||||
)
|
assertNotNull(result)
|
||||||
}.run {
|
assertEquals("bf0e5605-3a8f-4db9-8b98-c8e0691dd576", result[0].id.toString())
|
||||||
assertNotNull(message)
|
assertEquals("ff", result[0].first)
|
||||||
assertContains(message!!, "The query has no return")
|
assertEquals("sec", result[0].second)
|
||||||
}
|
assertEquals(123, result[0].third)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"execute with extra parameters" {
|
||||||
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
|
|
||||||
fun `selectOne with extra parameters`() {
|
|
||||||
val params: Map<String, Any?> = mapOf(
|
val params: Map<String, Any?> = mapOf(
|
||||||
"first" to "ff",
|
"first" to "ff",
|
||||||
"third" to 123,
|
"third" to 123,
|
||||||
"second" to "sec"
|
"second" to "sec"
|
||||||
)
|
)
|
||||||
val result: ObjTest3? = connection.selectOne(
|
val result: ObjTest3? = connection.execute(
|
||||||
"""
|
"""
|
||||||
SELECT json_build_object('first', :first::text, 'second', :second::text, 'third', :third::int), 'plop'::text as other
|
SELECT json_build_object(
|
||||||
|
'id', 'bf0e5605-3a8f-4db9-8b98-c8e0691dd576',
|
||||||
|
'first', :first::text,
|
||||||
|
'second', :second::text,
|
||||||
|
'third', :third::int
|
||||||
|
), 'plop'::text as other
|
||||||
""".trimIndent(),
|
""".trimIndent(),
|
||||||
params
|
params
|
||||||
) {
|
) {
|
||||||
assertNotNull(it)
|
assertNotNull(it)
|
||||||
|
assertEquals("bf0e5605-3a8f-4db9-8b98-c8e0691dd576", it.id.toString())
|
||||||
assertEquals("ff", it.first)
|
assertEquals("ff", it.first)
|
||||||
assertEquals("plop", rows[0].getString("other"))
|
assertEquals("plop", rows[0].getString("other"))
|
||||||
}
|
}
|
||||||
@@ -346,27 +313,30 @@ class ConnectionTest : TestAbstract() {
|
|||||||
assertEquals(123, result.third)
|
assertEquals(123, result.third)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test exec without parameters" {
|
||||||
fun `test exec without parameters`() {
|
|
||||||
connection.exec("select 42, 'hello';").run {
|
connection.exec("select 42, 'hello';").run {
|
||||||
assertEquals(42, rows[0].getInt(0))
|
assertEquals(42, rows[0].getInt(0))
|
||||||
assertEquals("hello", rows[0].getString(1))
|
assertEquals("hello", rows[0].getString(1))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"test exec with one object as parameter" {
|
||||||
fun `test exec with one object as parameter`() {
|
|
||||||
val obj = ObjTest("myName", UUID.fromString("c606e216-53b3-43c8-a900-e727cb4a017c"))
|
val obj = ObjTest("myName", UUID.fromString("c606e216-53b3-43c8-a900-e727cb4a017c"))
|
||||||
connection.exec("select ?::jsonb->>'name'", obj).run {
|
connection.exec("select ?::jsonb->>'name'", obj).run {
|
||||||
assertEquals("myName", rows[0].getString(0))
|
assertEquals("myName", rows[0].getString(0))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
"select one in transaction" {
|
||||||
fun `select one in transaction`() {
|
|
||||||
connection.inTransaction {
|
connection.inTransaction {
|
||||||
selectOne<ObjTestWithParameterObject>(
|
execute<ObjTestWithParameterObject>(
|
||||||
"SELECT json_build_object('first', :first::json, 'second', :second::json)",
|
"""
|
||||||
|
SELECT json_build_object(
|
||||||
|
'id', 'bf0e5605-3a8f-4db9-8b98-c8e0691dd576',
|
||||||
|
'first', :first::json,
|
||||||
|
'second', :second::json
|
||||||
|
)
|
||||||
|
""".trimIndent(),
|
||||||
mapOf(
|
mapOf(
|
||||||
"first" to ParameterObject("one"),
|
"first" to ParameterObject("one"),
|
||||||
"second" to ParameterObject("two")
|
"second" to ParameterObject("two")
|
||||||
@@ -378,4 +348,4 @@ class ConnectionTest : TestAbstract() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
package fr.postgresjson
|
|
||||||
|
|
||||||
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.Test
|
|
||||||
import org.junit.jupiter.api.TestInstance
|
|
||||||
import java.util.UUID
|
|
||||||
|
|
||||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
|
||||||
class EntityTest() {
|
|
||||||
private class User(id: UUID = UUID.randomUUID()) : Entity<UUID>(id)
|
|
||||||
private class ObjTest(val name: String) : UuidEntityExtended<Int?, User>(User(), User())
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun getObject() {
|
|
||||||
val obj = ObjTest("plop")
|
|
||||||
assertTrue(obj is ObjTest)
|
|
||||||
assertTrue(obj is UuidEntityExtended<Int?, User>)
|
|
||||||
assertTrue(obj is EntityI)
|
|
||||||
assertTrue(obj is Entity<UUID>)
|
|
||||||
assertTrue(obj is Published<User>)
|
|
||||||
assertTrue(obj is EntityCreatedBy<User>)
|
|
||||||
assertTrue(obj is EntityUpdatedBy<User>)
|
|
||||||
assertTrue(obj is EntityCreatedAt)
|
|
||||||
assertTrue(obj is EntityUpdatedAt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
package fr.postgresjson
|
package fr.postgresjson
|
||||||
|
|
||||||
import fr.postgresjson.connexion.Requester
|
import fr.postgresjson.connexion.Requester
|
||||||
import fr.postgresjson.connexion.selectOne
|
import fr.postgresjson.connexion.execute
|
||||||
import fr.postgresjson.migration.Migration
|
import fr.postgresjson.migration.Migration
|
||||||
import fr.postgresjson.migration.Migrations
|
import fr.postgresjson.migration.MigrationExecutor
|
||||||
import org.amshove.kluent.invoking
|
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`
|
||||||
@@ -12,13 +12,15 @@ 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.UUID
|
import java.util.UUID
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertNotNull
|
||||||
|
|
||||||
@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 = MigrationExecutor(connection, resources)
|
||||||
m.up().apply {
|
m.up().apply {
|
||||||
this `should contain` Pair("1", Migration.Status.OK)
|
this `should contain` Pair("1", Migration.Status.OK)
|
||||||
size `should be equal to` 1
|
size `should be equal to` 1
|
||||||
@@ -31,14 +33,14 @@ class MigrationTest : TestAbstract() {
|
|||||||
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)
|
MigrationExecutor(resources, connection)
|
||||||
} shouldThrow Migrations.DownMigrationNotDefined::class
|
} shouldThrow MigrationExecutor.DownMigrationNotDefined::class
|
||||||
}
|
}
|
||||||
|
|
||||||
@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 = MigrationExecutor(resources, connection)
|
||||||
repeat(3) {
|
repeat(3) {
|
||||||
m.down(true).apply {
|
m.down(true).apply {
|
||||||
this `should contain` Pair("1", Migration.Status.OK)
|
this `should contain` Pair("1", Migration.Status.OK)
|
||||||
@@ -50,10 +52,10 @@ 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 {
|
MigrationExecutor(resources, connection).apply {
|
||||||
runDry().size `should be equal to` 2
|
runDry().size `should be equal to` 2
|
||||||
}
|
}
|
||||||
Migrations(resources, connection).apply {
|
MigrationExecutor(resources, connection).apply {
|
||||||
runDry().size `should be equal to` 2
|
runDry().size `should be equal to` 2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,7 +63,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 {
|
MigrationExecutor(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
|
||||||
}
|
}
|
||||||
@@ -70,7 +72,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 {
|
MigrationExecutor(resources, connection).apply {
|
||||||
run().apply {
|
run().apply {
|
||||||
size `should be equal to` 1
|
size `should be equal to` 1
|
||||||
}
|
}
|
||||||
@@ -81,12 +83,12 @@ class MigrationTest : TestAbstract() {
|
|||||||
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 {
|
MigrationExecutor(listOf(resources, resourcesFunctions), connection).apply {
|
||||||
up().apply {
|
up().apply {
|
||||||
size `should be equal to` 6
|
size `should be equal to` 6
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Migrations(listOf(resources, resourcesFunctions), connection).apply {
|
MigrationExecutor(listOf(resources, resourcesFunctions), connection).apply {
|
||||||
forceAllDown().apply {
|
forceAllDown().apply {
|
||||||
size `should be equal to` 6
|
size `should be equal to` 6
|
||||||
}
|
}
|
||||||
@@ -96,34 +98,35 @@ 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 {
|
MigrationExecutor(resources, connection).apply {
|
||||||
run().size `should be equal to` 5
|
run().size `should be equal to` 5
|
||||||
}
|
}
|
||||||
|
|
||||||
val objTest: RequesterTest.ObjTest? = Requester(connection, functionsDirectory = resources)
|
val objTest: RequesterTest.ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function")
|
.getFunction("test_function")
|
||||||
.selectOne(listOf("test", "plip"))
|
.execute(listOf("test", "plip"))
|
||||||
|
|
||||||
Assertions.assertEquals(objTest!!.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d"))
|
assertNotNull(objTest)
|
||||||
Assertions.assertEquals(objTest.name, "test")
|
assertEquals(objTest.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d"))
|
||||||
|
assertEquals(objTest.name, "test")
|
||||||
}
|
}
|
||||||
|
|
||||||
@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 {
|
MigrationExecutor(resources, connection).apply {
|
||||||
run().size `should be equal to` 1
|
run().size `should be equal to` 1
|
||||||
}
|
}
|
||||||
|
|
||||||
val objTest: RequesterTest.ObjTest? = Requester(connection, functionsDirectory = resources)
|
val objTest: RequesterTest.ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function_duplicate")
|
.getFunction("test_function_duplicate")
|
||||||
.selectOne(listOf("test"))
|
.execute(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 {
|
MigrationExecutor(resources2, connection).apply {
|
||||||
run().size `should be equal to` 1
|
run().size `should be equal to` 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,11 @@ package fr.postgresjson
|
|||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference
|
import com.fasterxml.jackson.core.type.TypeReference
|
||||||
import fr.postgresjson.connexion.Connection.QueryError
|
import fr.postgresjson.connexion.Connection.QueryError
|
||||||
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.NoFunctionDefined
|
||||||
import fr.postgresjson.connexion.Requester.NoQueryDefined
|
import fr.postgresjson.connexion.Requester.NoQueryDefined
|
||||||
import fr.postgresjson.connexion.select
|
import fr.postgresjson.connexion.SqlSerializable
|
||||||
import fr.postgresjson.connexion.selectOne
|
import fr.postgresjson.connexion.execute
|
||||||
import fr.postgresjson.connexion.update
|
|
||||||
import fr.postgresjson.entity.UuidEntity
|
|
||||||
import fr.postgresjson.serializer.deserialize
|
import fr.postgresjson.serializer.deserialize
|
||||||
import org.junit.jupiter.api.Assertions.assertThrows
|
import org.junit.jupiter.api.Assertions.assertThrows
|
||||||
import org.junit.jupiter.api.Test
|
import org.junit.jupiter.api.Test
|
||||||
@@ -18,7 +15,8 @@ import kotlin.test.assertEquals
|
|||||||
import kotlin.test.assertNotNull
|
import kotlin.test.assertNotNull
|
||||||
|
|
||||||
class RequesterTest : TestAbstract() {
|
class RequesterTest : TestAbstract() {
|
||||||
class ObjTest(val name: String, id: UUID = UUID.fromString("5623d902-3067-42f3-bfd9-095dbb12c29f")) : UuidEntity(id)
|
@SqlSerializable
|
||||||
|
class ObjTest(val name: String, val id: UUID = UUID.fromString("5623d902-3067-42f3-bfd9-095dbb12c29f"))
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `requester constructor empty`() {
|
fun `requester constructor empty`() {
|
||||||
@@ -99,7 +97,7 @@ class RequesterTest : TestAbstract() {
|
|||||||
val objTest: ObjTest? = Requester(connection)
|
val objTest: ObjTest? = Requester(connection)
|
||||||
.apply { addQuery(resources) }
|
.apply { addQuery(resources) }
|
||||||
.getQuery("selectOne")
|
.getQuery("selectOne")
|
||||||
.selectOne()
|
.execute()
|
||||||
|
|
||||||
assertNotNull(objTest)
|
assertNotNull(objTest)
|
||||||
assertEquals(objTest.id, UUID.fromString("829b1a29-5db8-47f9-9562-961c561ac528"))
|
assertEquals(objTest.id, UUID.fromString("829b1a29-5db8-47f9-9562-961c561ac528"))
|
||||||
@@ -138,7 +136,7 @@ class RequesterTest : TestAbstract() {
|
|||||||
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, functionsDirectory = resources)
|
val objTest: ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function")
|
.getFunction("test_function")
|
||||||
.selectOne(listOf("test", "plip"))
|
.execute(listOf("test", "plip"))
|
||||||
|
|
||||||
assertNotNull(objTest)
|
assertNotNull(objTest)
|
||||||
assertEquals(objTest.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d"))
|
assertEquals(objTest.id, UUID.fromString("457daad5-4f1b-4eb7-80ec-6882adb8cc7d"))
|
||||||
@@ -162,7 +160,7 @@ class RequesterTest : TestAbstract() {
|
|||||||
.getQuery("selectOneWithParameters")
|
.getQuery("selectOneWithParameters")
|
||||||
.exec(listOf("myName"))
|
.exec(listOf("myName"))
|
||||||
|
|
||||||
assertEquals("myName", result.rows[0].getString(0)?.deserialize<ObjTest>()?.name)
|
assertEquals("myName", result.deserialize<ObjTest>()?.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -278,30 +276,30 @@ class RequesterTest : TestAbstract() {
|
|||||||
fun `call exec on function with pair as arguments`() {
|
fun `call exec on function with pair as arguments`() {
|
||||||
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
|
val resources = this::class.java.getResource("/sql/function/Test")?.toURI()
|
||||||
val result = Requester(connection, functionsDirectory = resources)
|
val result = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("function_void")
|
.getFunction("test_function_void")
|
||||||
.exec("name" to "test")
|
.exec("name" to "test")
|
||||||
|
|
||||||
assertEquals(1, result.rowsAffected)
|
assertEquals(1, result.rowsAffected)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `call selectOne on function`() {
|
fun `call execute 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, functionsDirectory = resources)
|
val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function")
|
.getFunction("test_function")
|
||||||
.selectOne(mapOf("name" to "myName"))
|
.execute(mapOf("name" to "myName"))
|
||||||
|
|
||||||
assertNotNull(obj)
|
assertNotNull(obj)
|
||||||
assertEquals("myName", obj.name)
|
assertEquals("myName", obj.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `call selectOne on function with object and named argument`() {
|
fun `call execute on function with object and named argument`() {
|
||||||
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, functionsDirectory = resources)
|
val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function_object")
|
.getFunction("test_function_object")
|
||||||
.selectOne("resource" to obj2)
|
.execute("resource" to obj2)
|
||||||
|
|
||||||
assertNotNull(obj)
|
assertNotNull(obj)
|
||||||
assertEquals("changedName", obj.name)
|
assertEquals("changedName", obj.name)
|
||||||
@@ -309,12 +307,12 @@ class RequesterTest : TestAbstract() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `call selectOne on function with object`() {
|
fun `call execute 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, functionsDirectory = resources)
|
val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function_object")
|
.getFunction("test_function_object")
|
||||||
.update(obj2)
|
.execute(listOf(obj2))
|
||||||
|
|
||||||
assertNotNull(obj)
|
assertNotNull(obj)
|
||||||
assertEquals("changedName", obj.name)
|
assertEquals("changedName", obj.name)
|
||||||
@@ -322,22 +320,22 @@ class RequesterTest : TestAbstract() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `call selectOne on function with object and no arguments`() {
|
fun `call execute on function with object and no arguments`() {
|
||||||
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, functionsDirectory = resources)
|
val obj: ObjTest? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function")
|
.getFunction("test_function")
|
||||||
.selectOne()
|
.execute()
|
||||||
|
|
||||||
assertNotNull(obj)
|
assertNotNull(obj)
|
||||||
assertEquals("plop", obj.name)
|
assertEquals("plop", obj.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `call selectOne on query`() {
|
fun `call execute 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, queriesDirectory = resources)
|
val obj: ObjTest? = Requester(connection, queriesDirectory = resources)
|
||||||
.getQuery("selectOneWithParameters")
|
.getQuery("selectOneWithParameters")
|
||||||
.selectOne(mapOf("name" to "myName"))
|
.execute(mapOf("name" to "myName"))
|
||||||
|
|
||||||
assertNotNull(obj)
|
assertNotNull(obj)
|
||||||
assertEquals("myName", obj.name)
|
assertEquals("myName", obj.name)
|
||||||
@@ -346,10 +344,11 @@ class RequesterTest : TestAbstract() {
|
|||||||
@Test
|
@Test
|
||||||
fun `call select (multiple) on function with named argument`() {
|
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, functionsDirectory = resources)
|
val obj: List<ObjTest>? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function_multiple")
|
.getFunction("test_function_multiple")
|
||||||
.select(mapOf("name" to "myName"))
|
.execute(mapOf("name" to "myName"))
|
||||||
|
|
||||||
|
assertNotNull(obj)
|
||||||
assertNotNull(obj[0])
|
assertNotNull(obj[0])
|
||||||
assertEquals("myName", obj[0].name)
|
assertEquals("myName", obj[0].name)
|
||||||
assertEquals("myName", obj[0].name)
|
assertEquals("myName", obj[0].name)
|
||||||
@@ -358,10 +357,11 @@ class RequesterTest : TestAbstract() {
|
|||||||
@Test
|
@Test
|
||||||
fun `call select (multiple) on function with ordered arguments`() {
|
fun `call select (multiple) on function with ordered arguments`() {
|
||||||
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, functionsDirectory = resources)
|
val obj: List<ObjTest>? = Requester(connection, functionsDirectory = resources)
|
||||||
.getFunction("test_function_multiple")
|
.getFunction("test_function_multiple")
|
||||||
.select(listOf("myName"))
|
.execute(listOf("myName"))
|
||||||
|
|
||||||
|
assertNotNull(obj)
|
||||||
assertEquals("myName", obj[0].name)
|
assertEquals("myName", obj[0].name)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -370,13 +370,13 @@ class RequesterTest : TestAbstract() {
|
|||||||
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
||||||
Requester(connection, queriesDirectory = resources)
|
Requester(connection, queriesDirectory = resources)
|
||||||
.getQuery("selectMultiple").apply {
|
.getQuery("selectMultiple").apply {
|
||||||
select<ObjTest>(mapOf("name" to "ff")).let { result ->
|
execute<List<ObjTest>>(mapOf("name" to "ff")).let { result ->
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("ff", result[0].name)
|
assertEquals("ff", result[0].name)
|
||||||
assertEquals("ff-2", result[1].name)
|
assertEquals("ff-2", result[1].name)
|
||||||
}
|
}
|
||||||
}.apply {
|
}.apply {
|
||||||
select(object : TypeReference<List<ObjTest>>() {}, mapOf("name" to "ff")).let { result ->
|
execute(object : TypeReference<List<ObjTest>>() {}, mapOf("name" to "ff")).let { result ->
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("ff", result[0].name)
|
assertEquals("ff", result[0].name)
|
||||||
assertEquals("ff-2", result[1].name)
|
assertEquals("ff-2", result[1].name)
|
||||||
@@ -389,13 +389,13 @@ class RequesterTest : TestAbstract() {
|
|||||||
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
||||||
Requester(connection, queriesDirectory = resources)
|
Requester(connection, queriesDirectory = resources)
|
||||||
.getQuery("selectMultiple").apply {
|
.getQuery("selectMultiple").apply {
|
||||||
select<ObjTest>("name" to "ff").let { result ->
|
execute<List<ObjTest>>("name" to "ff").let { result ->
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("ff", result[0].name)
|
assertEquals("ff", result[0].name)
|
||||||
assertEquals("ff-2", result[1].name)
|
assertEquals("ff-2", result[1].name)
|
||||||
}
|
}
|
||||||
}.apply {
|
}.apply {
|
||||||
select(object : TypeReference<List<ObjTest>>() {}, "name" to "ff").let { result ->
|
execute(object : TypeReference<List<ObjTest>>() {}, "name" to "ff").let { result ->
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("ff", result[0].name)
|
assertEquals("ff", result[0].name)
|
||||||
assertEquals("ff-2", result[1].name)
|
assertEquals("ff-2", result[1].name)
|
||||||
@@ -408,13 +408,13 @@ class RequesterTest : TestAbstract() {
|
|||||||
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
||||||
Requester(connection, queriesDirectory = resources)
|
Requester(connection, queriesDirectory = resources)
|
||||||
.getQuery("selectMultipleOrderedArgs").apply {
|
.getQuery("selectMultipleOrderedArgs").apply {
|
||||||
select<ObjTest>(listOf("ff", "aa")).let { result ->
|
execute<List<ObjTest>>(listOf("ff", "aa")).let { result ->
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("ff", result[0].name)
|
assertEquals("ff", result[0].name)
|
||||||
assertEquals("aa-2", result[1].name)
|
assertEquals("aa-2", result[1].name)
|
||||||
}
|
}
|
||||||
}.apply {
|
}.apply {
|
||||||
select(object : TypeReference<List<ObjTest>>() {}, listOf("ff", "aa")).let { result ->
|
execute(object : TypeReference<List<ObjTest>>() {}, listOf("ff", "aa")).let { result ->
|
||||||
assertNotNull(result)
|
assertNotNull(result)
|
||||||
assertEquals("ff", result[0].name)
|
assertEquals("ff", result[0].name)
|
||||||
assertEquals("aa-2", result[1].name)
|
assertEquals("aa-2", result[1].name)
|
||||||
@@ -423,71 +423,11 @@ class RequesterTest : TestAbstract() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `call select paginated on query`() {
|
fun `call execute on query with extra parameter`() {
|
||||||
val resources = this::class.java.getResource("/sql/query")?.toURI()
|
|
||||||
val result: Paginated<ObjTest> = Requester(connection, queriesDirectory = resources)
|
|
||||||
.getQuery("selectPaginated")
|
|
||||||
.select(1, 2, mapOf("name" to "ff"))
|
|
||||||
assertNotNull(result)
|
|
||||||
assertEquals("ff", result.result[0].name)
|
|
||||||
assertEquals("ff-2", result.result[1].name)
|
|
||||||
assertEquals(10, result.total)
|
|
||||||
assertEquals(0, result.offset)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun `call select paginated on function`() {
|
|
||||||
val resources = this::class.java.getResource("/sql/function")?.toURI()
|
|
||||||
Requester(connection, functionsDirectory = 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")
|
|
||||||
.select<ObjTest>(1, 2, "name" to "ff").run {
|
|
||||||
assertNotNull(result)
|
|
||||||
assertEquals("ff", result[0].name)
|
|
||||||
assertEquals("ff-2", result[1].name)
|
|
||||||
assertEquals(10, total)
|
|
||||||
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
|
|
||||||
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()
|
||||||
Requester(connection, queriesDirectory = resources)
|
Requester(connection, queriesDirectory = resources)
|
||||||
.getQuery("selectOneWithParameters").apply {
|
.getQuery("selectOneWithParameters").apply {
|
||||||
selectOne<ObjTest>(mapOf("name" to "myName")) {
|
execute<ObjTest>(mapOf("name" to "myName")) {
|
||||||
assertNotNull(it)
|
assertNotNull(it)
|
||||||
assertEquals("myName", it.name)
|
assertEquals("myName", it.name)
|
||||||
assertEquals("plop", rows[0].getString("other"))
|
assertEquals("plop", rows[0].getString("other"))
|
||||||
@@ -495,7 +435,7 @@ class RequesterTest : TestAbstract() {
|
|||||||
assertEquals("selectOneWithParameters", name)
|
assertEquals("selectOneWithParameters", name)
|
||||||
}
|
}
|
||||||
}.apply {
|
}.apply {
|
||||||
selectOne(typeReference = object : TypeReference<ObjTest>() {}, values = mapOf("name" to "myName")) {
|
execute(typeReference = object : TypeReference<ObjTest>() {}, values = mapOf("name" to "myName")) {
|
||||||
assertNotNull(it)
|
assertNotNull(it)
|
||||||
assertEquals("myName", it.name)
|
assertEquals("myName", it.name)
|
||||||
assertEquals("plop", rows[0].getString("other"))
|
assertEquals("plop", rows[0].getString("other"))
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package fr.postgresjson
|
package fr.postgresjson
|
||||||
|
|
||||||
import fr.postgresjson.entity.UuidEntity
|
|
||||||
import fr.postgresjson.serializer.Serializer
|
import fr.postgresjson.serializer.Serializer
|
||||||
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
|
||||||
import org.junit.jupiter.api.Assertions.assertTrue
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
@@ -13,8 +11,8 @@ import java.util.UUID
|
|||||||
|
|
||||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||||
internal class SerializerTest {
|
internal class SerializerTest {
|
||||||
private class ObjTest(var val1: String, var val2: Int, id: UUID = UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96")) : UuidEntity(id)
|
private class ObjTest(var val1: String, var val2: Int, val id: UUID = UUID.fromString("1e5f5d41-6d14-4007-897b-0ed2616bec96"))
|
||||||
private class ObjTestDate(var val1: DateTime, id: UUID = UUID.fromString("829b1a29-5db8-47f9-9562-961c561ac528")) : UuidEntity(id)
|
private class ObjTestDate(var val1: DateTime, val id: UUID = UUID.fromString("829b1a29-5db8-47f9-9562-961c561ac528"))
|
||||||
|
|
||||||
private val serializer = Serializer()
|
private val serializer = Serializer()
|
||||||
|
|
||||||
@@ -33,16 +31,10 @@ internal class SerializerTest {
|
|||||||
assertTrue(json.contains(""""val1":"plop","val2":123"""))
|
assertTrue(json.contains(""""val1":"plop","val2":123"""))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
fun serialize2() {
|
|
||||||
val json = obj.serialize()
|
|
||||||
assertTrue(json.contains(""""val1":"plop","val2":123"""))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun serializeList() {
|
fun serializeList() {
|
||||||
val list = listOf(ObjTest("one", 1), ObjTest("two", 2))
|
val list = listOf(ObjTest("one", 1), ObjTest("two", 2))
|
||||||
val json = list.serialize()
|
val json = serializer.serialize(list)
|
||||||
assertTrue(json.contains(""""val1":"one","val2":1"""))
|
assertTrue(json.contains(""""val1":"one","val2":1"""))
|
||||||
assertTrue(json.contains(""""val1":"two","val2":2"""))
|
assertTrue(json.contains(""""val1":"two","val2":2"""))
|
||||||
}
|
}
|
||||||
@@ -50,7 +42,7 @@ internal class SerializerTest {
|
|||||||
@Test
|
@Test
|
||||||
fun serializeDate() {
|
fun serializeDate() {
|
||||||
val objDate = ObjTestDate(DateTime.parse("2019-07-30T14:08:51.420108+04:00"))
|
val objDate = ObjTestDate(DateTime.parse("2019-07-30T14:08:51.420108+04:00"))
|
||||||
val json = objDate.serialize()
|
val json = serializer.serialize(objDate)
|
||||||
assertTrue(json.contains(""""val1":"2019-07-30T10:08:51.420Z""""), json)
|
assertTrue(json.contains(""""val1":"2019-07-30T10:08:51.420Z""""), json)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
26
src/test/kotlin/fr/postgresjson/SqlFixtureListener.kt
Normal file
26
src/test/kotlin/fr/postgresjson/SqlFixtureListener.kt
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package fr.postgresjson
|
||||||
|
|
||||||
|
import fr.postgresjson.connexion.Connection
|
||||||
|
import io.kotest.core.listeners.AfterSpecListener
|
||||||
|
import io.kotest.core.listeners.BeforeSpecListener
|
||||||
|
import io.kotest.core.spec.Spec
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
open class SqlFixtureListener : BeforeSpecListener, AfterSpecListener {
|
||||||
|
private val connection = Connection(database = "json_test", username = "test", password = "test", port = 35555)
|
||||||
|
|
||||||
|
override suspend fun beforeSpec(spec: Spec) {
|
||||||
|
val initSQL = File(this::class.java.getResource("/fixtures/init.sql")!!.toURI())
|
||||||
|
connection
|
||||||
|
.connect()
|
||||||
|
.sendQuery(initSQL.readText())
|
||||||
|
.join()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun afterSpec(spec: Spec) {
|
||||||
|
val downSQL = File(this::class.java.getResource("/fixtures/down.sql")!!.toURI())
|
||||||
|
connection
|
||||||
|
.apply { connect().sendQuery(downSQL.readText()).join() }
|
||||||
|
.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,8 +8,8 @@ import org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
@TestInstance(PER_CLASS)
|
@TestInstance(PER_CLASS)
|
||||||
abstract class TestAbstract {
|
open class TestAbstract {
|
||||||
protected val connection = Connection(database = "json_test", username = "test", password = "test", port = 5555)
|
protected val connection = Connection(database = "json_test", username = "test", password = "test", port = 35555)
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
fun beforeAll() {
|
fun beforeAll() {
|
||||||
|
|||||||
16
src/test/kotlin/fr/postgresjson/TestConnection.kt
Normal file
16
src/test/kotlin/fr/postgresjson/TestConnection.kt
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package fr.postgresjson
|
||||||
|
|
||||||
|
import fr.postgresjson.connexion.Connection
|
||||||
|
|
||||||
|
fun TestConnection(): Connection =
|
||||||
|
Connection(database = "json_test", username = "test", password = "test", port = 35555)
|
||||||
|
|
||||||
|
fun <A> Connection.rollbackAfter(block: Connection.() -> A?) = connect().run {
|
||||||
|
sendQuery("BEGIN")
|
||||||
|
try {
|
||||||
|
block().apply { sendQuery("ROLLBACK") }
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
sendQuery("ROLLBACK")
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
648
src/test/kotlin/fr/postgresjson/definition/FunctionTest.kt
Normal file
648
src/test/kotlin/fr/postgresjson/definition/FunctionTest.kt
Normal file
@@ -0,0 +1,648 @@
|
|||||||
|
package fr.postgresjson.definition
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.IN
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.INOUT
|
||||||
|
import fr.postgresjson.definition.Parameter.Direction.OUT
|
||||||
|
import fr.postgresjson.definition.Returns.Primitive
|
||||||
|
import fr.postgresjson.definition.parse.parseFunction
|
||||||
|
import io.kotest.core.spec.style.FreeSpec
|
||||||
|
import io.kotest.matchers.collections.shouldHaveSize
|
||||||
|
import io.kotest.matchers.shouldBe
|
||||||
|
import org.amshove.kluent.shouldBeInstanceOf
|
||||||
|
|
||||||
|
class FunctionTest : FreeSpec({
|
||||||
|
"Function name" - {
|
||||||
|
"all in lower" {
|
||||||
|
parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun() returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).apply {
|
||||||
|
name shouldBe "myfun"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"first letter caps without quoted" {
|
||||||
|
parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function Myfun() returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).apply {
|
||||||
|
name shouldBe "myfun"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"with numbers" {
|
||||||
|
parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun001() returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).apply {
|
||||||
|
name shouldBe "myfun001"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"escaped name with space" {
|
||||||
|
parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function "My fun"() returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).apply {
|
||||||
|
name shouldBe "My fun"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"quoted name with double quote in name" {
|
||||||
|
parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function "My""fun" () returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).apply {
|
||||||
|
name shouldBe "My\"fun"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"name with new line before and after" {
|
||||||
|
parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function
|
||||||
|
myfun
|
||||||
|
()
|
||||||
|
returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).apply {
|
||||||
|
name shouldBe "myfun"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters" - {
|
||||||
|
"One parameter text" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one text) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have one parameter" {
|
||||||
|
param shouldHaveSize 1
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have first parameter name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have first parameter type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Two parameters" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one text, two int) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 2 parameters" {
|
||||||
|
param shouldHaveSize 2
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have names" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
param[1].name shouldBe "two"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have first parameter type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
param[1].type.name shouldBe "int"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Escaped parameters name" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun("one""or two" text, "#@€" int) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 2 parameters" {
|
||||||
|
param shouldHaveSize 2
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have names" {
|
||||||
|
param[0].name shouldBe "one\"or two"
|
||||||
|
param[1].name shouldBe "#@€"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"Parameters with Caps" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun("One" text, Two text) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have first parameter name" {
|
||||||
|
param[0].name shouldBe "One"
|
||||||
|
param[1].name shouldBe "two"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with type `character varying(255)`" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one character varying(255)) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 1 parameters" {
|
||||||
|
param shouldHaveSize 1
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type name" {
|
||||||
|
param[0].type.name shouldBe "character varying"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type precision" {
|
||||||
|
param[0].type.precision shouldBe 255
|
||||||
|
param[0].type.scale shouldBe null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with type `numeric(16, 8)`" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one numeric(16, 8)) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 1 parameters" {
|
||||||
|
param shouldHaveSize 1
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type name" {
|
||||||
|
param[0].type.name shouldBe "numeric"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type precision" {
|
||||||
|
param[0].type.precision shouldBe 16
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type scale" {
|
||||||
|
param[0].type.scale shouldBe 8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with default text" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one text default 'example') returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 1 parameters" {
|
||||||
|
param shouldHaveSize 1
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have default text" {
|
||||||
|
param[0].default shouldBe "'example'"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with default int" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one int DEFAULT 123456 ) returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 1 parameters" {
|
||||||
|
param shouldHaveSize 1
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type name" {
|
||||||
|
param[0].type.name shouldBe "int"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have default text" {
|
||||||
|
param[0].default shouldBe "123456"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with multiple default and equal" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one int DEFAULT 123456 , two text default 'hello', three text = '654') returns text language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 3 parameters" {
|
||||||
|
param shouldHaveSize 3
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
param[1].name shouldBe "two"
|
||||||
|
param[2].name shouldBe "three"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have type name" {
|
||||||
|
param[0].type.name shouldBe "int"
|
||||||
|
param[1].type.name shouldBe "text"
|
||||||
|
param[2].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have default text" {
|
||||||
|
param[0].default shouldBe "123456"
|
||||||
|
param[1].default shouldBe "'hello'"
|
||||||
|
param[2].default shouldBe "'654'"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"parameters with IN OUT INOUT" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(in one text, inout two text, out three text, four text) language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 4 parameters" {
|
||||||
|
param shouldHaveSize 4
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
param[1].name shouldBe "two"
|
||||||
|
param[2].name shouldBe "three"
|
||||||
|
param[3].name shouldBe "four"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
param[1].type.name shouldBe "text"
|
||||||
|
param[2].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter direction" {
|
||||||
|
param[0].direction shouldBe IN
|
||||||
|
param[1].direction shouldBe INOUT
|
||||||
|
param[2].direction shouldBe OUT
|
||||||
|
param[3].direction shouldBe IN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with type array of numeric" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one numeric(10, 2)[]) language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 1 parameters" {
|
||||||
|
param shouldHaveSize 1
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type is array" {
|
||||||
|
param[0].type.isArray shouldBe true
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type name" {
|
||||||
|
param[0].type.name shouldBe "numeric"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type precision" {
|
||||||
|
param[0].type.precision shouldBe 10
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type scale" {
|
||||||
|
param[0].type.scale shouldBe 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with type array of text" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one text[], two int[], three text) language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have 2 parameters" {
|
||||||
|
param shouldHaveSize 3
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter name" {
|
||||||
|
param[0].name shouldBe "one"
|
||||||
|
param[1].name shouldBe "two"
|
||||||
|
param[2].name shouldBe "three"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type is array" {
|
||||||
|
param[0].type.isArray shouldBe true
|
||||||
|
param[1].type.isArray shouldBe true
|
||||||
|
param[2].type.isArray shouldBe false
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
param[1].type.name shouldBe "int"
|
||||||
|
param[2].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter direction" {
|
||||||
|
param[0].direction shouldBe IN
|
||||||
|
param[1].direction shouldBe IN
|
||||||
|
param[2].direction shouldBe IN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with type array multidimensional of text" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one text[][]) language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have parameter type is array" {
|
||||||
|
param[0].type.isArray shouldBe true
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Parameters with type fixed size array" - {
|
||||||
|
val param = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun(one text[45], two text[1][]) language plpgsql as
|
||||||
|
$$ begin end;$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).parameters
|
||||||
|
|
||||||
|
"should have parameter type is array" {
|
||||||
|
param[0].type.isArray shouldBe true
|
||||||
|
param[1].type.isArray shouldBe true
|
||||||
|
}
|
||||||
|
|
||||||
|
"should have parameter type name" {
|
||||||
|
param[0].type.name shouldBe "text"
|
||||||
|
param[1].type.name shouldBe "text"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should return the type with array" {
|
||||||
|
param[0].type.toString() shouldBe "text[45]"
|
||||||
|
param[1].type.toString() shouldBe "text[1][]"
|
||||||
|
}
|
||||||
|
|
||||||
|
"should return the type name" {
|
||||||
|
param[0].toString() shouldBe "in one text[45]"
|
||||||
|
param[1].toString() shouldBe "in two text[1][]"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"Function Returns" - {
|
||||||
|
"should return the type text" {
|
||||||
|
val returns = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun() returns text language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).returns
|
||||||
|
|
||||||
|
returns shouldBeInstanceOf Primitive::class
|
||||||
|
returns.definition shouldBe "text"
|
||||||
|
returns.isSetOf shouldBe false
|
||||||
|
}
|
||||||
|
|
||||||
|
"should return the type character varying" {
|
||||||
|
val returns = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun() returns character varying language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).returns
|
||||||
|
|
||||||
|
returns shouldBeInstanceOf Primitive::class
|
||||||
|
returns.definition shouldBe "character varying"
|
||||||
|
returns.isSetOf shouldBe false
|
||||||
|
}
|
||||||
|
|
||||||
|
"should return the type character varying(255)" {
|
||||||
|
val returns = parseFunction(
|
||||||
|
// language=PostgreSQL
|
||||||
|
"""
|
||||||
|
create or replace function myfun() returns character varying(255) language plpgsql as
|
||||||
|
$$ begin; end$$;
|
||||||
|
""".trimIndent()
|
||||||
|
).returns
|
||||||
|
|
||||||
|
returns shouldBeInstanceOf Primitive::class
|
||||||
|
returns.definition shouldBe "character varying(255)"
|
||||||
|
returns.isSetOf shouldBe false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// "function returns" - {
|
||||||
|
// "should return the type text if function return text" {
|
||||||
|
// Function(
|
||||||
|
// // language=PostgreSQL
|
||||||
|
// """
|
||||||
|
// create or replace function test001() returns text language plpgsql as
|
||||||
|
// $$ begin; end$$;
|
||||||
|
// """.trimIndent()
|
||||||
|
// ).returns shouldBe "text"
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// "return null if function return void" {
|
||||||
|
// Function(
|
||||||
|
// // language=PostgreSQL
|
||||||
|
// """
|
||||||
|
// create or replace function test001() returns void language plpgsql as
|
||||||
|
// $$ begin; end$$;
|
||||||
|
// """.trimIndent()
|
||||||
|
// ).returns shouldBe null
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// "Parameters" - {
|
||||||
|
// "One parameter text" - {
|
||||||
|
// val param = Function(
|
||||||
|
// // language=PostgreSQL
|
||||||
|
// """
|
||||||
|
// create or replace function myfun(
|
||||||
|
// one text
|
||||||
|
// ) returns text language plpgsql as
|
||||||
|
// $$ begin end;$$;
|
||||||
|
// """.trimIndent()
|
||||||
|
// ).parameters
|
||||||
|
//
|
||||||
|
// "Function must have one parameter" {
|
||||||
|
// param shouldHaveSize 1
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// "The parameter must be in lower case" {
|
||||||
|
// param.getOrNull(0)?.name shouldBe "one"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// "parameters" - {
|
||||||
|
// val param = Function(
|
||||||
|
// // language=PostgreSQL
|
||||||
|
// """
|
||||||
|
// create or replace function myfun(
|
||||||
|
// one text,
|
||||||
|
// "Two" INTEGER default 5,
|
||||||
|
// "Three ""and"" half" character varying = 'Yes',
|
||||||
|
// Three_and_more character varying(255) default 'Hello',
|
||||||
|
// dot point default '(1, 2)'::point,
|
||||||
|
// num NUMERIC(10, 3) default 123.654,
|
||||||
|
// arr01 text[] default '{hello, world, "and others", and\ more, "with \", ], [ , ) and as $$ in text"}'::text[],
|
||||||
|
// arr02 "point"[] default array['(1, 2)'::point, '(7, 12)'::point]::point[],
|
||||||
|
// arr03 text[] default array[
|
||||||
|
// 'text01',
|
||||||
|
// 'text02"([,#-',
|
||||||
|
// null
|
||||||
|
// ],
|
||||||
|
// last "text" default 'Hi'
|
||||||
|
// ) returns text language plpgsql as
|
||||||
|
// $$ begin end;$$;
|
||||||
|
// """.trimIndent()
|
||||||
|
// ).parameters
|
||||||
|
//
|
||||||
|
// "count must be correct" {
|
||||||
|
// param shouldHaveSize 10
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// "name" - {
|
||||||
|
// "in lower case" {
|
||||||
|
// param.getOrNull(0)?.name shouldBe "one"
|
||||||
|
// }
|
||||||
|
// "in camel case with double quote" {
|
||||||
|
// param.getOrNull(1)?.name shouldBe "Two"
|
||||||
|
// }
|
||||||
|
// "with spaces and double quote" {
|
||||||
|
// param.getOrNull(2)?.name shouldBe "Three \"and\" half"
|
||||||
|
// }
|
||||||
|
// "in snake_case" {
|
||||||
|
// param.getOrNull(3)?.name shouldBe "three_and_more"
|
||||||
|
// }
|
||||||
|
// "with numbers" {
|
||||||
|
// param.getOrNull(5)?.name shouldBe "arr01"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// "type" - {
|
||||||
|
// "text in lower case" {
|
||||||
|
// param.getOrNull(0)?.type shouldBe "text"
|
||||||
|
// }
|
||||||
|
// "integer in UPPER case" {
|
||||||
|
// param.getOrNull(1)?.type shouldBe "integer"
|
||||||
|
// }
|
||||||
|
// "character varying in two word" {
|
||||||
|
// param.getOrNull(2)?.type shouldBe "character varying"
|
||||||
|
// }
|
||||||
|
// "character varying with max size" - {
|
||||||
|
// "dont return the scale type in name" {
|
||||||
|
// param.getOrNull(3)?.type shouldBe "character varying"
|
||||||
|
// }
|
||||||
|
// "return the correct size" {
|
||||||
|
// param.getOrNull(3)?.type?.precision shouldBe 255
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// "numeric with precision and scale" - {
|
||||||
|
// "dont return the precision and scale type in name" {
|
||||||
|
// param.getOrNull(5)?.type shouldBe "numeric"
|
||||||
|
// }
|
||||||
|
// "return the correct precision" {
|
||||||
|
// param.getOrNull(5)?.type?.precision shouldBe 10
|
||||||
|
// }
|
||||||
|
// "return the correct scale" {
|
||||||
|
// param.getOrNull(5)?.type?.scale shouldBe 3
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// "array of text" {
|
||||||
|
// param.getOrNull(7)?.type shouldBe "text[]"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// "default" - {
|
||||||
|
// "with array of composite type Point" - {
|
||||||
|
// """must return "arr02" at name""" {
|
||||||
|
// param.getOrNull(7)?.name shouldBe "arr02"
|
||||||
|
// }
|
||||||
|
// """must return "point[]" at type""" {
|
||||||
|
// param.getOrNull(7)?.type shouldBe "point[]"
|
||||||
|
// }
|
||||||
|
// """must return "array[(1, 2)::point, (7, 12)::point]::point[]" at default""" {
|
||||||
|
// param.getOrNull(7)?.default shouldBe "array[(1, 2)::point, (7, 12)::point]::point[]"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
})
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package fr.postgresjson.functionGenerator
|
||||||
|
|
||||||
|
import fr.postgresjson.definition.parse.parseFunction
|
||||||
|
import io.kotest.core.Tag
|
||||||
|
import io.kotest.core.annotation.Ignored
|
||||||
|
import io.kotest.core.spec.style.StringSpec
|
||||||
|
import org.amshove.kluent.`should be equal to`
|
||||||
|
|
||||||
|
@Ignored
|
||||||
|
class FunctionGeneratorTest : StringSpec({
|
||||||
|
tags(Tag("Generator"))
|
||||||
|
val functionDirectory = this::class.java.getResource("/sql/function/Test")!!.toURI()
|
||||||
|
val generator = FunctionGenerator(functionDirectory)
|
||||||
|
|
||||||
|
"generate function with input object and output object" {
|
||||||
|
val functionSql = """
|
||||||
|
|create or replace function test_function_object (inout resource json)
|
||||||
|
|language plpgsql
|
||||||
|
|as
|
||||||
|
|$$
|
||||||
|
|begin
|
||||||
|
| resource = json_build_object('id', '1e5f5d41-6d14-4007-897b-0ed2616bec96', 'name', 'changedName');
|
||||||
|
|end;
|
||||||
|
|$$
|
||||||
|
""".trimMargin()
|
||||||
|
|
||||||
|
val expectedGenerated = """
|
||||||
|
|package fr.postgresjson.functionGenerator.generated
|
||||||
|
|
|
||||||
|
|import com.fasterxml.jackson.core.type.TypeReference
|
||||||
|
|import fr.postgresjson.connexion.Requester
|
||||||
|
|
|
||||||
|
|inline fun <reified E: Any, S: Any?> Requester.testFunctionObject(resource: S): E? {
|
||||||
|
| return getFunction("test_function_object")
|
||||||
|
| .execute<E>(object : TypeReference<E>() {}, mapOf("resource" to resource))
|
||||||
|
|}
|
||||||
|
""".trimMargin()
|
||||||
|
|
||||||
|
generator.generate(parseFunction(functionSql)) `should be equal to` expectedGenerated
|
||||||
|
}
|
||||||
|
|
||||||
|
"generate function with return void" {
|
||||||
|
val functionSql = """
|
||||||
|
|create or replace function test_function_void (name text default 'plop') returns void
|
||||||
|
|language plpgsql
|
||||||
|
|as
|
||||||
|
|$$
|
||||||
|
|begin
|
||||||
|
| perform 1;
|
||||||
|
|end;
|
||||||
|
|$$;
|
||||||
|
""".trimMargin()
|
||||||
|
|
||||||
|
val expectedGenerated = """
|
||||||
|
|package fr.postgresjson.functionGenerator.generated
|
||||||
|
|
|
||||||
|
|import fr.postgresjson.connexion.Requester
|
||||||
|
|
|
||||||
|
|fun Requester.testFunctionVoid(name: String = "plop"): Unit {
|
||||||
|
| getFunction("test_function_void")
|
||||||
|
| .exec(mapOf("name" to name))
|
||||||
|
|}
|
||||||
|
""".trimMargin()
|
||||||
|
|
||||||
|
generator.generate(parseFunction(functionSql)) `should be equal to` expectedGenerated
|
||||||
|
}
|
||||||
|
|
||||||
|
"generate function with multiple args and defaults" {
|
||||||
|
val functionSql = """
|
||||||
|
|create or replace function test_function_multiple (name text default 'plop', in hi text default 'hello', out result json)
|
||||||
|
|language plpgsql
|
||||||
|
|as
|
||||||
|
|$$
|
||||||
|
|begin
|
||||||
|
| result = json_build_array(
|
||||||
|
| json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', name),
|
||||||
|
| json_build_object('id', '8d20abb0-7f77-4b6c-9991-44acd3c88faa', 'name', hi)
|
||||||
|
| );
|
||||||
|
|end;
|
||||||
|
|$$
|
||||||
|
""".trimMargin()
|
||||||
|
|
||||||
|
val expectedGenerated = """
|
||||||
|
|package fr.postgresjson.functionGenerator.generated
|
||||||
|
|
|
||||||
|
|import com.fasterxml.jackson.core.type.TypeReference
|
||||||
|
|import fr.postgresjson.connexion.Requester
|
||||||
|
|
|
||||||
|
|inline fun <reified E: Any> Requester.testFunctionMultiple(name: String = "plop", hi: String = "hello"): E? {
|
||||||
|
| return getFunction("test_function_multiple")
|
||||||
|
| .execute<E>(object : TypeReference<E>() {}, mapOf("name" to name, "hi" to hi))
|
||||||
|
|}
|
||||||
|
""".trimMargin()
|
||||||
|
|
||||||
|
generator.generate(parseFunction(functionSql)) `should be equal to` expectedGenerated
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -74,7 +74,7 @@ BEGIN
|
|||||||
END;
|
END;
|
||||||
$$;
|
$$;
|
||||||
|
|
||||||
CREATE OR REPLACE FUNCTION function_void (name text default 'plop') returns void
|
CREATE OR REPLACE FUNCTION test_function_void (name text default 'plop') returns void
|
||||||
LANGUAGE plpgsql
|
LANGUAGE plpgsql
|
||||||
AS
|
AS
|
||||||
$$
|
$$
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
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;
|
|
||||||
$$
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
CREATE OR REPLACE FUNCTION function_void (name text default 'plop') returns void
|
|
||||||
LANGUAGE plpgsql
|
|
||||||
AS
|
|
||||||
$$
|
|
||||||
BEGIN
|
|
||||||
PERFORM 1;
|
|
||||||
END;
|
|
||||||
$$;
|
|
||||||
8
src/test/resources/sql/function/Test/test_function.sql
Normal file
8
src/test/resources/sql/function/Test/test_function.sql
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
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;
|
||||||
|
$$
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
create or replace function test_function_multiparam(
|
||||||
|
name varchar(45) default 'plop',
|
||||||
|
numeric(4, 5),
|
||||||
|
num float(5),
|
||||||
|
num2 timestamp without time zone default '2002-01-01T00:00:00'::timestamp,
|
||||||
|
num3 int,
|
||||||
|
num4 integer,
|
||||||
|
num5 smallint,
|
||||||
|
num6 bigint,
|
||||||
|
num7 decimal,
|
||||||
|
num8 decimal(4, 6),
|
||||||
|
num9 real,
|
||||||
|
num10 double precision,
|
||||||
|
num11 smallserial,
|
||||||
|
num12 serial,
|
||||||
|
num13 bigserial,
|
||||||
|
num14 serial,
|
||||||
|
num15 money,
|
||||||
|
num16 character varying(789),
|
||||||
|
num16b character varying(789) default 'abc',
|
||||||
|
num16c character varying default 'abc',
|
||||||
|
num17 character(56),
|
||||||
|
num18 char(2),
|
||||||
|
num19 any,
|
||||||
|
num20 anyelement,
|
||||||
|
num21 anyarray
|
||||||
|
)
|
||||||
|
language plpgsql
|
||||||
|
as
|
||||||
|
$$
|
||||||
|
begin
|
||||||
|
perform 1;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
CREATE OR REPLACE FUNCTION test_function_multiple (name text default 'plop', IN hi text default 'hello', out result json)
|
create or replace function test_function_multiple(name text default 'plop', in hi text default 'hello', out result json)
|
||||||
LANGUAGE plpgsql
|
language plpgsql
|
||||||
AS
|
as
|
||||||
$$
|
$$
|
||||||
BEGIN
|
begin
|
||||||
result = json_build_array(
|
result = json_build_array(
|
||||||
json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', name),
|
json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', name),
|
||||||
json_build_object('id', '8d20abb0-7f77-4b6c-9991-44acd3c88faa', 'name', hi)
|
json_build_object('id', '8d20abb0-7f77-4b6c-9991-44acd3c88faa', 'name', hi)
|
||||||
);
|
);
|
||||||
END;
|
end;
|
||||||
$$
|
$$
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
CREATE OR REPLACE FUNCTION test_function_object (inout resource json)
|
create or replace function test_function_object(inout resource json)
|
||||||
LANGUAGE plpgsql
|
language plpgsql
|
||||||
AS
|
as
|
||||||
$$
|
$$
|
||||||
BEGIN
|
begin
|
||||||
resource = json_build_object('id', '1e5f5d41-6d14-4007-897b-0ed2616bec96', 'name', 'changedName');
|
resource = json_build_object('id', '1e5f5d41-6d14-4007-897b-0ed2616bec96', 'name', 'changedName');
|
||||||
END;
|
end;
|
||||||
$$
|
$$
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
CREATE OR REPLACE FUNCTION test_function_paginated (name text default 'plop', IN "limit" int default 10, IN "offset" int default 0, out result json, out total int)
|
|
||||||
LANGUAGE plpgsql
|
|
||||||
AS
|
|
||||||
$$
|
|
||||||
BEGIN
|
|
||||||
SELECT json_build_array(
|
|
||||||
json_build_object('id', '457daad5-4f1b-4eb7-80ec-6882adb8cc7d', 'name', name::text),
|
|
||||||
json_build_object('id', '8d20abb0-7f77-4b6c-9991-44acd3c88faa', 'name', name::text || '-2')
|
|
||||||
),
|
|
||||||
10
|
|
||||||
INTO result, total
|
|
||||||
LIMIT "limit" OFFSET "offset";
|
|
||||||
END;
|
|
||||||
$$
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
create or replace function test_function_void(name text default 'plop') returns void
|
||||||
|
language plpgsql
|
||||||
|
as
|
||||||
|
$$
|
||||||
|
begin
|
||||||
|
perform 1;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
Reference in New Issue
Block a user