refactoring: cleanup and reformat

This commit is contained in:
2019-07-18 18:50:02 +02:00
parent 5949bc5d7b
commit ade162451c
15 changed files with 301 additions and 100 deletions

View File

@@ -38,7 +38,12 @@ class Connection(
fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>) = connect().inTransaction(f) fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>) = connect().inTransaction(f)
override fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<R>, values: List<Any?>, block: (QueryResult, R?) -> Unit): R? { override fun <R: EntityI<*>> select(
sql: String,
typeReference: TypeReference<R>,
values: List<Any?>,
block: (QueryResult, R?) -> Unit
): R? {
val result = exec(sql, compileArgs(values)) val result = exec(sql, compileArgs(values))
val json = result.rows[0].getString(0) val json = result.rows[0].getString(0)
return if (json === null) { return if (json === null) {
@@ -50,19 +55,37 @@ class Connection(
} }
} }
inline fun <reified R: EntityI<*>> selectOne(sql: String, values: List<Any?> = emptyList(), noinline block: SelectOneCallback<R> = {}): R? = inline fun <reified R: EntityI<*>> selectOne(
sql: String,
values: List<Any?> = emptyList(),
noinline block: SelectOneCallback<R> = {}
): R? =
select(sql, object: TypeReference<R>() {}, values, block) select(sql, object: TypeReference<R>() {}, values, block)
override fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<R>, values: Map<String, Any?>, block: (QueryResult, R?) -> Unit): R? { override fun <R: EntityI<*>> select(
sql: String,
typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: (QueryResult, R?) -> Unit
): R? {
return replaceArgs(sql, values) { return replaceArgs(sql, values) {
select(this.sql, typeReference, this.parameters, block) select(this.sql, typeReference, this.parameters, block)
} }
} }
inline fun <reified R: EntityI<*>> selectOne(sql: String, values: Map<String, Any?>, noinline block: SelectOneCallback<R> = {}): R? = inline fun <reified R: EntityI<*>> selectOne(
sql: String,
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
select(sql, object: TypeReference<R>() {}, values, block) select(sql, object: TypeReference<R>() {}, values, block)
override fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<List<R>>, values: List<Any?>, block: (QueryResult, List<R>) -> Unit): List<R> { 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, compileArgs(values)) val result = exec(sql, compileArgs(values))
val json = result.rows[0].getString(0) val json = result.rows[0].getString(0)
return if (json === null) { return if (json === null) {
@@ -74,7 +97,11 @@ class Connection(
} }
} }
inline fun <reified R: EntityI<*>> select(sql: String, values: List<Any?> = emptyList(), noinline block: SelectCallback<R> = {}): List<R> = inline fun <reified R: EntityI<*>> select(
sql: String,
values: List<Any?> = emptyList(),
noinline block: SelectCallback<R> = {}
): List<R> =
select(sql, object: TypeReference<List<R>>() {}, values, block) select(sql, object: TypeReference<List<R>>() {}, values, block)
override fun <R: EntityI<*>> select( override fun <R: EntityI<*>> select(
@@ -132,7 +159,11 @@ class Connection(
} }
} }
inline fun <reified R: EntityI<*>> select(sql: String, values: Map<String, Any?>, noinline block: SelectCallback<R> = {}): List<R> = inline fun <reified R: EntityI<*>> select(
sql: String,
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(sql, object: TypeReference<List<R>>() {}, values, block) select(sql, object: TypeReference<List<R>>() {}, values, block)
override fun exec(sql: String, values: List<Any?>): QueryResult { override fun exec(sql: String, values: List<Any?>): QueryResult {
@@ -184,7 +215,7 @@ class Connection(
data class ParametersQuery(val sql: String, val parameters: List<Any?>) data class ParametersQuery(val sql: String, val parameters: List<Any?>)
private fun <T> stopwatchQuery(sql: String, values: List<Any?> = emptyList(), callback: () -> T): T { private fun <T> stopwatchQuery(sql: String, values: List<Any?> = emptyList(), callback: () -> T): T {
val sqlForLog = "\n"+sql.prependIndent() val sqlForLog = "\n${sql.prependIndent()}"
try { try {
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
val result = callback() val result = callback()

View File

@@ -8,13 +8,43 @@ interface EmbedExecutable {
val connection: Connection val connection: Connection
override fun toString(): String override fun toString(): String
fun <R: EntityI<*>> select(typeReference: TypeReference<R>, values: List<Any?> = emptyList(), block: SelectOneCallback<R> = {}): R? /* Select One */
fun <R: EntityI<*>> select(typeReference: TypeReference<R>, values: Map<String, Any?>, block: SelectOneCallback<R> = {}): R? /**
* Select One entity with list of parameters
*/
fun <R: EntityI<*>> select(
typeReference: TypeReference<R>,
values: List<Any?> = emptyList(),
block: SelectOneCallback<R> = {}
): R?
fun <R: EntityI<*>> select(typeReference: TypeReference<List<R>>, values: List<Any?> = emptyList(), block: SelectCallback<R> = {}): List<R> fun <R: EntityI<*>> select(
fun <R: EntityI<*>> select(typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: SelectCallback<R> = {}): List<R> typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: SelectOneCallback<R> = {}
): R?
fun <R: EntityI<*>> select(page: Int, limit: Int, typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: SelectPaginatedCallback<R> = {}): Paginated<R> /* Select Miltiples */
fun <R: EntityI<*>> select(
typeReference: TypeReference<List<R>>,
values: List<Any?> = emptyList(),
block: SelectCallback<R> = {}
): List<R>
fun <R: EntityI<*>> select(
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: SelectCallback<R> = {}
): List<R>
/* Select Paginated */
fun <R: EntityI<*>> select(
page: Int,
limit: Int,
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: SelectPaginatedCallback<R> = {}
): Paginated<R>
fun exec(values: List<Any?> = emptyList()): QueryResult fun exec(values: List<Any?> = emptyList()): QueryResult
fun exec(values: Map<String, Any?>): QueryResult fun exec(values: Map<String, Any?>): QueryResult

View File

@@ -5,11 +5,49 @@ import com.github.jasync.sql.db.QueryResult
import fr.postgresjson.entity.EntityI import fr.postgresjson.entity.EntityI
interface Executable { interface Executable {
fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<R>, values: List<Any?> = emptyList(), block: SelectOneCallback<R> = {}): R? /* Select One */
fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<R>, values: Map<String, Any?>, block: SelectOneCallback<R> = {}): R?
fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<List<R>>, values: List<Any?> = emptyList(), block: SelectCallback<R> = {}): List<R> fun <R: EntityI<*>> select(
fun <R: EntityI<*>> select(sql: String, typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: SelectCallback<R> = {}): List<R> sql: String,
fun <R: EntityI<*>> select(sql: String, page: Int, limit: Int, typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: SelectPaginatedCallback<R> = {}): Paginated<R> typeReference: TypeReference<R>,
values: List<Any?> = emptyList(),
block: SelectOneCallback<R> = {}
): R?
fun <R: EntityI<*>> select(
sql: String,
typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: SelectOneCallback<R> = {}
): R?
/* Select Miltiples */
fun <R: EntityI<*>> select(
sql: String,
typeReference: TypeReference<List<R>>,
values: List<Any?> = emptyList(),
block: SelectCallback<R> = {}
): List<R>
fun <R: EntityI<*>> select(
sql: String,
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: SelectCallback<R> = {}
): List<R>
/* Select Paginated */
fun <R: EntityI<*>> select(
sql: String,
page: Int,
limit: Int,
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: SelectPaginatedCallback<R> = {}
): Paginated<R>
fun exec(sql: String, values: List<Any?> = emptyList()): QueryResult fun exec(sql: String, values: List<Any?> = emptyList()): QueryResult
fun exec(sql: String, values: Map<String, Any?>): QueryResult fun exec(sql: String, values: Map<String, Any?>): QueryResult
fun sendQuery(sql: String): QueryResult fun sendQuery(sql: String): QueryResult

View File

@@ -10,59 +10,102 @@ class Function(val definition: Function, override val connection: Connection): E
return definition.name return definition.name
} }
/* Select One */
/** /**
* Select One entity with list of parameters * Select One entity with list of parameters
*/ */
override fun <R: EntityI<*>> select(typeReference: TypeReference<R>, values: List<Any?>, block: (QueryResult, R?) -> Unit): R? { override fun <R: EntityI<*>> select(
typeReference: TypeReference<R>,
values: List<Any?>,
block: (QueryResult, R?) -> Unit
): R? {
val args = compileArgs(values) val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)" val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block) return connection.select(sql, typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> selectOne(values: List<Any?> = emptyList(), noinline block: SelectOneCallback<R> = {}): R? = inline fun <reified R: EntityI<*>> selectOne(
values: List<Any?> = emptyList(),
noinline block: SelectOneCallback<R> = {}
): R? =
select(object: TypeReference<R>() {}, values, block) select(object: TypeReference<R>() {}, values, block)
/** /**
* Select One entity with named parameters * Select One entity with named parameters
*/ */
override fun <R: EntityI<*>> select(typeReference: TypeReference<R>, values: Map<String, Any?>, block: (QueryResult, R?) -> Unit): R? { override fun <R: EntityI<*>> select(
typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: (QueryResult, R?) -> Unit
): R? {
val args = compileArgs(values) val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)" val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block) return connection.select(sql, typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> selectOne(values: Map<String, Any?>, noinline block: SelectOneCallback<R> = {}): R? = inline fun <reified R: EntityI<*>> selectOne(
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
select(object: TypeReference<R>() {}, values, block) select(object: TypeReference<R>() {}, values, block)
/* Select Multiples */
/** /**
* Select list of entities with list of parameters * Select list of entities with list of parameters
*/ */
override fun <R: EntityI<*>> select(typeReference: TypeReference<List<R>>, values: List<Any?>, block: (QueryResult, List<R>) -> Unit): List<R> { override fun <R: EntityI<*>> select(
typeReference: TypeReference<List<R>>,
values: List<Any?>,
block: (QueryResult, List<R>) -> Unit
): List<R> {
val args = compileArgs(values) val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)" val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block) return connection.select(sql, typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> select(values: List<Any?> = emptyList(), noinline block: SelectCallback<R> = {}): List<R> = inline fun <reified R: EntityI<*>> select(
values: List<Any?> = emptyList(),
noinline block: SelectCallback<R> = {}
): List<R> =
select(object: TypeReference<List<R>>() {}, values, block) select(object: TypeReference<List<R>>() {}, values, block)
/** /**
* Select list of entities with named parameters * Select list of entities with named parameters
*/ */
override fun <R: EntityI<*>> select(typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: (QueryResult, List<R>) -> Unit): List<R> { override fun <R: EntityI<*>> select(
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: (QueryResult, List<R>) -> Unit
): List<R> {
val args = compileArgs(values) val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)" val sql = "SELECT * FROM ${definition.name} ($args)"
return connection.select(sql, typeReference, values, block) return connection.select(sql, typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> select(values: Map<String, Any?>, noinline block: SelectCallback<R> = {}): List<R> = inline fun <reified R: EntityI<*>> select(
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(object: TypeReference<List<R>>() {}, values, block) select(object: TypeReference<List<R>>() {}, values, block)
override fun <R: EntityI<*>> select(page: Int, limit: Int, typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: (QueryResult, Paginated<R>) -> Unit): Paginated<R> { /* Select Paginated */
/**
* Select Multiple 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 offset = (page - 1) * limit
val newValues = values val newValues = values
.plus("offset" to offset) .plus("offset" to offset)
@@ -73,9 +116,17 @@ class Function(val definition: Function, override val connection: Connection): E
return connection.select(sql, page, limit, typeReference, values, block) return connection.select(sql, page, limit, typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> select(page: Int, limit: Int, values: Map<String, Any?> = emptyMap(), noinline block: SelectPaginatedCallback<R> = {}): Paginated<R> =
inline fun <reified R: EntityI<*>> 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) select(page, limit, object: TypeReference<List<R>>() {}, values, block)
/* Execute function without traitements */
override fun exec(values: List<Any?>): QueryResult { override fun exec(values: List<Any?>): QueryResult {
val args = compileArgs(values) val args = compileArgs(values)
val sql = "SELECT * FROM ${definition.name} ($args)" val sql = "SELECT * FROM ${definition.name} ($args)"

View File

@@ -10,40 +10,88 @@ class Query(private val sql: String, override val connection: Connection): Embed
return sql return sql
} }
override fun <R: EntityI<*>> select(typeReference: TypeReference<R>, values: List<Any?>, block: (QueryResult, R?) -> Unit): R? { /* Select One */
override fun <R: EntityI<*>> select(
typeReference: TypeReference<R>,
values: List<Any?>,
block: (QueryResult, R?) -> Unit
): R? {
return connection.select(this.toString(), typeReference, values, block) return connection.select(this.toString(), typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> selectOne(values: List<Any?> = emptyList(), noinline block: SelectOneCallback<R> = {}): R? = inline fun <reified R: EntityI<*>> selectOne(
values: List<Any?> = emptyList(),
noinline block: SelectOneCallback<R> = {}
): R? =
select(object: TypeReference<R>() {}, values, block) select(object: TypeReference<R>() {}, values, block)
override fun <R: EntityI<*>> select(typeReference: TypeReference<R>, values: Map<String, Any?>, block: (QueryResult, R?) -> Unit): R? { override fun <R: EntityI<*>> select(
typeReference: TypeReference<R>,
values: Map<String, Any?>,
block: (QueryResult, R?) -> Unit
): R? {
return connection.select(this.toString(), typeReference, values, block) return connection.select(this.toString(), typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> selectOne(values: Map<String, Any?>, noinline block: SelectOneCallback<R> = {}): R? = inline fun <reified R: EntityI<*>> selectOne(
values: Map<String, Any?>,
noinline block: SelectOneCallback<R> = {}
): R? =
select(object: TypeReference<R>() {}, values, block) select(object: TypeReference<R>() {}, values, block)
override fun <R: EntityI<*>> select(typeReference: TypeReference<List<R>>, values: List<Any?>, block: (QueryResult, List<R>) -> Unit): List<R> { /* Select Multiples */
override fun <R: EntityI<*>> select(
typeReference: TypeReference<List<R>>,
values: List<Any?>,
block: (QueryResult, List<R>) -> Unit
): List<R> {
return connection.select(this.toString(), typeReference, values, block) return connection.select(this.toString(), typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> select(values: List<Any?> = emptyList(), noinline block: SelectCallback<R> = {}): List<R> = inline fun <reified R: EntityI<*>> select(
values: List<Any?> = emptyList(),
noinline block: SelectCallback<R> = {}
): List<R> =
select(object: TypeReference<List<R>>() {}, values, block) select(object: TypeReference<List<R>>() {}, values, block)
override fun <R: EntityI<*>> select(typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: (QueryResult, List<R>) -> Unit): List<R> { override fun <R: EntityI<*>> select(
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: (QueryResult, List<R>) -> Unit
): List<R> {
return connection.select(this.toString(), typeReference, values, block) return connection.select(this.toString(), typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> select(values: Map<String, Any?>, noinline block: SelectCallback<R> = {}): List<R> = inline fun <reified R: EntityI<*>> select(
values: Map<String, Any?>,
noinline block: SelectCallback<R> = {}
): List<R> =
select(object: TypeReference<List<R>>() {}, values, block) select(object: TypeReference<List<R>>() {}, values, block)
override fun <R: EntityI<*>> select(page: Int, limit: Int, typeReference: TypeReference<List<R>>, values: Map<String, Any?>, block: (QueryResult, Paginated<R>) -> Unit): Paginated<R> { override fun <R: EntityI<*>> select(
page: Int,
limit: Int,
typeReference: TypeReference<List<R>>,
values: Map<String, Any?>,
block: (QueryResult, Paginated<R>) -> Unit
): Paginated<R> {
return connection.select(this.toString(), page, limit, typeReference, values, block) return connection.select(this.toString(), page, limit, typeReference, values, block)
} }
inline fun <reified R: EntityI<*>> select(page: Int, limit: Int, values: Map<String, Any?> = emptyMap(), noinline block: SelectPaginatedCallback<R> = {}): Paginated<R> =
/* Select Paginated */
inline fun <reified R: EntityI<*>> 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) select(page, limit, object: TypeReference<List<R>>() {}, values, block)
/* Execute function without traitements */
override fun exec(values: List<Any?>): QueryResult { override fun exec(values: List<Any?>): QueryResult {
return connection.exec(sql, values) return connection.exec(sql, values)
} }

View File

@@ -80,7 +80,8 @@ class Requester(
private val functionsDirectory: File? = null private val functionsDirectory: File? = null
) { ) {
fun createRequester(): Requester { fun createRequester(): Requester {
val con = Connection(host = host, port = port, database = database, username = username, password = password) val con =
Connection(host = host, port = port, database = database, username = username, password = password)
val req = Requester(con) val req = Requester(con)
return initRequester(req) return initRequester(req)

View File

@@ -3,19 +3,21 @@ package fr.postgresjson.definition
import java.io.File import java.io.File
open class Function ( open class Function(
override val script: String override val script: String
) : Resource, ParametersInterface { ): Resource, ParametersInterface {
val returns: String? val returns: String?
override val name: String override val name: String
override val parameters: List<Parameter> override val parameters: List<Parameter>
override var source: File? = null override var source: File? = null
init { init {
val functionRegex = """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 *[^ ]+)?""" val functionRegex =
"""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 *[^ ]+)?"""
.toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE)) .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*(,|$)""" 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)) .toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE))
val queryMatch = functionRegex.find(script) val queryMatch = functionRegex.find(script)
@@ -32,7 +34,8 @@ open class Function (
paramsMatch.groups["name"]!!.value.trim(), paramsMatch.groups["name"]!!.value.trim(),
paramsMatch.groups["type"]!!.value.trim(), paramsMatch.groups["type"]!!.value.trim(),
paramsMatch.groups["direction"]?.value?.trim(), paramsMatch.groups["direction"]?.value?.trim(),
paramsMatch.groups["default"]?.value?.trim()) paramsMatch.groups["default"]?.value?.trim()
)
}.toList() }.toList()
} else { } else {
listOf() listOf()
@@ -43,10 +46,11 @@ open class Function (
throw FunctionNotFound() throw FunctionNotFound()
} }
} }
abstract class ParseException(message: String, cause: Throwable? = null): Exception(message, cause) abstract class ParseException(message: String, cause: Throwable? = null): Exception(message, cause)
class FunctionNotFound(cause: Throwable? = null): ParseException("Function not found in script", cause) class FunctionNotFound(cause: Throwable? = null): ParseException("Function not found in script", cause)
fun getDefinition (): String { fun getDefinition(): String {
return "$name (" + parameters.joinToString(", ") + ") $returns" return "$name (" + parameters.joinToString(", ") + ") $returns"
} }
@@ -56,18 +60,25 @@ open class Function (
}.toMap() }.toMap()
} }
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()
} }
infix fun `is same` (other: Function): Boolean { infix fun `is same`(other: Function): Boolean {
return other.script == this.script return other.script == this.script
} }
companion object { companion object {
fun build(source: File): List<Function> { fun build(source: File): List<Function> {
return source.readText() return source.readText()
.split("CREATE +(OR REPLACE +)?(PROCEDURE|FUNCTION)".toRegex(setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE))) .split(
"CREATE +(OR REPLACE +)?(PROCEDURE|FUNCTION)".toRegex(
setOf(
RegexOption.IGNORE_CASE,
RegexOption.MULTILINE
)
)
)
.map { .map {
Function("CREATE OR REPLACE FUNCTION $it") Function("CREATE OR REPLACE FUNCTION $it")
} }

View File

@@ -7,8 +7,7 @@ interface ParameterI {
val default: String val default: String
} }
class Parameter(val name: String, val type: String, direction: Direction? = Direction.IN, val default: Any? = null) class Parameter(val name: String, val type: String, direction: Direction? = Direction.IN, val default: Any? = null) {
{
val direction: Direction val direction: Direction
init { init {
@@ -19,10 +18,10 @@ class Parameter(val name: String, val type: String, direction: Direction? = Dire
} }
} }
constructor(name: String, type: String, direction: String? = "IN", default: Any? = null) : this( constructor(name: String, type: String, direction: String? = "IN", default: Any? = null): this(
name = name, name = name,
type = type, type = type,
direction = direction?.let { Direction.valueOf(direction.toUpperCase())}, direction = direction?.let { Direction.valueOf(direction.toUpperCase()) },
default = default default = default
) )

View File

@@ -5,17 +5,17 @@ import kotlin.reflect.KClass
class EntitiesCollections { class EntitiesCollections {
private val collections: MutableMap<KClass<*>, EntityCollection<Any, EntityI<Any?>>> = mutableMapOf() private val collections: MutableMap<KClass<*>, EntityCollection<Any, EntityI<Any?>>> = mutableMapOf()
fun <I, R : EntityI<I?>> get(id: I, className: KClass<R>): R? { fun <I, R: EntityI<I?>> get(id: I, className: KClass<R>): R? {
val collection = collections[className] val collection = collections[className]
val entity = collection?.get(id!!) val entity = collection?.get(id!!)
return entity as R? return entity as R?
} }
inline fun <I, reified R : EntityI<I?>> get(id: I): R? { inline fun <I, reified R: EntityI<I?>> get(id: I): R? {
return get(id, R::class) return get(id, R::class)
} }
fun <I, R : EntityI<out I?>> set(entity: R): EntitiesCollections { fun <I, R: EntityI<out I?>> set(entity: R): EntitiesCollections {
if (collections[entity.className] == null) { if (collections[entity.className] == null) {
collections[entity.className] = EntityCollection() collections[entity.className] = EntityCollection()
} }
@@ -25,7 +25,7 @@ class EntitiesCollections {
return this return this
} }
class EntityCollection<T, E : EntityI<T?>> { class EntityCollection<T, E: EntityI<T?>> {
private var collection: MutableMap<T, E> = mutableMapOf() private var collection: MutableMap<T, E> = mutableMapOf()
fun get(id: T): E? { fun get(id: T): E? {

View File

@@ -12,22 +12,22 @@ interface EntityI<T> {
@JsonIgnore() get() = this::class as KClass<EntityI<T?>> @JsonIgnore() get() = this::class as KClass<EntityI<T?>>
} }
abstract class Entity<T>(override var id: T? = null) : EntityI<T?> abstract class Entity<T>(override var id: T? = null): EntityI<T?>
abstract class UuidEntity(override var id: UUID? = UUID.randomUUID()) : Entity<UUID?>(id) abstract class UuidEntity(override var id: UUID? = UUID.randomUUID()): Entity<UUID?>(id)
abstract class IdEntity(override var id: Int? = null) : Entity<Int?>(id) abstract class IdEntity(override var id: Int? = null): Entity<Int?>(id)
/* Version */ /* Version */
interface EntityVersioning<T> { interface EntityVersioning<T> {
var version: T var version: T
} }
interface EntityVersioningIncrement : EntityVersioning<Int?> interface EntityVersioningIncrement: EntityVersioning<Int?>
class EntityVersioningIncrementImp() : EntityVersioningIncrement { class EntityVersioningIncrementImp: EntityVersioningIncrement {
override var version: Int? = null override var version: Int? = null
} }
interface EntityVersioningDate : EntityVersioning<DateTime?> interface EntityVersioningDate: EntityVersioning<DateTime?>
class EntityVersioningDateImp() : EntityVersioningDate { class EntityVersioningDateImp: EntityVersioningDate {
override var version: DateTime? = null override var version: DateTime? = null
} }
@@ -40,15 +40,15 @@ interface EntityUpdatedAt {
var updatedAt: DateTime? var updatedAt: DateTime?
} }
class EntityCreatedAtImp : EntityCreatedAt { class EntityCreatedAtImp: EntityCreatedAt {
override var createdAt: DateTime? = null override var createdAt: DateTime? = null
} }
class EntityUpdatedAtImp : EntityUpdatedAt { class EntityUpdatedAtImp: EntityUpdatedAt {
override var updatedAt: DateTime? = null override var updatedAt: DateTime? = null
} }
interface User<T> : EntityI<T> { interface User<T>: EntityI<T> {
fun isValid(): Boolean fun isValid(): Boolean
} }
@@ -61,11 +61,11 @@ interface UpdatedBy<T> {
var updatedBy: User<T>? var updatedBy: User<T>?
} }
class EntityCreatedByImp<T> : CreatedBy<T> { class EntityCreatedByImp<T>: CreatedBy<T> {
override var createdBy: User<T>? = null override var createdBy: User<T>? = null
} }
class EntityUpdatedByImp<T> : UpdatedBy<T> { class EntityUpdatedByImp<T>: UpdatedBy<T> {
override var updatedBy: User<T>? = null override var updatedBy: User<T>? = null
} }
@@ -75,19 +75,19 @@ interface Published<UserT> {
var publishedBy: User<UserT>? var publishedBy: User<UserT>?
} }
class EntityPublishedImp<UserT> : Published<UserT> { class EntityPublishedImp<UserT>: Published<UserT> {
override var publishedAt: DateTime? = null override var publishedAt: DateTime? = null
override var publishedBy: User<UserT>? = null override var publishedBy: User<UserT>? = null
} }
/* Implementation */ /* Implementation */
abstract class EntityImp<T, UserT> : Entity<T>(), abstract class EntityImp<T, UserT>: Entity<T>(),
EntityCreatedAt by EntityCreatedAtImp(), EntityCreatedAt by EntityCreatedAtImp(),
EntityUpdatedAt by EntityUpdatedAtImp(), EntityUpdatedAt by EntityUpdatedAtImp(),
CreatedBy<UserT> by EntityCreatedByImp(), CreatedBy<UserT> by EntityCreatedByImp(),
UpdatedBy<UserT> by EntityUpdatedByImp() UpdatedBy<UserT> by EntityUpdatedByImp()
abstract class EntityExtended<T, UserT> : abstract class EntityExtended<T, UserT>:
EntityImp<T, UserT>(), EntityImp<T, UserT>(),
EntityVersioningIncrement by EntityVersioningIncrementImp(), EntityVersioningIncrement by EntityVersioningIncrementImp(),
Published<UserT> by EntityPublishedImp() Published<UserT> by EntityPublishedImp()

View File

@@ -59,7 +59,7 @@ data class Function(
connection.inTransaction { connection.inTransaction {
up() up()
down() down()
it.sendQuery("ROLLBACK"); it.sendQuery("ROLLBACK")
}.join() }.join()
return Status.OK // TODO return Status.OK // TODO

View File

@@ -4,13 +4,15 @@ import fr.postgresjson.connexion.Requester
import fr.postgresjson.entity.EntitiesCollections import fr.postgresjson.entity.EntitiesCollections
import fr.postgresjson.entity.EntityI import fr.postgresjson.entity.EntityI
import fr.postgresjson.serializer.Serializer import fr.postgresjson.serializer.Serializer
import jdk.jfr.Experimental
import kotlin.reflect.KClass import kotlin.reflect.KClass
interface RepositoryI<T, E : EntityI<T?>> { interface RepositoryI<T, E: EntityI<T?>> {
val entityName: KClass<E> val entityName: KClass<E>
} }
abstract class Repository<T, E : EntityI<T?>>(override val entityName: KClass<E>) : RepositoryI<T, E> { @Experimental
abstract class Repository<T, E: EntityI<T?>>(override val entityName: KClass<E>): RepositoryI<T, E> {
abstract var requester: Requester abstract var requester: Requester
abstract fun getClassName(): String abstract fun getClassName(): String

View File

@@ -18,7 +18,6 @@ import fr.postgresjson.entity.UuidEntity
import java.io.IOException import java.io.IOException
import java.util.* import java.util.*
class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) { class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
var collection: EntitiesCollections = EntitiesCollections() var collection: EntitiesCollections = EntitiesCollections()
@@ -35,11 +34,11 @@ class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
return mapper.writeValueAsString(source) return mapper.writeValueAsString(source)
} }
fun <E : EntityI<*>> deserialize(json: String, valueTypeRef: TypeReference<E>): E { fun <E: EntityI<*>> deserialize(json: String, valueTypeRef: TypeReference<E>): E {
return this.mapper.readValue(json, valueTypeRef) return this.mapper.readValue(json, valueTypeRef)
} }
inline fun <T, reified E : EntityI<T?>?> deserialize(json: String): E { inline fun <T, reified E: EntityI<T?>?> deserialize(json: String): E {
return this.mapper.readValue(json) return this.mapper.readValue(json)
} }
@@ -51,19 +50,19 @@ class Serializer(val mapper: ObjectMapper = jacksonObjectMapper()) {
return deserializeList(json, object: TypeReference<E>() {}) return deserializeList(json, object: TypeReference<E>() {})
} }
fun <E : EntityI<*>> deserialize(json: String, target: E): E { fun <E: EntityI<*>> deserialize(json: String, target: E): E {
return mapper.readerForUpdating(target).readValue<E>(json) return mapper.readerForUpdating(target).readValue<E>(json)
} }
} }
fun <T> EntityI<T?>.serialize() = Serializer().serialize(this) fun <T> EntityI<T?>.serialize() = Serializer().serialize(this)
inline fun <T, reified E : EntityI<T?>> E.deserialize(json: String) = Serializer().deserialize(json, this) inline fun <T, reified E: EntityI<T?>> E.deserialize(json: String) = Serializer().deserialize(json, this)
class EntityUuidDeserializer <T: UuidEntity> @JvmOverloads constructor(vc: Class<*>? = null) : StdDeserializer<T>(vc) { class EntityUuidDeserializer<T: UuidEntity> @JvmOverloads constructor(vc: Class<*>? = null): StdDeserializer<T>(vc) {
var collection: EntitiesCollections = EntitiesCollections() var collection: EntitiesCollections = EntitiesCollections()
constructor(collection: EntitiesCollections) : this() { constructor(collection: EntitiesCollections): this() {
this.collection = collection this.collection = collection
} }
@@ -78,10 +77,10 @@ class EntityUuidDeserializer <T: UuidEntity> @JvmOverloads constructor(vc: Class
} }
class EntityIdDeserializer <T: IdEntity> @JvmOverloads constructor(vc: Class<*>? = null) : StdDeserializer<T>(vc) { class EntityIdDeserializer<T: IdEntity> @JvmOverloads constructor(vc: Class<*>? = null): StdDeserializer<T>(vc) {
var collection: EntitiesCollections = EntitiesCollections() var collection: EntitiesCollections = EntitiesCollections()
constructor(collection: EntitiesCollections) : this() { constructor(collection: EntitiesCollections): this() {
this.collection = collection this.collection = collection
} }

View File

@@ -1,8 +0,0 @@
package fr.postgresjson.stopwatch
fun <T> elapse(callback: (start: Long) -> T, after: (elapse: Long) -> Unit): T {
val start = System.currentTimeMillis()
val result = callback(start)
after(System.currentTimeMillis() - start)
return result
}

View File

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