diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..c0b5eb66ca --- /dev/null +++ b/.editorconfig @@ -0,0 +1,2 @@ +[*.{kt,kts}] +disabled_rules=filename,no-wildcard-imports diff --git a/build.gradle.kts b/build.gradle.kts index 8f6f2eb5f3..dbbfa5b6de 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,9 +1,12 @@ plugins { kotlin("jvm") version "1.4.32" apply true id("io.github.gradle-nexus.publish-plugin") apply true + id("org.jmailen.kotlinter") version "3.3.0" } allprojects { + apply(plugin = "org.jmailen.kotlinter") + if (this.name != "exposed-tests" && this != rootProject) { apply(from = rootProject.file("buildScripts/gradle/publishing.gradle.kts")) } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/EntityID.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/EntityID.kt index 226db348d5..5c6ef6e445 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/EntityID.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/EntityID.kt @@ -1,7 +1,7 @@ package org.jetbrains.exposed.dao.id -open class EntityID> protected constructor(val table: IdTable, id: T?) : Comparable> { - constructor(id:T, table: IdTable) : this(table, id) +open class EntityID> protected constructor(val table: IdTable, id: T?) : Comparable> { + constructor(id: T, table: IdTable) : this(table, id) var _value: Any? = id val value: T get() { if (_value == null) { diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/IdTable.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/IdTable.kt index f22a554d31..4114f1e30a 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/IdTable.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/dao/id/IdTable.kt @@ -5,22 +5,22 @@ import org.jetbrains.exposed.sql.Table import java.util.* interface EntityIDFactory { - fun > createEntityID(value: T, table: IdTable) : EntityID + fun > createEntityID(value: T, table: IdTable): EntityID } object EntityIDFunctionProvider { - private val factory : EntityIDFactory + private val factory: EntityIDFactory init { factory = ServiceLoader.load(EntityIDFactory::class.java, EntityIDFactory::class.java.classLoader).firstOrNull() - ?: object : EntityIDFactory { - override fun > createEntityID(value: T, table: IdTable): EntityID { - return EntityID(value, table) - } + ?: object : EntityIDFactory { + override fun > createEntityID(value: T, table: IdTable): EntityID { + return EntityID(value, table) } + } } @Suppress("UNCHECKED_CAST") - fun > createEntityID(value: T, table: IdTable) = factory.createEntityID(value, table) + fun > createEntityID(value: T, table: IdTable) = factory.createEntityID(value, table) } /** @@ -28,8 +28,8 @@ object EntityIDFunctionProvider { * * @param name table name, by default name will be resolved from a class name with "Table" suffix removed (if present) */ -abstract class IdTable>(name: String = ""): Table(name) { - abstract val id : Column> +abstract class IdTable>(name: String = "") : Table(name) { + abstract val id: Column> } /** @@ -66,7 +66,7 @@ open class LongIdTable(name: String = "", columnName: String = "id") : IdTable(name) { override val id: Column> = uuid(columnName) - .autoGenerate() - .entityId() + .autoGenerate() + .entityId() override val primaryKey by lazy { super.primaryKey ?: PrimaryKey(id) } } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/AbstractQuery.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/AbstractQuery.kt index b6255513fc..1552559be5 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/AbstractQuery.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/AbstractQuery.kt @@ -87,4 +87,4 @@ abstract class AbstractQuery>(targets: List) : Sized return hasNext!! } } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Alias.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Alias.kt index 17f25a2ccb..da0ee84693 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Alias.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Alias.kt @@ -1,15 +1,14 @@ package org.jetbrains.exposed.sql - -class Alias(val delegate: T, val alias: String) : Table() { +class Alias(val delegate: T, val alias: String) : Table() { override val tableName: String get() = alias val tableNameWithAlias: String = "${delegate.tableName} AS $alias" - private fun Column.clone() = Column(this@Alias, name, columnType) + private fun Column.clone() = Column(this@Alias, name, columnType) - fun originalColumn(column: Column) : Column? { + fun originalColumn(column: Column): Column? { @Suppress("UNCHECKED_CAST") return if (column.table == this) delegate.columns.first { column.name == it.name } as Column @@ -35,7 +34,7 @@ class Alias(val delegate: T, val alias: String) : Table() { override fun hashCode(): Int = tableNameWithAlias.hashCode() @Suppress("UNCHECKED_CAST") - operator fun get(original: Column): Column = + operator fun get(original: Column): Column = delegate.columns.find { it == original }?.let { it.clone() as? Column } ?: error("Column not found in original table") } @@ -43,7 +42,7 @@ class Alias(val delegate: T, val alias: String) : Table() { class ExpressionAlias(val delegate: Expression, val alias: String) : Expression() { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append(delegate).append(" $alias") } - fun aliasOnlyExpression() : Expression { + fun aliasOnlyExpression(): Expression { return if (delegate is ExpressionWithColumnType) { object : Function(delegate.columnType) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append(alias) } @@ -56,14 +55,14 @@ class ExpressionAlias(val delegate: Expression, val alias: String) : Expre } } -class QueryAlias(val query: AbstractQuery<*>, val alias: String): ColumnSet() { +class QueryAlias(val query: AbstractQuery<*>, val alias: String) : ColumnSet() { - override fun describe(s: Transaction, queryBuilder: QueryBuilder) = queryBuilder{ + override fun describe(s: Transaction, queryBuilder: QueryBuilder) = queryBuilder { append("(") query.prepareSQL(queryBuilder) append(") ", alias) } - + override val columns: List> get() = query.set.source.columns.filter { it in query.set.fields }.map { it.clone() } @@ -79,40 +78,40 @@ class QueryAlias(val query: AbstractQuery<*>, val alias: String): ColumnSet() { return expressionAlias.delegate.alias("$alias.${expressionAlias.alias}").aliasOnlyExpression() } - override fun join(otherTable: ColumnSet, joinType: JoinType, onColumn: Expression<*>?, otherColumn: Expression<*>?, additionalConstraint: (SqlExpressionBuilder.()->Op)? ) : Join = - Join (this, otherTable, joinType, onColumn, otherColumn, additionalConstraint) + override fun join(otherTable: ColumnSet, joinType: JoinType, onColumn: Expression<*>?, otherColumn: Expression<*>?, additionalConstraint: (SqlExpressionBuilder.() -> Op)?): Join = + Join(this, otherTable, joinType, onColumn, otherColumn, additionalConstraint) - override infix fun innerJoin(otherTable: ColumnSet) : Join = Join (this, otherTable, JoinType.INNER) + override infix fun innerJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.INNER) - override infix fun leftJoin(otherTable: ColumnSet) : Join = Join (this, otherTable, JoinType.LEFT) + override infix fun leftJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.LEFT) - override infix fun rightJoin(otherTable: ColumnSet): Join = Join (this, otherTable, JoinType.RIGHT) + override infix fun rightJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.RIGHT) - override infix fun fullJoin(otherTable: ColumnSet): Join = Join (this, otherTable, JoinType.FULL) + override infix fun fullJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.FULL) - override infix fun crossJoin(otherTable: ColumnSet) : Join = Join (this, otherTable, JoinType.CROSS) + override infix fun crossJoin(otherTable: ColumnSet): Join = Join(this, otherTable, JoinType.CROSS) - private fun Column.clone() = Column(table.alias(alias), name, columnType) + private fun Column.clone() = Column(table.alias(alias), name, columnType) } -fun T.alias(alias: String) = Alias(this, alias) -fun > T.alias(alias: String) = QueryAlias(this, alias) +fun T.alias(alias: String) = Alias(this, alias) +fun > T.alias(alias: String) = QueryAlias(this, alias) fun Expression.alias(alias: String) = ExpressionAlias(this, alias) -fun Join.joinQuery(on: (SqlExpressionBuilder.(QueryAlias)->Op), joinType: JoinType = JoinType.INNER, joinPart: () -> AbstractQuery<*>): Join { +fun Join.joinQuery(on: (SqlExpressionBuilder.(QueryAlias) -> Op), joinType: JoinType = JoinType.INNER, joinPart: () -> AbstractQuery<*>): Join { val qAlias = joinPart().alias("q${joinParts.count { it.joinPart is QueryAlias }}") - return join (qAlias, joinType, additionalConstraint = { on(qAlias) } ) + return join(qAlias, joinType, additionalConstraint = { on(qAlias) }) } -fun Table.joinQuery(on: (SqlExpressionBuilder.(QueryAlias)->Op), joinType: JoinType = JoinType.INNER, joinPart: () -> AbstractQuery<*>) - = Join(this).joinQuery(on, joinType, joinPart) +fun Table.joinQuery(on: (SqlExpressionBuilder.(QueryAlias) -> Op), joinType: JoinType = JoinType.INNER, joinPart: () -> AbstractQuery<*>) = + Join(this).joinQuery(on, joinType, joinPart) val Join.lastQueryAlias: QueryAlias? get() = joinParts.map { it.joinPart as? QueryAlias }.firstOrNull() -fun wrapAsExpression(query: AbstractQuery<*>) = object : Expression() { +fun wrapAsExpression(query: AbstractQuery<*>) = object : Expression() { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append("(") query.prepareSQL(this) append(")") } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ColumnType.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ColumnType.kt index 4235d46dad..07e9701572 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ColumnType.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ColumnType.kt @@ -405,8 +405,6 @@ class DecimalColumnType( result = 31 * result + scale return result } - - } // Character columns @@ -467,7 +465,6 @@ abstract class StringColumnType( return result } - companion object { private val charactersToEscape = mapOf( '\'' to "\'\'", @@ -476,9 +473,6 @@ abstract class StringColumnType( '\n' to "\\n" ) } - - - } /** @@ -521,8 +515,6 @@ open class CharColumnType( result = 31 * result + colLength return result } - - } /** @@ -774,7 +766,8 @@ class EnumerationColumnType>( */ class EnumerationNameColumnType>( /** Returns the enum class used in this column type. */ - val klass: KClass, colLength: Int + val klass: KClass, + colLength: Int ) : VarCharColumnType(colLength) { @Suppress("UNCHECKED_CAST") override fun valueFromDB(value: Any): T = when (value) { @@ -814,5 +807,5 @@ class EnumerationNameColumnType>( * Marker interface for date/datetime related column types. **/ interface IDateColumnType { - val hasTimePart : Boolean + val hasTimePart: Boolean } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/CompositeColumn.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/CompositeColumn.kt index a1412bd4ec..96f07229ba 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/CompositeColumn.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/CompositeColumn.kt @@ -12,38 +12,37 @@ abstract class CompositeColumn : Expression() { * * @return key - real column, value - its parsed value */ - abstract fun getRealColumnsWithValues(compositeValue : T) : Map, Any?> + abstract fun getRealColumnsWithValues(compositeValue: T): Map, Any?> /** * Return list of real columns, wrapped by this composite column */ - abstract fun getRealColumns() : List> + abstract fun getRealColumns(): List> /** * Restore the composite value from its parts loaded from the DB */ - abstract fun restoreValueFromParts(parts : Map, Any?>) : T + abstract fun restoreValueFromParts(parts: Map, Any?>): T override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { getRealColumns().appendTo { +it } } - } /** * Extension of [CompositeColumn] which consists of two columns */ abstract class BiCompositeColumn( - protected val column1: Column, - protected val column2: Column, - val transformFromValue : (T) -> Pair, - val transformToValue: (Any?, Any?) -> T + protected val column1: Column, + protected val column2: Column, + val transformFromValue: (T) -> Pair, + val transformToValue: (Any?, Any?) -> T ) : CompositeColumn() { override fun getRealColumns(): List> = listOf(column1, column2) override fun getRealColumnsWithValues(compositeValue: T): Map, Any?> { - require (compositeValue != null || nullable) { + require(compositeValue != null || nullable) { "Can't set null value to non-nullable ${this::class.simpleName} column" } val (v1, v2) = transformFromValue(compositeValue) @@ -59,5 +58,4 @@ abstract class BiCompositeColumn( } return result as T } - } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Constraints.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Constraints.kt index 9353773b69..be6079ea32 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Constraints.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Constraints.kt @@ -47,11 +47,11 @@ enum class ReferenceOption { * Represents a foreign key constraint. */ data class ForeignKeyConstraint( - val target: Column<*>, - val from: Column<*>, - private val onUpdate: ReferenceOption?, - private val onDelete: ReferenceOption?, - private val name: String? + val target: Column<*>, + val from: Column<*>, + private val onUpdate: ReferenceOption?, + private val onDelete: ReferenceOption?, + private val name: String? ) : DdlAware { private val tx: Transaction get() = TransactionManager.current() @@ -76,7 +76,7 @@ data class ForeignKeyConstraint( /** Name of this constraint. */ val fkName: String get() = tx.db.identifierManager.cutIfNecessaryAndQuote( - name ?: "fk_${from.table.tableNameWithoutScheme}_${from.name}_${target.name}" + name ?: "fk_${from.table.tableNameWithoutScheme}_${from.name}_${target.name}" ).inProperCase() internal val foreignKeyPart: String get() = buildString { if (fkName.isNotBlank()) { diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Database.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Database.kt index af13e9e40b..536ef354ef 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Database.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Database.kt @@ -16,7 +16,7 @@ class Database private constructor(private val resolvedVendor: String? = null, v var useNestedTransactions: Boolean = false - internal fun metadata(body: ExposedDatabaseMetadata.() -> T) : T { + internal fun metadata(body: ExposedDatabaseMetadata.() -> T): T { val transaction = TransactionManager.currentOrNull() return if (transaction == null) { val connection = connector() @@ -58,8 +58,8 @@ class Database private constructor(private val resolvedVendor: String? = null, v companion object { private val dialects = ConcurrentHashMap DatabaseDialect>() - private val connectionInstanceImpl : DatabaseConnectionAutoRegistration = - ServiceLoader.load(DatabaseConnectionAutoRegistration::class.java, Database::class.java.classLoader).firstOrNull() ?: error("Can't load implementation for ${DatabaseConnectionAutoRegistration::class.simpleName}") + private val connectionInstanceImpl: DatabaseConnectionAutoRegistration = + ServiceLoader.load(DatabaseConnectionAutoRegistration::class.java, Database::class.java.classLoader).firstOrNull() ?: error("Can't load implementation for ${DatabaseConnectionAutoRegistration::class.simpleName}") private val driverMapping = mutableMapOf( "jdbc:h2" to "org.h2.Driver", @@ -93,7 +93,7 @@ class Database private constructor(private val resolvedVendor: String? = null, v registerDialect(MariaDBDialect.dialectName) { MariaDBDialect() } } - fun registerDialect(prefix:String, dialect: () -> DatabaseDialect) { + fun registerDialect(prefix: String, dialect: () -> DatabaseDialect) { dialects[prefix] = dialect } @@ -115,41 +115,53 @@ class Database private constructor(private val resolvedVendor: String? = null, v } } - fun connect(datasource: DataSource, setupConnection: (Connection) -> Unit = {}, - manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } + fun connect( + datasource: DataSource, + setupConnection: (Connection) -> Unit = {}, + manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } ): Database { return doConnect(explicitVendor = null, getNewConnection = { datasource.connection!! }, setupConnection = setupConnection, manager = manager) } @Deprecated(level = DeprecationLevel.ERROR, replaceWith = ReplaceWith("connectPool(datasource, setupConnection, manager)"), message = "Use connectPool instead") - fun connect(datasource: ConnectionPoolDataSource, setupConnection: (Connection) -> Unit = {}, - manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } + fun connect( + datasource: ConnectionPoolDataSource, + setupConnection: (Connection) -> Unit = {}, + manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } ): Database { return doConnect(explicitVendor = null, getNewConnection = { datasource.pooledConnection.connection!! }, setupConnection = setupConnection, manager = manager) } - fun connectPool(datasource: ConnectionPoolDataSource, setupConnection: (Connection) -> Unit = {}, - manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } + fun connectPool( + datasource: ConnectionPoolDataSource, + setupConnection: (Connection) -> Unit = {}, + manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } ): Database { return doConnect(explicitVendor = null, getNewConnection = { datasource.pooledConnection.connection!! }, setupConnection = setupConnection, manager = manager) } - fun connect(getNewConnection: () -> Connection, - manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } + fun connect( + getNewConnection: () -> Connection, + manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } ): Database { - return doConnect(explicitVendor = null, getNewConnection = getNewConnection, manager = manager ) + return doConnect(explicitVendor = null, getNewConnection = getNewConnection, manager = manager) } - fun connect(url: String, driver: String=getDriver(url), user: String = "", password: String = "", setupConnection: (Connection) -> Unit = {}, - manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } + fun connect( + url: String, + driver: String = getDriver(url), + user: String = "", + password: String = "", + setupConnection: (Connection) -> Unit = {}, + manager: (Database) -> TransactionManager = { ThreadLocalTransactionManager(it, DEFAULT_REPETITION_ATTEMPTS) } ): Database { Class.forName(driver).newInstance() - return doConnect(getDialectName(url), { DriverManager.getConnection(url, user, password) }, setupConnection, manager ) + return doConnect(getDialectName(url), { DriverManager.getConnection(url, user, password) }, setupConnection, manager) } - fun getDefaultIsolationLevel(db: Database) : Int = - when(db.vendor) { + fun getDefaultIsolationLevel(db: Database): Int = + when (db.vendor) { SQLiteDialect.dialectName -> Connection.TRANSACTION_SERIALIZABLE OracleDialect.dialectName -> Connection.TRANSACTION_READ_COMMITTED PostgreSQLDialect.dialectName -> Connection.TRANSACTION_READ_COMMITTED @@ -169,4 +181,4 @@ class Database private constructor(private val resolvedVendor: String? = null, v interface DatabaseConnectionAutoRegistration : (Connection) -> ExposedConnection<*> -val Database.name : String get() = url.substringAfterLast('/').substringBefore('?') +val Database.name: String get() = url.substringAfterLast('/').substringBefore('?') diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Exceptions.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Exceptions.kt index 09d2249146..94cd644098 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Exceptions.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Exceptions.kt @@ -2,7 +2,6 @@ package org.jetbrains.exposed.exceptions import org.jetbrains.exposed.sql.AbstractQuery -import org.jetbrains.exposed.sql.Query import org.jetbrains.exposed.sql.QueryBuilder import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.statements.StatementContext @@ -11,7 +10,7 @@ import org.jetbrains.exposed.sql.vendors.DatabaseDialect import java.sql.SQLException class ExposedSQLException(cause: Throwable?, val contexts: List, private val transaction: Transaction) : SQLException(cause) { - fun causedByQueries() : List = contexts.map { + fun causedByQueries(): List = contexts.map { try { if (transaction.debug) { it.expandArgs(transaction) @@ -29,7 +28,7 @@ class ExposedSQLException(cause: Throwable?, val contexts: List): QueryBuilder = apply(value::toQueryBuilder) - /** Appends the receiver [Char] to this [QueryBuilder]. */ operator fun Char.unaryPlus(): QueryBuilder = append(this) @@ -52,7 +50,6 @@ class QueryBuilder( /** Appends the receiver [Expression] to this [QueryBuilder]. */ operator fun Expression<*>.unaryPlus(): QueryBuilder = append(this) - /** Adds the specified [argument] as a value of the specified [column]. */ fun registerArgument(column: Column<*>, argument: T) { when (argument) { @@ -108,7 +105,6 @@ fun Iterable.appendTo( transform: QueryBuilder.(T) -> Unit ): QueryBuilder = builder.apply { this@appendTo.appendTo(separator, prefix, postfix, transform) } - /** * Represents an SQL expression of type [T]. */ diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Function.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Function.kt index 56d36d7652..780ae23ed1 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Function.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Function.kt @@ -42,7 +42,6 @@ open class CustomOperator( } } - // Mathematical Functions /** @@ -57,7 +56,6 @@ class Random( override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { +currentDialect.functionProvider.random(seed) } } - // String Functions /** @@ -130,7 +128,6 @@ class Trim( override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append("TRIM(", expr, ")") } } - // General-Purpose Aggregate Functions /** @@ -160,7 +157,8 @@ class Max, in S : T?>( */ class Avg, in S : T?>( /** Returns the expression from which the average is calculated. */ - val expr: Expression, scale: Int + val expr: Expression, + scale: Int ) : Function(DecimalColumnType(Int.MAX_VALUE, scale)) { override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append("AVG(", expr, ")") } } @@ -193,7 +191,6 @@ class Count( } } - // Aggregate Functions for Statistics /** @@ -244,7 +241,6 @@ class VarSamp( override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append("VAR_SAMP(", expr, ")") } } - // Sequence Manipulation Functions /** @@ -262,7 +258,6 @@ sealed class NextVal ( class LongNextVal(seq: Sequence) : NextVal(seq, LongColumnType()) } - // Conditional Expressions class Case(val value: Expression<*>? = null) { @@ -305,7 +300,6 @@ class Coalesce( override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append("COALESCE(", expr, ", ", alternate, ")") } } - // Value Expressions /** diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/IterableEx.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/IterableEx.kt index aff2c4aa47..d4443f9542 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/IterableEx.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/IterableEx.kt @@ -1,16 +1,16 @@ package org.jetbrains.exposed.sql -interface SizedIterable: Iterable { +interface SizedIterable : Iterable { fun limit(n: Int, offset: Long = 0): SizedIterable fun count(): Long fun empty(): Boolean fun forUpdate(): SizedIterable = this fun notForUpdate(): SizedIterable = this - fun copy() : SizedIterable - fun orderBy(vararg order: Pair, SortOrder>) : SizedIterable + fun copy(): SizedIterable + fun orderBy(vararg order: Pair, SortOrder>): SizedIterable } -fun emptySized() : SizedIterable = EmptySizedIterable() +fun emptySized(): SizedIterable = EmptySizedIterable() class EmptySizedIterable : SizedIterable, Iterator { override fun count(): Long = 0 @@ -32,7 +32,7 @@ class EmptySizedIterable : SizedIterable, Iterator { override fun orderBy(vararg order: Pair, SortOrder>): SizedIterable = this } -class SizedCollection(val delegate: Collection): SizedIterable { +class SizedCollection(val delegate: Collection) : SizedIterable { constructor(vararg values: T) : this(values.toList()) override fun limit(n: Int, offset: Long): SizedIterable { return if (offset >= Int.MAX_VALUE) @@ -48,7 +48,7 @@ class SizedCollection(val delegate: Collection): SizedIterable { override fun orderBy(vararg order: Pair, SortOrder>): SizedIterable = this } -class LazySizedCollection(_delegate: SizedIterable): SizedIterable { +class LazySizedCollection(_delegate: SizedIterable) : SizedIterable { private var delegate: SizedIterable = _delegate private var _wrapper: List? = null @@ -79,7 +79,7 @@ class LazySizedCollection(_delegate: SizedIterable): SizedIterable override fun notForUpdate(): SizedIterable { val localDelegate = delegate - if(_wrapper != null && localDelegate is Query && localDelegate.hasCustomForUpdateState() && localDelegate.isForUpdate()) { + if (_wrapper != null && localDelegate is Query && localDelegate.hasCustomForUpdateState() && localDelegate.isForUpdate()) { throw IllegalStateException("Impossible to change forUpdate state for loaded data") } if (_wrapper == null) { @@ -114,7 +114,7 @@ class LazySizedCollection(_delegate: SizedIterable): SizedIterable } } -infix fun SizedIterable.mapLazy(f:(T)->R):SizedIterable { +infix fun SizedIterable.mapLazy(f: (T) -> R): SizedIterable { val source = this return object : SizedIterable { override fun limit(n: Int, offset: Long): SizedIterable = source.copy().limit(n, offset).mapLazy(f) @@ -127,12 +127,11 @@ infix fun SizedIterable.mapLazy(f:(T)->R):SizedIterable { override operator fun iterator(): Iterator { val sourceIterator = source.iterator() - return object: Iterator { + return object : Iterator { override operator fun next(): R = f(sourceIterator.next()) override fun hasNext(): Boolean = sourceIterator.hasNext() } - } } } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Op.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Op.kt index e966c9c595..bf2f094734 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Op.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Op.kt @@ -37,7 +37,6 @@ abstract class Op : Expression() { } } - // Logical Operators /** @@ -50,7 +49,6 @@ class NotOp( override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append("NOT (", expr, ")") } } - /** * Marker interface which indicates that expression should be wrapped with braces when used in compound operators */ @@ -89,10 +87,12 @@ fun not(op: Expression): Op = NotOp(op) infix fun Expression.and(op: Expression): Op = when { this is AndOp && op is AndOp -> AndOp(expressions + op.expressions) this is AndOp -> AndOp(expressions + op) - op is AndOp -> AndOp(ArrayList>(op.expressions.size + 1).also { - it.add(this) - it.addAll(op.expressions) - }) + op is AndOp -> AndOp( + ArrayList>(op.expressions.size + 1).also { + it.add(this) + it.addAll(op.expressions) + } + ) else -> AndOp(listOf(this, op)) } @@ -100,10 +100,12 @@ infix fun Expression.and(op: Expression): Op = when { infix fun Expression.or(op: Expression): Op = when { this is OrOp && op is OrOp -> OrOp(expressions + op.expressions) this is OrOp -> OrOp(expressions + op) - op is OrOp -> OrOp(ArrayList>(op.expressions.size + 1).also { - it.add(this) - it.addAll(op.expressions) - }) + op is OrOp -> OrOp( + ArrayList>(op.expressions.size + 1).also { + it.add(this) + it.addAll(op.expressions) + } + ) else -> OrOp(listOf(this, op)) } @@ -125,7 +127,6 @@ inline fun Expression.andNot(op: SqlExpressionBuilder.() -> Op /** Returns the result of performing a logical `or` operation between this expression and the negate [op]. */ inline fun Expression.orNot(op: SqlExpressionBuilder.() -> Op): Op = or(not(Op.build(op))) - // Comparison Operators /** @@ -210,7 +211,6 @@ class IsNotNullOp( override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append(expr, " IS NOT NULL") } } - // Mathematical Operators /** @@ -261,7 +261,7 @@ class DivideOp( columnType: IColumnType ) : CustomOperator("/", columnType, dividend, divisor) { companion object { - fun DivideOp.withScale(scale: Int) : DivideOp { + fun DivideOp.withScale(scale: Int): DivideOp { val precision = (columnType as DecimalColumnType).precision + scale val decimalColumnType = DecimalColumnType(precision, scale) @@ -274,7 +274,6 @@ class DivideOp( } } - /** * Represents an SQL operator that calculates the remainder of dividing [expr1] by [expr2]. */ @@ -293,7 +292,6 @@ class ModOp( } } - // Pattern Matching /** @@ -328,7 +326,6 @@ class RegexpOp( @Deprecated("Use NotOp(RegexpOp()) instead", ReplaceWith("NotOp(RegexpOp(expr1, expr2, true))"), DeprecationLevel.ERROR) class NotRegexpOp(expr1: Expression<*>, expr2: Expression<*>) : ComparisonOp(expr1, expr2, "NOT REGEXP") - // Subquery Expressions /** @@ -393,7 +390,6 @@ class EqSubQueryOp(expr: Expression, query: AbstractQuery<*>) : SubQueryOp */ class NotEqSubQueryOp(expr: Expression, query: AbstractQuery<*>) : SubQueryOp("!=", expr, query) - // Array Comparisons /** @@ -438,7 +434,6 @@ class InListOrNotInListOp( } } - // Literals /** @@ -450,7 +445,6 @@ class LiteralOp( val value: T ) : ExpressionWithColumnType() { override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { +columnType.valueToString(value) } - } /** Returns the specified [value] as a boolean literal. */ @@ -494,7 +488,7 @@ fun doubleLiteral(value: Double): LiteralOp = LiteralOp(DoubleColumnType fun stringLiteral(value: String): LiteralOp = LiteralOp(TextColumnType(), value) /** Returns the specified [value] as a decimal literal. */ -fun decimalLiteral(value: BigDecimal) : LiteralOp = LiteralOp(DecimalColumnType(value.precision(), value.scale()), value.setScale(1)) +fun decimalLiteral(value: BigDecimal): LiteralOp = LiteralOp(DecimalColumnType(value.precision(), value.scale()), value.setScale(1)) // Query Parameters @@ -554,8 +548,7 @@ fun doubleParam(value: Double): Expression = QueryParameter(value, Doubl fun stringParam(value: String): Expression = QueryParameter(value, TextColumnType()) /** Returns the specified [value] as a decimal query parameter. */ -fun decimalParam(value: BigDecimal) : Expression = QueryParameter(value, DecimalColumnType(value.precision(), value.scale())) - +fun decimalParam(value: BigDecimal): Expression = QueryParameter(value, DecimalColumnType(value.precision(), value.scale())) // Misc. diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Queries.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Queries.kt index 3a5adb901f..901f9d94e9 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Queries.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Queries.kt @@ -10,14 +10,14 @@ import java.util.* /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testSelect01 */ -inline fun FieldSet.select(where: SqlExpressionBuilder.()->Op) : Query = select(SqlExpressionBuilder.where()) +inline fun FieldSet.select(where: SqlExpressionBuilder.() -> Op): Query = select(SqlExpressionBuilder.where()) -fun FieldSet.select(where: Op) : Query = Query(this, where) +fun FieldSet.select(where: Op): Query = Query(this, where) /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testSelectDistinct */ -fun FieldSet.selectAll() : Query = Query(this, null) +fun FieldSet.selectAll(): Query = Query(this, null) /** * That function will make multiple queries with limit equals to [batchSize] @@ -28,8 +28,8 @@ fun FieldSet.selectAll() : Query = Query(this, null) * @param where Where condition to be applied */ fun FieldSet.selectBatched( - batchSize: Int = 1000, - where: SqlExpressionBuilder.() -> Op + batchSize: Int = 1000, + where: SqlExpressionBuilder.() -> Op ): Iterable> { return selectBatched(batchSize, SqlExpressionBuilder.where()) } @@ -42,7 +42,7 @@ fun FieldSet.selectBatched( * @param batchSize Size of a sub-collections to return */ fun FieldSet.selectAllBatched( - batchSize: Int = 1000 + batchSize: Int = 1000 ): Iterable> { return selectBatched(batchSize, Op.TRUE) } @@ -50,10 +50,10 @@ fun FieldSet.selectAllBatched( /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testDelete01 */ -fun Table.deleteWhere(limit: Int? = null, offset: Long? = null, op: SqlExpressionBuilder.()->Op) = +fun Table.deleteWhere(limit: Int? = null, offset: Long? = null, op: SqlExpressionBuilder.() -> Op) = DeleteStatement.where(TransactionManager.current(), this@deleteWhere, SqlExpressionBuilder.op(), false, limit, offset) -fun Table.deleteIgnoreWhere(limit: Int? = null, offset: Long? = null, op: SqlExpressionBuilder.()->Op) = +fun Table.deleteIgnoreWhere(limit: Int? = null, offset: Long? = null, op: SqlExpressionBuilder.() -> Op) = DeleteStatement.where(TransactionManager.current(), this@deleteIgnoreWhere, SqlExpressionBuilder.op(), true, limit, offset) /** @@ -65,7 +65,7 @@ fun Table.deleteAll() = /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testInsert01 */ -fun T.insert(body: T.(InsertStatement)->Unit): InsertStatement = InsertStatement(this).apply { +fun T.insert(body: T.(InsertStatement) -> Unit): InsertStatement = InsertStatement(this).apply { body(this) execute(TransactionManager.current()) } @@ -73,7 +73,7 @@ fun T.insert(body: T.(InsertStatement)->Unit): InsertStatement /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testGeneratedKey03 */ -fun , T: IdTable> T.insertAndGetId(body: T.(InsertStatement>)->Unit) = +fun , T : IdTable> T.insertAndGetId(body: T.(InsertStatement>) -> Unit) = InsertStatement>(this, false).run { body(this) execute(TransactionManager.current()) @@ -83,14 +83,14 @@ fun , T: IdTable> T.insertAndGetId(body: T.(InsertState /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testBatchInsert01 */ -fun T.batchInsert( +fun T.batchInsert( data: Iterable, ignore: Boolean = false, shouldReturnGeneratedValues: Boolean = true, - body: BatchInsertStatement.(E)->Unit + body: BatchInsertStatement.(E) -> Unit ): List { if (data.count() == 0) return emptyList() - fun newBatchStatement() : BatchInsertStatement { + fun newBatchStatement(): BatchInsertStatement { return if (currentDialect is SQLServerDialect && this.autoIncColumn != null) { SQLServerBatchInsertStatement(this, ignore, shouldReturnGeneratedValues) } else { @@ -103,7 +103,7 @@ fun T.batchInsert( fun BatchInsertStatement.handleBatchException(removeLastData: Boolean = false, body: BatchInsertStatement.() -> Unit) { try { body() - if(removeLastData) + if (removeLastData) validateLastBatch() } catch (e: BatchDataInconsistentException) { if (this.data.size == 1) { @@ -137,12 +137,12 @@ fun T.batchInsert( return result } -fun T.insertIgnore(body: T.(UpdateBuilder<*>)->Unit): InsertStatement = InsertStatement(this, isIgnore = true).apply { +fun T.insertIgnore(body: T.(UpdateBuilder<*>) -> Unit): InsertStatement = InsertStatement(this, isIgnore = true).apply { body(this) execute(TransactionManager.current()) } -fun , T: IdTable> T.insertIgnoreAndGetId(body: T.(UpdateBuilder<*>)->Unit) = InsertStatement>(this, isIgnore = true).run { +fun , T : IdTable> T.insertIgnoreAndGetId(body: T.(UpdateBuilder<*>) -> Unit) = InsertStatement>(this, isIgnore = true).run { body(this) execute(TransactionManager.current()) getOrNull(id) @@ -151,7 +151,7 @@ fun , T: IdTable> T.insertIgnoreAndGetId(body: T.(Updat /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testReplace01 */ -fun T.replace(body: T.(UpdateBuilder<*>)->Unit): ReplaceStatement = ReplaceStatement(this).apply { +fun T.replace(body: T.(UpdateBuilder<*>) -> Unit): ReplaceStatement = ReplaceStatement(this).apply { body(this) execute(TransactionManager.current()) } @@ -159,24 +159,22 @@ fun T.replace(body: T.(UpdateBuilder<*>)->Unit): ReplaceStatement T.insert(selectQuery: AbstractQuery<*>, columns: List> = this.columns.filterNot { it.columnType.isAutoInc }) = +fun T.insert(selectQuery: AbstractQuery<*>, columns: List> = this.columns.filterNot { it.columnType.isAutoInc }) = InsertSelectStatement(columns, selectQuery).execute(TransactionManager.current()) - -fun T.insertIgnore(selectQuery: AbstractQuery<*>, columns: List> = this.columns.filterNot { it.columnType.isAutoInc }) = +fun T.insertIgnore(selectQuery: AbstractQuery<*>, columns: List> = this.columns.filterNot { it.columnType.isAutoInc }) = InsertSelectStatement(columns, selectQuery, true).execute(TransactionManager.current()) - /** * @sample org.jetbrains.exposed.sql.tests.shared.DMLTests.testUpdate01 */ -fun T.update(where: (SqlExpressionBuilder.()->Op)? = null, limit: Int? = null, body: T.(UpdateStatement)->Unit): Int { +fun T.update(where: (SqlExpressionBuilder.() -> Op)? = null, limit: Int? = null, body: T.(UpdateStatement) -> Unit): Int { val query = UpdateStatement(this, limit, where?.let { SqlExpressionBuilder.it() }) body(query) return query.execute(TransactionManager.current())!! } -fun Join.update(where: (SqlExpressionBuilder.()->Op)? = null, limit: Int? = null, body: (UpdateStatement)->Unit) : Int { +fun Join.update(where: (SqlExpressionBuilder.() -> Op)? = null, limit: Int? = null, body: (UpdateStatement) -> Unit): Int { val query = UpdateStatement(this, limit, where?.let { SqlExpressionBuilder.it() }) body(query) return query.execute(TransactionManager.current())!! @@ -214,10 +212,10 @@ fun checkExcessiveIndices(vararg tables: Table) { } } - val excessiveIndices = currentDialect.existingIndices(*tables).flatMap { it.value }.groupBy { Triple(it.table, it.unique, it.columns.joinToString { it.name }) }.filter { it.value.size > 1} + val excessiveIndices = currentDialect.existingIndices(*tables).flatMap { it.value }.groupBy { Triple(it.table, it.unique, it.columns.joinToString { it.name }) }.filter { it.value.size > 1 } if (excessiveIndices.isNotEmpty()) { exposedLogger.warn("List of excessive indices:") - excessiveIndices.forEach { (triple, indices)-> + excessiveIndices.forEach { (triple, indices) -> exposedLogger.warn("\t\t\t'${triple.first.tableName}'.'${triple.third}' -> ${indices.joinToString(", ") {it.indexName}}") } exposedLogger.info("SQL Queries to remove excessive indices:") @@ -230,8 +228,8 @@ fun checkExcessiveIndices(vararg tables: Table) { } private fun FieldSet.selectBatched( - batchSize: Int = 1000, - whereOp: Op + batchSize: Int = 1000, + whereOp: Op ): Iterable> { require(batchSize > 0) { "Batch size should be greater than 0" } @@ -247,9 +245,9 @@ private fun FieldSet.selectBatched( var lastOffset = 0L while (true) { val query = - select { whereOp and (autoIncColumn greater lastOffset) } - .limit(batchSize) - .orderBy(autoIncColumn, SortOrder.ASC) + select { whereOp and (autoIncColumn greater lastOffset) } + .limit(batchSize) + .orderBy(autoIncColumn, SortOrder.ASC) // query.iterator() executes the query val results = query.iterator().asSequence().toList() @@ -266,7 +264,7 @@ private fun FieldSet.selectBatched( } private fun toLong(autoIncVal: Any): Long = when (autoIncVal) { - is EntityID<*> ->toLong(autoIncVal.value) + is EntityID<*> -> toLong(autoIncVal.value) is Int -> autoIncVal.toLong() else -> autoIncVal as Long } @@ -315,7 +313,7 @@ private fun checkMissingIndices(vararg tables: Table): List { } } - notMappedIndices.getOrPut(table.nameInDatabaseCase()) {hashSetOf()}.addAll(existingTableIndices.subtract(mappedIndices)) + notMappedIndices.getOrPut(table.nameInDatabaseCase()) { hashSetOf() }.addAll(existingTableIndices.subtract(mappedIndices)) missingIndices.addAll(mappedIndices.subtract(existingTableIndices)) } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Query.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Query.kt index 0ae366e313..b7ef750a23 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Query.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Query.kt @@ -2,7 +2,6 @@ package org.jetbrains.exposed.sql import org.jetbrains.exposed.sql.statements.Statement import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi -import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.vendors.currentDialect import java.sql.ResultSet import java.util.* @@ -21,7 +20,7 @@ open class Query(override var set: FieldSet, where: Op?) : AbstractQuer private var forUpdate: Boolean? = null - //private set + // private set var where: Op? = where private set @@ -162,9 +161,11 @@ open class Query(override var set: FieldSet, where: Op?) : AbstractQuer try { var expInx = 0 adjustSlice { - slice(originalSet.fields.map { - it as? ExpressionAlias<*> ?: ((it as? Column<*>)?.makeAlias() ?: it.alias("exp${expInx++}")) - }) + slice( + originalSet.fields.map { + it as? ExpressionAlias<*> ?: ((it as? Column<*>)?.makeAlias() ?: it.alias("exp${expInx++}")) + } + ) } alias("subquery").selectAll().count() diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ResultRow.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ResultRow.kt index fbb6ea3f77..f1ad570acb 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ResultRow.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/ResultRow.kt @@ -5,7 +5,7 @@ import org.jetbrains.exposed.sql.vendors.withDialect import java.sql.ResultSet class ResultRow(val fieldIndex: Map, Int>) { - private val database : Database? = TransactionManager.currentOrNull()?.db + private val database: Database? = TransactionManager.currentOrNull()?.db private val data = arrayOfNulls(fieldIndex.size) /** @@ -20,8 +20,10 @@ class ResultRow(val fieldIndex: Map, Int>) { val d = getRaw(c) if (d == null && c is Column<*> && c.dbDefaultValue != null && !c.columnType.nullable) { - exposedLogger.warn("Column ${TransactionManager.current().fullIdentity(c)} is marked as not null, " + - "has default db value, but returns null. Possible have to re-read it from DB.") + exposedLogger.warn( + "Column ${TransactionManager.current().fullIdentity(c)} is marked as not null, " + + "has default db value, but returns null. Possible have to re-read it from DB." + ) } return database?.dialect?.let { @@ -36,7 +38,7 @@ class ResultRow(val fieldIndex: Map, Int>) { data[index] = value } - fun hasValue(c: Expression): Boolean = fieldIndex[c]?.let{ data[it] != NotInitializedValue } ?: false + fun hasValue(c: Expression): Boolean = fieldIndex[c]?.let { data[it] != NotInitializedValue } ?: false fun getOrNull(c: Expression): T? = if (hasValue(c)) rawToColumnValue(getRaw(c), c) else null @@ -72,7 +74,7 @@ class ResultRow(val fieldIndex: Map, Int>) { } override fun toString(): String = - fieldIndex.entries.joinToString { "${it.key}=${data[it.value]}" } + fieldIndex.entries.joinToString { "${it.key}=${data[it.value]}" } internal object NotInitializedValue @@ -85,23 +87,23 @@ class ResultRow(val fieldIndex: Map, Int>) { fun create(rs: ResultSet, fieldsIndex: Map, Int>): ResultRow { return ResultRow(fieldsIndex).apply { - fieldsIndex.forEach{ (field, index) -> + fieldsIndex.forEach { (field, index) -> val value = (field as? Column<*>)?.columnType?.readObject(rs, index + 1) ?: rs.getObject(index + 1) data[index] = value } } } - fun createAndFillValues(data: Map, Any?>) : ResultRow = - ResultRow(data.keys.mapIndexed { i, c -> c to i }.toMap()).also { row -> - data.forEach { (c, v) -> row[c] = v } - } + fun createAndFillValues(data: Map, Any?>): ResultRow = + ResultRow(data.keys.mapIndexed { i, c -> c to i }.toMap()).also { row -> + data.forEach { (c, v) -> row[c] = v } + } - fun createAndFillDefaults(columns : List>): ResultRow = - ResultRow(columns.mapIndexed { i, c -> c to i }.toMap()).apply { - columns.forEach { - this[it] = it.defaultValueFun?.invoke() ?: if (!it.columnType.nullable) NotInitializedValue else null - } + fun createAndFillDefaults(columns: List>): ResultRow = + ResultRow(columns.mapIndexed { i, c -> c to i }.toMap()).apply { + columns.forEach { + this[it] = it.defaultValueFun?.invoke() ?: if (!it.columnType.nullable) NotInitializedValue else null } + } } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLExpressionBuilder.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLExpressionBuilder.kt index a8a757ea04..e0394ea49e 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLExpressionBuilder.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLExpressionBuilder.kt @@ -33,7 +33,6 @@ fun Expression.substring(start: Int, length: Int): Substring /** Removes the longest string containing only spaces from both ends of string expression. */ fun Expression.trim(): Trim = Trim(this) - // General-Purpose Aggregate Functions /** Returns the minimum value of this expression across all non-null input values, or `null` if there are no non-null values. */ @@ -54,7 +53,6 @@ fun ExpressionWithColumnType<*>.count(): Count = Count(this) /** Returns the number of distinct input rows for which the value of this expression is not null. */ fun Column<*>.countDistinct(): Count = Count(this, true) - // Aggregate Functions for Statistics /** @@ -85,7 +83,6 @@ fun ExpressionWithColumnType.varPop(scale: Int = 2): VarPop = V */ fun ExpressionWithColumnType.varSamp(scale: Int = 2): VarSamp = VarSamp(this, scale) - // Sequence Manipulation Functions /** Advances this sequence and returns the new value. */ @@ -102,7 +99,6 @@ fun Sequence.nextLongVal(): NextVal = NextVal.LongNextVal(this) /** Specifies a conversion from one data type to another. */ fun Expression<*>.castTo(columnType: IColumnType): ExpressionWithColumnType = Cast(this, columnType) - // Misc. /** @@ -127,7 +123,7 @@ fun CustomLongFunction( ): CustomFunction = CustomFunction(functionName, LongColumnType(), *params) @Deprecated("Implement interface ISqlExpressionBuilder instead inherit this class") -open class SqlExpressionBuilderClass: ISqlExpressionBuilder +open class SqlExpressionBuilderClass : ISqlExpressionBuilder @Suppress("INAPPLICABLE_JVM_NAME") interface ISqlExpressionBuilder { @@ -159,7 +155,6 @@ interface ISqlExpressionBuilder { return EqOp(this, wrap(entityID)) } - /** Checks if this expression is not equals to some [other] value. */ infix fun ExpressionWithColumnType.neq(other: T): Op = if (other == null) isNotNull() else NeqOp(this, wrap(other)) @@ -169,7 +164,6 @@ interface ISqlExpressionBuilder { /** Checks if this expression is not equals to some [t] value. */ infix fun > ExpressionWithColumnType>.neq(t: T?): Op = if (t == null) isNotNull() else NeqOp(this, wrap(t)) - /** Checks if this expression is less than some [t] value. */ infix fun , S : T?> ExpressionWithColumnType.less(t: T): LessOp = LessOp(this, wrap(t)) @@ -180,7 +174,6 @@ interface ISqlExpressionBuilder { @JvmName("lessEntityID") infix fun > ExpressionWithColumnType>.less(t: T): LessOp = LessOp(this, wrap(t)) - /** Checks if this expression is less than or equal to some [t] value */ infix fun , S : T?> ExpressionWithColumnType.lessEq(t: T): LessEqOp = LessEqOp(this, wrap(t)) @@ -191,7 +184,6 @@ interface ISqlExpressionBuilder { @JvmName("lessEqEntityID") infix fun > ExpressionWithColumnType>.lessEq(t: T): LessEqOp = LessEqOp(this, wrap(t)) - /** Checks if this expression is greater than some [t] value. */ infix fun , S : T?> ExpressionWithColumnType.greater(t: T): GreaterOp = GreaterOp(this, wrap(t)) @@ -202,7 +194,6 @@ interface ISqlExpressionBuilder { @JvmName("greaterEntityID") infix fun > ExpressionWithColumnType>.greater(t: T): GreaterOp = GreaterOp(this, wrap(t)) - /** Checks if this expression is greater than or equal to some [t] value */ infix fun , S : T?> ExpressionWithColumnType.greaterEq(t: T): GreaterEqOp = GreaterEqOp(this, wrap(t)) @@ -213,7 +204,6 @@ interface ISqlExpressionBuilder { @JvmName("greaterEqEntityID") infix fun > ExpressionWithColumnType>.greaterEq(t: T): GreaterEqOp = GreaterEqOp(this, wrap(t)) - // Comparison Predicates /** Returns `true` if this expression is between the values [from] and [to], `false` otherwise. */ @@ -225,7 +215,6 @@ interface ISqlExpressionBuilder { /** Returns `true` if this expression is not null, `false` otherwise. */ fun Expression.isNotNull(): IsNotNullOp = IsNotNullOp(this) - // Mathematical Operators /** Adds the [t] value to this expression. */ @@ -234,42 +223,36 @@ interface ISqlExpressionBuilder { /** Adds the [other] expression to this expression. */ infix operator fun ExpressionWithColumnType.plus(other: Expression): PlusOp = PlusOp(this, other, columnType) - /** Subtracts the [t] value from this expression. */ infix operator fun ExpressionWithColumnType.minus(t: T): MinusOp = MinusOp(this, wrap(t), columnType) /** Subtracts the [other] expression from this expression. */ infix operator fun ExpressionWithColumnType.minus(other: Expression): MinusOp = MinusOp(this, other, columnType) - /** Multiplies this expression by the [t] value. */ infix operator fun ExpressionWithColumnType.times(t: T): TimesOp = TimesOp(this, wrap(t), columnType) /** Multiplies this expression by the [other] expression. */ infix operator fun ExpressionWithColumnType.times(other: Expression): TimesOp = TimesOp(this, other, columnType) - /** Divides this expression by the [t] value. */ infix operator fun ExpressionWithColumnType.div(t: T): DivideOp = DivideOp(this, wrap(t), columnType) /** Divides this expression by the [other] expression. */ infix operator fun ExpressionWithColumnType.div(other: Expression): DivideOp = DivideOp(this, other, columnType) - /** Calculates the remainder of dividing this expression by the [t] value. */ infix operator fun ExpressionWithColumnType.rem(t: S): ModOp = ModOp(this, wrap(t), columnType) /** Calculates the remainder of dividing this expression by the [other] expression. */ infix operator fun ExpressionWithColumnType.rem(other: Expression): ModOp = ModOp(this, other, columnType) - /** Calculates the remainder of dividing this expression by the [t] value. */ infix fun ExpressionWithColumnType.mod(t: S): ModOp = this % t /** Calculates the remainder of dividing this expression by the [other] expression. */ infix fun ExpressionWithColumnType.mod(other: Expression): ModOp = this % other - // String Functions /** Concatenates the text representations of all the [expr]. */ @@ -330,7 +313,6 @@ interface ISqlExpressionBuilder { @Deprecated("Use not(RegexpOp()) instead", ReplaceWith("regexp(pattern).not()"), DeprecationLevel.ERROR) infix fun ExpressionWithColumnType.notRegexp(pattern: String): Op = TODO() - // Conditional Expressions /** Returns the first of its arguments that is not null. */ @@ -339,7 +321,6 @@ interface ISqlExpressionBuilder { fun case(value: Expression<*>? = null): Case = Case(value) - // Subquery Expressions /** Checks if this expression is equals to any row returned from [query]. */ @@ -378,7 +359,6 @@ interface ISqlExpressionBuilder { return notInList(list.map { EntityIDFunctionProvider.createEntityID(it, idTable) }) } - // Misc. /** Returns the specified [value] as a query parameter of type [T]. */ @@ -426,4 +406,4 @@ interface ISqlExpressionBuilder { /** * Builder object for creating SQL expressions. */ -object SqlExpressionBuilder: ISqlExpressionBuilder +object SqlExpressionBuilder : ISqlExpressionBuilder diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLLog.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLLog.kt index e082b94bef..26f2347fef 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLLog.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SQLLog.kt @@ -8,12 +8,12 @@ import org.slf4j.LoggerFactory import java.util.* interface SqlLogger { - fun log (context: StatementContext, transaction: Transaction) + fun log(context: StatementContext, transaction: Transaction) } val exposedLogger = LoggerFactory.getLogger("Exposed")!! -inline fun logTimeSpent(message: String, block: ()->R) : R { +inline fun logTimeSpent(message: String, block: () -> R): R { val start = System.currentTimeMillis() val answer = block() exposedLogger.info(message + " took " + (System.currentTimeMillis() - start) + "ms") @@ -21,13 +21,13 @@ inline fun logTimeSpent(message: String, block: ()->R) : R { } object StdOutSqlLogger : SqlLogger { - override fun log (context: StatementContext, transaction: Transaction) { + override fun log(context: StatementContext, transaction: Transaction) { System.out.println("SQL: ${context.expandArgs(transaction)}") } } object Slf4jSqlDebugLogger : SqlLogger { - override fun log (context: StatementContext, transaction: Transaction) { + override fun log(context: StatementContext, transaction: Transaction) { if (exposedLogger.isDebugEnabled) { exposedLogger.debug(context.expandArgs(TransactionManager.current())) } @@ -37,15 +37,15 @@ object Slf4jSqlDebugLogger : SqlLogger { class CompositeSqlLogger : SqlLogger, StatementInterceptor { private val loggers: ArrayList = ArrayList(2) - fun addLogger (logger: SqlLogger) { + fun addLogger(logger: SqlLogger) { loggers.add(logger) } - fun removeLogger (logger: SqlLogger) { + fun removeLogger(logger: SqlLogger) { loggers.remove(logger) } - override fun log (context: StatementContext, transaction: Transaction) { + override fun log(context: StatementContext, transaction: Transaction) { for (logger in loggers) { logger.log(context, transaction) } @@ -58,9 +58,9 @@ class CompositeSqlLogger : SqlLogger, StatementInterceptor { } } -fun Transaction.addLogger(vararg logger: SqlLogger) : CompositeSqlLogger { +fun Transaction.addLogger(vararg logger: SqlLogger): CompositeSqlLogger { return CompositeSqlLogger().apply { logger.forEach { this.addLogger(it) } registerInterceptor(this) } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Schema.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Schema.kt index 181ccddca5..b4e1d0078b 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Schema.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Schema.kt @@ -19,13 +19,15 @@ import java.lang.StringBuilder * * */ -data class Schema(private val name: String, - val authorization: String? = null, - val password: String? = null, - val defaultTablespace: String? = null, - val temporaryTablespace: String? = null, - val quota: String? = null, - val on: String? = null) { +data class Schema( + private val name: String, + val authorization: String? = null, + val password: String? = null, + val defaultTablespace: String? = null, + val temporaryTablespace: String? = null, + val quota: String? = null, + val on: String? = null +) { val identifier get() = TransactionManager.current().db.identifierManager.cutIfNecessaryAndQuote(name) @@ -39,7 +41,7 @@ data class Schema(private val name: String, fun createStatement(): List { - if (!currentDialect.supportsCreateSchema ) { + if (!currentDialect.supportsCreateSchema) { throw UnsupportedByDialectException("The current dialect doesn't support create schema statement", currentDialect) } @@ -47,7 +49,7 @@ data class Schema(private val name: String, } fun dropStatement(cascade: Boolean): List { - if (!currentDialect.supportsCreateSchema ) { + if (!currentDialect.supportsCreateSchema) { throw UnsupportedByDialectException("The current dialect doesn't support drop schema statement", currentDialect) } @@ -55,7 +57,7 @@ data class Schema(private val name: String, } fun setSchemaStatement(): List { - if (!currentDialect.supportsCreateSchema ) { + if (!currentDialect.supportsCreateSchema) { throw UnsupportedByDialectException("The current dialect doesn't support schemas", currentDialect) } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SchemaUtils.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SchemaUtils.kt index 52dfed18b3..7101ef632a 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SchemaUtils.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/SchemaUtils.kt @@ -8,7 +8,7 @@ object SchemaUtils { private class TableDepthGraph(val tables: List
) { val graph = fetchAllTables().associate { t -> t to t.columns.mapNotNull { c -> - c.referee?.let{ it.table to c.columnType.nullable } + c.referee?.let { it.table to c.columnType.nullable } }.toMap() } @@ -26,7 +26,7 @@ object SchemaUtils { return result } - fun sorted() : List
{ + fun sorted(): List
{ val visited = mutableSetOf
() val result = arrayListOf
() @@ -46,18 +46,18 @@ object SchemaUtils { return result } - fun hasCycle() : Boolean { + fun hasCycle(): Boolean { val visited = mutableSetOf
() val recursion = mutableSetOf
() val sortedTables = sorted() - fun traverse(table: Table) : Boolean { + fun traverse(table: Table): Boolean { if (table in recursion) return true if (table in visited) return false recursion += table visited += table - return if (graph[table]!!.any{ traverse(it.key) }) { + return if (graph[table]!!.any { traverse(it.key) }) { true } else { recursion -= table @@ -118,7 +118,7 @@ object SchemaUtils { } for (table in tables) { - //create columns + // create columns val thisTableExistingColumns = existingTableColumns[table].orEmpty() val missingTableColumns = table.columns.filterNot { c -> thisTableExistingColumns.any { it.name.equals(c.name, true) } } missingTableColumns.flatMapTo(statements) { it.ddl } @@ -151,9 +151,10 @@ object SchemaUtils { val existingConstraint = existingColumnConstraint[table to column]?.firstOrNull() if (existingConstraint == null) { statements.addAll(createFKey(column)) - } else if (existingConstraint.target.table != foreignKey.target.table - || foreignKey.deleteRule != existingConstraint.deleteRule - || foreignKey.updateRule != existingConstraint.updateRule) { + } else if (existingConstraint.target.table != foreignKey.target.table || + foreignKey.deleteRule != existingConstraint.deleteRule || + foreignKey.updateRule != existingConstraint.updateRule + ) { statements.addAll(existingConstraint.dropStatement()) statements.addAll(createFKey(column)) } @@ -253,7 +254,6 @@ object SchemaUtils { } } - /** * Creates table with name "busy" (if not present) and single column to be used as "synchronization" point. Table wont be dropped after execution. * @@ -281,9 +281,9 @@ object SchemaUtils { if (tables.isEmpty()) return with(TransactionManager.current()) { var tablesForDeletion = - sortTablesByReferences(tables.toList()) - .reversed() - .filter { it in tables } + sortTablesByReferences(tables.toList()) + .reversed() + .filter { it in tables } if (!currentDialect.supportsIfNotExists) { tablesForDeletion = tablesForDeletion.filter { it.exists() } } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Sequence.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Sequence.kt index cb61fcec5c..d95fc1bd63 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Sequence.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Sequence.kt @@ -3,7 +3,6 @@ package org.jetbrains.exposed.sql import org.jetbrains.exposed.exceptions.UnsupportedByDialectException import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.vendors.currentDialect -import java.lang.StringBuilder /** * Database Sequence. @@ -16,13 +15,15 @@ import java.lang.StringBuilder * @param cycle Allows the sequence to wrap around when the [maxValue] or [minValue] has been reached by an ascending or descending sequence respectively. * @param cache Specifies how many sequence numbers are to be preallocated and stored in memory for faster access. */ -class Sequence(private val name: String, - val startWith: Long? = null, - val incrementBy: Long? = null, - val minValue: Long? = null, - val maxValue: Long? = null, - val cycle: Boolean? = null, - val cache: Long? = null) { +class Sequence( + private val name: String, + val startWith: Long? = null, + val incrementBy: Long? = null, + val minValue: Long? = null, + val maxValue: Long? = null, + val cycle: Boolean? = null, + val cache: Long? = null +) { val identifier get() = TransactionManager.current().db.identifierManager.cutIfNecessaryAndQuote(name) @@ -33,7 +34,7 @@ class Sequence(private val name: String, * Returns the SQL command that creates sequence with the specified properties. */ fun createStatement(): List { - if (!currentDialect.supportsCreateSequence ) { + if (!currentDialect.supportsCreateSequence) { throw UnsupportedByDialectException("The current dialect doesn't support create sequence statement", currentDialect) } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Table.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Table.kt index 7bfa3edd26..84bd37db3c 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Table.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Table.kt @@ -44,7 +44,6 @@ interface FieldSet { return unrolled } - } /** @@ -297,7 +296,6 @@ class Join( append(")") } } - } } @@ -364,7 +362,7 @@ open class Table(name: String = "") : ColumnSet(), DdlAware { /** Adds a column of the specified [type] and with the specified [name] to the table. */ fun registerColumn(name: String, type: IColumnType): Column = Column(this, name, type).also { _columns.addColumn(it) } - fun > registerCompositeColumn(column: T) : T = column.apply { getRealColumns().forEach { _columns.addColumn(it) } } + fun > registerCompositeColumn(column: T): T = column.apply { getRealColumns().forEach { _columns.addColumn(it) } } /** * Replaces the specified [oldColumn] with the specified [newColumn] in the table. @@ -459,14 +457,14 @@ open class Table(name: String = "") : ColumnSet(), DdlAware { */ @Deprecated( "This function will be no longer supported. Please use the new declarations of primary key by " + - "overriding the primaryKey property in the current table. " + - "Example : object TableName : Table() { override val primaryKey = PrimaryKey(column1, column2, name = \"CustomPKConstraintName\") }" + "overriding the primaryKey property in the current table. " + + "Example : object TableName : Table() { override val primaryKey = PrimaryKey(column1, column2, name = \"CustomPKConstraintName\") }" ) fun Column.primaryKey(indx: Int? = null): Column = apply { require(indx == null || table.columns.none { it.indexInPK == indx }) { "Table $tableName already contains PK at $indx" } indexInPK = indx ?: table.columns.count { it.indexInPK != null } + 1 exposedLogger.error( - "primaryKey(indx) method is deprecated. Use override val primaryKey=PrimaryKey() declaration instead." + "primaryKey(indx) method is deprecated. Use override val primaryKey=PrimaryKey() declaration instead." ) } @@ -633,11 +631,14 @@ open class Table(name: String = "") : ColumnSet(), DdlAware { sql: String? = null, fromDb: (Any) -> T, toDb: (T) -> Any - ): Column = registerColumn(name, object : StringColumnType() { - override fun sqlType(): String = sql ?: error("Column $name should exists in database ") - override fun valueFromDB(value: Any): T = if (value::class.isSubclassOf(Enum::class)) value as T else fromDb(value) - override fun notNullValueToDB(value: Any): Any = toDb(value as T) - }) + ): Column = registerColumn( + name, + object : StringColumnType() { + override fun sqlType(): String = sql ?: error("Column $name should exists in database ") + override fun valueFromDB(value: Any): T = if (value::class.isSubclassOf(Enum::class)) value as T else fromDb(value) + override fun notNullValueToDB(value: Any): Any = toDb(value as T) + } + ) // Auto-generated values @@ -726,11 +727,11 @@ open class Table(name: String = "") : ColumnSet(), DdlAware { fkName: String? = null ): C = apply { this.foreignKey = ForeignKeyConstraint( - target = ref, - from = this, - onUpdate = onUpdate, - onDelete = onDelete, - name = fkName + target = ref, + from = this, + onUpdate = onUpdate, + onDelete = onDelete, + name = fkName ) } @@ -753,11 +754,11 @@ open class Table(name: String = "") : ColumnSet(), DdlAware { fkName: String? = null ): C = apply { this.foreignKey = ForeignKeyConstraint( - target = ref, - from = this, - onUpdate = onUpdate, - onDelete = onDelete, - name = fkName + target = ref, + from = this, + onUpdate = onUpdate, + onDelete = onDelete, + name = fkName ) } @@ -915,7 +916,7 @@ open class Table(name: String = "") : ColumnSet(), DdlAware { } @Suppress("UNCHECKED_CAST") - fun > C.nullable(): CompositeColumn = apply { + fun > C.nullable(): CompositeColumn = apply { nullable = true getRealColumns().filter { !it.columnType.nullable }.forEach { (it as Column).nullable() } } as CompositeColumn @@ -1133,4 +1134,3 @@ fun ColumnSet.targetTables(): List
= when (this) { is Join -> this.table.targetTables() + this.joinParts.flatMap { it.joinPart.targetTables() } else -> error("No target provided for update") } - diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Transaction.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Transaction.kt index d234150c21..8c89158fa5 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Transaction.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Transaction.kt @@ -150,8 +150,8 @@ open class Transaction(private val transactionImpl: TransactionInterface) : User } fun identity(table: Table): String = - (table as? Alias<*>)?.let { "${identity(it.delegate)} ${db.identifierManager.quoteIfNecessary(it.alias)}"} - ?: db.identifierManager.quoteIfNecessary(table.tableName.inProperCase()) + (table as? Alias<*>)?.let { "${identity(it.delegate)} ${db.identifierManager.quoteIfNecessary(it.alias)}" } + ?: db.identifierManager.quoteIfNecessary(table.tableName.inProperCase()) fun fullIdentity(column: Column<*>): String = QueryBuilder(false).also { fullIdentity(column, it) @@ -166,7 +166,6 @@ open class Transaction(private val transactionImpl: TransactionInterface) : User append(identity(column)) } - fun identity(column: Column<*>): String = db.identifierManager.quoteIdentifierWhenWrongCaseOrNecessary(column.name) fun closeExecutedStatements() { @@ -186,4 +185,3 @@ open class Transaction(private val transactionImpl: TransactionInterface) : User } } } - diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Union.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Union.kt index 5ebfa70737..6dd2c401dd 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Union.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/Union.kt @@ -2,7 +2,6 @@ package org.jetbrains.exposed.sql import org.jetbrains.exposed.sql.statements.Statement import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi -import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.vendors.currentDialect import java.sql.ResultSet @@ -13,7 +12,7 @@ class Union( init { require(rawStatements.isNotEmpty()) { "UNION is empty" } require(rawStatements.none { it is Query && it.isForUpdate() }) { "FOR UPDATE is not allowed within UNION" } - require(rawStatements.all { it is AbstractQuery<*> }) { "Only Query or Union supported as statements for UNION"} + require(rawStatements.all { it is AbstractQuery<*> }) { "Only Query or Union supported as statements for UNION" } require(rawStatements.map { (it as AbstractQuery<*>).set.realFields.size }.distinct().size == 1) { "Each UNION query must have the same number of columns" } @@ -99,7 +98,6 @@ class Union( } } } - } fun Query.union(other: Query) = Union(unionAll = false, this, other) diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchInsertStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchInsertStatement.kt index 75fcb0720b..fba4afc60e 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchInsertStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchInsertStatement.kt @@ -6,10 +6,13 @@ import org.jetbrains.exposed.sql.transactions.TransactionManager import java.sql.ResultSet import java.util.* -class BatchDataInconsistentException(message : String) : Exception(message) +class BatchDataInconsistentException(message: String) : Exception(message) -open class BatchInsertStatement(table: Table, ignore: Boolean = false, - protected val shouldReturnGeneratedValues: Boolean = true): InsertStatement>(table, ignore) { +open class BatchInsertStatement( + table: Table, + ignore: Boolean = false, + protected val shouldReturnGeneratedValues: Boolean = true +) : InsertStatement>(table, ignore) { override val isAlwaysBatch = true diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchUpdateStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchUpdateStatement.kt index 4d34c0cc39..8dbcf285bd 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchUpdateStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/BatchUpdateStatement.kt @@ -9,7 +9,7 @@ import org.jetbrains.exposed.sql.Transaction import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import java.util.* -open class BatchUpdateStatement(val table: IdTable<*>): UpdateStatement(table, null) { +open class BatchUpdateStatement(val table: IdTable<*>) : UpdateStatement(table, null) { val data = ArrayList, Map, Any?>>>() override val firstDataSet: List, Any?>> get() = data.first().second.toList() @@ -36,11 +36,11 @@ open class BatchUpdateStatement(val table: IdTable<*>): UpdateStatement(table, n override fun update(column: Column, value: Expression) = error("Expressions unsupported in batch update") override fun prepareSQL(transaction: Transaction): String = - "${super.prepareSQL(transaction)} WHERE ${transaction.identity(table.id)} = ?" + "${super.prepareSQL(transaction)} WHERE ${transaction.identity(table.id)} = ?" override fun PreparedStatementApi.executeInternal(transaction: Transaction): Int = if (data.size == 1) executeUpdate() else executeBatch().sum() override fun arguments(): Iterable>> = data.map { (id, row) -> firstDataSet.map { it.first.columnType to row[it.first] } + (table.id.columnType to id) } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/DeleteStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/DeleteStatement.kt index 8b2d231310..6dc8e9874b 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/DeleteStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/DeleteStatement.kt @@ -3,7 +3,7 @@ package org.jetbrains.exposed.sql.statements import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi -open class DeleteStatement(val table: Table, val where: Op? = null, val isIgnore: Boolean = false, val limit: Int? = null, val offset: Long? = null): Statement(StatementType.DELETE, listOf(table)) { +open class DeleteStatement(val table: Table, val where: Op? = null, val isIgnore: Boolean = false, val limit: Int? = null, val offset: Long? = null) : Statement(StatementType.DELETE, listOf(table)) { override fun PreparedStatementApi.executeInternal(transaction: Transaction): Int { return executeUpdate() @@ -18,8 +18,8 @@ open class DeleteStatement(val table: Table, val where: Op? = null, val } companion object { - fun where(transaction: Transaction, table: Table, op: Op, isIgnore: Boolean = false, limit: Int? = null, offset: Long? = null): Int - = DeleteStatement(table, op, isIgnore, limit, offset).execute(transaction) ?: 0 + fun where(transaction: Transaction, table: Table, op: Op, isIgnore: Boolean = false, limit: Int? = null, offset: Long? = null): Int = + DeleteStatement(table, op, isIgnore, limit, offset).execute(transaction) ?: 0 fun all(transaction: Transaction, table: Table): Int = DeleteStatement(table).execute(transaction) ?: 0 } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertSelectStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertSelectStatement.kt index c9cdd72b16..7c833b11ab 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertSelectStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertSelectStatement.kt @@ -3,7 +3,7 @@ package org.jetbrains.exposed.sql.statements import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi -open class InsertSelectStatement(val columns: List>, val selectQuery: AbstractQuery<*>, val isIgnore: Boolean = false): Statement(StatementType.INSERT, listOf(columns.first().table)) { +open class InsertSelectStatement(val columns: List>, val selectQuery: AbstractQuery<*>, val isIgnore: Boolean = false) : Statement(StatementType.INSERT, listOf(columns.first().table)) { init { if (columns.isEmpty()) error("Can't insert without provided columns") @@ -12,7 +12,6 @@ open class InsertSelectStatement(val columns: List>, val selectQuery: if (columns.size != selectQuery.set.fields.size) error("Columns count doesn't equal to query columns count") } - override fun PreparedStatementApi.executeInternal(transaction: Transaction): Int? = executeUpdate() override fun arguments(): Iterable>> = selectQuery.arguments() diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertStatement.kt index 06f4ff6269..7c747048af 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertStatement.kt @@ -8,7 +8,7 @@ import org.jetbrains.exposed.sql.vendors.inProperCase import java.sql.ResultSet import java.sql.SQLException -open class InsertStatement(val table: Table, val isIgnore: Boolean = false) : UpdateBuilder(StatementType.INSERT, listOf(table)) { +open class InsertStatement(val table: Table, val isIgnore: Boolean = false) : UpdateBuilder(StatementType.INSERT, listOf(table)) { var resultedValues: List? = null private set @@ -37,7 +37,7 @@ open class InsertStatement(val table: Table, val isIgnore: Boolean = fa } } - val firstAutoIncColumn = autoIncColumns.firstOrNull() + val firstAutoIncColumn = autoIncColumns.firstOrNull() if (firstAutoIncColumn != null || returnedColumns.isNotEmpty()) { while (rs?.next() == true) { val returnedValues = returnedColumns.associateTo(mutableMapOf()) { it.first to rs.getObject(it.second) } @@ -97,7 +97,7 @@ open class InsertStatement(val table: Table, val isIgnore: Boolean = fa override fun prepareSQL(transaction: Transaction): String { val builder = QueryBuilder(true) val values = arguments!!.first() - val sql = if(values.isEmpty()) "" + val sql = if (values.isEmpty()) "" else with(builder) { values.appendTo(prefix = "VALUES (", postfix = ")") { (col, value) -> registerArgument(col, value) @@ -107,7 +107,7 @@ open class InsertStatement(val table: Table, val isIgnore: Boolean = fa return transaction.db.dialect.functionProvider.insert(isIgnore, table, values.map { it.first }, sql, transaction) } - protected open fun PreparedStatementApi.execInsertFunction() : Pair { + protected open fun PreparedStatementApi.execInsertFunction(): Pair { val inserted = if (arguments().count() > 1 || isAlwaysBatch) executeBatch().count() else executeUpdate() val rs = if (autoIncColumns.isNotEmpty()) { resultSet } else null return inserted to rs @@ -120,7 +120,7 @@ open class InsertStatement(val table: Table, val isIgnore: Boolean = fa } } - protected val autoIncColumns : List> get() { + protected val autoIncColumns: List> get() { val nextValExpressionColumns = values.filterValues { it is NextVal<*> }.keys return targets.flatMap { it.columns }.filter { column -> when { @@ -154,7 +154,7 @@ open class InsertStatement(val table: Table, val isIgnore: Boolean = fa listOf(result).apply { field = this } } - override fun arguments() : List>> { + override fun arguments(): List>> { return arguments!!.map { args -> val builder = QueryBuilder(true) args.filter { (_, value) -> diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/ReplaceStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/ReplaceStatement.kt index 255abb2da6..49ff9a670f 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/ReplaceStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/ReplaceStatement.kt @@ -3,6 +3,6 @@ package org.jetbrains.exposed.sql.statements import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.Transaction -open class ReplaceStatement(table: Table) : InsertStatement(table) { +open class ReplaceStatement(table: Table) : InsertStatement(table) { override fun prepareSQL(transaction: Transaction): String = transaction.db.dialect.functionProvider.replace(table, arguments!!.first(), transaction) } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/Statement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/Statement.kt index eff7cbe357..d87f7f845f 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/Statement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/Statement.kt @@ -8,7 +8,6 @@ import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi import java.sql.SQLException import java.util.* - internal object DefaultValueMarker { override fun toString(): String = "DEFAULT" } @@ -21,7 +20,7 @@ abstract class Statement(val type: StatementType, val targets: List
>> - open fun prepared(transaction: Transaction, sql: String) : PreparedStatementApi = + open fun prepared(transaction: Transaction, sql: String): PreparedStatementApi = transaction.connection.prepareStatement(sql, false) open val isAlwaysBatch: Boolean = false @@ -75,7 +74,7 @@ class StatementContext(val statement: Statement<*>, val args: Iterable(type: StatementType, targets: List
): Statement(type, targets) { +abstract class UpdateBuilder(type: StatementType, targets: List
) : Statement(type, targets) { protected val values: MutableMap, Any?> = LinkedHashMap() open operator fun set(column: Column, value: S) { @@ -21,29 +21,29 @@ abstract class UpdateBuilder(type: StatementType, targets: List
): } @JvmName("setWithEntityIdExpression") - operator fun , E: Expression> set(column: Column, value: E) { + operator fun , E : Expression> set(column: Column, value: E) { require(!values.containsKey(column)) { "$column is already initialized" } values[column] = value } @JvmName("setWithEntityIdValue") - operator fun , ID:EntityID, E: S?> set(column: Column, value: E) { + operator fun , ID : EntityID, E : S?> set(column: Column, value: E) { require(!values.containsKey(column)) { "$column is already initialized" } values[column] = value } - open operator fun > set(column: Column, value: E) = update(column, value) + open operator fun > set(column: Column, value: E) = update(column, value) open operator fun set(column: CompositeColumn, value: S) { column.getRealColumnsWithValues(value).forEach { (realColumn, itsValue) -> set(realColumn as Column, itsValue) } } - open fun update(column: Column, value: Expression) { + open fun update(column: Column, value: Expression) { require(!values.containsKey(column)) { "$column is already initialized" } values[column] = value } - open fun update(column: Column, value: SqlExpressionBuilder.() -> Expression) { + open fun update(column: Column, value: SqlExpressionBuilder.() -> Expression) { require(!values.containsKey(column)) { "$column is already initialized" } values[column] = SqlExpressionBuilder.value() } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/UpdateStatement.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/UpdateStatement.kt index b0a6ec2cb1..e8e422cace 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/UpdateStatement.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/UpdateStatement.kt @@ -4,7 +4,7 @@ import org.jetbrains.exposed.exceptions.throwUnsupportedException import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi -open class UpdateStatement(val targetsSet: ColumnSet, val limit: Int?, val where: Op? = null): UpdateBuilder(StatementType.UPDATE, targetsSet.targetTables()) { +open class UpdateStatement(val targetsSet: ColumnSet, val limit: Int?, val where: Op? = null) : UpdateBuilder(StatementType.UPDATE, targetsSet.targetTables()) { open val firstDataSet: List, Any?>> get() = values.toList() @@ -28,5 +28,4 @@ open class UpdateStatement(val targetsSet: ColumnSet, val limit: Int?, val where where?.toQueryBuilder(this) if (args.isNotEmpty()) listOf(args) else emptyList() } - } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ConnectionApi.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ConnectionApi.kt index a7a3c685b1..31ef210a03 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ConnectionApi.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ConnectionApi.kt @@ -1,6 +1,6 @@ package org.jetbrains.exposed.sql.statements.api -interface ExposedConnection { +interface ExposedConnection { val isClosed: Boolean fun commit() fun rollback() @@ -9,8 +9,8 @@ interface ExposedConnection { var transactionIsolation: Int val connection: OriginalConnection - fun prepareStatement(sql: String, returnKeys: Boolean) : PreparedStatementApi - fun prepareStatement(sql: String, columns: Array) : PreparedStatementApi + fun prepareStatement(sql: String, returnKeys: Boolean): PreparedStatementApi + fun prepareStatement(sql: String, columns: Array): PreparedStatementApi fun executeInBatch(sqls: List) var catalog: String @@ -18,9 +18,9 @@ interface ExposedConnection { fun metadata(body: ExposedDatabaseMetadata.() -> T): T - fun setSavepoint(name: String) : ExposedSavepoint + fun setSavepoint(name: String): ExposedSavepoint fun releaseSavepoint(savepoint: ExposedSavepoint) fun rollback(savepoint: ExposedSavepoint) -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedBlob.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedBlob.kt index f4a8913a00..a0bebaab30 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedBlob.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedBlob.kt @@ -11,4 +11,4 @@ class ExposedBlob(val bytes: ByteArray) { } override fun hashCode(): Int = bytes.contentHashCode() -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedDatabaseMetadata.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedDatabaseMetadata.kt index 097e73aafa..572018165c 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedDatabaseMetadata.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedDatabaseMetadata.kt @@ -16,9 +16,9 @@ abstract class ExposedDatabaseMetadata(val database: String) { abstract val defaultIsolationLevel: Int - abstract val supportsAlterTableWithAddColumn : Boolean - abstract val supportsMultipleResultSets : Boolean - abstract val supportsSelectForUpdate : Boolean + abstract val supportsAlterTableWithAddColumn: Boolean + abstract val supportsMultipleResultSets: Boolean + abstract val supportsSelectForUpdate: Boolean @Deprecated( message = "it's temporary solution which will be replaced in a future releases. Do not use it in your code", @@ -29,7 +29,7 @@ abstract class ExposedDatabaseMetadata(val database: String) { abstract val tableNames: Map> abstract val schemaNames: List - abstract fun columns(vararg tables: Table) : Map> + abstract fun columns(vararg tables: Table): Map> abstract fun existingIndices(vararg tables: Table): Map> @@ -38,4 +38,4 @@ abstract class ExposedDatabaseMetadata(val database: String) { abstract fun cleanCache() abstract val identifierManager: IdentifierManagerApi -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedSavepoint.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedSavepoint.kt index fdfc3e3208..277e7a7330 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedSavepoint.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/ExposedSavepoint.kt @@ -1,3 +1,3 @@ package org.jetbrains.exposed.sql.statements.api -abstract class ExposedSavepoint(val name: String) \ No newline at end of file +abstract class ExposedSavepoint(val name: String) diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/IdentifierManagerApi.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/IdentifierManagerApi.kt index 442be8e364..cb32902449 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/IdentifierManagerApi.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/IdentifierManagerApi.kt @@ -6,23 +6,23 @@ import org.jetbrains.exposed.sql.vendors.currentDialect import java.util.* abstract class IdentifierManagerApi { - abstract val quoteString : String - protected abstract val isUpperCaseIdentifiers : Boolean - protected abstract val isUpperCaseQuotedIdentifiers : Boolean - protected abstract val isLowerCaseIdentifiers : Boolean - protected abstract val isLowerCaseQuotedIdentifiers : Boolean - protected abstract val supportsMixedIdentifiers : Boolean - protected abstract val supportsMixedQuotedIdentifiers : Boolean - protected abstract fun dbKeywords() : List + abstract val quoteString: String + protected abstract val isUpperCaseIdentifiers: Boolean + protected abstract val isUpperCaseQuotedIdentifiers: Boolean + protected abstract val isLowerCaseIdentifiers: Boolean + protected abstract val isLowerCaseQuotedIdentifiers: Boolean + protected abstract val supportsMixedIdentifiers: Boolean + protected abstract val supportsMixedQuotedIdentifiers: Boolean + protected abstract fun dbKeywords(): List val keywords by lazy { ANSI_SQL_2003_KEYWORDS + VENDORS_KEYWORDS[currentDialect.name].orEmpty() + dbKeywords() } - protected abstract val extraNameCharacters : String - protected abstract val oracleVersion : OracleVersion - protected abstract val maxColumnNameLength : Int + protected abstract val extraNameCharacters: String + protected abstract val oracleVersion: OracleVersion + protected abstract val maxColumnNameLength: Int protected enum class OracleVersion { Oracle11g, Oracle12plus, NonOracle } protected val identifierLengthLimit by lazy { - when(oracleVersion) { + when (oracleVersion) { OracleVersion.Oracle11g -> 30 OracleVersion.Oracle12plus -> 128 else -> maxColumnNameLength.takeIf { it > 0 } ?: Int.MAX_VALUE @@ -36,15 +36,15 @@ abstract class IdentifierManagerApi { private fun String.isIdentifier() = !isEmpty() && first().isIdentifierStart() && all { it.isIdentifierStart() || it in '0'..'9' } private fun Char.isIdentifierStart(): Boolean = this in 'a'..'z' || this in 'A'..'Z' || this == '_' || this in extraNameCharacters - fun needQuotes (identity: String) : Boolean { + fun needQuotes(identity: String): Boolean { return checkedIdentities.getOrPut(identity.toLowerCase()) { !identity.isAlreadyQuoted() && (keywords.any { identity.equals(it, true) } || !identity.isIdentifier()) } } - private fun String.isAlreadyQuoted() = startsWith(quoteString) && endsWith(quoteString) + private fun String.isAlreadyQuoted() = startsWith(quoteString) && endsWith(quoteString) - fun shouldQuoteIdentifier(identity: String) : Boolean { + fun shouldQuoteIdentifier(identity: String): Boolean { val alreadyQuoted = identity.isAlreadyQuoted() val alreadyLower = identity == identity.toLowerCase() val alreadyUpper = identity == identity.toUpperCase() @@ -59,7 +59,7 @@ abstract class IdentifierManagerApi { } } - fun inProperCase(identity: String) : String { + fun inProperCase(identity: String): String { val alreadyQuoted = identity.isAlreadyQuoted() return when { alreadyQuoted && supportsMixedQuotedIdentifiers -> identity @@ -73,15 +73,15 @@ abstract class IdentifierManagerApi { } } - fun quoteIfNecessary (identity: String) : String { + fun quoteIfNecessary(identity: String): String { return if (identity.contains('.')) - identity.split('.').joinToString(".") {quoteTokenIfNecessary(it)} + identity.split('.').joinToString(".") { quoteTokenIfNecessary(it) } else { quoteTokenIfNecessary(identity) } } - fun quoteIdentifierWhenWrongCaseOrNecessary(identity: String) : String { + fun quoteIdentifierWhenWrongCaseOrNecessary(identity: String): String { val inProperCase = inProperCase(identity) return if (shouldQuoteIdentifier(identity) && inProperCase != identity) quote(identity) @@ -91,7 +91,7 @@ abstract class IdentifierManagerApi { fun cutIfNecessaryAndQuote(identity: String) = quoteIfNecessary(identity.take(identifierLengthLimit)) - private fun quoteTokenIfNecessary(token: String) : String = if (needQuotes(token)) quote(token) else token + private fun quoteTokenIfNecessary(token: String): String = if (needQuotes(token)) quote(token) else token private fun quote(identity: String) = "$quoteString$identity$quoteString".trim() -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/PreparedStatementApi.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/PreparedStatementApi.kt index 3ff6bd8950..2c3bfddc36 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/PreparedStatementApi.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/statements/api/PreparedStatementApi.kt @@ -18,9 +18,9 @@ interface PreparedStatementApi { fun addBatch() - fun executeQuery() : ResultSet + fun executeQuery(): ResultSet - fun executeUpdate() : Int + fun executeUpdate(): Int val resultSet: ResultSet? @@ -32,5 +32,5 @@ interface PreparedStatementApi { fun closeIfPossible() - fun executeBatch() : List -} \ No newline at end of file + fun executeBatch(): List +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/ThreadLocalTransactionManager.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/ThreadLocalTransactionManager.kt index 8ba3b050f6..611cfa9bd9 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/ThreadLocalTransactionManager.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/ThreadLocalTransactionManager.kt @@ -9,8 +9,10 @@ import org.jetbrains.exposed.sql.statements.api.ExposedConnection import org.jetbrains.exposed.sql.statements.api.ExposedSavepoint import java.sql.SQLException -class ThreadLocalTransactionManager(private val db: Database, - @Volatile override var defaultRepetitionAttempts: Int) : TransactionManager { +class ThreadLocalTransactionManager( + private val db: Database, + @Volatile override var defaultRepetitionAttempts: Int +) : TransactionManager { @Volatile override var defaultIsolationLevel: Int = -1 get() { @@ -23,14 +25,16 @@ class ThreadLocalTransactionManager(private val db: Database, val threadLocal = ThreadLocal() override fun newTransaction(isolation: Int, outerTransaction: Transaction?): Transaction = - (outerTransaction?.takeIf { !db.useNestedTransactions } ?: Transaction( - ThreadLocalTransaction( - db = db, - transactionIsolation = outerTransaction?.transactionIsolation ?: isolation, - threadLocal = threadLocal, - outerTransaction = outerTransaction + ( + outerTransaction?.takeIf { !db.useNestedTransactions } ?: Transaction( + ThreadLocalTransaction( + db = db, + transactionIsolation = outerTransaction?.transactionIsolation ?: isolation, + threadLocal = threadLocal, + outerTransaction = outerTransaction + ) ) - )).apply { + ).apply { bindTransactionToThread(this) } @@ -64,7 +68,6 @@ class ThreadLocalTransactionManager(private val db: Database, connection.setSavepoint(savepointName) } else null - override fun commit() { if (connectionLazy.isInitialized()) { if (!useSavePoints) { @@ -105,7 +108,7 @@ class ThreadLocalTransactionManager(private val db: Database, get() { var nestedLevel = 0 var currenTransaction = outerTransaction - while(currenTransaction?.outerTransaction != null) { + while (currenTransaction?.outerTransaction != null) { nestedLevel++ currenTransaction = currenTransaction.outerTransaction } @@ -126,7 +129,7 @@ fun transaction(transactionIsolation: Int, repetitionAttempts: Int, db: Data val transaction = outerManager.newTransaction(transactionIsolation, outer) try { transaction.statement().also { - if(outer.db.useNestedTransactions) + if (outer.db.useNestedTransactions) transaction.commit() } } finally { @@ -139,7 +142,7 @@ fun transaction(transactionIsolation: Int, repetitionAttempts: Int, db: Data try { TransactionManager.resetCurrent(existingForDb) transaction.statement().also { - if(db.useNestedTransactions) + if (db.useNestedTransactions) transaction.commit() } } finally { @@ -150,14 +153,14 @@ fun transaction(transactionIsolation: Int, repetitionAttempts: Int, db: Data } fun inTopLevelTransaction( - transactionIsolation: Int, - repetitionAttempts: Int, - db: Database? = null, - outerTransaction: Transaction? = null, - statement: Transaction.() -> T + transactionIsolation: Int, + repetitionAttempts: Int, + db: Database? = null, + outerTransaction: Transaction? = null, + statement: Transaction.() -> T ): T { - fun run():T { + fun run(): T { var repetitions = 0 val outerManager = outerTransaction?.db.transactionManager.takeIf { it.currentOrNull() != null } @@ -227,4 +230,4 @@ internal fun closeStatementsAndConnection(transaction: Transaction) { exposedLogger.warn("Statements close failed", e) } transaction.closeLoggingException { exposedLogger.warn("Transaction close failed: ${it.message}. Statement: $currentStatement", it) } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionApi.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionApi.kt index 392f882963..d7dae7962a 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionApi.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionApi.kt @@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicReference interface TransactionInterface { - val db : Database + val db: Database val connection: ExposedConnection<*> @@ -49,7 +49,7 @@ interface TransactionManager { var defaultRepetitionAttempts: Int - fun newTransaction(isolation: Int = defaultIsolationLevel, outerTransaction: Transaction? = null) : Transaction + fun newTransaction(isolation: Int = defaultIsolationLevel, outerTransaction: Transaction? = null): Transaction fun currentOrNull(): Transaction? @@ -71,7 +71,7 @@ interface TransactionManager { currentThreadManager.remove() } registeredDatabases[database] = manager - databases.push(database) + databases.push(database) } fun closeAndUnregister(database: Database) { @@ -96,8 +96,7 @@ interface TransactionManager { val manager: TransactionManager get() = currentThreadManager.get() - - fun resetCurrent(manager: TransactionManager?) { + fun resetCurrent(manager: TransactionManager?) { manager?.let { currentThreadManager.set(it) } ?: currentThreadManager.remove() } @@ -111,21 +110,21 @@ interface TransactionManager { } } -internal fun TransactionInterface.rollbackLoggingException(log: (Exception) -> Unit){ +internal fun TransactionInterface.rollbackLoggingException(log: (Exception) -> Unit) { try { rollback() - } catch (e: Exception){ + } catch (e: Exception) { log(e) } } -internal inline fun TransactionInterface.closeLoggingException(log: (Exception) -> Unit){ +internal inline fun TransactionInterface.closeLoggingException(log: (Exception) -> Unit) { try { close() - } catch (e: Exception){ + } catch (e: Exception) { log(e) } } val Database?.transactionManager: TransactionManager - get() = TransactionManager.managerFor(this) ?: throw RuntimeException("database $this don't have any transaction manager") \ No newline at end of file + get() = TransactionManager.managerFor(this) ?: throw RuntimeException("database $this don't have any transaction manager") diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionScope.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionScope.kt index 9d49686b37..eb0981cbda 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionScope.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionScope.kt @@ -6,10 +6,10 @@ import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty @Suppress("UNCHECKED_CAST") -fun transactionScope(init: Transaction.() -> T) = TransactionStore(init) as ReadWriteProperty -fun nullableTransactionScope() = TransactionStore() +fun transactionScope(init: Transaction.() -> T) = TransactionStore(init) as ReadWriteProperty +fun nullableTransactionScope() = TransactionStore() -class TransactionStore(val init: (Transaction.() -> T)? = null) : ReadWriteProperty { +class TransactionStore(val init: (Transaction.() -> T)? = null) : ReadWriteProperty { private val key = Key() @@ -25,7 +25,7 @@ class TransactionStore(val init: (Transaction.() -> T)? = null) : ReadWri } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { - TransactionManager.currentOrNull()?.let{ + TransactionManager.currentOrNull()?.let { if (value == null) it.removeUserData(key) else diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/experimental/Suspended.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/experimental/Suspended.kt index af02b9d2de..1b686afff9 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/experimental/Suspended.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/experimental/Suspended.kt @@ -58,7 +58,7 @@ suspend fun suspendedTransactionAsync( db: Database? = null, transactionIsolation: Int? = null, statement: suspend Transaction.() -> T -) : Deferred { +): Deferred { val currentTransaction = TransactionManager.currentOrNull() return withTransactionScope(context, null, db, transactionIsolation) { suspendedTransactionAsyncInternal(currentTransaction != tx, statement) @@ -79,22 +79,24 @@ private fun Transaction.closeAsync() { } } -private suspend fun withTransactionScope(context: CoroutineContext?, - currentTransaction: Transaction?, - db: Database? = null, - transactionIsolation: Int?, - body: suspend TransactionScope.() -> T) : T { +private suspend fun withTransactionScope( + context: CoroutineContext?, + currentTransaction: Transaction?, + db: Database? = null, + transactionIsolation: Int?, + body: suspend TransactionScope.() -> T +): T { val currentScope = coroutineContext[TransactionScope] - suspend fun newScope(_tx: Transaction?) : T { + suspend fun newScope(_tx: Transaction?): T { val manager = (_tx?.db ?: db)?.transactionManager ?: TransactionManager.manager - val tx = lazy(LazyThreadSafetyMode.NONE){ _tx ?: manager.newTransaction(transactionIsolation ?: manager.defaultIsolationLevel) } + val tx = lazy(LazyThreadSafetyMode.NONE) { _tx ?: manager.newTransaction(transactionIsolation ?: manager.defaultIsolationLevel) } val element = TransactionCoroutineElement(tx, manager) val newContext = context ?: coroutineContext - return TransactionScope(tx, newContext + element).body() + return TransactionScope(tx, newContext + element).body() } val sameTransaction = currentTransaction == currentScope?.tx val sameContext = context == coroutineContext @@ -106,7 +108,8 @@ private suspend fun withTransactionScope(context: CoroutineContext?, } private fun TransactionScope.suspendedTransactionAsyncInternal( - shouldCommit: Boolean, statement: suspend Transaction.() -> T + shouldCommit: Boolean, + statement: suspend Transaction.() -> T ): Deferred = async { val transaction = tx.value try { @@ -123,4 +126,4 @@ private fun TransactionScope.suspendedTransactionAsyncInternal( } finally { if (shouldCommit) transaction.closeAsync() } -} \ No newline at end of file +} diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Default.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Default.kt index 509b31335c..ea1a9b31b9 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Default.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Default.kt @@ -409,7 +409,7 @@ abstract class FunctionProvider { limit: Int?, where: Op?, transaction: Transaction - ) : String = transaction.throwUnsupportedException("UPDATE with a join clause is unsupported") + ): String = transaction.throwUnsupportedException("UPDATE with a join clause is unsupported") /** * Returns the SQL command that insert a new row into a table, but if another row with the same primary/unique key already exists then it updates the values of that row instead. @@ -587,7 +587,7 @@ interface DatabaseDialect { fun dropSchema(schema: Schema, cascade: Boolean): String = buildString { append("DROP SCHEMA IF EXISTS ", schema.identifier) - if(cascade) { + if (cascade) { append(" CASCADE") } } @@ -672,7 +672,6 @@ abstract class VendorDialect( columnConstraintsCache[table.nameInDatabaseCase()].orEmpty().forEach { constraints.getOrPut(it.from.table to it.from) { arrayListOf() }.add(it) } - } return constraints } @@ -734,7 +733,7 @@ abstract class VendorDialect( private val explicitDialect = ThreadLocal() -internal fun withDialect(dialect: DatabaseDialect, body: () -> T) : T { +internal fun withDialect(dialect: DatabaseDialect, body: () -> T): T { return try { explicitDialect.set(dialect) body() diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/H2.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/H2.kt index 74ffd8eaf2..b751cdd5ab 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/H2.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/H2.kt @@ -36,7 +36,7 @@ internal object H2FunctionProvider : FunctionProvider() { ): String { val uniqueIdxCols = table.indices.filter { it.unique }.flatMap { it.columns.toList() } val primaryKeys = table.primaryKey?.columns?.toList() ?: emptyList() - val uniqueCols = (uniqueIdxCols + primaryKeys).distinct() + val uniqueCols = (uniqueIdxCols + primaryKeys).distinct() val borderDate = Date(118, 2, 18) return when { // INSERT IGNORE support added in H2 version 1.4.197 (2018-03-18) @@ -117,9 +117,9 @@ internal object H2FunctionProvider : FunctionProvider() { */ open class H2Dialect : VendorDialect(dialectName, H2DataTypeProvider, H2FunctionProvider) { - private var isMySQLMode : Boolean? = null + private var isMySQLMode: Boolean? = null - internal fun isMySQLMode() : Boolean { + internal fun isMySQLMode(): Boolean { return isMySQLMode ?: TransactionManager.currentOrNull()?.let { tr -> tr.exec("SELECT VALUE FROM INFORMATION_SCHEMA.SETTINGS WHERE NAME = 'MODE'") { rs -> diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Mysql.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Mysql.kt index f93614aa48..4d211be92c 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Mysql.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/Mysql.kt @@ -141,20 +141,20 @@ open class MysqlDialect : VendorDialect(dialectName, MysqlDataTypeProvider, Mysq val constraintsToLoad = HashMap>() tr.exec( "SELECT\n" + - " rc.CONSTRAINT_NAME,\n" + - " ku.TABLE_NAME,\n" + - " ku.COLUMN_NAME,\n" + - " ku.REFERENCED_TABLE_NAME,\n" + - " ku.REFERENCED_COLUMN_NAME,\n" + - " rc.UPDATE_RULE,\n" + - " rc.DELETE_RULE\n" + - "FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n" + - " INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku\n" + - " ON ku.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA AND rc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME\n" + - "WHERE ku.TABLE_SCHEMA = $schemaName " + - " AND ku.CONSTRAINT_SCHEMA = $schemaName" + - " AND rc.CONSTRAINT_SCHEMA = $schemaName" + - " AND $inTableList" + " rc.CONSTRAINT_NAME,\n" + + " ku.TABLE_NAME,\n" + + " ku.COLUMN_NAME,\n" + + " ku.REFERENCED_TABLE_NAME,\n" + + " ku.REFERENCED_COLUMN_NAME,\n" + + " rc.UPDATE_RULE,\n" + + " rc.DELETE_RULE\n" + + "FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n" + + " INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku\n" + + " ON ku.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA AND rc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME\n" + + "WHERE ku.TABLE_SCHEMA = $schemaName " + + " AND ku.CONSTRAINT_SCHEMA = $schemaName" + + " AND rc.CONSTRAINT_SCHEMA = $schemaName" + + " AND $inTableList" ) { rs -> while (rs.next()) { val fromTableName = rs.getString("TABLE_NAME")!! @@ -195,10 +195,12 @@ open class MysqlDialect : VendorDialect(dialectName, MysqlDataTypeProvider, Mysq append("CREATE SCHEMA IF NOT EXISTS ", schema.identifier) if (schema.authorization != null) { - throw UnsupportedByDialectException("${currentDialect.name} do not have database owners. " + - "You can use GRANT to allow or deny rights on database.", currentDialect) + throw UnsupportedByDialectException( + "${currentDialect.name} do not have database owners. " + + "You can use GRANT to allow or deny rights on database.", + currentDialect + ) } - } override fun dropSchema(schema: Schema, cascade: Boolean): String = "DROP SCHEMA IF EXISTS ${schema.identifier}" diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/OracleDialect.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/OracleDialect.kt index 35df9728b9..85c7d86e1c 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/OracleDialect.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/OracleDialect.kt @@ -251,7 +251,7 @@ open class OracleDialect : VendorDialect(dialectName, OracleDataTypeProvider, Or override fun dropSchema(schema: Schema, cascade: Boolean): String = buildString { append("DROP USER ", schema.identifier) - if(cascade) { + if (cascade) { append(" CASCADE") } } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt index c608a9fbab..55f36af42a 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLServerDialect.kt @@ -32,7 +32,7 @@ internal object SQLServerFunctionProvider : FunctionProvider() { append("NEXT VALUE FOR ", seq.identifier) } - override fun random(seed: Int?): String = if (seed != null) "RAND(${seed})" else "RAND(CHECKSUM(NEWID()))" + override fun random(seed: Int?): String = if (seed != null) "RAND($seed)" else "RAND(CHECKSUM(NEWID()))" override fun groupConcat(expr: GroupConcat, queryBuilder: QueryBuilder) { val tr = TransactionManager.current() @@ -173,7 +173,7 @@ open class SQLServerDialect : VendorDialect(dialectName, SQLServerDataTypeProvid override fun dropSchema(schema: Schema, cascade: Boolean): String = buildString { append("DROP SCHEMA ", schema.identifier) - if(cascade) { + if (cascade) { append(" CASCADE") } } diff --git a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLiteDialect.kt b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLiteDialect.kt index 55f4576204..d5bff0ed37 100644 --- a/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLiteDialect.kt +++ b/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/vendors/SQLiteDialect.kt @@ -44,7 +44,7 @@ internal object SQLiteFunctionProvider : FunctionProvider() { return when { expr.orderBy.isNotEmpty() -> tr.throwUnsupportedException("SQLite doesn't support ORDER BY in GROUP_CONCAT function.") expr.distinct -> tr.throwUnsupportedException("SQLite doesn't support DISTINCT in GROUP_CONCAT function.") - else -> super.groupConcat(expr, queryBuilder)//.replace(" SEPARATOR ", ", ") + else -> super.groupConcat(expr, queryBuilder) // .replace(" SEPARATOR ", ", ") } } diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityID.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityID.kt index 5fbc2c9695..42e677017b 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityID.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityID.kt @@ -4,9 +4,8 @@ import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IdTable import org.jetbrains.exposed.sql.transactions.TransactionManager -class DaoEntityID>(id: T?, table: IdTable) : EntityID(table, id) { +class DaoEntityID>(id: T?, table: IdTable) : EntityID(table, id) { override fun invokeOnNoValue() { TransactionManager.current().entityCache.flushInserts(table) } } - diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityIDFactory.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityIDFactory.kt index 8a135f6543..6ca4d64b4d 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityIDFactory.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/DaoEntityIDFactory.kt @@ -8,4 +8,4 @@ class DaoEntityIDFactory : EntityIDFactory { override fun > createEntityID(value: T, table: IdTable): EntityID { return DaoEntityID(value, table) } -} \ No newline at end of file +} diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Deprecations.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Deprecations.kt index 017b64c6f2..37ebcedc6d 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Deprecations.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Deprecations.kt @@ -6,12 +6,12 @@ import org.jetbrains.exposed.sql.Table import java.util.* @Deprecated( - message = "Package was changed please re-import", - replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.EntityID"), - level = DeprecationLevel.WARNING + message = "Package was changed please re-import", + replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.EntityID"), + level = DeprecationLevel.WARNING ) -open class EntityID> protected constructor(val table: IdTable, id: T?) : Comparable> { - constructor(id:T, table: IdTable) : this(table, id) +open class EntityID> protected constructor(val table: IdTable, id: T?) : Comparable> { + constructor(id: T, table: IdTable) : this(table, id) var _value: Any? = id val value: T get() { if (_value == null) { @@ -39,37 +39,37 @@ open class EntityID> protected constructor(val table: IdTable } @Deprecated( - message = "Package was changed please re-import", - replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.IdTable"), - level = DeprecationLevel.HIDDEN + message = "Package was changed please re-import", + replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.IdTable"), + level = DeprecationLevel.HIDDEN ) -abstract class IdTable>(name: String = ""): Table(name) { - abstract val id : Column> +abstract class IdTable>(name: String = "") : Table(name) { + abstract val id: Column> } @Deprecated( - message = "Package was changed please re-import", - replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.IntIdTable"), - level = DeprecationLevel.HIDDEN + message = "Package was changed please re-import", + replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.IntIdTable"), + level = DeprecationLevel.HIDDEN ) -open class IntIdTable(name: String = "", columnName: String = "id") - : org.jetbrains.exposed.dao.id.IdTable(name) { +open class IntIdTable(name: String = "", columnName: String = "id") : + org.jetbrains.exposed.dao.id.IdTable(name) { override val id = integer(columnName).autoIncrement().primaryKey().entityId() } @Deprecated( - message = "Package was changed please re-import", - replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.LongIdTable"), - level = DeprecationLevel.WARNING + message = "Package was changed please re-import", + replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.LongIdTable"), + level = DeprecationLevel.WARNING ) open class LongIdTable(name: String = "", columnName: String = "id") : org.jetbrains.exposed.dao.id.IdTable(name) { override val id = long(columnName).autoIncrement().primaryKey().entityId() } @Deprecated( - message = "Package was changed please re-import", - replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.UUIDTable"), - level = DeprecationLevel.WARNING + message = "Package was changed please re-import", + replaceWith = ReplaceWith("org.jetbrains.exposed.dao.id.UUIDTable"), + level = DeprecationLevel.WARNING ) open class UUIDTable(name: String = "", columnName: String = "id") : org.jetbrains.exposed.dao.id.IdTable(name) { override val id = uuid(columnName).primaryKey().autoGenerate().entityId() diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Entity.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Entity.kt index d0f5a61077..b65ace51b5 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Entity.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/Entity.kt @@ -10,7 +10,7 @@ import kotlin.reflect.KProperty open class ColumnWithTransform(val column: Column, val toColumn: (TReal) -> TColumn, val toReal: (TColumn) -> TReal) -open class Entity>(val id: EntityID) { +open class Entity>(val id: EntityID) { var klass: EntityClass> by Delegates.notNull() internal set @@ -20,11 +20,11 @@ open class Entity>(val id: EntityID) { val writeValues = LinkedHashMap, Any?>() var _readValues: ResultRow? = null val readValues: ResultRow - get() = _readValues ?: run { - val table = klass.table - _readValues = klass.searchQuery( Op.build {table.id eq id }).firstOrNull() ?: table.select { table.id eq id }.first() - _readValues!! - } + get() = _readValues ?: run { + val table = klass.table + _readValues = klass.searchQuery(Op.build { table.id eq id }).firstOrNull() ?: table.select { table.id eq id }.first() + _readValues!! + } internal fun isNewEntity(): Boolean { val cache = TransactionManager.current().entityCache @@ -54,7 +54,7 @@ open class Entity>(val id: EntityID) { _readValues = reloaded.readValues } - operator fun , RID:Comparable, T: Entity> Reference.getValue(o: Entity, desc: KProperty<*>): T { + operator fun , RID : Comparable, T : Entity> Reference.getValue(o: Entity, desc: KProperty<*>): T { val refValue = reference.getValue(o, desc) return when { refValue is EntityID<*> && reference.referee() == factory.table.id -> factory.findById(refValue.value as RID) @@ -62,14 +62,14 @@ open class Entity>(val id: EntityID) { } ?: error("Cannot find ${factory.table.tableName} WHERE id=$refValue") } - operator fun , RID:Comparable, T: Entity> Reference.setValue(o: Entity, desc: KProperty<*>, value: T) { + operator fun , RID : Comparable, T : Entity> Reference.setValue(o: Entity, desc: KProperty<*>, value: T) { if (db != value.db) error("Can't link entities from different databases.") value.id.value // flush before creating reference on it val refValue = value.run { reference.referee()!!.getValue(this, desc) } reference.setValue(o, desc, refValue) } - operator fun , RID:Comparable, T: Entity> OptionalReference.getValue(o: Entity, desc: KProperty<*>): T? { + operator fun , RID : Comparable, T : Entity> OptionalReference.getValue(o: Entity, desc: KProperty<*>): T? { val refValue = reference.getValue(o, desc) return when { refValue == null -> null @@ -78,7 +78,7 @@ open class Entity>(val id: EntityID) { } } - operator fun , RID:Comparable, T: Entity> OptionalReference.setValue(o: Entity, desc: KProperty<*>, value: T?) { + operator fun , RID : Comparable, T : Entity> OptionalReference.setValue(o: Entity, desc: KProperty<*>, value: T?) { if (value != null && db != value.db) error("Can't link entities from different databases.") value?.id?.value // flush before creating reference on it val refValue = value?.run { reference.referee()!!.getValue(this, desc) } @@ -93,7 +93,7 @@ open class Entity>(val id: EntityID) { } @Suppress("UNCHECKED_CAST") - fun Column.lookupInReadValues(found: (T?) -> R?, notFound: () -> R?): R? = + fun Column.lookupInReadValues(found: (T?) -> R?, notFound: () -> R?): R? = if (_readValues?.hasValue(this) == true) found(readValues[this]) else @@ -133,26 +133,26 @@ open class Entity>(val id: EntityID) { } operator fun ColumnWithTransform.getValue(o: Entity, desc: KProperty<*>): TReal = - toReal(column.getValue(o, desc)) + toReal(column.getValue(o, desc)) operator fun ColumnWithTransform.setValue(o: Entity, desc: KProperty<*>, value: TReal) { column.setValue(o, desc, toColumn(value)) } - infix fun , Target: Entity> EntityClass.via(table: Table): InnerTableLink, TID, Target> = - InnerTableLink(table, this@via) + infix fun , Target : Entity> EntityClass.via(table: Table): InnerTableLink, TID, Target> = + InnerTableLink(table, this@via) - fun , Target: Entity> EntityClass.via(sourceColumn: Column>, targetColumn: Column>) = - InnerTableLink(sourceColumn.table, this@via, sourceColumn, targetColumn) + fun , Target : Entity> EntityClass.via(sourceColumn: Column>, targetColumn: Column>) = + InnerTableLink(sourceColumn.table, this@via, sourceColumn, targetColumn) /** * Delete this entity. * * This will remove the entity from the database as well as the cache. */ - open fun delete(){ + open fun delete() { val table = klass.table - table.deleteWhere {table.id eq id} + table.deleteWhere { table.id eq id } klass.removeFromCache(this) TransactionManager.current().registerChange(klass, id, EntityChangeType.Removed) } @@ -168,13 +168,12 @@ open class Entity>(val id: EntityID) { // Store values before update to prevent flush inside UpdateStatement val _writeValues = writeValues.toMap() storeWrittenValues() - table.update({table.id eq id}) { + table.update({ table.id eq id }) { for ((c, v) in _writeValues) { it[c] = v } } - } - else { + } else { batch.addBatch(id) for ((c, v) in writeValues) { batch[c] = v @@ -194,7 +193,7 @@ open class Entity>(val id: EntityID) { for ((c, v) in writeValues) { _readValues!![c] = v } - if (klass.dependsOnColumns.any { it.table == klass.table && !_readValues!!.hasValue(it) } ) { + if (klass.dependsOnColumns.any { it.table == klass.table && !_readValues!!.hasValue(it) }) { _readValues = null } } diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityBatchUpdate.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityBatchUpdate.kt index 31676a909f..cf95723d45 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityBatchUpdate.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityBatchUpdate.kt @@ -26,7 +26,7 @@ class EntityBatchUpdate(val klass: EntityClass<*, Entity<*>>) { } fun execute(transaction: Transaction): Int { - val updateSets = data.filterNot {it.second.isEmpty()}.groupBy { it.second.keys } + val updateSets = data.filterNot { it.second.isEmpty() }.groupBy { it.second.keys } return updateSets.values.fold(0) { acc, set -> acc + BatchUpdateStatement(klass.table).let { it.data.addAll(set) diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityCache.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityCache.kt index f77665c4bf..6a0fd7cee0 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityCache.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityCache.kt @@ -5,9 +5,8 @@ import org.jetbrains.exposed.dao.id.IdTable import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transactionScope import java.util.* -import java.util.concurrent.CopyOnWriteArrayList -val Transaction.entityCache : EntityCache by transactionScope { EntityCache(this) } +val Transaction.entityCache: EntityCache by transactionScope { EntityCache(this) } @Suppress("UNCHECKED_CAST") class EntityCache(private val transaction: Transaction) { @@ -16,20 +15,20 @@ class EntityCache(private val transaction: Transaction) { val inserts = LinkedHashMap, MutableList>>() val referrers = HashMap, MutableMap, SizedIterable<*>>>() - private fun getMap(f: EntityClass<*, *>) : MutableMap> = getMap(f.table) + private fun getMap(f: EntityClass<*, *>): MutableMap> = getMap(f.table) - private fun getMap(table: IdTable<*>) : MutableMap> = data.getOrPut(table) { + private fun getMap(table: IdTable<*>): MutableMap> = data.getOrPut(table) { LinkedHashMap() } - fun > getOrPutReferrers(sourceId: EntityID<*>, key: Column<*>, refs: ()-> SizedIterable): SizedIterable = - referrers.getOrPut(sourceId){ HashMap() }.getOrPut(key) { LazySizedCollection(refs()) } as SizedIterable + fun > getOrPutReferrers(sourceId: EntityID<*>, key: Column<*>, refs: () -> SizedIterable): SizedIterable = + referrers.getOrPut(sourceId) { HashMap() }.getOrPut(key) { LazySizedCollection(refs()) } as SizedIterable - fun , T: Entity> find(f: EntityClass, id: EntityID): T? = getMap(f)[id.value] as T? ?: inserts[f.table]?.firstOrNull { it.id == id } as? T + fun , T : Entity> find(f: EntityClass, id: EntityID): T? = getMap(f)[id.value] as T? ?: inserts[f.table]?.firstOrNull { it.id == id } as? T - fun , T: Entity> findAll(f: EntityClass): Collection = getMap(f).values as Collection + fun , T : Entity> findAll(f: EntityClass): Collection = getMap(f).values as Collection - fun , T: Entity> store(f: EntityClass, o: T) { + fun , T : Entity> store(f: EntityClass, o: T) { getMap(f)[o.id.value] = o } @@ -37,11 +36,11 @@ class EntityCache(private val transaction: Transaction) { getMap(o.klass.table)[o.id.value] = o } - fun , T: Entity> remove(table: IdTable, o: T) { + fun , T : Entity> remove(table: IdTable, o: T) { getMap(table).remove(o.id.value) } - fun , T: Entity> scheduleInsert(f: EntityClass, o: T) { + fun , T : Entity> scheduleInsert(f: EntityClass, o: T) { inserts.getOrPut(f.table) { arrayListOf() }.add(o as Entity<*>) } @@ -138,7 +137,7 @@ class EntityCache(private val transaction: Transaction) { transaction.registerChange(entry.klass, entry.id, EntityChangeType.Created) } toFlush = partition.second - } while(toFlush.isNotEmpty()) + } while (toFlush.isNotEmpty()) } } @@ -162,4 +161,4 @@ fun Transaction.flushCache(): List> { flush() return newEntities } -} \ No newline at end of file +} diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityClass.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityClass.kt index 608134c782..1dabc600ad 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityClass.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityClass.kt @@ -13,7 +13,7 @@ import kotlin.reflect.full.primaryConstructor import kotlin.sequences.Sequence @Suppress("UNCHECKED_CAST") -abstract class EntityClass, out T: Entity>(val table: IdTable, entityType: Class? = null) { +abstract class EntityClass, out T : Entity>(val table: IdTable, entityType: Class? = null) { internal val klass: Class<*> = entityType ?: javaClass.enclosingClass as Class private val ctor = klass.kotlin.primaryConstructor!! @@ -39,7 +39,7 @@ abstract class EntityClass, out T: Entity>(val table: Id * * @return The entity that has this id or null if no entity was found. */ - open fun findById(id: EntityID): T? = testCache(id) ?: find{table.id eq id}.firstOrNull() + open fun findById(id: EntityID): T? = testCache(id) ?: find { table.id eq id }.firstOrNull() /** * Reloads entity fields from database as new object. @@ -72,7 +72,7 @@ abstract class EntityClass, out T: Entity>(val table: Id fun testCache(id: EntityID): T? = warmCache().find(this, id) - fun testCache(cacheCheckCondition: T.()->Boolean): Sequence = warmCache().findAll(this).asSequence().filter { it.cacheCheckCondition() } + fun testCache(cacheCheckCondition: T.() -> Boolean): Sequence = warmCache().findAll(this).asSequence().filter { it.cacheCheckCondition() } fun removeFromCache(entity: Entity) { val cache = warmCache() @@ -81,7 +81,7 @@ abstract class EntityClass, out T: Entity>(val table: Id cache.removeTablesReferrers(listOf(table)) } - open fun forEntityIds(ids: List>) : SizedIterable { + open fun forEntityIds(ids: List>): SizedIterable { val distinctIds = ids.distinct() if (distinctIds.isEmpty()) return emptySized() @@ -94,7 +94,7 @@ abstract class EntityClass, out T: Entity>(val table: Id return wrapRows(searchQuery(Op.build { table.id inList distinctIds })) } - fun forIds(ids: List) : SizedIterable = forEntityIds(ids.map { DaoEntityID(it, table) }) + fun forIds(ids: List): SizedIterable = forEntityIds(ids.map { DaoEntityID(it, table) }) fun wrapRows(rows: SizedIterable): SizedIterable = rows mapLazy { wrapRow(it) @@ -109,7 +109,7 @@ abstract class EntityClass, out T: Entity>(val table: Id } @Suppress("MemberVisibilityCanBePrivate") - fun wrapRow(row: ResultRow) : T { + fun wrapRow(row: ResultRow): T { val entity = wrap(row[table.id], row) if (entity._readValues == null) entity._readValues = row @@ -117,8 +117,8 @@ abstract class EntityClass, out T: Entity>(val table: Id return entity } - fun wrapRow(row: ResultRow, alias: Alias>) : T { - require(alias.delegate == table) { "Alias for a wrong table ${alias.delegate.tableName} while ${table.tableName} expected"} + fun wrapRow(row: ResultRow, alias: Alias>): T { + require(alias.delegate == table) { "Alias for a wrong table ${alias.delegate.tableName} while ${table.tableName} expected" } val newFieldsMapping = row.fieldIndex.mapNotNull { (exp, _) -> val column = exp as? Column<*> val value = row[exp] @@ -132,8 +132,8 @@ abstract class EntityClass, out T: Entity>(val table: Id return wrapRow(ResultRow.createAndFillValues(newFieldsMapping)) } - fun wrapRow(row: ResultRow, alias: QueryAlias) : T { - require(alias.columns.any { (it.table as Alias<*>).delegate == table }) { "QueryAlias doesn't have any column from ${table.tableName} table"} + fun wrapRow(row: ResultRow, alias: QueryAlias): T { + require(alias.columns.any { (it.table as Alias<*>).delegate == table }) { "QueryAlias doesn't have any column from ${table.tableName} table" } val originalColumns = alias.query.set.source.columns val newFieldsMapping = row.fieldIndex.mapNotNull { (exp, _) -> val value = row[exp] @@ -141,7 +141,8 @@ abstract class EntityClass, out T: Entity>(val table: Id exp is Column && exp.table is Alias<*> -> { val delegate = (exp.table as Alias<*>).delegate val column = originalColumns.single { - delegate == it.table && exp.name == it.name } + delegate == it.table && exp.name == it.name + } column to value } exp is Column && exp.table == table -> null @@ -172,9 +173,9 @@ abstract class EntityClass, out T: Entity>(val table: Id * * @return All the entities that conform to the [op] statement. */ - fun find(op: SqlExpressionBuilder.()-> Op): SizedIterable = find(SqlExpressionBuilder.op()) + fun find(op: SqlExpressionBuilder.() -> Op): SizedIterable = find(SqlExpressionBuilder.op()) - fun findWithCacheCondition(cacheCheckCondition: T.()->Boolean, op: SqlExpressionBuilder.()-> Op): Sequence { + fun findWithCacheCondition(cacheCheckCondition: T.() -> Boolean, op: SqlExpressionBuilder.() -> Op): Sequence { val cached = testCache(cacheCheckCondition) return if (cached.any()) cached else find(op).asSequence() } @@ -183,7 +184,7 @@ abstract class EntityClass, out T: Entity>(val table: Id open val dependsOnColumns: List> get() = dependsOnTables.columns open fun searchQuery(op: Op): Query = - dependsOnTables.slice(dependsOnColumns).select { op }.setForUpdateStatus() + dependsOnTables.slice(dependsOnColumns).select { op }.setForUpdateStatus() /** * Count the amount of entities that conform to the [op] statement. @@ -192,14 +193,14 @@ abstract class EntityClass, out T: Entity>(val table: Id * * @return The amount of entities that conform to the [op] statement. */ - fun count(op: Op? = null): Long { + fun count(op: Op? = null): Long { val countExpression = table.id.count() val query = table.slice(countExpression).selectAll().notForUpdate() op?.let { query.adjustWhere { op } } return query.first()[countExpression] } - protected open fun createInstance(entityId: EntityID, row: ResultRow?) : T = ctor.call(entityId) as T + protected open fun createInstance(entityId: EntityID, row: ResultRow?): T = ctor.call(entityId) as T fun wrap(id: EntityID, row: ResultRow?): T { val transaction = TransactionManager.current() @@ -255,50 +256,50 @@ abstract class EntityClass, out T: Entity>(val table: Id return prototype } - inline fun view (op: SqlExpressionBuilder.() -> Op) = View(SqlExpressionBuilder.op(), this) + inline fun view(op: SqlExpressionBuilder.() -> Op) = View(SqlExpressionBuilder.op(), this) private val refDefinitions = HashMap, KClass<*>>, Any>() - private inline fun registerRefRule(column: Column<*>, ref:()-> R): R = - refDefinitions.getOrPut(column to R::class, ref) as R + private inline fun registerRefRule(column: Column<*>, ref: () -> R): R = + refDefinitions.getOrPut(column to R::class, ref) as R - infix fun > referencedOn(column: Column) = registerRefRule(column) { Reference(column, this) } + infix fun > referencedOn(column: Column) = registerRefRule(column) { Reference(column, this) } - infix fun > optionalReferencedOn(column: Column) = registerRefRule(column) { OptionalReference(column, this) } + infix fun > optionalReferencedOn(column: Column) = registerRefRule(column) { OptionalReference(column, this) } - infix fun , Target: Entity, REF:Comparable> EntityClass.backReferencedOn(column: Column) - : ReadOnlyProperty, Target> = registerRefRule(column) { BackReference(column, this) } + infix fun , Target : Entity, REF : Comparable> EntityClass.backReferencedOn(column: Column): + ReadOnlyProperty, Target> = registerRefRule(column) { BackReference(column, this) } @JvmName("backReferencedOnOpt") - infix fun , Target: Entity, REF:Comparable> EntityClass.backReferencedOn(column: Column) - : ReadOnlyProperty, Target> = registerRefRule(column) { BackReference(column, this) } + infix fun , Target : Entity, REF : Comparable> EntityClass.backReferencedOn(column: Column): + ReadOnlyProperty, Target> = registerRefRule(column) { BackReference(column, this) } - infix fun , Target: Entity, REF:Comparable> EntityClass.optionalBackReferencedOn(column: Column) - = registerRefRule(column) { OptionalBackReference, REF>(column as Column, this) } + infix fun , Target : Entity, REF : Comparable> EntityClass.optionalBackReferencedOn(column: Column) = + registerRefRule(column) { OptionalBackReference, REF>(column as Column, this) } @JvmName("optionalBackReferencedOnOpt") - infix fun , Target: Entity, REF:Comparable> EntityClass.optionalBackReferencedOn(column: Column) - = registerRefRule(column) { OptionalBackReference, REF>(column, this) } + infix fun , Target : Entity, REF : Comparable> EntityClass.optionalBackReferencedOn(column: Column) = + registerRefRule(column) { OptionalBackReference, REF>(column, this) } - infix fun , Target: Entity, REF: Comparable> EntityClass.referrersOn(column: Column) - = registerRefRule(column) { Referrers, TargetID, Target, REF>(column, this, true) } + infix fun , Target : Entity, REF : Comparable> EntityClass.referrersOn(column: Column) = + registerRefRule(column) { Referrers, TargetID, Target, REF>(column, this, true) } - fun , Target: Entity, REF: Comparable> EntityClass.referrersOn(column: Column, cache: Boolean) - = registerRefRule(column) { Referrers, TargetID, Target, REF>(column, this, cache) } + fun , Target : Entity, REF : Comparable> EntityClass.referrersOn(column: Column, cache: Boolean) = + registerRefRule(column) { Referrers, TargetID, Target, REF>(column, this, cache) } - infix fun , Target: Entity, REF: Comparable> EntityClass.optionalReferrersOn(column : Column) - = registerRefRule(column) { OptionalReferrers, TargetID, Target, REF>(column, this, true) } + infix fun , Target : Entity, REF : Comparable> EntityClass.optionalReferrersOn(column: Column) = + registerRefRule(column) { OptionalReferrers, TargetID, Target, REF>(column, this, true) } - fun , Target: Entity, REF: Comparable> EntityClass.optionalReferrersOn(column: Column, cache: Boolean = false) = - registerRefRule(column) { OptionalReferrers, TargetID, Target, REF>(column, this, cache) } + fun , Target : Entity, REF : Comparable> EntityClass.optionalReferrersOn(column: Column, cache: Boolean = false) = + registerRefRule(column) { OptionalReferrers, TargetID, Target, REF>(column, this, cache) } - fun Column.transform(toColumn: (TReal) -> TColumn, toReal: (TColumn) -> TReal): ColumnWithTransform = ColumnWithTransform(this, toColumn, toReal) + fun Column.transform(toColumn: (TReal) -> TColumn, toReal: (TColumn) -> TReal): ColumnWithTransform = ColumnWithTransform(this, toColumn, toReal) private fun Query.setForUpdateStatus(): Query = if (this@EntityClass is ImmutableEntityClass<*, *>) this.notForUpdate() else this @Suppress("CAST_NEVER_SUCCEEDS") - fun warmUpOptReferences(references: List, refColumn: Column, forUpdate: Boolean? = null): List - = warmUpReferences(references, refColumn as Column, forUpdate) + fun warmUpOptReferences(references: List, refColumn: Column, forUpdate: Boolean? = null): List = + warmUpReferences(references, refColumn as Column, forUpdate) fun warmUpReferences(references: List, refColumn: Column, forUpdate: Boolean? = null): List { val parentTable = refColumn.referee?.table as? IdTable<*> @@ -314,7 +315,7 @@ abstract class EntityClass, out T: Entity>(val table: Id } if (toLoad.isNotEmpty()) { val findQuery = find { refColumn inList toLoad } - val entities = when(forUpdate) { + val entities = when (forUpdate) { true -> findQuery.forUpdate() false -> findQuery.notForUpdate() else -> findQuery @@ -329,16 +330,16 @@ abstract class EntityClass, out T: Entity>(val table: Id return distinctRefIds.flatMap { cache.referrers[it]?.get(refColumn)?.toList().orEmpty() } as List } else { - val baseQuery = searchQuery(Op.build{ refColumn inList distinctRefIds }) + val baseQuery = searchQuery(Op.build { refColumn inList distinctRefIds }) val finalQuery = if (parentTable.id in baseQuery.set.fields) baseQuery else { - baseQuery.adjustSlice{ slice(this.fields + parentTable.id) }. - adjustColumnSet { innerJoin(parentTable, { refColumn }, { refColumn.referee!! }) } + baseQuery.adjustSlice { slice(this.fields + parentTable.id) } + .adjustColumnSet { innerJoin(parentTable, { refColumn }, { refColumn.referee!! }) } } val findQuery = wrapRows(finalQuery) - val entities = when(forUpdate) { + val entities = when (forUpdate) { true -> findQuery.forUpdate() false -> findQuery.notForUpdate() else -> findQuery @@ -355,8 +356,8 @@ abstract class EntityClass, out T: Entity>(val table: Id if (references.isEmpty()) return emptyList() val distinctRefIds = references.distinct() val sourceRefColumn = linkTable.columns.singleOrNull { it.referee == references.first().table.id } as? Column> - ?: error("Can't detect source reference column") - val targetRefColumn = linkTable.columns.singleOrNull {it.referee == table.id} as? Column> ?: error("Can't detect target reference column") + ?: error("Can't detect source reference column") + val targetRefColumn = linkTable.columns.singleOrNull { it.referee == table.id } as? Column> ?: error("Can't detect target reference column") val transaction = TransactionManager.current() @@ -365,11 +366,13 @@ abstract class EntityClass, out T: Entity>(val table: Id val alreadyInJoin = (dependsOnTables as? Join)?.alreadyInJoin(linkTable) ?: false val entityTables = if (alreadyInJoin) dependsOnTables else dependsOnTables.join(linkTable, JoinType.INNER, targetRefColumn, table.id) - val columns = (dependsOnColumns + (if (!alreadyInJoin) linkTable.columns else emptyList()) - - sourceRefColumn).distinct() + sourceRefColumn + val columns = ( + dependsOnColumns + (if (!alreadyInJoin) linkTable.columns else emptyList()) - + sourceRefColumn + ).distinct() + sourceRefColumn val query = entityTables.slice(columns).select { sourceRefColumn inList idsToLoad } - val entitiesWithRefs = when(forUpdate) { + val entitiesWithRefs = when (forUpdate) { true -> query.forUpdate() false -> query.notForUpdate() else -> query @@ -385,10 +388,10 @@ abstract class EntityClass, out T: Entity>(val table: Id return inCache.values.flatMap { it.toList() as List } + loaded.orEmpty() } - fun , T: Entity> isAssignableTo(entityClass: EntityClass) = entityClass.klass.isAssignableFrom(klass) + fun , T : Entity> isAssignableTo(entityClass: EntityClass) = entityClass.klass.isAssignableFrom(klass) } -abstract class ImmutableEntityClass, out T: Entity>(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) { +abstract class ImmutableEntityClass, out T : Entity>(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) { open fun forceUpdateEntity(entity: Entity, column: Column, value: T) { table.update({ table.id eq entity.id }) { it[column] = value @@ -402,7 +405,7 @@ abstract class ImmutableEntityClass, out T: Entity>(table: } } -abstract class ImmutableCachedEntityClass, out T: Entity>(table: IdTable, entityType: Class? = null) : ImmutableEntityClass(table, entityType) { +abstract class ImmutableCachedEntityClass, out T : Entity>(table: IdTable, entityType: Class? = null) : ImmutableEntityClass(table, entityType) { private val cacheLoadingState = Key() private var _cachedValues: MutableMap>> = ConcurrentHashMap() @@ -424,7 +427,7 @@ abstract class ImmutableCachedEntityClass, out T: Entity>( } else -> { tr.putUserData(cacheLoadingState, this) - super.all().toList() /* force iteration to initialize lazy collection */ + super.all().toList() /* force iteration to initialize lazy collection */ _cachedValues[db] = transactionCache.data[table] ?: mutableMapOf() tr.removeUserData(cacheLoadingState) } diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityHook.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityHook.kt index 0075eae2b7..933087084b 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityHook.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityHook.kt @@ -7,7 +7,6 @@ import org.jetbrains.exposed.sql.transactions.transactionScope import java.util.* import java.util.concurrent.ConcurrentLinkedDeque import java.util.concurrent.ConcurrentLinkedQueue -import java.util.concurrent.CopyOnWriteArrayList enum class EntityChangeType { Created, @@ -15,18 +14,17 @@ enum class EntityChangeType { Removed; } - data class EntityChange(val entityClass: EntityClass<*, Entity<*>>, val entityId: EntityID<*>, val changeType: EntityChangeType, val transactionId: String) -fun, T: Entity> EntityChange.toEntity() : T? = (entityClass as EntityClass).findById(entityId as EntityID) +fun , T : Entity> EntityChange.toEntity(): T? = (entityClass as EntityClass).findById(entityId as EntityID) -fun,T: Entity> EntityChange.toEntity(klass: EntityClass) : T? { +fun , T : Entity> EntityChange.toEntity(klass: EntityClass): T? { if (!entityClass.isAssignableTo(klass)) return null @Suppress("UNCHECKED_CAST") return toEntity() } -private val Transaction.entityEvents : Deque by transactionScope { ConcurrentLinkedDeque() } +private val Transaction.entityEvents: Deque by transactionScope { ConcurrentLinkedDeque() } private val entitySubscribers = ConcurrentLinkedQueue<(EntityChange) -> Unit>() object EntityHook { @@ -57,14 +55,13 @@ fun Transaction.alertSubscribers() { fun Transaction.registeredChanges() = entityEvents.toList() -fun withHook(action: (EntityChange) -> Unit, body: ()->T): T { +fun withHook(action: (EntityChange) -> Unit, body: () -> T): T { EntityHook.subscribe(action) try { return body().apply { TransactionManager.current().commit() } - } - finally { + } finally { EntityHook.unsubscribe(action) } -} \ No newline at end of file +} diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityLifecycleInterceptor.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityLifecycleInterceptor.kt index 7e562b2ea8..b0a6d81b95 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityLifecycleInterceptor.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/EntityLifecycleInterceptor.kt @@ -30,7 +30,7 @@ class EntityLifecycleInterceptor : GlobalStatementInterceptor { } else -> { - if(statement.type.group == StatementGroup.DDL) + if (statement.type.group == StatementGroup.DDL) transaction.flushCache() } } @@ -55,4 +55,4 @@ class EntityLifecycleInterceptor : GlobalStatementInterceptor { val tables = query.targets.filterIsInstance(IdTable::class.java).toSet() entityCache.flush(tables) } -} \ No newline at end of file +} diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/InnerTableLink.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/InnerTableLink.kt index c5a4da3c12..30988fe0fb 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/InnerTableLink.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/InnerTableLink.kt @@ -7,14 +7,15 @@ import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty @Suppress("UNCHECKED_CAST") -class InnerTableLink, Source: Entity, ID:Comparable, Target: Entity>( - val table: Table, - val target: EntityClass, - val sourceColumn: Column>? = null, - _targetColumn: Column>? = null) : ReadWriteProperty> { +class InnerTableLink, Source : Entity, ID : Comparable, Target : Entity>( + val table: Table, + val target: EntityClass, + val sourceColumn: Column>? = null, + _targetColumn: Column>? = null +) : ReadWriteProperty> { init { _targetColumn?.let { - requireNotNull(sourceColumn) { "Both source and target columns should be specified"} + requireNotNull(sourceColumn) { "Both source and target columns should be specified" } require(_targetColumn.referee?.table == target.table) { "Column $_targetColumn point to wrong table, expected ${target.table.tableName}" } @@ -23,29 +24,31 @@ class InnerTableLink, Source: Entity, ID:Comparable } } sourceColumn?.let { - requireNotNull(_targetColumn) { "Both source and target columns should be specified"} + requireNotNull(_targetColumn) { "Both source and target columns should be specified" } } } private val targetColumn = _targetColumn - ?: table.columns.singleOrNull { it.referee == target.table.id } as? Column> - ?: error("Table does not reference target") + ?: table.columns.singleOrNull { it.referee == target.table.id } as? Column> + ?: error("Table does not reference target") private fun getSourceRefColumn(o: Source): Column> { return sourceColumn ?: table.columns.singleOrNull { it.referee == o.klass.table.id } as? Column> - ?: error("Table does not reference source") + ?: error("Table does not reference source") } override operator fun getValue(o: Source, unused: KProperty<*>): SizedIterable { if (o.id._value == null) return emptySized() val sourceRefColumn = getSourceRefColumn(o) - val alreadyInJoin = (target.dependsOnTables as? Join)?.alreadyInJoin(table)?: false + val alreadyInJoin = (target.dependsOnTables as? Join)?.alreadyInJoin(table) ?: false val entityTables = if (alreadyInJoin) target.dependsOnTables else target.dependsOnTables.join(table, JoinType.INNER, target.table.id, targetColumn) - val columns = (target.dependsOnColumns + (if (!alreadyInJoin) table.columns else emptyList()) - - sourceRefColumn).distinct() + sourceRefColumn + val columns = ( + target.dependsOnColumns + (if (!alreadyInJoin) table.columns else emptyList()) - + sourceRefColumn + ).distinct() + sourceRefColumn - val query = {target.wrapRows(entityTables.slice(columns).select{sourceRefColumn eq o.id})} + val query = { target.wrapRows(entityTables.slice(columns).select { sourceRefColumn eq o.id }) } return TransactionManager.current().entityCache.getOrPutReferrers(o.id, sourceRefColumn, query) } @@ -77,4 +80,4 @@ class InnerTableLink, Source: Entity, ID:Comparable } } } -} \ No newline at end of file +} diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/IntEntity.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/IntEntity.kt index 28c3913c33..bb0f437893 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/IntEntity.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/IntEntity.kt @@ -5,4 +5,4 @@ import org.jetbrains.exposed.dao.id.IdTable abstract class IntEntity(id: EntityID) : Entity(id) -abstract class IntEntityClass(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) +abstract class IntEntityClass(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/LongEntity.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/LongEntity.kt index e248d75de3..e5526e602c 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/LongEntity.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/LongEntity.kt @@ -5,5 +5,4 @@ import org.jetbrains.exposed.dao.id.IdTable abstract class LongEntity(id: EntityID) : Entity(id) -abstract class LongEntityClass(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) - +abstract class LongEntityClass(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/References.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/References.kt index 998d5c31fc..cf400b9e3e 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/References.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/References.kt @@ -19,33 +19,33 @@ private fun checkReference(reference: Column<*>, factoryTable: IdTable<*>) { } } -class Reference, ID:Comparable, out Target : Entity> (val reference: Column, val factory: EntityClass) { +class Reference, ID : Comparable, out Target : Entity> (val reference: Column, val factory: EntityClass) { init { checkReference(reference, factory.table) } } -class OptionalReference, ID:Comparable, out Target : Entity> (val reference: Column, val factory: EntityClass) { +class OptionalReference, ID : Comparable, out Target : Entity> (val reference: Column, val factory: EntityClass) { init { checkReference(reference, factory.table) } } -internal class BackReference, out Parent: Entity, ChildID:Comparable, in Child: Entity, REF> +internal class BackReference, out Parent : Entity, ChildID : Comparable, in Child : Entity, REF> (reference: Column, factory: EntityClass) : ReadOnlyProperty { internal val delegate = Referrers(reference, factory, true) override operator fun getValue(thisRef: Child, property: KProperty<*>) = delegate.getValue(thisRef.apply { thisRef.id.value }, property).single() // flush entity before to don't miss newly created entities } -class OptionalBackReference, out Parent: Entity, ChildID:Comparable, in Child: Entity, REF> +class OptionalBackReference, out Parent : Entity, ChildID : Comparable, in Child : Entity, REF> (reference: Column, factory: EntityClass) : ReadOnlyProperty { internal val delegate = OptionalReferrers(reference, factory, true) - override operator fun getValue(thisRef: Child, property: KProperty<*>) = delegate.getValue(thisRef.apply { thisRef.id.value }, property).singleOrNull() // flush entity before to don't miss newly created entities + override operator fun getValue(thisRef: Child, property: KProperty<*>) = delegate.getValue(thisRef.apply { thisRef.id.value }, property).singleOrNull() // flush entity before to don't miss newly created entities } -class Referrers, in Parent: Entity, ChildID:Comparable, out Child: Entity, REF> +class Referrers, in Parent : Entity, ChildID : Comparable, out Child : Entity, REF> (val reference: Column, val factory: EntityClass, val cache: Boolean) : ReadOnlyProperty> { init { reference.referee ?: error("Column $reference is not a reference") @@ -59,12 +59,12 @@ class Referrers, in Parent: Entity, Chil val value = thisRef.run { reference.referee()!!.lookup() } if (thisRef.id._value == null || value == null) return emptySized() - val query = {factory.find{reference eq value }} + val query = { factory.find { reference eq value } } return if (cache) TransactionManager.current().entityCache.getOrPutReferrers(thisRef.id, reference, query) else query() } } -class OptionalReferrers, in Parent: Entity, ChildID:Comparable, out Child: Entity, REF> +class OptionalReferrers, in Parent : Entity, ChildID : Comparable, out Child : Entity, REF> (val reference: Column, val factory: EntityClass, val cache: Boolean) : ReadOnlyProperty> { init { reference.referee ?: error("Column $reference is not a reference") @@ -78,26 +78,28 @@ class OptionalReferrers, in Parent: Entity()!!.lookup() } if (thisRef.id._value == null || value == null) return emptySized() - val query = {factory.find{reference eq value }} - return if (cache) TransactionManager.current().entityCache.getOrPutReferrers(thisRef.id, reference, query) else query() + val query = { factory.find { reference eq value } } + return if (cache) TransactionManager.current().entityCache.getOrPutReferrers(thisRef.id, reference, query) else query() } } -private fun > getReferenceObjectFromDelegatedProperty(entity: SRC, property: KProperty1) : Any? { - property.isAccessible = true +private fun > getReferenceObjectFromDelegatedProperty(entity: SRC, property: KProperty1): Any? { + property.isAccessible = true return property.getDelegate(entity) } -private fun > filterRelationsForEntity(entity: SRC, relations: Array, Any?>>): Collection> { +private fun > filterRelationsForEntity(entity: SRC, relations: Array, Any?>>): Collection> { val validMembers = entity::class.memberProperties return validMembers.filter { it in relations } as Collection> } @Suppress("UNCHECKED_CAST") -private fun > List>.preloadRelations(vararg relations: KProperty1, Any?>, - nodesVisited: MutableSet> = mutableSetOf()) { - val entity = this.firstOrNull() ?: return - if(nodesVisited.contains(entity.klass)) { +private fun > List>.preloadRelations( + vararg relations: KProperty1, Any?>, + nodesVisited: MutableSet> = mutableSetOf() +) { + val entity = this.firstOrNull() ?: return + if (nodesVisited.contains(entity.klass)) { return } else { nodesVisited.add(entity.klass) @@ -105,7 +107,7 @@ private fun > List>.preloadRelations(vararg relati val directRelations = filterRelationsForEntity(entity, relations) directRelations.forEach { - when(val refObject = getReferenceObjectFromDelegatedProperty(entity, it)) { + when (val refObject = getReferenceObjectFromDelegatedProperty(entity, it)) { is Reference<*, *, *> -> { (refObject as Reference>, *, Entity<*>>).reference.let { refColumn -> this.map { it.run { refColumn.lookup() } }.takeIf { it.isNotEmpty() }?.let { refIds -> @@ -133,7 +135,7 @@ private fun > List>.preloadRelations(vararg relati } } is InnerTableLink<*, *, *, *> -> { - refObject.target.warmUpLinkedReferences(this.map{ it.id }, refObject.table) + refObject.target.warmUpLinkedReferences(this.map { it.id }, refObject.table) } is BackReference<*, *, *, *, *> -> { (refObject.delegate as Referrers, *, Entity<*>, Any>).reference.let { refColumn -> @@ -151,15 +153,15 @@ private fun > List>.preloadRelations(vararg relati } } - if(directRelations.isNotEmpty() && relations.size != directRelations.size) { - val remainingRelations = relations.toList() - directRelations + if (directRelations.isNotEmpty() && relations.size != directRelations.size) { + val remainingRelations = relations.toList() - directRelations directRelations.map { relationProperty -> val relationsToLoad = this.flatMap { - when(val relation = (relationProperty as KProperty1, *>).get(it)) { + when (val relation = (relationProperty as KProperty1, *>).get(it)) { is SizedIterable<*> -> relation.toList() is Entity<*> -> listOf(relation) - null -> listOf() - else -> error("Unrecognised loaded relation") + null -> listOf() + else -> error("Unrecognised loaded relation") } as List> }.groupBy { it::class } @@ -170,10 +172,10 @@ private fun > List>.preloadRelations(vararg relati } } -fun , SRC: Entity, REF : Entity<*>> Iterable.with(vararg relations: KProperty1): Iterable = toList().apply { +fun , SRC : Entity, REF : Entity<*>> Iterable.with(vararg relations: KProperty1): Iterable = toList().apply { preloadRelations(*relations) } -fun , SRC: Entity> SRC.load(vararg relations: KProperty1, Any?>): SRC = apply { +fun , SRC : Entity> SRC.load(vararg relations: KProperty1, Any?>): SRC = apply { listOf(this).with(*relations) } diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/UUIDEntity.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/UUIDEntity.kt index 8f2e7e3d75..3dd5e9144d 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/UUIDEntity.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/UUIDEntity.kt @@ -6,5 +6,4 @@ import java.util.* abstract class UUIDEntity(id: EntityID) : Entity(id) -abstract class UUIDEntityClass(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) - +abstract class UUIDEntityClass(table: IdTable, entityType: Class? = null) : EntityClass(table, entityType) diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/View.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/View.kt index afe7770f11..748430858b 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/View.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/View.kt @@ -6,7 +6,7 @@ import org.jetbrains.exposed.sql.SizedIterable import org.jetbrains.exposed.sql.SortOrder import kotlin.reflect.KProperty -class View> (val op : Op, val factory: EntityClass<*, Target>) : SizedIterable { +class View> (val op: Op, val factory: EntityClass<*, Target>) : SizedIterable { override fun limit(n: Int, offset: Long): SizedIterable = factory.find(op).limit(n, offset) override fun count(): Long = factory.find(op).count() override fun empty(): Boolean = factory.find(op).empty() @@ -17,4 +17,4 @@ class View> (val op : Op, val factory: EntityClas operator fun getValue(o: Any?, desc: KProperty<*>): SizedIterable = factory.find(op) override fun copy(): SizedIterable = View(op, factory) override fun orderBy(vararg order: Pair, SortOrder>): SizedIterable = factory.find(op).orderBy(*order) -} \ No newline at end of file +} diff --git a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/exceptions/EntityNotFoundException.kt b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/exceptions/EntityNotFoundException.kt index 7b38d20185..f820483085 100644 --- a/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/exceptions/EntityNotFoundException.kt +++ b/exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/exceptions/EntityNotFoundException.kt @@ -3,5 +3,5 @@ package org.jetbrains.exposed.dao.exceptions import org.jetbrains.exposed.dao.EntityClass import org.jetbrains.exposed.dao.id.EntityID -class EntityNotFoundException(val id: EntityID<*>, val entity: EntityClass<*, *>) - : Exception("Entity ${entity.klass.simpleName}, id=$id not found in the database") +class EntityNotFoundException(val id: EntityID<*>, val entity: EntityClass<*, *>) : + Exception("Entity ${entity.klass.simpleName}, id=$id not found in the database") diff --git a/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateColumnType.kt b/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateColumnType.kt index 541214b774..d9d57609ad 100644 --- a/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateColumnType.kt +++ b/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateColumnType.kt @@ -133,7 +133,7 @@ class JavaInstantColumnType : ColumnType(), IDateColumnType { else -> error("Unexpected value: $value of ${value::class.qualifiedName}") } - return when(currentDialect) { + return when (currentDialect) { is OracleDialect -> "'${SQLITE_AND_ORACLE_DATE_TIME_STRING_FORMATTER.format(instant)}'" else -> "'${DEFAULT_DATE_TIME_STRING_FORMATTER.format(instant)}'" } diff --git a/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateFunctions.kt b/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateFunctions.kt index 57a2e95bf2..4f07c5a6eb 100644 --- a/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateFunctions.kt +++ b/exposed-java-time/src/main/kotlin/org/jetbrains/exposed/sql/java-time/JavaDateFunctions.kt @@ -77,7 +77,6 @@ fun Expression.hour(): Hour = Hour(this) fun Expression.minute(): Minute = Minute(this) fun Expression.second(): Second = Second(this) - fun dateParam(value: LocalDate): Expression = QueryParameter(value, JavaLocalDateColumnType.INSTANCE) fun dateTimeParam(value: LocalDateTime): Expression = QueryParameter(value, JavaLocalDateTimeColumnType.INSTANCE) diff --git a/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/DefaultsTest.kt b/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/DefaultsTest.kt index 2fafab0dfe..f67fdae3a2 100644 --- a/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/DefaultsTest.kt +++ b/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/DefaultsTest.kt @@ -26,7 +26,6 @@ import org.jetbrains.exposed.sql.vendors.OracleDialect import org.jetbrains.exposed.sql.vendors.SQLServerDialect import org.junit.Test import java.time.* -import java.util.UUID class DefaultsTest : DatabaseTestsBase() { object TableWithDBDefault : IntIdTable() { @@ -58,7 +57,8 @@ class DefaultsTest : DatabaseTestsBase() { DBDefault.new { field = "2" t1 = LocalDateTime.now().minusDays(5) - }) + } + ) commit() created.forEach { DBDefault.removeFromCache(it) @@ -76,7 +76,9 @@ class DefaultsTest : DatabaseTestsBase() { DBDefault.new { field = "2" t1 = LocalDateTime.now().minusDays(5) - }, DBDefault.new { field = "1" }) + }, + DBDefault.new { field = "1" } + ) flushCache() created.forEach { @@ -100,12 +102,15 @@ class DefaultsTest : DatabaseTestsBase() { } } - private val initBatch = listOf<(BatchInsertStatement) -> Unit>({ - it[TableWithDBDefault.field] = "1" - }, { - it[TableWithDBDefault.field] = "2" - it[TableWithDBDefault.t1] = LocalDateTime.now() - }) + private val initBatch = listOf<(BatchInsertStatement) -> Unit>( + { + it[TableWithDBDefault.field] = "1" + }, + { + it[TableWithDBDefault.field] = "2" + it[TableWithDBDefault.t1] = LocalDateTime.now() + } + ) @Test fun testRawBatchInsertFails01() { @@ -188,21 +193,21 @@ class DefaultsTest : DatabaseTestsBase() { val longType = currentDialectTest.dataTypeProvider.longType() val q = db.identifierManager.quoteString val baseExpression = "CREATE TABLE " + addIfNotExistsIfSupported() + - "${"t".inProperCase()} (" + - "${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerAutoincType()} PRIMARY KEY, " + - "${"s".inProperCase()} VARCHAR(100) DEFAULT 'test' NOT NULL, " + - "${"sn".inProperCase()} VARCHAR(100) DEFAULT 'testNullable' NULL, " + - "${"l".inProperCase()} ${currentDialectTest.dataTypeProvider.longType()} DEFAULT 42 NOT NULL, " + - "$q${"c".inProperCase()}$q CHAR DEFAULT 'X' NOT NULL, " + - "${"t1".inProperCase()} $dtType ${currentDT.itOrNull()}, " + - "${"t2".inProperCase()} $dtType ${nowExpression.itOrNull()}, " + - "${"t3".inProperCase()} $dtType ${dtLiteral.itOrNull()}, " + - "${"t4".inProperCase()} DATE ${dLiteral.itOrNull()}, " + - "${"t5".inProperCase()} $dtType ${tsLiteral.itOrNull()}, " + - "${"t6".inProperCase()} $dtType ${tsLiteral.itOrNull()}, " + - "${"t7".inProperCase()} $longType ${durLiteral.itOrNull()}, " + - "${"t8".inProperCase()} $longType ${durLiteral.itOrNull()}" + - ")" + "${"t".inProperCase()} (" + + "${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerAutoincType()} PRIMARY KEY, " + + "${"s".inProperCase()} VARCHAR(100) DEFAULT 'test' NOT NULL, " + + "${"sn".inProperCase()} VARCHAR(100) DEFAULT 'testNullable' NULL, " + + "${"l".inProperCase()} ${currentDialectTest.dataTypeProvider.longType()} DEFAULT 42 NOT NULL, " + + "$q${"c".inProperCase()}$q CHAR DEFAULT 'X' NOT NULL, " + + "${"t1".inProperCase()} $dtType ${currentDT.itOrNull()}, " + + "${"t2".inProperCase()} $dtType ${nowExpression.itOrNull()}, " + + "${"t3".inProperCase()} $dtType ${dtLiteral.itOrNull()}, " + + "${"t4".inProperCase()} DATE ${dLiteral.itOrNull()}, " + + "${"t5".inProperCase()} $dtType ${tsLiteral.itOrNull()}, " + + "${"t6".inProperCase()} $dtType ${tsLiteral.itOrNull()}, " + + "${"t7".inProperCase()} $longType ${durLiteral.itOrNull()}, " + + "${"t8".inProperCase()} $longType ${durLiteral.itOrNull()}" + + ")" val expected = if (currentDialectTest is OracleDialect) arrayListOf("CREATE SEQUENCE t_id_seq", baseExpression) @@ -315,7 +320,8 @@ class DefaultsTest : DatabaseTestsBase() { withDb(TestDB.SQLSERVER) { try { - exec(""" + exec( + """ CREATE TABLE TemporalTable ( id uniqueidentifier PRIMARY KEY, @@ -324,7 +330,8 @@ class DefaultsTest : DatabaseTestsBase() { sysEnd DATETIME2 GENERATED ALWAYS AS ROW END, PERIOD FOR SYSTEM_TIME ([sysStart], [sysEnd]) ) - """.trimIndent()) + """.trimIndent() + ) val names = listOf("name") val batchInsert: List = diff --git a/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/JavaTimeTests.kt b/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/JavaTimeTests.kt index 985af231b6..511e4c9458 100644 --- a/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/JavaTimeTests.kt +++ b/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/JavaTimeTests.kt @@ -10,7 +10,6 @@ import org.jetbrains.exposed.sql.tests.shared.assertEquals import org.jetbrains.exposed.sql.vendors.MysqlDialect import org.junit.Test import java.time.* -import java.time.format.DateTimeFormatter import java.time.temporal.Temporal import kotlin.test.assertEquals @@ -74,23 +73,23 @@ open class JavaTimeBaseTest : DatabaseTestsBase() { } } -fun assertEqualDateTime(d1: T?, d2: T?) { - when{ +fun assertEqualDateTime(d1: T?, d2: T?) { + when { d1 == null && d2 == null -> return d1 == null && d2 != null -> error("d1 is null while d2 is not on ${currentDialectTest.name}") - d2 == null -> error ("d1 is not null while d2 is null on ${currentDialectTest.name}") + d2 == null -> error("d1 is not null while d2 is null on ${currentDialectTest.name}") d1 == null -> error("Impossible") d1 is LocalDateTime && d2 is LocalDateTime && (currentDialectTest as? MysqlDialect)?.isFractionDateTimeSupported() == false -> - assertEquals(d1.toInstant(ZoneOffset.UTC).toEpochMilli() / 1000, d2.toInstant(ZoneOffset.UTC).toEpochMilli() / 1000, "Failed on ${currentDialectTest.name}") + assertEquals(d1.toInstant(ZoneOffset.UTC).toEpochMilli() / 1000, d2.toInstant(ZoneOffset.UTC).toEpochMilli() / 1000, "Failed on ${currentDialectTest.name}") d1 is Instant && d2 is Instant && (currentDialectTest as? MysqlDialect)?.isFractionDateTimeSupported() == false -> - assertEquals(d1.toEpochMilli() / 1000, d2.toEpochMilli() / 1000, "Failed on ${currentDialectTest.name}") - d1 is Instant && d2 is Instant -> assertEquals(d1.toEpochMilli(), d2.toEpochMilli(), "Failed on ${currentDialectTest.name}") + assertEquals(d1.toEpochMilli() / 1000, d2.toEpochMilli() / 1000, "Failed on ${currentDialectTest.name}") + d1 is Instant && d2 is Instant -> assertEquals(d1.toEpochMilli(), d2.toEpochMilli(), "Failed on ${currentDialectTest.name}") d1 is LocalDateTime && d2 is LocalDateTime -> { val d1Millis = Instant.from(d1.atZone(ZoneId.systemDefault())).toEpochMilli() val d2Millis = Instant.from(d2.atZone(ZoneId.systemDefault())).toEpochMilli() assertEquals(d1Millis, d2Millis, "Failed on ${currentDialectTest.name}") } - else -> assertEquals(d1, d2, "Failed on ${currentDialectTest.name}") + else -> assertEquals(d1, d2, "Failed on ${currentDialectTest.name}") } } @@ -106,4 +105,4 @@ val today: LocalDate = LocalDate.now() object CitiesTime : IntIdTable("CitiesTime") { val name = varchar("name", 50) // Column val local_time = datetime("local_time").nullable() // Column -} \ No newline at end of file +} diff --git a/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/MiscTableTest.kt b/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/MiscTableTest.kt index ad65ad971c..c9f51b877c 100644 --- a/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/MiscTableTest.kt +++ b/exposed-java-time/src/test/kotlin/org/jetbrains/exposed/MiscTableTest.kt @@ -60,7 +60,7 @@ class MiscTableTest : DatabaseTestsBase() { val row = tbl.selectAll().single() tbl.checkRow( - row, 13, null,-10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, + row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, "test", null, "test", null, BigDecimal("239.42"), null, null, null ) tbl.checkRowDates(row, date, null, time, null, timestamp, null, duration, null) @@ -1134,17 +1134,32 @@ class MiscTableTest : DatabaseTestsBase() { fun Misc.checkRowFull( row: ResultRow, - by: Byte, byn: Byte?, - sm: Short, smn: Short?, - n: Int, nn: Int?, - d: LocalDate, dn: LocalDate?, - t: LocalDateTime, tn: LocalDateTime?, - ts: Instant, tsn: Instant?, - dr: Duration, drn: Duration?, - e: MiscTable.E, en: MiscTable.E?, - es: MiscTable.E, esn: MiscTable.E?, - c: String, cn: String?, s: String, sn: String?, - dc: BigDecimal, dcn: BigDecimal?, fcn: Float?, dblcn: Double? + by: Byte, + byn: Byte?, + sm: Short, + smn: Short?, + n: Int, + nn: Int?, + d: LocalDate, + dn: LocalDate?, + t: LocalDateTime, + tn: LocalDateTime?, + ts: Instant, + tsn: Instant?, + dr: Duration, + drn: Duration?, + e: MiscTable.E, + en: MiscTable.E?, + es: MiscTable.E, + esn: MiscTable.E?, + c: String, + cn: String?, + s: String, + sn: String?, + dc: BigDecimal, + dcn: BigDecimal?, + fcn: Float?, + dblcn: Double? ) { checkRow(row, by, byn, sm, smn, n, nn, e, en, es, esn, c, cn, s, sn, dc, dcn, fcn, dblcn) checkRowDates(row, d, dn, t, tn, ts, tsn, dr, drn) @@ -1152,10 +1167,14 @@ fun Misc.checkRowFull( fun Misc.checkRowDates( row: ResultRow, - d: LocalDate, dn: LocalDate?, - t: LocalDateTime, tn: LocalDateTime?, - ts: Instant, tsn: Instant? = null, - dr: Duration, drn: Duration? = null + d: LocalDate, + dn: LocalDate?, + t: LocalDateTime, + tn: LocalDateTime?, + ts: Instant, + tsn: Instant? = null, + dr: Duration, + drn: Duration? = null ) { assertEqualDateTime(d, row[this.d]) assertEqualDateTime(dn, row[this.dn]) @@ -1166,4 +1185,3 @@ fun Misc.checkRowDates( assertEquals(dr, row[this.dr]) assertEquals(drn, row[this.drn]) } - diff --git a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/jdbc/ExposedConnectionImpl.kt b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/jdbc/ExposedConnectionImpl.kt index b705087d94..e103580422 100644 --- a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/jdbc/ExposedConnectionImpl.kt +++ b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/jdbc/ExposedConnectionImpl.kt @@ -6,4 +6,4 @@ import java.sql.Connection class ExposedConnectionImpl : DatabaseConnectionAutoRegistration { override fun invoke(connection: Connection) = JdbcConnectionImpl(connection) -} \ No newline at end of file +} diff --git a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcConnectionImpl.kt b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcConnectionImpl.kt index 335eb3fc8c..11ad4cb458 100644 --- a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcConnectionImpl.kt +++ b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcConnectionImpl.kt @@ -16,11 +16,11 @@ class JdbcConnectionImpl(override val connection: Connection) : ExposedConnectio // Oracle driver could throw excpection on catalog override var catalog: String - get() = try { connection.catalog } catch (_: Exception) { null } ?: connection.metaData.userName ?: "" + get() = try { connection.catalog } catch (_: Exception) { null } ?: connection.metaData.userName ?: "" set(value) { try { connection.catalog = value } catch (_: Exception) {} } override var schema: String - get() = try { connection.schema } catch (_: Exception) { "" } + get() = try { connection.schema } catch (_: Exception) { "" } set(value) { try { connection.schema = value } catch (_: Exception) {} } override fun commit() { @@ -50,7 +50,7 @@ class JdbcConnectionImpl(override val connection: Connection) : ExposedConnectio override fun metadata(body: ExposedDatabaseMetadata.() -> T): T = metadata.body() - override fun prepareStatement(sql: String, returnKeys: Boolean) : PreparedStatementApi { + override fun prepareStatement(sql: String, returnKeys: Boolean): PreparedStatementApi { val generated = if (returnKeys) PreparedStatement.RETURN_GENERATED_KEYS else diff --git a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcDatabaseMetadataImpl.kt b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcDatabaseMetadataImpl.kt index 14b03cfc2c..da2b994fb0 100644 --- a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcDatabaseMetadataImpl.kt +++ b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcDatabaseMetadataImpl.kt @@ -12,7 +12,7 @@ import kotlin.collections.HashMap class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) : ExposedDatabaseMetadata(database) { override val url: String by lazyMetadata { url } - override val version: BigDecimal by lazyMetadata { BigDecimal("$databaseMajorVersion.$databaseMinorVersion")} + override val version: BigDecimal by lazyMetadata { BigDecimal("$databaseMajorVersion.$databaseMinorVersion") } override val databaseDialectName: String by lazyMetadata { when (driverName) { @@ -35,7 +35,7 @@ class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) } } - private val databaseName get() = when(databaseDialectName) { + private val databaseName get() = when (databaseDialectName) { MysqlDialect.dialectName, MariaDBDialect.dialectName -> currentScheme else -> database } @@ -70,15 +70,17 @@ class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) _currentScheme = null } - private inner class CachableMapWithDefault(private val map:MutableMap = mutableMapOf(), val default: (K) -> V) : Map by map { + private inner class CachableMapWithDefault(private val map: MutableMap = mutableMapOf(), val default: (K) -> V) : Map by map { override fun get(key: K): V? = map.getOrPut(key, { default(key) }) override fun containsKey(key: K): Boolean = true override fun isEmpty(): Boolean = false } - override val tableNames: Map> get() = CachableMapWithDefault(default = { schemeName -> - tableNamesFor(schemeName) - }) + override val tableNames: Map> get() = CachableMapWithDefault( + default = { schemeName -> + tableNamesFor(schemeName) + } + ) private fun tableNamesFor(scheme: String): List = with(metadata) { val useCatalogInsteadOfScheme = currentDialect is MysqlDialect @@ -127,9 +129,9 @@ class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) } override fun columns(vararg tables: Table): Map> { - val rs = metadata.getColumns(databaseName, currentScheme, "%", "%") + val rs = metadata.getColumns(databaseName, currentScheme, "%", "%") val result = rs.extractColumns(tables) { - //@see java.sql.DatabaseMetaData.getColumns + // @see java.sql.DatabaseMetaData.getColumns val columnMetadata = ColumnMetadata(it.getString("COLUMN_NAME")/*.quoteIdentifierWhenWrongCaseOrNecessary(tr)*/, it.getInt("DATA_TYPE"), it.getBoolean("NULLABLE"), it.getInt("COLUMN_SIZE").takeIf { it != 0 }) it.getString("TABLE_NAME") to columnMetadata } @@ -140,14 +142,14 @@ class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) private val existingIndicesCache = HashMap>() override fun existingIndices(vararg tables: Table): Map> { - for(table in tables) { + for (table in tables) { val tableName = table.nameInDatabaseCase() val transaction = TransactionManager.current() existingIndicesCache.getOrPut(table) { val pkNames = metadata.getPrimaryKeys(databaseName, currentScheme, tableName).let { rs -> val names = arrayListOf() - while(rs.next()) { + while (rs.next()) { rs.getString("PK_NAME")?.let { names += it } } rs.close() @@ -194,11 +196,11 @@ class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) val constraintUpdateRule = ReferenceOption.resolveRefOptionFromJdbc(getInt("UPDATE_RULE")) val constraintDeleteRule = ReferenceOption.resolveRefOptionFromJdbc(getInt("DELETE_RULE")) ForeignKeyConstraint( - target = targetColumn, - from = fromColumn, - onUpdate = constraintUpdateRule, - onDelete = constraintDeleteRule, - name = constraintName + target = targetColumn, + from = fromColumn, + onUpdate = constraintUpdateRule, + onDelete = constraintDeleteRule, + name = constraintName ) }.filterNotNull() } @@ -212,9 +214,9 @@ class JdbcDatabaseMetadataImpl(database: String, val metadata: DatabaseMetaData) private fun lazyMetadata(body: DatabaseMetaData.() -> T) = lazy { metadata.body() } } -fun ResultSet.iterate(body: ResultSet.() -> T) : List { +fun ResultSet.iterate(body: ResultSet.() -> T): List { val result = arrayListOf() - while(next()) { + while (next()) { result.add(body()) } close() diff --git a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcPreparedStatementImpl.kt b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcPreparedStatementImpl.kt index 35dfcc7813..7bd5fef26e 100644 --- a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcPreparedStatementImpl.kt +++ b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcPreparedStatementImpl.kt @@ -46,4 +46,4 @@ class JdbcPreparedStatementImpl(val statement: PreparedStatement, val wasGenerat } override fun executeBatch(): List = statement.executeBatch().toList() -} \ No newline at end of file +} diff --git a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcSavepoint.kt b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcSavepoint.kt index 0f55f14f65..d87c5808a8 100644 --- a/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcSavepoint.kt +++ b/exposed-jdbc/src/main/kotlin/org/jetbrains/exposed/sql/statements/jdbc/JdbcSavepoint.kt @@ -3,4 +3,4 @@ package org.jetbrains.exposed.sql.statements.jdbc import org.jetbrains.exposed.sql.statements.api.ExposedSavepoint import java.sql.Savepoint -class JdbcSavepoint(name: String, internal val savepoint: Savepoint) : ExposedSavepoint(name) \ No newline at end of file +class JdbcSavepoint(name: String, internal val savepoint: Savepoint) : ExposedSavepoint(name) diff --git a/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateColumnType.kt b/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateColumnType.kt index f54eca7c1c..cdf0489133 100644 --- a/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateColumnType.kt +++ b/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateColumnType.kt @@ -21,18 +21,18 @@ private val SQLITE_AND_ORACLE_DATE_TIME_STRING_FORMATTER = DateTimeFormat.forPat private val SQLITE_DATE_STRING_FORMATTER = ISODateTimeFormat.yearMonthDay() private fun formatterForDateTimeString(date: String) = dateTimeWithFractionFormat(date.substringAfterLast('.', "").length) -private fun dateTimeWithFractionFormat(fraction: Int) : DateTimeFormatter { +private fun dateTimeWithFractionFormat(fraction: Int): DateTimeFormatter { val baseFormat = "YYYY-MM-dd HH:mm:ss" - val newFormat = if(fraction in 1..9) + val newFormat = if (fraction in 1..9) (1..fraction).joinToString(prefix = "$baseFormat.", separator = "") { "S" } else baseFormat return DateTimeFormat.forPattern(newFormat) } -class DateColumnType(val time: Boolean): ColumnType(), IDateColumnType { +class DateColumnType(val time: Boolean) : ColumnType(), IDateColumnType { override val hasTimePart: Boolean = time - override fun sqlType(): String = if (time) currentDialect.dataTypeProvider.dateTimeType() else "DATE" + override fun sqlType(): String = if (time) currentDialect.dataTypeProvider.dateTimeType() else "DATE" override fun nonNullValueToString(value: Any): String { if (value is String) return value @@ -50,9 +50,9 @@ class DateColumnType(val time: Boolean): ColumnType(), IDateColumnType { "'${DEFAULT_DATE_STRING_FORMATTER.print(dateTime)}'" } - override fun valueFromDB(value: Any): Any = when(value) { + override fun valueFromDB(value: Any): Any = when (value) { is DateTime -> value - is java.sql.Date -> DateTime(value.time) + is java.sql.Date -> DateTime(value.time) is java.sql.Timestamp -> DateTime(value.time) is Int -> DateTime(value.toLong()) is Long -> DateTime(value) @@ -77,7 +77,7 @@ class DateColumnType(val time: Boolean): ColumnType(), IDateColumnType { override fun notNullValueToDB(value: Any): Any = when { value is DateTime && time && currentDialect is SQLiteDialect -> SQLITE_AND_ORACLE_DATE_TIME_STRING_FORMATTER.print(value) - value is DateTime && time -> java.sql.Timestamp(value.millis) + value is DateTime && time -> java.sql.Timestamp(value.millis) value is DateTime -> java.sql.Date(value.millis) else -> value } diff --git a/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateFunctions.kt b/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateFunctions.kt index 1e212f0821..2f54cddc8d 100644 --- a/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateFunctions.kt +++ b/exposed-jodatime/src/main/kotlin/org/jetbrains/exposed/sql/jodatime/DateFunctions.kt @@ -5,8 +5,8 @@ import org.jetbrains.exposed.sql.Function import org.jetbrains.exposed.sql.vendors.* import org.joda.time.DateTime -class Date(val expr: Expression): Function(DateColumnType(false)) { - override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append("DATE(", expr,")") } +class Date(val expr: Expression) : Function(DateColumnType(false)) { + override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { append("DATE(", expr, ")") } } class CurrentDateTime : Function(DateColumnType(false)) { @@ -18,51 +18,50 @@ class CurrentDateTime : Function(DateColumnType(false)) { } } -class Year(val expr: Expression): Function(IntegerColumnType()) { +class Year(val expr: Expression) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { currentDialect.functionProvider.year(expr, queryBuilder) } } -class Month(val expr: Expression): Function(IntegerColumnType()) { +class Month(val expr: Expression) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { currentDialect.functionProvider.month(expr, queryBuilder) } } -class Day(val expr: Expression): Function(IntegerColumnType()) { +class Day(val expr: Expression) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { currentDialect.functionProvider.day(expr, queryBuilder) } } -class Hour(val expr: Expression): Function(IntegerColumnType()) { +class Hour(val expr: Expression) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { currentDialect.functionProvider.hour(expr, queryBuilder) } } -class Minute(val expr: Expression): Function(IntegerColumnType()) { +class Minute(val expr: Expression) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { currentDialect.functionProvider.minute(expr, queryBuilder) } } -class Second(val expr: Expression): Function(IntegerColumnType()) { +class Second(val expr: Expression) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { currentDialect.functionProvider.second(expr, queryBuilder) } } -fun Expression.date() = Date(this) - -fun Expression.year() = Year(this) -fun Expression.month() = Month(this) -fun Expression.day() = Day(this) -fun Expression.hour() = Hour(this) -fun Expression.minute() = Minute(this) -fun Expression.second() = Second(this) +fun Expression.date() = Date(this) +fun Expression.year() = Year(this) +fun Expression.month() = Month(this) +fun Expression.day() = Day(this) +fun Expression.hour() = Hour(this) +fun Expression.minute() = Minute(this) +fun Expression.second() = Second(this) fun dateParam(value: DateTime): Expression = QueryParameter(value, DateColumnType(false)) fun dateTimeParam(value: DateTime): Expression = QueryParameter(value, DateColumnType(true)) diff --git a/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeDefaultsTest.kt b/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeDefaultsTest.kt index 6ee367c092..f8a5da062c 100644 --- a/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeDefaultsTest.kt +++ b/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeDefaultsTest.kt @@ -35,7 +35,7 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { val clientDefault = integer("clientDefault").clientDefault { cIndex++ } } - class DBDefault(id: EntityID): IntEntity(id) { + class DBDefault(id: EntityID) : IntEntity(id) { var field by TableWithDBDefault.field var t1 by TableWithDBDefault.t1 val clientDefault by TableWithDBDefault.clientDefault @@ -53,11 +53,12 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { fun testDefaultsWithExplicit01() { withTables(TableWithDBDefault) { val created = listOf( - DBDefault.new { field = "1" }, - DBDefault.new { - field = "2" - t1 = DateTime.now().minusDays(5) - }) + DBDefault.new { field = "1" }, + DBDefault.new { + field = "2" + t1 = DateTime.now().minusDays(5) + } + ) flushCache() created.forEach { DBDefault.removeFromCache(it) @@ -72,10 +73,12 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { fun testDefaultsWithExplicit02() { withTables(TableWithDBDefault) { val created = listOf( - DBDefault.new{ - field = "2" - t1 = DateTime.now().minusDays(5) - }, DBDefault.new{ field = "1" }) + DBDefault.new { + field = "2" + t1 = DateTime.now().minusDays(5) + }, + DBDefault.new { field = "1" } + ) flushCache() created.forEach { @@ -90,8 +93,8 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { fun testDefaultsInvokedOnlyOncePerEntity() { withTables(TableWithDBDefault) { TableWithDBDefault.cIndex = 0 - val db1 = DBDefault.new{ field = "1" } - val db2 = DBDefault.new{ field = "2" } + val db1 = DBDefault.new { field = "1" } + val db2 = DBDefault.new { field = "2" } flushCache() assertEquals(0, db1.clientDefault) assertEquals(1, db2.clientDefault) @@ -99,12 +102,15 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { } } - private val initBatch = listOf<(BatchInsertStatement) -> Unit>({ - it[TableWithDBDefault.field] = "1" - }, { - it[TableWithDBDefault.field] = "2" - it[TableWithDBDefault.t1] = DateTime.now() - }) + private val initBatch = listOf<(BatchInsertStatement) -> Unit>( + { + it[TableWithDBDefault.field] = "1" + }, + { + it[TableWithDBDefault.field] = "2" + it[TableWithDBDefault.t1] = DateTime.now() + } + ) @Test fun testRawBatchInsertFails01() { @@ -156,7 +162,7 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { } fun Expression<*>.itOrNull() = when { - currentDialectTest.isAllowedAsColumnDefault(this) -> + currentDialectTest.isAllowedAsColumnDefault(this) -> "DEFAULT ${currentDialectTest.dataTypeProvider.processForDefaultValue(this)} NOT NULL" else -> "NULL" } @@ -165,17 +171,17 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { val dtType = currentDialectTest.dataTypeProvider.dateTimeType() val q = db.identifierManager.quoteString val baseExpression = "CREATE TABLE " + addIfNotExistsIfSupported() + - "${"t".inProperCase()} (" + - "${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerAutoincType()} PRIMARY KEY, " + - "${"s".inProperCase()} VARCHAR(100) DEFAULT 'test' NOT NULL, " + - "${"sn".inProperCase()} VARCHAR(100) DEFAULT 'testNullable' NULL, " + - "${"l".inProperCase()} ${currentDialectTest.dataTypeProvider.longType()} DEFAULT 42 NOT NULL, " + - "$q${"c".inProperCase()}$q CHAR DEFAULT 'X' NOT NULL, " + - "${"t1".inProperCase()} $dtType ${currentDT.itOrNull()}, " + - "${"t2".inProperCase()} $dtType ${nowExpression.itOrNull()}, " + - "${"t3".inProperCase()} $dtType ${dtLiteral.itOrNull()}, " + - "${"t4".inProperCase()} DATE ${dtLiteral.itOrNull()}" + - ")" + "${"t".inProperCase()} (" + + "${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerAutoincType()} PRIMARY KEY, " + + "${"s".inProperCase()} VARCHAR(100) DEFAULT 'test' NOT NULL, " + + "${"sn".inProperCase()} VARCHAR(100) DEFAULT 'testNullable' NULL, " + + "${"l".inProperCase()} ${currentDialectTest.dataTypeProvider.longType()} DEFAULT 42 NOT NULL, " + + "$q${"c".inProperCase()}$q CHAR DEFAULT 'X' NOT NULL, " + + "${"t1".inProperCase()} $dtType ${currentDT.itOrNull()}, " + + "${"t2".inProperCase()} $dtType ${nowExpression.itOrNull()}, " + + "${"t3".inProperCase()} $dtType ${dtLiteral.itOrNull()}, " + + "${"t4".inProperCase()} DATE ${dtLiteral.itOrNull()}" + + ")" val expected = if (currentDialectTest is OracleDialect) arrayListOf("CREATE SEQUENCE t_id_seq", baseExpression) @@ -184,7 +190,7 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { assertEqualLists(expected, TestTable.ddl) - val id1 = TestTable.insertAndGetId { } + val id1 = TestTable.insertAndGetId { } val row1 = TestTable.select { TestTable.id eq id1 }.single() assertEquals("test", row1[TestTable.s]) @@ -246,7 +252,7 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { assertEquals("bar", result[foo.name]) assertEqualDateTime(nonDefaultDate, result[foo.defaultDateTime]) - foo.update({foo.id eq id}) { + foo.update({ foo.id eq id }) { it[foo.name] = "baz" } @@ -277,12 +283,12 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { } val after = currentDateTime() - assertEquals(0, TestDate.select { TestDate.time less before }.count()) + assertEquals(0, TestDate.select { TestDate.time less before }.count()) assertEquals(4, TestDate.select { TestDate.time greater before }.count()) - assertEquals(2, TestDate.select { TestDate.time less middle }.count()) + assertEquals(2, TestDate.select { TestDate.time less middle }.count()) assertEquals(2, TestDate.select { TestDate.time greater middle }.count()) - assertEquals(4, TestDate.select { TestDate.time less after }.count()) - assertEquals(0, TestDate.select { TestDate.time greater after }.count()) + assertEquals(4, TestDate.select { TestDate.time less after }.count()) + assertEquals(0, TestDate.select { TestDate.time greater after }.count()) } } @@ -342,7 +348,7 @@ class JodaTimeDefaultsTest : JodaTimeBaseTest() { } fun Table.insertAndWait(duration: Long) { - this.insert { } + this.insert { } TransactionManager.current().commit() Thread.sleep(duration) } diff --git a/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeMiscTableTest.kt b/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeMiscTableTest.kt index cb5ab32e38..e380579705 100644 --- a/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeMiscTableTest.kt +++ b/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeMiscTableTest.kt @@ -43,8 +43,10 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { } val row = tbl.selectAll().single() - tbl.checkRow(row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, - null, "test", null, "test", null, BigDecimal("239.42"), null, null, null) + tbl.checkRow( + row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, + null, "test", null, "test", null, BigDecimal("239.42"), null, null, null + ) tbl.checkRowDates(row, date, null, time, null) assertEquals('(', row[tbl.char]) } @@ -82,8 +84,10 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { } val row = tbl.selectAll().single() - tbl.checkRow(row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, - null, "test", null, "test", null, BigDecimal("239.42"), null, null, null) + tbl.checkRow( + row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, + null, "test", null, "test", null, BigDecimal("239.42"), null, null, null + ) tbl.checkRowDates(row, date, null, time, null) } } @@ -121,8 +125,10 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { } val row = tbl.selectAll().single() - tbl.checkRow(row, 13, 13, -10, -10, 42, 42, MiscTable.E.ONE, MiscTable.E.ONE, MiscTable.E.ONE, MiscTable.E.ONE, - "test", "test", "test", "test",BigDecimal("239.42"), BigDecimal("239.42"), 239.42f, 567.89) + tbl.checkRow( + row, 13, 13, -10, -10, 42, 42, MiscTable.E.ONE, MiscTable.E.ONE, MiscTable.E.ONE, MiscTable.E.ONE, + "test", "test", "test", "test", BigDecimal("239.42"), BigDecimal("239.42"), 239.42f, 567.89 + ) tbl.checkRowDates(row, date, date, time, time) } } @@ -151,7 +157,7 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { val row = tbl.selectAll().single() tbl.checkRow( row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, - shortStringThatNeedsEscaping, null, stringThatNeedsEscaping, null, + shortStringThatNeedsEscaping, null, stringThatNeedsEscaping, null, BigDecimal("239.42"), null, null, null ) tbl.checkRowDates(row, date, null, time, null) @@ -179,8 +185,10 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { it[char] = '(' } - tbl.checkInsert(row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, - null, "test", null, BigDecimal("239.42"), null, null, null) + tbl.checkInsert( + row, 13, null, -10, null, 42, null, MiscTable.E.ONE, null, MiscTable.E.ONE, + null, "test", null, BigDecimal("239.42"), null, null, null + ) tbl.checkRowDates(row.resultedValues!!.single(), date, null, time, null) assertEquals('(', row[tbl.char]) } @@ -207,25 +215,25 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { it[dc] = dec } - tbl.checkRowFull(tbl.select { tbl.n.eq(42) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.nn.isNull() }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.nn.eq(null as Int?) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.n.eq(42) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.nn.isNull() }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.nn.eq(null as Int?) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.d.eq(date) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.dn.isNull() }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.dn.eq(null as DateTime?) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.d.eq(date) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.dn.isNull() }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.dn.eq(null as DateTime?) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.t.eq(time) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.tn.isNull() }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.tn.eq(null as DateTime?) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.t.eq(time) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.tn.isNull() }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.tn.eq(null as DateTime?) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.e.eq(MiscTable.E.ONE) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.en.isNull() }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.en.eq(null as MiscTable.E?) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.e.eq(MiscTable.E.ONE) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.en.isNull() }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.en.eq(null as MiscTable.E?) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.s.eq(sTest) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.sn.isNull() }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) - tbl.checkRowFull(tbl.select { tbl.sn.eq(null as String?) }.single(), 13, null , -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.s.eq(sTest) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.sn.isNull() }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(tbl.select { tbl.sn.eq(null as String?) }.single(), 13, null, -10, null, 42, null, date, null, time, null, MiscTable.E.ONE, null, MiscTable.E.ONE, null, sTest, null, sTest, null, dec, null, null, null) } } @@ -328,7 +336,7 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { } val row = tbl.selectAll().single() - tbl.checkRowFull(row, 13, null , -10, null, 42, null, date, null, time, null, eOne, null, eOne, null, sTest, null, sTest, null, dec, null, null, null) + tbl.checkRowFull(row, 13, null, -10, null, 42, null, date, null, time, null, eOne, null, eOne, null, sTest, null, sTest, null, dec, null, null, null) } } @@ -361,20 +369,36 @@ class JodaTimeMiscTableTest : JodaTimeBaseTest() { } val row = tbl.select { tbl.n eq 101 }.single() - tbl.checkRowFull(row, 13, null , -10, null, 101, null, date, null, time, null, eOne, null, eOne, null, "1234", "1234", "23456789", "3456789", dec, null, null, null) + tbl.checkRowFull(row, 13, null, -10, null, 101, null, date, null, time, null, eOne, null, eOne, null, "1234", "1234", "23456789", "3456789", dec, null, null, null) } } } -fun Misc.checkRowFull(row: ResultRow, - by: Byte, byn: Byte?, - sm: Short, smn: Short?, - n: Int, nn: Int?, - d: DateTime, dn: DateTime?, t: DateTime, tn: DateTime?, - e: MiscTable.E, en: MiscTable.E?, - es: MiscTable.E, esn: MiscTable.E?, - c: String, cn: String?, s: String, sn: String?, - dc: BigDecimal, dcn: BigDecimal?, fcn: Float?, dblcn: Double?) { +fun Misc.checkRowFull( + row: ResultRow, + by: Byte, + byn: Byte?, + sm: Short, + smn: Short?, + n: Int, + nn: Int?, + d: DateTime, + dn: DateTime?, + t: DateTime, + tn: DateTime?, + e: MiscTable.E, + en: MiscTable.E?, + es: MiscTable.E, + esn: MiscTable.E?, + c: String, + cn: String?, + s: String, + sn: String?, + dc: BigDecimal, + dcn: BigDecimal?, + fcn: Float?, + dblcn: Double? +) { checkRow(row, by, byn, sm, smn, n, nn, e, en, es, esn, c, cn, s, sn, dc, dcn, fcn, dblcn) checkRowDates(row, d, dn, t, tn) } diff --git a/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeTests.kt b/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeTests.kt index c977324530..63f897e981 100644 --- a/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeTests.kt +++ b/exposed-jodatime/src/test/kotlin/org/jetbrains/exposed/JodaTimeTests.kt @@ -45,15 +45,15 @@ open class JodaTimeBaseTest : DatabaseTestsBase() { } fun assertEqualDateTime(d1: DateTime?, d2: DateTime?) { - when{ + when { d1 == null && d2 == null -> return d1 == null && d2 != null -> error("d1 is null while d2 is not on ${currentDialectTest.name}") - d2 == null -> error ("d1 is not null while d2 is null on ${currentDialectTest.name}") + d2 == null -> error("d1 is not null while d2 is null on ${currentDialectTest.name}") d1 == null -> error("Impossible") // Mysql doesn't support millis prior 5.6.4 (currentDialectTest as? MysqlDialect)?.isFractionDateTimeSupported() == false -> - assertEquals(d1.millis / 1000, d2.millis / 1000, "Failed on ${currentDialectTest.name}") - else -> assertEquals(d1.millis, d2.millis, "Failed on ${currentDialectTest.name}") + assertEquals(d1.millis / 1000, d2.millis / 1000, "Failed on ${currentDialectTest.name}") + else -> assertEquals(d1.millis, d2.millis, "Failed on ${currentDialectTest.name}") } } diff --git a/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumn.kt b/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumn.kt index bff6ad0963..ccc7315533 100644 --- a/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumn.kt +++ b/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumn.kt @@ -38,10 +38,10 @@ class CompositeMoneyColumn( amount = Column(table, amountName, DecimalColumnType(precision, scale)), currency = Column(table, currencyName, CurrencyColumnType()) - ) \ No newline at end of file + ) diff --git a/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumnType.kt b/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumnType.kt index de3e450741..fef945653a 100644 --- a/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumnType.kt +++ b/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CompositeMoneyColumnType.kt @@ -7,8 +7,7 @@ import javax.money.CurrencyUnit import javax.money.MonetaryAmount fun Table.compositeMoney(precision: Int, scale: Int, amountName: String, currencyName: String = amountName + "_C") = - registerCompositeColumn(CompositeMoneyColumn(this, precision, scale, amountName, currencyName)) - + registerCompositeColumn(CompositeMoneyColumn(this, precision, scale, amountName, currencyName)) fun Table.compositeMoney(amountColumn: Column, currencyColumn: Column): CompositeMoneyColumn { return CompositeMoneyColumn(amountColumn, currencyColumn).also { @@ -25,4 +24,4 @@ fun Table.compositeMoney(amountColumn: Column, currencyColumn: Colu registerCompositeColumn(it) } } -} \ No newline at end of file +} diff --git a/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CurrencyColumnType.kt b/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CurrencyColumnType.kt index fd02e148dd..42f6dc1203 100644 --- a/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CurrencyColumnType.kt +++ b/exposed-money/src/main/kotlin/org/jetbrains/exposed/sql/money/CurrencyColumnType.kt @@ -28,7 +28,6 @@ class CurrencyColumnType : VarCharColumnType(3) { else -> valueFromDB(value.toString()) } } - } fun Table.currency(name: String): Column = registerColumn(name, CurrencyColumnType()) diff --git a/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyDefaultsTest.kt b/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyDefaultsTest.kt index fb92803f9f..2682e5f1c8 100644 --- a/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyDefaultsTest.kt +++ b/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyDefaultsTest.kt @@ -20,8 +20,8 @@ class MoneyDefaultsTest : DatabaseTestsBase() { var cIndex = 0 val field = varchar("field", 100) - val t1 = compositeMoney(10, 0,"t1").default(defaultValue) - val t2 = compositeMoney(10, 0,"t2").nullable() + val t1 = compositeMoney(10, 0, "t1").default(defaultValue) + val t2 = compositeMoney(10, 0, "t2").nullable() val clientDefault = integer("clientDefault").clientDefault { cIndex++ } } @@ -50,11 +50,12 @@ class MoneyDefaultsTest : DatabaseTestsBase() { fun testDefaultsWithExplicit() { withTables(TableWithDBDefault) { val created = listOf( - DBDefault.new { field = "1" }, - DBDefault.new { - field = "2" - t1 = Money.of(BigDecimal.TEN, "USD") - }) + DBDefault.new { field = "1" }, + DBDefault.new { + field = "2" + t1 = Money.of(BigDecimal.TEN, "USD") + } + ) flushCache() created.forEach { DBDefault.removeFromCache(it) diff --git a/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyTests.kt b/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyTests.kt index 30b42f1bbb..2d04a8fc82 100644 --- a/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyTests.kt +++ b/exposed-money/src/test/kotlin/org/jetbrains/exposed/sql/money/MoneyTests.kt @@ -52,9 +52,9 @@ open class MoneyBaseTest : DatabaseTestsBase() { } val predicates = listOf( - Account.composite_money eq money, - (Account.composite_money.currency eq money.currency), - (Account.composite_money.amount eq BigDecimal.TEN) + Account.composite_money eq money, + (Account.composite_money.currency eq money.currency), + (Account.composite_money.amount eq BigDecimal.TEN) ) predicates.forEach { @@ -80,25 +80,21 @@ open class MoneyBaseTest : DatabaseTestsBase() { assertEquals(toInsert, inserted) } - } - } class AccountDao(id: EntityID) : IntEntity(id) { - val money : MonetaryAmount by Account.composite_money + val money: MonetaryAmount by Account.composite_money - val currency : CurrencyUnit? by Account.composite_money.currency + val currency: CurrencyUnit? by Account.composite_money.currency - val amount : BigDecimal? by Account.composite_money.amount + val amount: BigDecimal? by Account.composite_money.amount companion object : EntityClass(Account) - } object Account : IntIdTable("AccountTable") { val composite_money = compositeMoney(8, AMOUNT_SCALE, "composite_money") - } diff --git a/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/DatabaseInitializer.kt b/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/DatabaseInitializer.kt index dafecadc95..542edfb438 100644 --- a/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/DatabaseInitializer.kt +++ b/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/DatabaseInitializer.kt @@ -40,4 +40,4 @@ fun discoverExposedTables(applicationContext: ApplicationContext, excludedPackag val packages = AutoConfigurationPackages.get(applicationContext) val components = packages.map { provider.findCandidateComponents(it) }.flatten() return components.map { Class.forName(it.beanClassName).kotlin.objectInstance as Table } -} \ No newline at end of file +} diff --git a/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfiguration.kt b/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfiguration.kt index ed6d89fcef..9463ffa300 100644 --- a/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfiguration.kt +++ b/exposed-spring-boot-starter/src/main/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfiguration.kt @@ -24,7 +24,6 @@ open class ExposedAutoConfiguration(private val applicationContext: ApplicationC open fun springTransactionManager(datasource: DataSource) = SpringTransactionManager(datasource) @Bean - @ConditionalOnProperty("spring.exposed.generate-ddl", havingValue="true", matchIfMissing = false) + @ConditionalOnProperty("spring.exposed.generate-ddl", havingValue = "true", matchIfMissing = false) open fun databaseInitializer() = DatabaseInitializer(applicationContext, excludedPackages) - -} \ No newline at end of file +} diff --git a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/DatabaseInitializerTest.kt b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/DatabaseInitializerTest.kt index 350d96eef0..5b6487575a 100644 --- a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/DatabaseInitializerTest.kt +++ b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/DatabaseInitializerTest.kt @@ -1,6 +1,5 @@ package org.jetbrains.exposed.spring - import org.jetbrains.exposed.exceptions.ExposedSQLException import org.jetbrains.exposed.spring.tables.TestTable import org.jetbrains.exposed.spring.tables.ignore.IgnoreTable @@ -14,8 +13,10 @@ import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.ApplicationContext -@SpringBootTest(classes = [Application::class], - properties = ["spring.autoconfigure.exclude=org.jetbrains.exposed.spring.autoconfigure.ExposedAutoConfiguration"]) +@SpringBootTest( + classes = [Application::class], + properties = ["spring.autoconfigure.exclude=org.jetbrains.exposed.spring.autoconfigure.ExposedAutoConfiguration"] +) open class DatabaseInitializerTest { @Autowired @@ -32,4 +33,4 @@ open class DatabaseInitializerTest { } } } -} \ No newline at end of file +} diff --git a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfigurationTest.kt b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfigurationTest.kt index 0ecce394c0..4161645273 100644 --- a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfigurationTest.kt +++ b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/autoconfigure/ExposedAutoConfigurationTest.kt @@ -14,8 +14,10 @@ import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.util.concurrent.CompletableFuture -@SpringBootTest(classes = [org.jetbrains.exposed.spring.Application::class], - properties = ["spring.datasource.url=jdbc:h2:mem:test", "spring.datasource.driver-class-name=org.h2.Driver"]) +@SpringBootTest( + classes = [org.jetbrains.exposed.spring.Application::class], + properties = ["spring.datasource.url=jdbc:h2:mem:test", "spring.datasource.driver-class-name=org.h2.Driver"] +) open class ExposedAutoConfigurationTest { @Autowired(required = false) @@ -35,8 +37,10 @@ open class ExposedAutoConfigurationTest { } } -@SpringBootTest(classes = [org.jetbrains.exposed.spring.Application::class], - properties = ["spring.datasource.url=jdbc:h2:mem:test", "spring.datasource.driver-class-name=org.h2.Driver","spring.exposed.generate-ddl=true"]) +@SpringBootTest( + classes = [org.jetbrains.exposed.spring.Application::class], + properties = ["spring.datasource.url=jdbc:h2:mem:test", "spring.datasource.driver-class-name=org.h2.Driver", "spring.exposed.generate-ddl=true"] +) open class ExposedAutoConfigurationTestAutoGenerateDDL { @Autowired(required = false) diff --git a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/TestTable.kt b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/TestTable.kt index 1f455b0dc9..347e16cabd 100644 --- a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/TestTable.kt +++ b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/TestTable.kt @@ -2,6 +2,6 @@ package org.jetbrains.exposed.spring.tables import org.jetbrains.exposed.dao.id.IntIdTable -object TestTable: IntIdTable("test_table") { +object TestTable : IntIdTable("test_table") { var name = varchar("name", 100) -} \ No newline at end of file +} diff --git a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/ignore/IgnoreTable.kt b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/ignore/IgnoreTable.kt index cccaa5cfb0..8dbc05d0d1 100644 --- a/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/ignore/IgnoreTable.kt +++ b/exposed-spring-boot-starter/src/test/kotlin/org/jetbrains/exposed/spring/tables/ignore/IgnoreTable.kt @@ -2,6 +2,6 @@ package org.jetbrains.exposed.spring.tables.ignore import org.jetbrains.exposed.dao.id.IntIdTable -object IgnoreTable: IntIdTable("ignore_table") { +object IgnoreTable : IntIdTable("ignore_table") { var name = varchar("name", 100) -} \ No newline at end of file +} diff --git a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/DatabaseTestsBase.kt b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/DatabaseTestsBase.kt index 7d304f6fae..2bdf5e4d98 100644 --- a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/DatabaseTestsBase.kt +++ b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/DatabaseTestsBase.kt @@ -10,13 +10,23 @@ import java.sql.Connection import java.util.* import kotlin.concurrent.thread -enum class TestDB(val connection: () -> String, val driver: String, val user: String = "root", val pass: String = "", - val beforeConnection: () -> Unit = {}, val afterTestFinished: () -> Unit = {}, var db: Database? = null) { - H2({"jdbc:h2:mem:regular;DB_CLOSE_DELAY=-1;"}, "org.h2.Driver"), - H2_MYSQL({"jdbc:h2:mem:mysql;MODE=MySQL;DB_CLOSE_DELAY=-1"}, "org.h2.Driver", beforeConnection = { - Mode.getInstance("MySQL").convertInsertNullToZero = false - }), - SQLITE({"jdbc:sqlite:file:test?mode=memory&cache=shared"}, "org.sqlite.JDBC"), +enum class TestDB( + val connection: () -> String, + val driver: String, + val user: String = "root", + val pass: String = "", + val beforeConnection: () -> Unit = {}, + val afterTestFinished: () -> Unit = {}, + var db: Database? = null +) { + H2({ "jdbc:h2:mem:regular;DB_CLOSE_DELAY=-1;" }, "org.h2.Driver"), + H2_MYSQL( + { "jdbc:h2:mem:mysql;MODE=MySQL;DB_CLOSE_DELAY=-1" }, "org.h2.Driver", + beforeConnection = { + Mode.getInstance("MySQL").convertInsertNullToZero = false + } + ), + SQLITE({ "jdbc:sqlite:file:test?mode=memory&cache=shared" }, "org.sqlite.JDBC"), MYSQL( connection = { if (runTestContainersMySQL()) { @@ -35,35 +45,51 @@ enum class TestDB(val connection: () -> String, val driver: String, val user: St beforeConnection = { if (runTestContainersMySQL()) mySQLProcess }, afterTestFinished = { if (runTestContainersMySQL()) mySQLProcess.close() } ), - POSTGRESQL({"jdbc:postgresql://localhost:12346/template1?user=postgres&password=&lc_messages=en_US.UTF-8"}, "org.postgresql.Driver", - beforeConnection = { postgresSQLProcess }, afterTestFinished = { postgresSQLProcess.close() }), - POSTGRESQLNG({"jdbc:pgsql://localhost:12346/template1?user=postgres&password="}, "com.impossibl.postgres.jdbc.PGDriver", - user = "postgres", beforeConnection = { postgresSQLProcess }, afterTestFinished = { postgresSQLProcess.close() }), - ORACLE(driver = "oracle.jdbc.OracleDriver", user = "ExposedTest", pass = "12345", - connection = {"jdbc:oracle:thin:@//${System.getProperty("exposed.test.oracle.host", "localhost")}" + - ":${System.getProperty("exposed.test.oracle.port", "1521")}/XEPDB1"}, - beforeConnection = { - Locale.setDefault(Locale.ENGLISH) - val tmp = Database.connect(ORACLE.connection(), user = "sys as sysdba", password = "Oracle18", driver = ORACLE.driver) - transaction(Connection.TRANSACTION_READ_COMMITTED, 1, tmp) { - try { - exec("DROP USER ExposedTest CASCADE") - } catch (e: Exception) { // ignore - exposedLogger.warn("Exception on deleting ExposedTest user", e) - } - exec("CREATE USER ExposedTest ACCOUNT UNLOCK IDENTIFIED BY 12345") - exec("grant all privileges to ExposedTest") + POSTGRESQL( + { "jdbc:postgresql://localhost:12346/template1?user=postgres&password=&lc_messages=en_US.UTF-8" }, "org.postgresql.Driver", + beforeConnection = { postgresSQLProcess }, afterTestFinished = { postgresSQLProcess.close() } + ), + POSTGRESQLNG( + { "jdbc:pgsql://localhost:12346/template1?user=postgres&password=" }, "com.impossibl.postgres.jdbc.PGDriver", + user = "postgres", beforeConnection = { postgresSQLProcess }, afterTestFinished = { postgresSQLProcess.close() } + ), + ORACLE( + driver = "oracle.jdbc.OracleDriver", user = "ExposedTest", pass = "12345", + connection = { + "jdbc:oracle:thin:@//${System.getProperty("exposed.test.oracle.host", "localhost")}" + + ":${System.getProperty("exposed.test.oracle.port", "1521")}/XEPDB1" + }, + beforeConnection = { + Locale.setDefault(Locale.ENGLISH) + val tmp = Database.connect(ORACLE.connection(), user = "sys as sysdba", password = "Oracle18", driver = ORACLE.driver) + transaction(Connection.TRANSACTION_READ_COMMITTED, 1, tmp) { + try { + exec("DROP USER ExposedTest CASCADE") + } catch (e: Exception) { // ignore + exposedLogger.warn("Exception on deleting ExposedTest user", e) } - Unit - }), + exec("CREATE USER ExposedTest ACCOUNT UNLOCK IDENTIFIED BY 12345") + exec("grant all privileges to ExposedTest") + } + Unit + } + ), - SQLSERVER({"jdbc:sqlserver://${System.getProperty("exposed.test.sqlserver.host", "192.168.99.100")}" + - ":${System.getProperty("exposed.test.sqlserver.port", "32781")}"}, - "com.microsoft.sqlserver.jdbc.SQLServerDriver", "SA", "yourStrong(!)Password"), + SQLSERVER( + { + "jdbc:sqlserver://${System.getProperty("exposed.test.sqlserver.host", "192.168.99.100")}" + + ":${System.getProperty("exposed.test.sqlserver.port", "32781")}" + }, + "com.microsoft.sqlserver.jdbc.SQLServerDriver", "SA", "yourStrong(!)Password" + ), - MARIADB({"jdbc:mariadb://${System.getProperty("exposed.test.mariadb.host", "192.168.99.100")}" + - ":${System.getProperty("exposed.test.mariadb.port", "3306")}/testdb"}, - "org.mariadb.jdbc.Driver"); + MARIADB( + { + "jdbc:mariadb://${System.getProperty("exposed.test.mariadb.host", "192.168.99.100")}" + + ":${System.getProperty("exposed.test.mariadb.port", "3306")}/testdb" + }, + "org.mariadb.jdbc.Driver" + ); fun connect() = Database.connect(connection(), user = user, password = pass, driver = driver) @@ -83,10 +109,10 @@ private val registeredOnShutdown = HashSet() private val postgresSQLProcess by lazy { EmbeddedPostgres.builder() - .setPgBinaryResolver{ system, _ -> - EmbeddedPostgres::class.java.getResourceAsStream("/postgresql-$system-x86_64.txz") - } - .setPort(12346).start() + .setPgBinaryResolver { system, _ -> + EmbeddedPostgres::class.java.getResourceAsStream("/postgresql-$system-x86_64.txz") + } + .setPort(12346).start() } // MySQLContainer has to be extended, otherwise it leads to Kotlin compiler issues: https://github.com/testcontainers/testcontainers-java/issues/318 @@ -94,11 +120,11 @@ internal class SpecifiedMySQLContainer(val image: String) : MySQLContainer? = null, excludeSettings: List = emptyList(), statement: Transaction.(TestDB) -> Unit) { + fun withDb(db: List? = null, excludeSettings: List = emptyList(), statement: Transaction.(TestDB) -> Unit) { val enabledInTests = TestDB.enabledInTests() val toTest = db?.intersect(enabledInTests) ?: enabledInTests - excludeSettings toTest.forEach { dbSettings -> @@ -143,7 +171,7 @@ abstract class DatabaseTestsBase { } } - fun withTables (excludeSettings: List, vararg tables: Table, statement: Transaction.(TestDB) -> Unit) { + fun withTables(excludeSettings: List, vararg tables: Table, statement: Transaction.(TestDB) -> Unit) { (TestDB.enabledInTests() - excludeSettings).forEach { testDB -> withDb(testDB) { SchemaUtils.create(*tables) @@ -158,7 +186,7 @@ abstract class DatabaseTestsBase { } } - fun withSchemas (excludeSettings: List, vararg schemas: Schema, statement: Transaction.() -> Unit) { + fun withSchemas(excludeSettings: List, vararg schemas: Schema, statement: Transaction.() -> Unit) { (TestDB.enabledInTests() - excludeSettings).forEach { testDB -> withDb(testDB) { SchemaUtils.createSchema(*schemas) @@ -174,14 +202,13 @@ abstract class DatabaseTestsBase { } } - fun withTables (vararg tables: Table, statement: Transaction.(TestDB) -> Unit) = withTables(excludeSettings = emptyList(), tables = *tables, statement = statement) + fun withTables(vararg tables: Table, statement: Transaction.(TestDB) -> Unit) = withTables(excludeSettings = emptyList(), tables = *tables, statement = statement) - fun withSchemas (vararg schemas: Schema, statement: Transaction.() -> Unit) = withSchemas(excludeSettings = emptyList(), schemas = *schemas, statement = statement) + fun withSchemas(vararg schemas: Schema, statement: Transaction.() -> Unit) = withSchemas(excludeSettings = emptyList(), schemas = *schemas, statement = statement) fun addIfNotExistsIfSupported() = if (currentDialectTest.supportsIfNotExists) { "IF NOT EXISTS " } else { "" } - } diff --git a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/RepeatableTest.kt b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/RepeatableTest.kt index 919efb0e67..5cf14dcef1 100644 --- a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/RepeatableTest.kt +++ b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/RepeatableTest.kt @@ -24,5 +24,4 @@ class RepeatableTestRule : TestRule { } else base } - -} \ No newline at end of file +} diff --git a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/TestUtils.kt b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/TestUtils.kt index 0615078756..28a56f3e35 100644 --- a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/TestUtils.kt +++ b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/TestUtils.kt @@ -7,8 +7,7 @@ fun String.inProperCase(): String = TransactionManager.currentOrNull()?.db?.iden val currentDialectTest: DatabaseDialect get() = TransactionManager.current().db.dialect -val currentDialectIfAvailableTest : DatabaseDialect? get() = +val currentDialectIfAvailableTest: DatabaseDialect? get() = if (TransactionManager.isInitialized() && TransactionManager.currentOrNull() != null) { currentDialectTest } else null - diff --git a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/Assert.kt b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/Assert.kt index bd1c6e6e55..ed3ba9faeb 100644 --- a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/Assert.kt +++ b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/Assert.kt @@ -8,36 +8,36 @@ import kotlin.test.assertFails import kotlin.test.assertTrue import kotlin.test.fail -private fun assertEqualCollectionsImpl(collection : Collection, expected : Collection) { - assertEquals (expected.size, collection.size, "Count mismatch on ${currentDialectTest.name}") +private fun assertEqualCollectionsImpl(collection: Collection, expected: Collection) { + assertEquals(expected.size, collection.size, "Count mismatch on ${currentDialectTest.name}") for (p in collection) { - assertTrue(expected.any {p == it}, "Unexpected element in collection pair $p on ${currentDialectTest.name}") + assertTrue(expected.any { p == it }, "Unexpected element in collection pair $p on ${currentDialectTest.name}") } } -fun assertEqualCollections (collection : Collection, expected : Collection) { +fun assertEqualCollections(collection: Collection, expected: Collection) { assertEqualCollectionsImpl(collection, expected) } -fun assertEqualCollections (collection : Collection, vararg expected : T) { +fun assertEqualCollections(collection: Collection, vararg expected: T) { assertEqualCollectionsImpl(collection, expected.toList()) } -fun assertEqualCollections (collection : Iterable, vararg expected : T) { +fun assertEqualCollections(collection: Iterable, vararg expected: T) { assertEqualCollectionsImpl(collection.toList(), expected.toList()) } -fun assertEqualCollections (collection : Iterable, expected : Collection) { +fun assertEqualCollections(collection: Iterable, expected: Collection) { assertEqualCollectionsImpl(collection.toList(), expected) } -fun assertEqualLists (l1: List, l2: List) { +fun assertEqualLists(l1: List, l2: List) { assertEquals(l1.size, l2.size, "Count mismatch on ${currentDialectIfAvailableTest?.name.orEmpty()}") for (i in 0 until l1.size) assertEquals(l1[i], l2[i], "Error at pos $i on ${currentDialectIfAvailableTest?.name.orEmpty()}:") } -fun assertEqualLists (l1: List, vararg expected : T) { +fun assertEqualLists(l1: List, vararg expected: T) { assertEqualLists(l1, expected.toList()) } @@ -56,11 +56,11 @@ fun Transaction.assertFailAndRollback(message: kotlin.String, block: () -> Unit) rollback() } -inline fun expectException(body: () -> Unit) { +inline fun expectException(body: () -> Unit) { try { body() fail("${T::class.simpleName} expected.") } catch (e: Exception) { if (e !is T) fail("Expected ${T::class.simpleName} but ${e::class.simpleName} thrown.") } -} \ No newline at end of file +} diff --git a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/MiscTable.kt b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/MiscTable.kt index 0e9bad60e8..d28d316f41 100644 --- a/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/MiscTable.kt +++ b/exposed-tests/src/main/kotlin/org/jetbrains/exposed/sql/tests/shared/MiscTable.kt @@ -45,12 +45,24 @@ open class MiscTable : Table() { fun MiscTable.checkRow( row: ResultRow, - by: Byte, byn: Byte?, - sm: Short, smn: Short?, - n: Int, nn: Int?, e: MiscTable.E, en: MiscTable.E?, - es: MiscTable.E, esn: MiscTable.E?, - c: String, cn: String?, s: String, sn: String?, - dc: BigDecimal, dcn: BigDecimal?, fcn: Float?, dblcn: Double? + by: Byte, + byn: Byte?, + sm: Short, + smn: Short?, + n: Int, + nn: Int?, + e: MiscTable.E, + en: MiscTable.E?, + es: MiscTable.E, + esn: MiscTable.E?, + c: String, + cn: String?, + s: String, + sn: String?, + dc: BigDecimal, + dcn: BigDecimal?, + fcn: Float?, + dblcn: Double? ) { assertEquals(row[this.by], by) assertEquals(row[this.byn], byn) @@ -72,12 +84,25 @@ fun MiscTable.checkRow( assertEquals(row[this.dblcn], dblcn) } -fun MiscTable.checkInsert(row: InsertStatement, - by: Byte, byn: Byte?, - sm: Short, smn: Short?, - n: Int, nn: Int?, e: MiscTable.E, en: MiscTable.E?, - es: MiscTable.E, esn: MiscTable.E?, s: String, sn: String?, - dc: BigDecimal, dcn: BigDecimal?, fcn: Float?, dblcn: Double?) { +fun MiscTable.checkInsert( + row: InsertStatement, + by: Byte, + byn: Byte?, + sm: Short, + smn: Short?, + n: Int, + nn: Int?, + e: MiscTable.E, + en: MiscTable.E?, + es: MiscTable.E, + esn: MiscTable.E?, + s: String, + sn: String?, + dc: BigDecimal, + dcn: BigDecimal?, + fcn: Float?, + dblcn: Double? +) { assertEquals(row[this.by], by) assertEquals(row[this.byn], byn) assertEquals(row[this.sm], sm) @@ -94,4 +119,4 @@ fun MiscTable.checkInsert(row: InsertStatement, assertEquals(row[this.dcn], dcn) assertEquals(row[this.fcn], fcn) assertEquals(row[this.dblcn], dblcn) -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/dao/SamplesDao.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/dao/SamplesDao.kt index 5bf3ecb777..fa817b96a9 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/dao/SamplesDao.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/dao/SamplesDao.kt @@ -1,7 +1,7 @@ package org.jetbrains.exposed.sql.tests.demo.dao -import org.jetbrains.exposed.dao.id.* import org.jetbrains.exposed.dao.* +import org.jetbrains.exposed.dao.id.* import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction @@ -13,7 +13,7 @@ object Users : IntIdTable() { val age = integer("age") } -object Cities: IntIdTable() { +object Cities : IntIdTable() { val name = varchar("name", 50) } @@ -38,7 +38,7 @@ fun main() { transaction { addLogger(StdOutSqlLogger) - SchemaUtils.create (Cities, Users) + SchemaUtils.create(Cities, Users) val stPete = City.new { name = "St. Petersburg" @@ -74,7 +74,7 @@ fun main() { class SamplesDao { @Test - fun ensureSamplesDoesntCrash(){ + fun ensureSamplesDoesntCrash() { main() } } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/sql/SamplesSQL.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/sql/SamplesSQL.kt index 248ff35eb8..3ed0e9791c 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/sql/SamplesSQL.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/demo/sql/SamplesSQL.kt @@ -26,7 +26,7 @@ fun main() { transaction { addLogger(StdOutSqlLogger) - SchemaUtils.create (Cities, Users) + SchemaUtils.create(Cities, Users) val saintPetersburgId = Cities.insert { it[name] = "St. Petersburg" @@ -73,11 +73,11 @@ fun main() { it[Users.cityId] = null } - Users.update({ Users.id eq "alex"}) { + Users.update({ Users.id eq "alex" }) { it[name] = "Alexey" } - Users.deleteWhere{ Users.name like "%thing"} + Users.deleteWhere { Users.name like "%thing" } println("All cities:") @@ -86,24 +86,24 @@ fun main() { } println("Manual join:") - (Users innerJoin Cities).slice(Users.name, Cities.name). - select {(Users.id.eq("andrey") or Users.name.eq("Sergey")) and - Users.id.eq("sergey") and Users.cityId.eq(Cities.id)}.forEach { - println("${it[Users.name]} lives in ${it[Cities.name]}") - } + (Users innerJoin Cities).slice(Users.name, Cities.name) + .select { + (Users.id.eq("andrey") or Users.name.eq("Sergey")) and + Users.id.eq("sergey") and Users.cityId.eq(Cities.id) + }.forEach { + println("${it[Users.name]} lives in ${it[Cities.name]}") + } println("Join with foreign key:") - - (Users innerJoin Cities).slice(Users.name, Users.cityId, Cities.name). - select { Cities.name.eq("St. Petersburg") or Users.cityId.isNull()}.forEach { - if (it[Users.cityId] != null) { - println("${it[Users.name]} lives in ${it[Cities.name]}") - } - else { - println("${it[Users.name]} lives nowhere") + (Users innerJoin Cities).slice(Users.name, Users.cityId, Cities.name) + .select { Cities.name.eq("St. Petersburg") or Users.cityId.isNull() }.forEach { + if (it[Users.cityId] != null) { + println("${it[Users.name]} lives in ${it[Cities.name]}") + } else { + println("${it[Users.name]} lives nowhere") + } } - } println("Functions and group by:") @@ -118,13 +118,13 @@ fun main() { } } - SchemaUtils.drop (Users, Cities) + SchemaUtils.drop(Users, Cities) } } class SamplesSQL { @Test - fun ensureSamplesDoesntCrash(){ + fun ensureSamplesDoesntCrash() { main() } } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/H2Tests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/H2Tests.kt index f26b33f2c3..57941d4e85 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/H2Tests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/H2Tests.kt @@ -5,7 +5,6 @@ import org.jetbrains.exposed.sql.tests.DatabaseTestsBase import org.jetbrains.exposed.sql.tests.TestDB import org.jetbrains.exposed.sql.tests.shared.assertEquals import org.junit.Test -import kotlin.test.assertFailsWith class H2Tests : DatabaseTestsBase() { @@ -21,7 +20,6 @@ class H2Tests : DatabaseTestsBase() { } assertEquals("one", Testing.select { Testing.id.eq(1) }.single()[Testing.string]) - } } @@ -37,7 +35,6 @@ class H2Tests : DatabaseTestsBase() { } assertEquals("one", Testing.select { Testing.id.eq(1) }.single()[Testing.string]) - } } @@ -85,4 +82,4 @@ class H2Tests : DatabaseTestsBase() { override val primaryKey = PrimaryKey(id) } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseEntityTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseEntityTest.kt index 0e467cfa5c..df98af1b5d 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseEntityTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseEntityTest.kt @@ -20,9 +20,9 @@ import kotlin.test.assertNull class MultiDatabaseEntityTest { - private val db1 by lazy { Database.connect("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "")} - private val db2 by lazy { Database.connect("jdbc:h2:mem:db2;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "")} - private var currentDB : Database? = null + private val db1 by lazy { Database.connect("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "") } + private val db2 by lazy { Database.connect("jdbc:h2:mem:db2;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "") } + private var currentDB: Database? = null @Before fun before() { @@ -48,7 +48,6 @@ class MultiDatabaseEntityTest { } } - @Test fun testSimpleCreateEntitiesInDifferentDatabase() { transaction(db1) { @@ -153,11 +152,11 @@ class MultiDatabaseEntityTest { var db1y1 by Delegates.notNull() var db2y1 by Delegates.notNull() transaction(db1) { - db1b1 = EntityTestsData.BEntity.new(1) { } - + db1b1 = EntityTestsData.BEntity.new(1) { } + transaction(db2) { assertEquals(0L, EntityTestsData.BEntity.count()) - db2b1 = EntityTestsData.BEntity.new(2) { } + db2b1 = EntityTestsData.BEntity.new(2) { } db2y1 = EntityTestsData.YEntity.new("2") { } db2b1.y = db2y1 } @@ -175,7 +174,6 @@ class MultiDatabaseEntityTest { assertEquals(db2b1.id, b2Reread.id) assertEquals(db2y1.id, b2Reread.y?.id) b2Reread.y = null - } } inTopLevelTransaction(Connection.TRANSACTION_READ_COMMITTED, 1, db1) { @@ -190,7 +188,7 @@ class MultiDatabaseEntityTest { @Test(expected = IllegalStateException::class) fun crossReferencesProhibitedForEntitiesFromDifferentDB() { transaction(db1) { - val db1b1 = EntityTestsData.BEntity.new(1) { } + val db1b1 = EntityTestsData.BEntity.new(1) { } transaction(db2) { assertEquals(0L, EntityTestsData.BEntity.count()) @@ -198,4 +196,4 @@ class MultiDatabaseEntityTest { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseTest.kt index 2240fb0481..b9568ea130 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/h2/MultiDatabaseTest.kt @@ -3,7 +3,6 @@ package org.jetbrains.exposed.sql.tests.h2 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.jetbrains.exposed.sql.* -import org.jetbrains.exposed.sql.tests.DatabaseTestsBase import org.jetbrains.exposed.sql.tests.shared.assertEqualLists import org.jetbrains.exposed.sql.tests.shared.assertEquals import org.jetbrains.exposed.sql.tests.shared.assertFalse @@ -21,9 +20,9 @@ import kotlin.test.assertEquals class MultiDatabaseTest { - private val db1 by lazy { Database.connect("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "")} - private val db2 by lazy { Database.connect("jdbc:h2:mem:db2;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "")} - private var currentDB : Database? = null + private val db1 by lazy { Database.connect("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "") } + private val db2 by lazy { Database.connect("jdbc:h2:mem:db2;DB_CLOSE_DELAY=-1;", "org.h2.Driver", "root", "") } + private var currentDB: Database? = null @Before fun before() { diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/mysql/MysqlTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/mysql/MysqlTests.kt index e8c9531eeb..ba8cff7a4d 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/mysql/MysqlTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/mysql/MysqlTests.kt @@ -1,9 +1,9 @@ package org.jetbrains.exposed.sql.tests.mysql import org.jetbrains.exposed.sql.tests.DatabaseTestsBase +import org.jetbrains.exposed.sql.tests.RepeatableTestRule import org.jetbrains.exposed.sql.tests.TestDB import org.jetbrains.exposed.sql.transactions.TransactionManager -import org.jetbrains.exposed.sql.tests.RepeatableTestRule import org.junit.Rule import org.junit.Test import kotlin.test.assertFalse @@ -12,11 +12,11 @@ class MysqlTests : DatabaseTestsBase() { @get:Rule val repeatRule = RepeatableTestRule() - + @Test fun testEmbeddedConnection() { withDb(TestDB.MYSQL) { assertFalse(TransactionManager.current().exec("SELECT VERSION();") { it.next(); it.getString(1) }.isNullOrEmpty()) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/AliasesTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/AliasesTests.kt index 00dbb1db05..1e8483d12f 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/AliasesTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/AliasesTests.kt @@ -38,11 +38,11 @@ class AliasesTests : DatabaseTestsBase() { val fAlias = Facilities.slice(Facilities.stableId, fcAlias).selectAll().groupBy(Facilities.stableId).alias("f") val sliceColumns = Stables.columns + fAlias[fcAlias] val stats = Stables.join(fAlias, JoinType.LEFT, Stables.id, fAlias[Facilities.stableId]) - .slice(sliceColumns) - .selectAll() - .groupBy(*sliceColumns.toTypedArray()).map { - it[Stables.name] to it[fAlias[fcAlias]] - }.toMap() + .slice(sliceColumns) + .selectAll() + .groupBy(*sliceColumns.toTypedArray()).map { + it[Stables.name] to it[fAlias[fcAlias]] + }.toMap() assertEquals(2, stats.size) assertEquals(1, stats["Stables1"]) assertNull(stats["Stables2"]) @@ -78,7 +78,7 @@ class AliasesTests : DatabaseTestsBase() { @Test fun `test wrap row with Aliased table`() { withTables(EntityTestsData.XTable) { - val entity1 = EntityTestsData.XEntity.new { + val entity1 = EntityTestsData.XEntity.new { this.b1 = false } @@ -96,7 +96,7 @@ class AliasesTests : DatabaseTestsBase() { @Test fun `test wrap row with Aliased query`() { withTables(EntityTestsData.XTable) { - val entity1 = EntityTestsData.XEntity.new { + val entity1 = EntityTestsData.XEntity.new { this.b1 = false } @@ -119,20 +119,20 @@ class AliasesTests : DatabaseTestsBase() { this[EntityTestsData.XTable.b1] = it } val aliasedExpression = EntityTestsData.XTable.id.max().alias("maxId") - val aliasedQuery = EntityTestsData.XTable. - slice(EntityTestsData.XTable.b1, aliasedExpression). - selectAll(). - groupBy(EntityTestsData.XTable.b1). - alias("maxBoolean") + val aliasedQuery = EntityTestsData.XTable + .slice(EntityTestsData.XTable.b1, aliasedExpression) + .selectAll() + .groupBy(EntityTestsData.XTable.b1) + .alias("maxBoolean") val aliasedBool = aliasedQuery[EntityTestsData.XTable.b1] val expressionToCheck = aliasedQuery[aliasedExpression] assertEquals("maxBoolean.maxId", expressionToCheck.toString()) - val resultQuery = aliasedQuery. - leftJoin(EntityTestsData.XTable, { this[aliasedExpression]}, { id }). - slice(aliasedBool, expressionToCheck). - selectAll() + val resultQuery = aliasedQuery + .leftJoin(EntityTestsData.XTable, { this[aliasedExpression] }, { id }) + .slice(aliasedBool, expressionToCheck) + .selectAll() val result = resultQuery.map { it[aliasedBool] to it[expressionToCheck]!!.value @@ -153,4 +153,4 @@ class AliasesTests : DatabaseTestsBase() { }.slice(t1Alias[table1Count]).selectAll().toList() } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ConnectionTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ConnectionTests.kt index 8c3b7beae3..7fbef0b0d3 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ConnectionTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ConnectionTests.kt @@ -16,15 +16,15 @@ class ConnectionTests : DatabaseTestsBase() { @Test fun testGettingColumnMetadata() { - withDb (TestDB.H2){ + withDb(TestDB.H2) { SchemaUtils.create(People) val columnMetadata = connection.metadata { requireNotNull(columns(People)[People]) }.toSet() val expected = setOf( - ColumnMetadata("ID", Types.BIGINT, false, 19), - ColumnMetadata("NAME", Types.VARCHAR, true, 80) + ColumnMetadata("ID", Types.BIGINT, false, 19), + ColumnMetadata("NAME", Types.VARCHAR, true, 80) ) assertEquals(expected, columnMetadata) } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/CoroutineTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/CoroutineTests.kt index ea270f8705..e7f1e3e5c5 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/CoroutineTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/CoroutineTests.kt @@ -10,18 +10,15 @@ import org.jetbrains.exposed.exceptions.ExposedSQLException import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.statements.api.ExposedConnection import org.jetbrains.exposed.sql.tests.DatabaseTestsBase +import org.jetbrains.exposed.sql.tests.RepeatableTest import org.jetbrains.exposed.sql.tests.TestDB import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransaction import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync -import org.jetbrains.exposed.sql.tests.RepeatableTest -import org.jetbrains.exposed.sql.transactions.inTopLevelTransaction import org.jetbrains.exposed.sql.transactions.transaction -import org.jetbrains.exposed.sql.transactions.transactionManager import org.junit.Rule import org.junit.Test import java.lang.Exception -import java.lang.IllegalStateException import java.sql.Connection import java.util.concurrent.Executors import kotlin.test.assertNotNull @@ -63,7 +60,6 @@ class CoroutineTests : DatabaseTestsBase() { while (!mainJob.isCompleted) Thread.sleep(100) mainJob.getCompletionExceptionOrNull()?.let { throw it } assertEquals(1, Testing.select { Testing.id.eq(1) }.single()[Testing.id].value) - } } @@ -72,7 +68,7 @@ class CoroutineTests : DatabaseTestsBase() { withTables(Testing) { val job = GlobalScope.async { val launchResult = suspendedTransactionAsync(Dispatchers.IO, db = db) { - Testing.insert{} + Testing.insert {} suspendedTransaction { assertEquals(1, Testing.select { Testing.id.eq(1) }.singleOrNull()?.getOrNull(Testing.id)?.value) @@ -101,7 +97,7 @@ class CoroutineTests : DatabaseTestsBase() { @Test @RepeatableTest(10) fun nestedSuspendTxTest() { - suspend fun insertTesting(db : Database) = newSuspendedTransaction(db = db) { + suspend fun insertTesting(db: Database) = newSuspendedTransaction(db = db) { Testing.insert {} } withTables(listOf(TestDB.SQLITE), Testing) { @@ -139,7 +135,7 @@ class CoroutineTests : DatabaseTestsBase() { val job = launch(Dispatchers.IO) { newSuspendedTransaction(db = db) { repeat(10) { - Testing.insert { } + Testing.insert { } } commit() (1..10).map { @@ -171,7 +167,7 @@ class CoroutineTests : DatabaseTestsBase() { val results = (1..5).map { indx -> suspendedTransactionAsync(Dispatchers.IO, db = db) { - Testing.insert { } + Testing.insert { } indx } }.awaitAll() @@ -188,7 +184,7 @@ class CoroutineTests : DatabaseTestsBase() { @Test @RepeatableTest(10) fun suspendedAndNormalTransactions() { - var db : Database? = null + var db: Database? = null withDb { db = this.db SchemaUtils.create(Testing) @@ -247,4 +243,4 @@ class CoroutineTests : DatabaseTestsBase() { assertEquals(1, Testing.selectAll().count()) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/DDLTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/DDLTests.kt index 5164655ebe..969a33bcb9 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/DDLTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/DDLTests.kt @@ -13,7 +13,6 @@ import org.jetbrains.exposed.sql.tests.TestDB import org.jetbrains.exposed.sql.tests.currentDialectTest import org.jetbrains.exposed.sql.tests.inProperCase import org.jetbrains.exposed.sql.tests.shared.dml.DMLTestsData -import org.jetbrains.exposed.sql.vendors.PostgreSQLDialect import org.jetbrains.exposed.sql.vendors.SQLServerDialect import org.jetbrains.exposed.sql.vendors.SQLiteDialect import org.junit.Test @@ -32,7 +31,7 @@ class DDLTests : DatabaseTestsBase() { } withTables { - assertEquals (false, TestTable.exists()) + assertEquals(false, TestTable.exists()) } } @@ -45,17 +44,17 @@ class DDLTests : DatabaseTestsBase() { } withTables(TestTable) { - assertEquals (true, TestTable.exists()) + assertEquals(true, TestTable.exists()) } } - object KeyWordTable : IntIdTable(name ="keywords") { + object KeyWordTable : IntIdTable(name = "keywords") { val bool = bool("bool") } @Test fun tableExistsWithKeyword() { withTables(KeyWordTable) { - assertEquals (true, KeyWordTable.exists()) + assertEquals(true, KeyWordTable.exists()) KeyWordTable.insert { it[bool] = true } @@ -74,8 +73,11 @@ class DDLTests : DatabaseTestsBase() { withTables(excludeSettings = listOf(TestDB.SQLITE), tables = *arrayOf(UnnamedTable)) { val q = db.identifierManager.quoteString val tableName = if (currentDialectTest.needsQuotesWhenSymbolsInNames) { "$q${"UnnamedTable$1".inProperCase()}$q" } else { "UnnamedTable$1".inProperCase() } - assertEquals("CREATE TABLE " + addIfNotExistsIfSupported() + "$tableName " + - "(${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerType()} PRIMARY KEY, $q${"name".inProperCase()}$q VARCHAR(42) NOT NULL)", UnnamedTable.ddl) + assertEquals( + "CREATE TABLE " + addIfNotExistsIfSupported() + "$tableName " + + "(${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerType()} PRIMARY KEY, $q${"name".inProperCase()}$q VARCHAR(42) NOT NULL)", + UnnamedTable.ddl + ) } } @@ -83,8 +85,11 @@ class DDLTests : DatabaseTestsBase() { withDb(TestDB.SQLITE) { val q = db.identifierManager.quoteString val tableName = if (currentDialectTest.needsQuotesWhenSymbolsInNames) { "$q${"UnnamedTable$1".inProperCase()}$q" } else { "UnnamedTable$1".inProperCase() } - assertEquals("CREATE TABLE " + addIfNotExistsIfSupported() + "$tableName " + - "(${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerType()} NOT NULL PRIMARY KEY, $q${"name".inProperCase()}$q VARCHAR(42) NOT NULL)", UnnamedTable.ddl) + assertEquals( + "CREATE TABLE " + addIfNotExistsIfSupported() + "$tableName " + + "(${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerType()} NOT NULL PRIMARY KEY, $q${"name".inProperCase()}$q VARCHAR(42) NOT NULL)", + UnnamedTable.ddl + ) } } @@ -92,7 +97,7 @@ class DDLTests : DatabaseTestsBase() { val TestTable = object : Table("test_named_table") { } - withDb (TestDB.H2 ) { + withDb(TestDB.H2) { assertEquals("CREATE TABLE IF NOT EXISTS ${"test_named_table".inProperCase()}", TestTable.ddl) DMLTestsData.Users.select { exists(DMLTestsData.UserData.select { DMLTestsData.Users.id eq DMLTestsData.UserData.user_id }) @@ -110,10 +115,13 @@ class DDLTests : DatabaseTestsBase() { } withTables(excludeSettings = listOf(TestDB.MYSQL, TestDB.ORACLE, TestDB.MARIADB, TestDB.SQLITE), tables = *arrayOf(TestTable)) { - assertEquals("CREATE TABLE " + addIfNotExistsIfSupported() + "${"different_column_types".inProperCase()} " + + assertEquals( + "CREATE TABLE " + addIfNotExistsIfSupported() + "${"different_column_types".inProperCase()} " + "(${"id".inProperCase()} ${currentDialectTest.dataTypeProvider.integerAutoincType()} NOT NULL, " + "\"${"name".inProperCase()}\" VARCHAR(42) PRIMARY KEY, " + - "${"age".inProperCase()} ${currentDialectTest.dataTypeProvider.integerType()} NULL)", TestTable.ddl) + "${"age".inProperCase()} ${currentDialectTest.dataTypeProvider.integerType()} NULL)", + TestTable.ddl + ) } } @@ -134,7 +142,7 @@ class DDLTests : DatabaseTestsBase() { val ageDescription = "${"age".inProperCase()} ${db.dialect.dataTypeProvider.integerType()} NULL" val constraint = "CONSTRAINT pk_with_different_column_types PRIMARY KEY (${"id".inProperCase()}, $q${"name".inProperCase()}$q)" - assertEquals( "$tableDescription ($idDescription, $nameDescription, $ageDescription, $constraint)", TestTable.ddl) + assertEquals("$tableDescription ($idDescription, $nameDescription, $ageDescription, $constraint)", TestTable.ddl) } } @@ -208,7 +216,7 @@ class DDLTests : DatabaseTestsBase() { override val primaryKey = PrimaryKey(id) init { - index (false, lvalue, rvalue) + index(false, lvalue, rvalue) } } @@ -218,8 +226,11 @@ class DDLTests : DatabaseTestsBase() { assertEquals("CREATE INDEX ${"t2_name".inProperCase()} ON ${"t2".inProperCase()} ($q${"name".inProperCase()}$q)", a1) val a2 = SchemaUtils.createIndex(t.indices[1]) - assertEquals("CREATE INDEX ${"t2_lvalue_rvalue".inProperCase()} ON ${"t2".inProperCase()} " + - "(${"lvalue".inProperCase()}, ${"rvalue".inProperCase()})", a2) + assertEquals( + "CREATE INDEX ${"t2_lvalue_rvalue".inProperCase()} ON ${"t2".inProperCase()} " + + "(${"lvalue".inProperCase()}, ${"rvalue".inProperCase()})", + a2 + ) } } @@ -238,7 +249,6 @@ class DDLTests : DatabaseTestsBase() { assertEquals("CREATE UNIQUE INDEX ${"t1_name".inProperCase()} ON ${"t1".inProperCase()} ($q${"name".inProperCase()}$q)", alter) else assertEquals("ALTER TABLE ${"t1".inProperCase()} ADD CONSTRAINT ${"t1_name_unique".inProperCase()} UNIQUE ($q${"name".inProperCase()}$q)", alter) - } } @@ -257,7 +267,6 @@ class DDLTests : DatabaseTestsBase() { assertEquals("CREATE UNIQUE INDEX ${"U_T1_NAME"} ON ${"t1".inProperCase()} ($q${"name".inProperCase()}$q)", alter) else assertEquals("ALTER TABLE ${"t1".inProperCase()} ADD CONSTRAINT ${"U_T1_NAME"} UNIQUE ($q${"name".inProperCase()}$q)", alter) - } } @@ -306,7 +315,7 @@ class DDLTests : DatabaseTestsBase() { } @Test fun testBlob() { - val t = object: Table("t1") { + val t = object : Table("t1") { val id = integer("id").autoIncrement("t1_seq") val b = blob("blob") @@ -326,9 +335,8 @@ class DDLTests : DatabaseTestsBase() { it[t.b] = blob } get (t.id) - val readOn = t.select { t.id eq id }.first()[t.b] - val text = String(readOn.bytes)//.reader().readText() + val text = String(readOn.bytes) // .reader().readText() assertEquals("Hello there!", text) } @@ -388,7 +396,7 @@ class DDLTests : DatabaseTestsBase() { t.insert { it[t.binary] = worldBytes it[t.byteCol] = byteArrayOf(1) - } + } assertEqualCollections(t.selectAll().readAsString(), "Hello!", "World!") @@ -480,7 +488,7 @@ class DDLTests : DatabaseTestsBase() { @Test fun testCrossReference() { withTables(Table1, Table2) { - val table2id = Table2.insertAndGetId{} + val table2id = Table2.insertAndGetId {} val table1id = Table1.insertAndGetId { it[table2] = table2id } @@ -506,11 +514,11 @@ class DDLTests : DatabaseTestsBase() { } @Test fun testUUIDColumnType() { - val Node = object: IntIdTable("node") { + val Node = object : IntIdTable("node") { val uuid = uuid("uuid") } - withTables(Node){ + withTables(Node) { val key: UUID = UUID.randomUUID() val id = Node.insertAndGetId { it[uuid] = key } assertNotNull(id) @@ -522,11 +530,11 @@ class DDLTests : DatabaseTestsBase() { } @Test fun testBooleanColumnType() { - val BoolTable = object: Table("booleanTable") { + val BoolTable = object : Table("booleanTable") { val bool = bool("bool") } - withTables(BoolTable){ + withTables(BoolTable) { BoolTable.insert { it[bool] = true } @@ -538,11 +546,11 @@ class DDLTests : DatabaseTestsBase() { @ExperimentalUnsignedTypes @Test fun testUByteColumnType() { - val UbyteTable = object: Table("ubyteTable") { + val UbyteTable = object : Table("ubyteTable") { val ubyte = ubyte("ubyte") } - withTables(UbyteTable){ + withTables(UbyteTable) { UbyteTable.insert { it[ubyte] = 123u } @@ -554,11 +562,11 @@ class DDLTests : DatabaseTestsBase() { @ExperimentalUnsignedTypes @Test fun testUshortColumnType() { - val UshortTable = object: Table("ushortTable") { + val UshortTable = object : Table("ushortTable") { val ushort = ushort("ushort") } - withTables(UshortTable){ + withTables(UshortTable) { UshortTable.insert { it[ushort] = 123u } @@ -570,11 +578,11 @@ class DDLTests : DatabaseTestsBase() { @ExperimentalUnsignedTypes @Test fun testUintColumnType() { - val UintTable = object: Table("uintTable") { + val UintTable = object : Table("uintTable") { val uint = uinteger("uint") } - withTables(UintTable){ + withTables(UintTable) { UintTable.insert { it[uint] = 123u } @@ -586,11 +594,11 @@ class DDLTests : DatabaseTestsBase() { @ExperimentalUnsignedTypes @Test fun testUlongColumnType() { - val UlongTable = object: Table("ulongTable") { + val UlongTable = object : Table("ulongTable") { val ulong = ulong("ulong") } - withTables(UlongTable){ + withTables(UlongTable) { UlongTable.insert { it[ulong] = 123uL } @@ -673,7 +681,7 @@ class DDLTests : DatabaseTestsBase() { internal enum class Foo { Bar, Baz } - class PGEnum>(enumTypeName: String, enumValue: T?) : PGobject() { + class PGEnum>(enumTypeName: String, enumValue: T?) : PGobject() { init { value = enumValue?.name type = enumTypeName @@ -706,7 +714,7 @@ class DDLTests : DatabaseTestsBase() { } withTables(Subscriptions) { - val query = Subscriptions.join(Users, JoinType.INNER, additionalConstraint = {Subscriptions.user eq Users.id}).selectAll() + val query = Subscriptions.join(Users, JoinType.INNER, additionalConstraint = { Subscriptions.user eq Users.id }).selectAll() assertEquals(0L, query.count()) } } @@ -738,5 +746,3 @@ class DDLTests : DatabaseTestsBase() { val reference = reference("testOne", TableFromSchemeOne) } } - - diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/FunctionsTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/FunctionsTests.kt index 34643ec69a..b7ec3874ed 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/FunctionsTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/FunctionsTests.kt @@ -30,7 +30,7 @@ class FunctionsTests : DatabaseTestsBase() { Sum(cities.id + userData.value, IntegerColumnType()) } val r = (users innerJoin userData innerJoin cities).slice(users.id, sum) - .selectAll().groupBy(users.id).orderBy(users.id).toList() + .selectAll().groupBy(users.id).orderBy(users.id).toList() assertEquals(2, r.size) assertEquals("eugene", r[0][users.id]) assertEquals(22, r[0][sum]) @@ -46,7 +46,7 @@ class FunctionsTests : DatabaseTestsBase() { val mod1 = Expression.build { sum % 100 } val mod2 = Expression.build { sum mod 100 } val r = (users innerJoin userData innerJoin cities).slice(users.id, sum, mod1, mod1) - .selectAll().groupBy(users.id).orderBy(users.id).toList() + .selectAll().groupBy(users.id).orderBy(users.id).toList() assertEquals(2, r.size) assertEquals("eugene", r[0][users.id]) assertEquals(202, r[0][sum]) @@ -64,7 +64,7 @@ class FunctionsTests : DatabaseTestsBase() { withCitiesAndUsers { cities, users, userData -> val substring = users.name.substring(1, 2) val r = (users).slice(users.id, substring) - .selectAll().orderBy(users.id).toList() + .selectAll().orderBy(users.id).toList() assertEquals(5, r.size) assertEquals("Al", r[0][substring]) assertEquals("An", r[1][substring]) @@ -76,7 +76,7 @@ class FunctionsTests : DatabaseTestsBase() { @Test fun testLengthWithCount01() { - class LengthFunction>(val exp: T) : Function(IntegerColumnType()) { + class LengthFunction>(val exp: T) : Function(IntegerColumnType()) { override fun toQueryBuilder(queryBuilder: QueryBuilder) = queryBuilder { if (currentDialectTest is SQLServerDialect) append("LEN(", exp, ')') else append("LENGTH(", exp, ')') @@ -84,7 +84,7 @@ class FunctionsTests : DatabaseTestsBase() { } withCitiesAndUsers { cities, _, _ -> val sumOfLength = LengthFunction(cities.name).sum() - val expectedValue = cities.selectAll().sumBy{ it[cities.name].length } + val expectedValue = cities.selectAll().sumBy { it[cities.name].length } val results = cities.slice(sumOfLength).selectAll().toList() assertEquals(1, results.size) @@ -92,7 +92,6 @@ class FunctionsTests : DatabaseTestsBase() { } } - @Test fun testSelectCase01() { withCitiesAndUsers { cities, users, userData -> @@ -165,11 +164,11 @@ class FunctionsTests : DatabaseTestsBase() { @Test fun testConcat02() { withCitiesAndUsers { _, users, _ -> val concatField = concat(users.id, stringLiteral(" - "), users.name) - val result = users.slice(concatField).select{ users.id eq "andrey" }.single() + val result = users.slice(concatField).select { users.id eq "andrey" }.single() assertEquals("andrey - Andrey", result[concatField]) val concatField2 = concat("!", listOf(users.id, users.name)) - val result2 = users.slice(concatField2).select{ users.id eq "andrey" }.single() + val result2 = users.slice(concatField2).select { users.id eq "andrey" }.single() assertEquals("andrey!Andrey", result2[concatField2]) } } @@ -177,11 +176,11 @@ class FunctionsTests : DatabaseTestsBase() { @Test fun testConcatWithNumbers() { withCitiesAndUsers { _, _, data -> val concatField = concat(data.user_id, stringLiteral(" - "), data.comment, stringLiteral(" - "), data.value) - val result = data.slice(concatField).select{ data.user_id eq "sergey" }.single() + val result = data.slice(concatField).select { data.user_id eq "sergey" }.single() assertEquals("sergey - Comment for Sergey - 30", result[concatField]) val concatField2 = concat("!", listOf(data.user_id, data.comment, data.value)) - val result2 = data.slice(concatField2).select{ data.user_id eq "sergey" }.single() + val result2 = data.slice(concatField2).select { data.user_id eq "sergey" }.single() assertEquals("sergey!Comment for Sergey!30", result2[concatField2]) } } @@ -238,8 +237,10 @@ class FunctionsTests : DatabaseTestsBase() { val thirdOp = exists(DMLTestsData.Cities.selectAll()) assertEquals("($initialOp) AND $thirdOp", (initialOp and thirdOp).toString()) - assertEquals("($initialOp) AND ($secondOp) AND $thirdOp", - (initialOp and secondOp and thirdOp).toString()) + assertEquals( + "($initialOp) AND ($secondOp) AND $thirdOp", + (initialOp and secondOp and thirdOp).toString() + ) } } @@ -254,8 +255,10 @@ class FunctionsTests : DatabaseTestsBase() { val thirdOp = exists(DMLTestsData.Cities.selectAll()) assertEquals("($initialOp) OR $thirdOp", (initialOp or thirdOp).toString()) - assertEquals("($initialOp) OR ($secondOp) OR $thirdOp", - (initialOp or secondOp or thirdOp).toString()) + assertEquals( + "($initialOp) OR ($secondOp) OR $thirdOp", + (initialOp or secondOp or thirdOp).toString() + ) } } @@ -282,14 +285,14 @@ class FunctionsTests : DatabaseTestsBase() { fun testCustomOperator() { // implement a + operator using CustomOperator infix fun Expression<*>.plus(operand: Int) = - CustomOperator("+", IntegerColumnType(), this, intParam(operand)) + CustomOperator("+", IntegerColumnType(), this, intParam(operand)) withCitiesAndUsers { cities, users, userData -> userData - .select { (userData.value plus 15).eq(35) } - .forEach { - assertEquals(it[userData.value], 20) - } + .select { (userData.value plus 15).eq(35) } + .forEach { + assertEquals(it[userData.value], 20) + } } } @@ -305,7 +308,6 @@ class FunctionsTests : DatabaseTestsBase() { else assertEquals(1000, it[coalesceExp1]) } - } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/NestedTransactionsTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/NestedTransactionsTest.kt index 9c36fcd2e7..bec4ce2e3f 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/NestedTransactionsTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/NestedTransactionsTest.kt @@ -61,11 +61,11 @@ class NestedTransactionsTest : DatabaseTestsBase() { inTopLevelTransaction(this.transactionIsolation, 1) { throw IllegalStateException("Should be rethrow") } - } catch (e: Exception){ + } catch (e: Exception) { assertTrue(e is IllegalStateException) } assertNotNull(TransactionManager.currentOrNull()) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/SchemaTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/SchemaTests.kt index 60c5fe80d6..0c4ac056fc 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/SchemaTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/SchemaTests.kt @@ -68,7 +68,7 @@ class SchemaTests : DatabaseTestsBase() { exec("CREATE TABLE test(id INT PRIMARY KEY)") SchemaUtils.setSchema(schema) - exec("CREATE TABLE test(id INT REFERENCES ${firstCatalogName}.test(id))") + exec("CREATE TABLE test(id INT REFERENCES $firstCatalogName.test(id))") val catalogName = connection.catalog @@ -117,4 +117,4 @@ class SchemaTests : DatabaseTestsBase() { assertFalse(schema2.exists()) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ThreadLocalManagerTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ThreadLocalManagerTest.kt index 4ad2e66b66..6da0e1c0c7 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ThreadLocalManagerTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ThreadLocalManagerTest.kt @@ -36,7 +36,7 @@ private open class DataSourceStub : DataSource { override fun getLoginTimeout(): Int { throw NotImplementedError() } } -class ConnectionTimeoutTest : DatabaseTestsBase(){ +class ConnectionTimeoutTest : DatabaseTestsBase() { private class ExceptionOnGetConnectionDataSource : DataSourceStub() { var connectCount = 0 @@ -50,7 +50,7 @@ class ConnectionTimeoutTest : DatabaseTestsBase(){ private class GetConnectException : SQLTransientException() @Test - fun `connect fail causes repeated connect attempts`(){ + fun `connect fail causes repeated connect attempts`() { val datasource = ExceptionOnGetConnectionDataSource() val db = Database.connect(datasource = datasource) @@ -60,7 +60,7 @@ class ConnectionTimeoutTest : DatabaseTestsBase(){ // NO OP } fail("Should have thrown ${GetConnectException::class.simpleName}") - } catch (e : ExposedSQLException){ + } catch (e: ExposedSQLException) { assertTrue(e.cause is GetConnectException) assertEquals(42, datasource.connectCount) } @@ -111,7 +111,7 @@ class ConnectionExceptions { fun `transaction repetition works even if rollback throws exception`() { `_transaction repetition works even if rollback throws exception`(::ExceptionOnRollbackConnection) } - private fun `_transaction repetition works even if rollback throws exception`(connectionDecorator: (Connection) -> ConnectionSpy){ + private fun `_transaction repetition works even if rollback throws exception`(connectionDecorator: (Connection) -> ConnectionSpy) { Class.forName(TestDB.H2.driver).newInstance() val wrappingDataSource = ConnectionExceptions.WrappingDataSource(TestDB.H2, connectionDecorator) @@ -121,7 +121,7 @@ class ConnectionExceptions { this.exec("BROKEN_SQL_THAT_CAUSES_EXCEPTION()") } fail("Should have thrown an exception") - } catch (e : SQLException){ + } catch (e: SQLException) { assertThat(e.toString(), Matchers.containsString("BROKEN_SQL_THAT_CAUSES_EXCEPTION")) assertEquals(5, wrappingDataSource.connections.size) wrappingDataSource.connections.forEach { @@ -164,10 +164,10 @@ class ConnectionExceptions { } @Test - fun `transaction throws exception if all commits throws exception`(){ + fun `transaction throws exception if all commits throws exception`() { `_transaction throws exception if all commits throws exception`(::ExceptionOnCommitConnection) } - private fun `_transaction throws exception if all commits throws exception`(connectionDecorator: (Connection) -> ConnectionSpy){ + private fun `_transaction throws exception if all commits throws exception`(connectionDecorator: (Connection) -> ConnectionSpy) { Class.forName(TestDB.H2.driver).newInstance() val wrappingDataSource = ConnectionExceptions.WrappingDataSource(TestDB.H2, connectionDecorator) @@ -177,7 +177,7 @@ class ConnectionExceptions { this.exec("SELECT 1;") } fail("Should have thrown an exception") - } catch (e : CommitException){ + } catch (e: CommitException) { // Yay } } @@ -196,12 +196,12 @@ class ConnectionExceptions { } @Test - fun `transaction repetition works even if rollback and close throws exception`(){ + fun `transaction repetition works even if rollback and close throws exception`() { `_transaction repetition works even if rollback throws exception`(::ExceptionOnRollbackCloseConnection) } @Test - fun `transaction repetition works when commit and close throws exception`(){ + fun `transaction repetition works when commit and close throws exception`() { `_transaction repetition works when commit throws exception`(::ExceptionOnCommitConnection) } @@ -218,15 +218,14 @@ class ConnectionExceptions { } @Test - fun `transaction throws exception if all commits and close throws exception`(){ + fun `transaction throws exception if all commits and close throws exception`() { `_transaction throws exception if all commits throws exception`(::ExceptionOnCommitCloseConnection) } @After - fun `teardown`(){ + fun `teardown`() { TransactionManager.resetCurrent(null) } - } class ThreadLocalManagerTest : DatabaseTestsBase() { diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateMissingTablesAndColumnsTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateMissingTablesAndColumnsTests.kt index e5f092db2d..bbf3a595e7 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateMissingTablesAndColumnsTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateMissingTablesAndColumnsTests.kt @@ -121,7 +121,6 @@ class CreateMissingTablesAndColumnsTests : DatabaseTestsBase() { } val t = IntIdTable(tableName) - withDb(TestDB.H2) { SchemaUtils.createMissingTablesAndColumns(initialTable) assertEquals("ALTER TABLE ${tableName.inProperCase()} ADD ${"id".inProperCase()} ${t.id.columnType.sqlType()}", t.id.ddl.first()) @@ -177,7 +176,7 @@ class CreateMissingTablesAndColumnsTests : DatabaseTestsBase() { } } - object MultipleIndexesTable: Table("H2_MULTIPLE_INDEXES") { + object MultipleIndexesTable : Table("H2_MULTIPLE_INDEXES") { val value1 = varchar("value1", 255) val value2 = varchar("value2", 255) @@ -194,15 +193,14 @@ class CreateMissingTablesAndColumnsTests : DatabaseTestsBase() { } } - object PlayerTable: IntIdTable() { + object PlayerTable : IntIdTable() { val username = varchar("username", 10).uniqueIndex().nullable() } - object SessionsTable: IntIdTable() { + object SessionsTable : IntIdTable() { val playerId = integer("player_id").references(PlayerTable.id) } - @Test fun createTableWithReservedIdentifierInColumnName() { withDb(TestDB.MYSQL) { SchemaUtils.createMissingTablesAndColumns(T1, T2) @@ -213,11 +211,11 @@ class CreateMissingTablesAndColumnsTests : DatabaseTestsBase() { } } - object T1: Table("ARRAY") { + object T1 : Table("ARRAY") { val name = integer("name").uniqueIndex() val tmp = varchar("temp", 255) } - object T2: Table("CHAIN") { + object T2 : Table("CHAIN") { val ref = integer("ref").references(T1.name) } @@ -237,4 +235,4 @@ class CreateMissingTablesAndColumnsTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateSequenceTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateSequenceTest.kt index 7028d805c5..656a61d5d2 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateSequenceTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateSequenceTest.kt @@ -14,12 +14,12 @@ class SequencesTests : DatabaseTestsBase() { if (currentDialectTest.supportsCreateSequence) { assertEquals( "CREATE SEQUENCE " + addIfNotExistsIfSupported() + "${myseq.identifier} " + - "START WITH ${myseq.startWith} " + - "INCREMENT BY ${myseq.incrementBy} " + - "MINVALUE ${myseq.minValue} " + - "MAXVALUE ${myseq.maxValue} " + - "CYCLE " + - "CACHE ${myseq.cache}", + "START WITH ${myseq.startWith} " + + "INCREMENT BY ${myseq.incrementBy} " + + "MINVALUE ${myseq.minValue} " + + "MAXVALUE ${myseq.maxValue} " + + "CYCLE " + + "CACHE ${myseq.cache}", myseq.ddl ) } @@ -79,7 +79,6 @@ class SequencesTests : DatabaseTestsBase() { } } - @Test fun `test select with nextVal`() { withTables(Developer) { @@ -100,7 +99,6 @@ class SequencesTests : DatabaseTestsBase() { val expSecondValue = expFirstValue + myseq.incrementBy!! assertEquals(expSecondValue, secondValue.toLong()) - } finally { SchemaUtils.dropSequence(myseq) } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateTableTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateTableTests.kt index 898f48153c..145b16d09b 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateTableTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/CreateTableTests.kt @@ -48,11 +48,12 @@ class CreateTableTests : DatabaseTestsBase() { val tableName = account.tableName assertEquals( - "CREATE TABLE " + addIfNotExistsIfSupported() + "${tableName.inProperCase()} (" + - "${account.columns.joinToString { it.descriptionDdl() }}, " + - "CONSTRAINT pk_$tableName PRIMARY KEY ($id1ProperName, $id2ProperName)" + - ")", - account.ddl) + "CREATE TABLE " + addIfNotExistsIfSupported() + "${tableName.inProperCase()} (" + + "${account.columns.joinToString { it.descriptionDdl() }}, " + + "CONSTRAINT pk_$tableName PRIMARY KEY ($id1ProperName, $id2ProperName)" + + ")", + account.ddl + ) } } @@ -67,14 +68,15 @@ class CreateTableTests : DatabaseTestsBase() { val tableName = Person.tableName assertEquals( - "CREATE TABLE " + addIfNotExistsIfSupported() + "${tableName.inProperCase()} (" + - "${Person.columns.joinToString { it.descriptionDdl() }}, " + - "CONSTRAINT $pkConstraintName PRIMARY KEY ($id1ProperName, $id2ProperName)" + - ")", - Person.ddl) + "CREATE TABLE " + addIfNotExistsIfSupported() + "${tableName.inProperCase()} (" + + "${Person.columns.joinToString { it.descriptionDdl() }}, " + + "CONSTRAINT $pkConstraintName PRIMARY KEY ($id1ProperName, $id2ProperName)" + + ")", + Person.ddl + ) } - //Table with single column in primary key. + // Table with single column in primary key. val user = object : Table("User") { val user_name = varchar("user_name", 25) @@ -86,11 +88,12 @@ class CreateTableTests : DatabaseTestsBase() { // Must generate primary key constraint, because the constraint name was defined. assertEquals( - "CREATE TABLE " + addIfNotExistsIfSupported() + "$tableName (" + - "${user.columns.joinToString { it.descriptionDdl() }}, " + - "CONSTRAINT $pkConstraintName PRIMARY KEY ($userNameProperName)" + - ")", - user.ddl) + "CREATE TABLE " + addIfNotExistsIfSupported() + "$tableName (" + + "${user.columns.joinToString { it.descriptionDdl() }}, " + + "CONSTRAINT $pkConstraintName PRIMARY KEY ($userNameProperName)" + + ")", + user.ddl + ) } } @@ -179,11 +182,11 @@ class CreateTableTests : DatabaseTestsBase() { val parent = object : LongIdTable("parent1") {} val child = object : LongIdTable("child1") { val parentId = reference( - name = "parent_id", - foreign = parent, - onUpdate = ReferenceOption.NO_ACTION, - onDelete = ReferenceOption.NO_ACTION, - fkName = fkName + name = "parent_id", + foreign = parent, + onUpdate = ReferenceOption.NO_ACTION, + onDelete = ReferenceOption.NO_ACTION, + fkName = fkName ) } withTables(parent, child) { @@ -209,11 +212,11 @@ class CreateTableTests : DatabaseTestsBase() { } val child = object : LongIdTable("child2") { val parentId = reference( - name = "parent_id", - refColumn = parent.uniqueId, - onUpdate = ReferenceOption.NO_ACTION, - onDelete = ReferenceOption.NO_ACTION, - fkName = fkName + name = "parent_id", + refColumn = parent.uniqueId, + onUpdate = ReferenceOption.NO_ACTION, + onDelete = ReferenceOption.NO_ACTION, + fkName = fkName ) } withTables(parent, child) { @@ -237,11 +240,11 @@ class CreateTableTests : DatabaseTestsBase() { val parent = object : LongIdTable("parent3") {} val child = object : LongIdTable("child3") { val parentId = optReference( - name = "parent_id", - foreign = parent, - onUpdate = ReferenceOption.NO_ACTION, - onDelete = ReferenceOption.NO_ACTION, - fkName = fkName + name = "parent_id", + foreign = parent, + onUpdate = ReferenceOption.NO_ACTION, + onDelete = ReferenceOption.NO_ACTION, + fkName = fkName ) } withTables(parent, child) { @@ -267,11 +270,11 @@ class CreateTableTests : DatabaseTestsBase() { } val child = object : LongIdTable("child4") { val parentId = optReference( - name = "parent_id", - refColumn = parent.uniqueId, - onUpdate = ReferenceOption.NO_ACTION, - onDelete = ReferenceOption.NO_ACTION, - fkName = fkName + name = "parent_id", + refColumn = parent.uniqueId, + onUpdate = ReferenceOption.NO_ACTION, + onDelete = ReferenceOption.NO_ACTION, + fkName = fkName ) } withTables(parent, child) { @@ -289,8 +292,8 @@ class CreateTableTests : DatabaseTestsBase() { } } - object OneTable : IntIdTable("one") {} - object OneOneTable : IntIdTable("one.one") {} + object OneTable : IntIdTable("one") + object OneOneTable : IntIdTable("one.one") @Test fun `test create table with same name in different schemas`() { diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/EnumerationTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/EnumerationTests.kt index 90a333ffe8..ffaa4daf4a 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/EnumerationTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/EnumerationTests.kt @@ -21,17 +21,21 @@ class EnumerationTests : DatabaseTestsBase() { internal fun initEnumColumn(sql: String) { (columns as MutableList>).remove(enumColumn) - enumColumn = customEnumeration("enumColumn", sql, { value -> - when { - currentDialectTest is H2Dialect && value is Int -> DDLTests.Foo.values()[value] - else -> DDLTests.Foo.valueOf(value as String) + enumColumn = customEnumeration( + "enumColumn", sql, + { value -> + when { + currentDialectTest is H2Dialect && value is Int -> DDLTests.Foo.values()[value] + else -> DDLTests.Foo.valueOf(value as String) + } + }, + { value -> + when (currentDialectTest) { + is PostgreSQLDialect -> DDLTests.PGEnum(sql, value) + else -> value.name + } } - }, { value -> - when (currentDialectTest) { - is PostgreSQLDialect -> DDLTests.PGEnum(sql, value) - else -> value.name - } - }) + ) } } @@ -60,7 +64,7 @@ class EnumerationTests : DatabaseTestsBase() { EnumTable.insert { it[enumColumn] = DDLTests.Foo.Bar } - assertEquals(DDLTests.Foo.Bar, EnumTable.selectAll().single()[EnumTable.enumColumn]) + assertEquals(DDLTests.Foo.Bar, EnumTable.selectAll().single()[EnumTable.enumColumn]) EnumTable.update { it[enumColumn] = DDLTests.Foo.Baz @@ -103,7 +107,7 @@ class EnumerationTests : DatabaseTestsBase() { } SchemaUtils.create(EnumTable) - EnumTable.insert { } + EnumTable.insert { } val default = EnumTable.selectAll().single()[EnumTable.enumColumn] assertEquals(DDLTests.Foo.Bar, default) } finally { @@ -113,4 +117,4 @@ class EnumerationTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/ReplaceColumnTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/ReplaceColumnTests.kt index 19a9b4e940..4c0a44f26c 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/ReplaceColumnTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/ReplaceColumnTests.kt @@ -5,7 +5,6 @@ import org.jetbrains.exposed.exceptions.DuplicateColumnException import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.tests.DatabaseTestsBase import org.junit.Test - import kotlin.test.assertFailsWith class ReplaceColumnTests : DatabaseTestsBase() { @@ -15,10 +14,11 @@ class ReplaceColumnTests : DatabaseTestsBase() { val assertionFailureMessage = "Can't replace a column with another one that has the same name as an existing column" withTables(IDTable) { - assertFailsWith(exceptionClass = DuplicateColumnException::class, - message = assertionFailureMessage + assertFailsWith( + exceptionClass = DuplicateColumnException::class, + message = assertionFailureMessage ) { - //Duplicate the id column by replacing the IDTable.code by a column with the name "id" + // Duplicate the id column by replacing the IDTable.code by a column with the name "id" val id = Column(IDTable, IDTable.id.name, IDTable.id.columnType) IDTable.replaceColumn(IDTable.code, id) } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/WhereConditionsTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/WhereConditionsTests.kt index d0d4e84f8c..d2079704f6 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/WhereConditionsTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/ddl/WhereConditionsTests.kt @@ -1,8 +1,5 @@ package org.jetbrains.exposed.sql.tests.shared.ddl -import kotlin.test.assertEquals -import kotlin.test.assertTrue - import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select @@ -10,41 +7,43 @@ import org.jetbrains.exposed.sql.stringLiteral import org.jetbrains.exposed.sql.tests.DatabaseTestsBase import org.jetbrains.exposed.sql.upperCase import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue /** * This class contains tests for logical sql operators */ -class WhereConditionsTests: DatabaseTestsBase() { - object User: Table() { - val name = varchar("name", 20) - } +class WhereConditionsTests : DatabaseTestsBase() { + object User : Table() { + val name = varchar("name", 20) + } - @Test - fun whereLikeExpressionTest() { - withTables(User) { - User.insert { - it[name] = "HICHEM" - } - val namesResult = User.select { - User.name like stringLiteral("Hich%").upperCase() - }.map { it[User.name] } + @Test + fun whereLikeExpressionTest() { + withTables(User) { + User.insert { + it[name] = "HICHEM" + } + val namesResult = User.select { + User.name like stringLiteral("Hich%").upperCase() + }.map { it[User.name] } - assertEquals(1, namesResult.size) - assertEquals("HICHEM", namesResult.first()) + assertEquals(1, namesResult.size) + assertEquals("HICHEM", namesResult.first()) + } } - } - @Test - fun whereNotLikeExpressionTest() { - withTables(User) { - User.insert { - it[name] = "HICHEM" - } - val namesResult = User.select { - User.name notLike stringLiteral("Hich%").upperCase() - }.map { it } + @Test + fun whereNotLikeExpressionTest() { + withTables(User) { + User.insert { + it[name] = "HICHEM" + } + val namesResult = User.select { + User.name notLike stringLiteral("Hich%").upperCase() + }.map { it } - assertTrue(namesResult.isEmpty()) + assertTrue(namesResult.isEmpty()) + } } - } } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/AdjustQueryTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/AdjustQueryTests.kt index 5da3003eef..7e39545bf4 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/AdjustQueryTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/AdjustQueryTests.kt @@ -43,7 +43,7 @@ class AdjustQueryTests : DatabaseTestsBase() { val expectedColumnSet = users innerJoin cities queryAdjusted.adjustColumnSet { innerJoin(cities) } val actualColumnSet = queryAdjusted.set.source - fun ColumnSet.repr(): String = QueryBuilder(false).also { this.describe(TransactionManager.current(), it ) }.toString() + fun ColumnSet.repr(): String = QueryBuilder(false).also { this.describe(TransactionManager.current(), it) }.toString() assertNotEquals(oldColumnSet.repr(), actualColumnSet.repr()) assertEquals(expectedColumnSet.repr(), actualColumnSet.repr()) @@ -78,7 +78,7 @@ class AdjustQueryTests : DatabaseTestsBase() { withCitiesAndUsers { cities, users, _ -> val queryAdjusted = (users innerJoin cities) .slice(users.name, cities.name) - .select{ predicate } + .select { predicate } queryAdjusted.andWhere { predicate @@ -114,4 +114,4 @@ class AdjustQueryTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ArithmeticTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ArithmeticTests.kt index 32d7b27976..4ea7048189 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ArithmeticTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ArithmeticTests.kt @@ -44,4 +44,4 @@ class ArithmeticTests : DatabaseTestsBase() { assertEquals(BigDecimal.valueOf(3.33), resultWithScale) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ConditionsTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ConditionsTests.kt index f6a6fde3b8..576a41f4d5 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ConditionsTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ConditionsTests.kt @@ -74,4 +74,4 @@ class ConditionsTests : DatabaseTestsBase() { ) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/CountTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/CountTests.kt index 5311460ada..639030d66c 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/CountTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/CountTests.kt @@ -41,4 +41,4 @@ class CountTests : DatabaseTestsBase() { assertEquals(1L, OrgMemberships.selectAll().count()) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DMLTestData.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DMLTestData.kt index 71b5e419ca..69822f8695 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DMLTestData.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DMLTestData.kt @@ -104,7 +104,6 @@ fun DatabaseTestsBase.withCitiesAndUsers(exclude: List = emptyList(), st statement(Cities, Users, UserData) } - } object OrgMemberships : IntIdTable() { @@ -130,5 +129,4 @@ class Org(id: EntityID) : IntEntity(id) { var name by Orgs.name } - -internal fun Iterable.toCityNameList(): List = map { it[DMLTestsData.Cities.name] } \ No newline at end of file +internal fun Iterable.toCityNameList(): List = map { it[DMLTestsData.Cities.name] } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DeleteTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DeleteTests.kt index eab46d24a2..b909aff5c7 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DeleteTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/DeleteTests.kt @@ -22,7 +22,6 @@ class DeleteTests : DatabaseTestsBase() { exclude } - @Test fun testDelete01() { withCitiesAndUsers { cities, users, userData -> @@ -62,4 +61,4 @@ class DeleteTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ExistsTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ExistsTests.kt index 474fc76b0a..03f1bd16b9 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ExistsTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ExistsTests.kt @@ -34,7 +34,7 @@ class ExistsTests : DatabaseTestsBase() { withCitiesAndUsers { cities, users, userData -> val r = users.select { exists(userData.select((userData.user_id eq users.id) and (userData.comment like "%here%"))) or - exists(userData.select((userData.user_id eq users.id) and (userData.comment like "%Sergey"))) + exists(userData.select((userData.user_id eq users.id) and (userData.comment like "%Sergey"))) } .orderBy(users.id).toList() assertEquals(2, r.size) @@ -42,4 +42,4 @@ class ExistsTests : DatabaseTestsBase() { assertEquals("Something", r[1][users.name]) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/GroupByTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/GroupByTests.kt index 7026648756..346ad0ceea 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/GroupByTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/GroupByTests.kt @@ -50,7 +50,7 @@ class GroupByTests : DatabaseTestsBase() { val maxExpr = cities.id.max() val r = (cities innerJoin users).slice(cities.name, users.id.count(), maxExpr).selectAll() .groupBy(cities.name) - .having{users.id.count().eq(maxExpr)} + .having { users.id.count().eq(maxExpr) } .orderBy(cities.name) .toList() @@ -156,7 +156,7 @@ class GroupByTests : DatabaseTestsBase() { @Test fun testGroupConcat() { withCitiesAndUsers(listOf(TestDB.SQLITE)) { cities, users, _ -> - fun GroupConcat.checkExcept(vararg dialects: KClass, assert: (Map) ->Unit) { + fun GroupConcat.checkExcept(vararg dialects: KClass, assert: (Map) -> Unit) { try { val result = cities.leftJoin(users) .slice(cities.name, this) @@ -166,7 +166,7 @@ class GroupByTests : DatabaseTestsBase() { } assert(result) } catch (e: UnsupportedByDialectException) { - assertTrue(e.dialect::class in dialects, e.message!! ) + assertTrue(e.dialect::class in dialects, e.message!!) } } users.name.groupConcat().checkExcept(PostgreSQLDialect::class, PostgreSQLNGDialect::class, SQLServerDialect::class, OracleDialect::class) { @@ -197,7 +197,8 @@ class GroupByTests : DatabaseTestsBase() { } users.name.groupConcat(separator = " | ", orderBy = users.name to SortOrder.ASC).checkExcept( - PostgreSQLDialect::class, PostgreSQLNGDialect::class) { + PostgreSQLDialect::class, PostgreSQLNGDialect::class + ) { assertEquals(3, it.size) assertEquals("Andrey", it["St. Petersburg"]) assertEquals("Eugene | Sergey", it["Munich"]) @@ -205,7 +206,8 @@ class GroupByTests : DatabaseTestsBase() { } users.name.groupConcat(separator = " | ", orderBy = users.name to SortOrder.DESC).checkExcept( - PostgreSQLDialect::class, PostgreSQLNGDialect::class) { + PostgreSQLDialect::class, PostgreSQLNGDialect::class + ) { assertEquals(3, it.size) assertEquals("Andrey", it["St. Petersburg"]) assertEquals("Sergey | Eugene", it["Munich"]) @@ -213,4 +215,4 @@ class GroupByTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertSelectTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertSelectTests.kt index e4f98861f6..d910522282 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertSelectTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertSelectTests.kt @@ -61,4 +61,4 @@ class InsertSelectTests : DatabaseTestsBase() { assertEquals(1, users.select { users.name eq "Foo" }.count()) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertTests.kt index 38563c7682..4a6d1e5835 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/InsertTests.kt @@ -45,7 +45,7 @@ class InsertTests : DatabaseTestsBase() { } private val insertIgnoreSupportedDB = TestDB.values().toList() - - listOf(TestDB.SQLITE, TestDB.MYSQL, TestDB.H2_MYSQL, TestDB.POSTGRESQL, TestDB.POSTGRESQLNG) + listOf(TestDB.SQLITE, TestDB.MYSQL, TestDB.H2_MYSQL, TestDB.POSTGRESQL, TestDB.POSTGRESQLNG) @Test fun testInsertIgnoreAndGetId01() { @@ -53,7 +53,6 @@ class InsertTests : DatabaseTestsBase() { val name = varchar("foo", 10).uniqueIndex() } - withTables(insertIgnoreSupportedDB, idTable) { idTable.insertIgnoreAndGetId { it[idTable.name] = "1" @@ -123,7 +122,7 @@ class InsertTests : DatabaseTestsBase() { } val insertIgnoreSupportedDB = TestDB.values().toList() - - listOf(TestDB.SQLITE, TestDB.MYSQL, TestDB.H2_MYSQL, TestDB.POSTGRESQL, TestDB.POSTGRESQLNG) + listOf(TestDB.SQLITE, TestDB.MYSQL, TestDB.H2_MYSQL, TestDB.POSTGRESQL, TestDB.POSTGRESQLNG) withTables(insertIgnoreSupportedDB, idTable) { val id = idTable.insertIgnore { it[idTable.id] = EntityID(1, idTable) @@ -133,7 +132,6 @@ class InsertTests : DatabaseTestsBase() { } } - @Test fun testBatchInsert01() { withCitiesAndUsers { cities, users, _ -> @@ -235,7 +233,7 @@ class InsertTests : DatabaseTestsBase() { fun expression(value: String) = stringLiteral(value).trim().substring(2, 4) fun verify(value: String) { - val row = tbl.select{ tbl.string eq value }.single() + val row = tbl.select { tbl.string eq value }.single() assertEquals(row[tbl.string], value) } @@ -272,7 +270,7 @@ class InsertTests : DatabaseTestsBase() { } fun verify(value: String) { - val row = tbl2.select{ tbl2.string2 eq value }.single() + val row = tbl2.select { tbl2.string2 eq value }.single() assertEquals(row[tbl2.string2], value) } @@ -290,14 +288,12 @@ class InsertTests : DatabaseTestsBase() { } } - private object OrderedDataTable : IntIdTable() - { + private object OrderedDataTable : IntIdTable() { val name = text("name") val order = integer("order") } - class OrderedData(id : EntityID) : IntEntity(id) - { + class OrderedData(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(OrderedDataTable) var name by OrderedDataTable.name @@ -388,4 +384,4 @@ class InsertTests : DatabaseTestsBase() { } } */ -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/JoinTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/JoinTests.kt index f45ffec24c..c459a7c497 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/JoinTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/JoinTests.kt @@ -190,16 +190,16 @@ class JoinTests : DatabaseTestsBase() { } } - @Test fun testNoWarningsOnLeftJoinRegression(){ - val MainTable = object : Table("maintable"){ + @Test fun testNoWarningsOnLeftJoinRegression() { + val MainTable = object : Table("maintable") { val id = integer("idCol") } - val JoinTable = object : Table("jointable"){ + val JoinTable = object : Table("jointable") { val id = integer("idCol") val data = integer("dataCol").default(42) } - withTables(MainTable, JoinTable){ + withTables(MainTable, JoinTable) { MainTable.insert { it[id] = 2 } MainTable.join(JoinTable, JoinType.LEFT, JoinTable.id, MainTable.id) @@ -211,4 +211,4 @@ class JoinTests : DatabaseTestsBase() { // Assert no logging took place. No idea how to. } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/OrderByTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/OrderByTests.kt index a25c6477dc..197e06a7fb 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/OrderByTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/OrderByTests.kt @@ -35,7 +35,7 @@ class OrderByTests : DatabaseTestsBase() { assertEquals(5, r.size) val usersWithoutCities = listOf("alex", "smth") val otherUsers = listOf("eugene", "sergey", "andrey") - val expected = if(isNullFirst()) usersWithoutCities + otherUsers + val expected = if (isNullFirst()) usersWithoutCities + otherUsers else otherUsers + usersWithoutCities expected.forEachIndexed { index, e -> assertEquals(e, r[index][users.id]) @@ -50,7 +50,7 @@ class OrderByTests : DatabaseTestsBase() { assertEquals(5, r.size) val usersWithoutCities = listOf("alex", "smth") val otherUsers = listOf("eugene", "sergey", "andrey") - val expected = if(isNullFirst()) usersWithoutCities + otherUsers + val expected = if (isNullFirst()) usersWithoutCities + otherUsers else otherUsers + usersWithoutCities expected.forEachIndexed { index, e -> assertEquals(e, r[index][users.id]) @@ -77,7 +77,7 @@ class OrderByTests : DatabaseTestsBase() { assertEquals(5, r.size) val usersWithoutCities = listOf("alex", "smth") val otherUsers = listOf("eugene", "sergey", "andrey") - val expected = if(isNullFirst()) usersWithoutCities + otherUsers + val expected = if (isNullFirst()) usersWithoutCities + otherUsers else otherUsers + usersWithoutCities expected.forEachIndexed { index, e -> assertEquals(e, r[index][users.id]) @@ -102,11 +102,13 @@ class OrderByTests : DatabaseTestsBase() { @Test fun testOrderByExpressions() { withCitiesAndUsers { cities, users, userData -> - val expression = wrapAsExpression(users - .slice(users.id.count()) - .select { - cities.id eq users.cityId - }) + val expression = wrapAsExpression( + users + .slice(users.id.count()) + .select { + cities.id eq users.cityId + } + ) val result = cities .selectAll() @@ -119,4 +121,4 @@ class OrderByTests : DatabaseTestsBase() { println(result) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ReplaceTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ReplaceTests.kt index 61bc5a4677..1a1385c2d7 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ReplaceTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/ReplaceTests.kt @@ -26,4 +26,4 @@ class ReplaceTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectBatchedTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectBatchedTests.kt index 0daeefa438..c2edaab188 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectBatchedTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectBatchedTests.kt @@ -20,10 +20,13 @@ class SelectBatchedTests : DatabaseTestsBase() { .toList().map { it.toCityNameList() } val expectedNames = names.take(50) - assertEqualLists(listOf( - expectedNames.take(25), - expectedNames.takeLast(25) - ), batches) + assertEqualLists( + listOf( + expectedNames.take(25), + expectedNames.takeLast(25) + ), + batches + ) } } @@ -73,4 +76,4 @@ class SelectBatchedTests : DatabaseTestsBase() { fun `when batch size is 0 or less, should throw an exception`() { DMLTestsData.Cities.selectAllBatched(batchSize = -1) } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectTests.kt index cd060c9966..b4707b39ba 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/SelectTests.kt @@ -74,7 +74,6 @@ class SelectTests : DatabaseTestsBase() { } } - @Test fun testInList01() { withCitiesAndUsers { cities, users, userData -> @@ -122,7 +121,7 @@ class SelectTests : DatabaseTestsBase() { // only 2 cities with id 1 and 2 respectively assertEquals(1, r[0]) assertEquals(3, r[1]) - //there is no city with id=2 + // there is no city with id=2 assertNull(r.find { it == cityId }) } } @@ -180,4 +179,4 @@ class SelectTests : DatabaseTestsBase() { assertEquals(1, secondEntries.size) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/UpdateTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/UpdateTests.kt index 9debde7512..23378f0612 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/UpdateTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/dml/UpdateTests.kt @@ -18,7 +18,6 @@ class UpdateTests : DatabaseTestsBase() { exclude } - @Test fun testUpdate01() { withCitiesAndUsers { _, users, _ -> @@ -64,7 +63,7 @@ class UpdateTests : DatabaseTestsBase() { } } } - + @Test fun testUpdateWithJoin() { val dialects = listOf(TestDB.SQLITE) @@ -81,4 +80,4 @@ class UpdateTests : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityHookTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityHookTest.kt index 33c96beee6..a1f366b347 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityHookTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityHookTest.kt @@ -19,16 +19,16 @@ object EntityHookTestData { val age = integer("age") } - object Cities: IntIdTable() { + object Cities : IntIdTable() { val name = varchar("name", 50) val country = reference("country", Countries) } - object Countries: IntIdTable() { + object Countries : IntIdTable() { val name = varchar("name", 50) } - object UsersToCities: org.jetbrains.exposed.sql.Table() { + object UsersToCities : org.jetbrains.exposed.sql.Table() { val user = reference("user", Users, onDelete = ReferenceOption.CASCADE) val city = reference("city", Cities, onDelete = ReferenceOption.CASCADE) } @@ -49,17 +49,17 @@ object EntityHookTestData { var country by Country referencedOn Cities.country } - class Country(id: EntityID): IntEntity(id) { + class Country(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(Countries) var name by Countries.name val cities by City referrersOn Cities.country } - val allTables = arrayOf(Users, Cities, UsersToCities, Countries) + val allTables = arrayOf(Users, Cities, UsersToCities, Countries) } -class EntityHookTest: DatabaseTestsBase() { +class EntityHookTest : DatabaseTestsBase() { private fun trackChanges(statement: Transaction.() -> T): Triple, String> { val alreadyChanged = TransactionManager.current().registeredChanges().size @@ -85,7 +85,7 @@ class EntityHookTest: DatabaseTestsBase() { assertEquals(2, events.count()) assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.City)?.name }, "St. Petersburg") assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.Country)?.name }, "RU") - events.forEach{ + events.forEach { assertEquals(txId, it.transactionId) } } @@ -144,7 +144,7 @@ class EntityHookTest: DatabaseTestsBase() { assertEquals(2, events.count()) assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.City)?.name }, "Munich") assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.Country)?.name }, "DE") - events.forEach{ + events.forEach { assertEquals(txId, it.transactionId) } } @@ -184,7 +184,7 @@ class EntityHookTest: DatabaseTestsBase() { assertEquals(2, events.count()) assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.City)?.name }, "St. Petersburg") assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.User)?.name }, "John") - events.forEach{ + events.forEach { assertEquals(txId, it.transactionId) } } @@ -225,7 +225,7 @@ class EntityHookTest: DatabaseTestsBase() { assertEquals(3, events.count()) assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.City)?.name }, "St. Petersburg", "Munich") assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.User)?.name }, "John") - events.forEach{ + events.forEach { assertEquals(txId, it.transactionId) } } @@ -265,7 +265,7 @@ class EntityHookTest: DatabaseTestsBase() { assertEquals(2, events.count()) assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.City)?.name }, "St. Petersburg") assertEqualCollections(events.mapNotNull { it.toEntity(EntityHookTestData.User)?.name }, "John") - events.forEach{ + events.forEach { assertEquals(txId, it.transactionId) } } @@ -297,5 +297,4 @@ class EntityHookTest: DatabaseTestsBase() { assertEquals(EntityChangeType.Updated, updateEvent.changeType) } } - } diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityTests.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityTests.kt index f759807a15..0c8b9579fe 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityTests.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/EntityTests.kt @@ -26,7 +26,7 @@ import kotlin.test.assertNull object EntityTestsData { - object YTable: IdTable("YTable") { + object YTable : IdTable("YTable") { override val id: Column> = varchar("uuid", 36).entityId().clientDefault { EntityID(UUID.randomUUID().toString(), YTable) } @@ -37,13 +37,13 @@ object EntityTestsData { override val primaryKey = PrimaryKey(id) } - object XTable: IntIdTable("XTable") { + object XTable : IntIdTable("XTable") { val b1 = bool("b1").default(true) val b2 = bool("b2").default(false) val y1 = optReference("y1", YTable) } - class XEntity(id: EntityID): Entity(id) { + class XEntity(id: EntityID) : Entity(id) { var b1 by XTable.b1 var b2 by XTable.b2 @@ -54,10 +54,10 @@ object EntityTestsData { A, B } - open class AEntity(id: EntityID): IntEntity(id) { + open class AEntity(id: EntityID) : IntEntity(id) { var b1 by XTable.b1 - companion object: IntEntityClass(XTable) { + companion object : IntEntityClass(XTable) { fun create(b1: Boolean, type: XType): AEntity { val init: AEntity.() -> Unit = { this.b1 = b1 @@ -71,11 +71,11 @@ object EntityTestsData { } } - class BEntity(id: EntityID): AEntity(id) { + class BEntity(id: EntityID) : AEntity(id) { var b2 by XTable.b2 var y by YEntity optionalReferencedOn XTable.y1 - companion object: IntEntityClass(XTable) { + companion object : IntEntityClass(XTable) { fun create(init: AEntity.() -> Unit): BEntity { val answer = new { init() @@ -93,12 +93,12 @@ object EntityTestsData { } } -class EntityTests: DatabaseTestsBase() { +class EntityTests : DatabaseTestsBase() { @Test fun testDefaults01() { withTables(EntityTestsData.YTable, EntityTestsData.XTable) { - val x = EntityTestsData.XEntity.new { } - assertEquals (x.b1, true, "b1 mismatched") - assertEquals (x.b2, false, "b2 mismatched") + val x = EntityTestsData.XEntity.new { } + assertEquals(x.b1, true, "b1 mismatched") + assertEquals(x.b2, false, "b2 mismatched") } } @@ -108,13 +108,13 @@ class EntityTests: DatabaseTestsBase() { val b: EntityTestsData.BEntity = EntityTestsData.AEntity.create(false, EntityTestsData.XType.B) as EntityTestsData.BEntity val y = EntityTestsData.YEntity.new { x = false } - assertEquals (a.b1, false, "a.b1 mismatched") - assertEquals (b.b1, false, "b.b1 mismatched") - assertEquals (b.b2, false, "b.b2 mismatched") + assertEquals(a.b1, false, "a.b1 mismatched") + assertEquals(b.b1, false, "b.b1 mismatched") + assertEquals(b.b2, false, "b.b2 mismatched") b.y = y - assertFalse (b.y!!.x) + assertFalse(b.y!!.x) assertNotNull(y.b) } } @@ -153,7 +153,7 @@ class EntityTests: DatabaseTestsBase() { objectsToVerify.add(y1 to testDb) } objectsToVerify.forEach { (human, testDb) -> - assertEquals("foo", human.h, "Failed on ${testDb.name}" ) + assertEquals("foo", human.h, "Failed on ${testDb.name}") } } @@ -167,8 +167,8 @@ class EntityTests: DatabaseTestsBase() { objectsToVerify.add(x to testDb) } objectsToVerify.forEach { (human, testDb) -> - assertEquals("foo", human.h, "Failed on ${testDb.name}" ) - assertEquals(2, human.id.value, "Failed on ${testDb.name}" ) + assertEquals("foo", human.h, "Failed on ${testDb.name}") + assertEquals(2, human.id.value, "Failed on ${testDb.name}") } } @@ -177,7 +177,7 @@ class EntityTests: DatabaseTestsBase() { companion object : IntEntityClass(OneAutoFieldTable) } - //GitHub issue #95: Dao new{ } with no values problem "NoSuchElementException: List is empty" + // GitHub issue #95: Dao new{ } with no values problem "NoSuchElementException: List is empty" @Test fun testOneFieldEntity() { withTables(OneAutoFieldTable) { @@ -189,9 +189,9 @@ class EntityTests: DatabaseTestsBase() { @Test fun testBackReference01() { withTables(EntityTestsData.YTable, EntityTestsData.XTable) { - val y = EntityTestsData.YEntity.new { } + val y = EntityTestsData.YEntity.new { } flushCache() - val b = EntityTestsData.BEntity.new { } + val b = EntityTestsData.BEntity.new { } b.y = y assertEquals(b, y.b) } @@ -200,9 +200,9 @@ class EntityTests: DatabaseTestsBase() { @Test fun testBackReference02() { withTables(EntityTestsData.YTable, EntityTestsData.XTable) { - val b = EntityTestsData.BEntity.new { } + val b = EntityTestsData.BEntity.new { } flushCache() - val y = EntityTestsData.YEntity.new { } + val y = EntityTestsData.YEntity.new { } b.y = y assertEquals(b, y.b) } @@ -224,14 +224,14 @@ class EntityTests: DatabaseTestsBase() { val title = varchar("title", 50) } - class Board(id: EntityID): IntEntity(id) { + class Board(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(Boards) var name by Boards.name val posts by Post.optionalReferrersOn(Posts.board) } - class Post(id: EntityID): LongEntity(id) { + class Post(id: EntityID) : LongEntity(id) { companion object : LongEntityClass(Posts) var board by Board optionalReferencedOn Posts.board @@ -240,7 +240,6 @@ class EntityTests: DatabaseTestsBase() { var optCategory by Category optionalReferencedOn Posts.optCategory } - class Category(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(Categories) @@ -342,7 +341,6 @@ class EntityTests: DatabaseTestsBase() { } } - object Humans : IntIdTable("human") { val h = text("h", eagerLoading = true) } @@ -352,13 +350,13 @@ class EntityTests: DatabaseTestsBase() { val name = text("name") } - open class Human (id: EntityID) : IntEntity(id) { + open class Human(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(Humans) var h by Humans.h } class User(id: EntityID) : IntEntity(id) { - companion object : IntEntityClass(Users){ + companion object : IntEntityClass(Users) { fun create(name: String): User { val h = Human.new { h = name.take(2) } return User.new(h.id.value) { @@ -482,7 +480,6 @@ class EntityTests: DatabaseTestsBase() { post1.category = category2 - val post2 = Post.new { category = category1 } @@ -546,7 +543,7 @@ class EntityTests: DatabaseTestsBase() { } private fun newTransaction(statement: Transaction.() -> T) = - inTopLevelTransaction(TransactionManager.manager.defaultIsolationLevel, 1, null, null, statement) + inTopLevelTransaction(TransactionManager.manager.defaultIsolationLevel, 1, null, null, statement) @Test fun sharingEntityBetweenTransactions() { withTables(Humans) { @@ -574,8 +571,8 @@ class EntityTests: DatabaseTestsBase() { } object Students : LongIdTable(name = "students") { - val name = varchar("name", 255) - val school = reference("school_id", Schools) + val name = varchar("name", 255) + val school = reference("school_id", Schools) } object StudentBios : LongIdTable(name = "student_bio") { @@ -584,34 +581,34 @@ class EntityTests: DatabaseTestsBase() { } object Notes : LongIdTable(name = "notes") { - val text = varchar("text", 255) - val student = reference("student_id", Students) + val text = varchar("text", 255) + val student = reference("student_id", Students) } object Detentions : LongIdTable(name = "detentions") { - val reason = varchar("reason", 255) - val student = optReference("student_id", Students) + val reason = varchar("reason", 255) + val student = optReference("student_id", Students) } object Holidays : LongIdTable(name = "holidays") { - val holidayStart = long("holiday_start") - val holidayEnd = long("holiday_end") + val holidayStart = long("holiday_start") + val holidayEnd = long("holiday_end") } object SchoolHolidays : Table(name = "school_holidays") { - val school = reference("school_id", Schools, ReferenceOption.CASCADE, ReferenceOption.CASCADE) - val holiday = reference("holiday_id", Holidays, ReferenceOption.CASCADE, ReferenceOption.CASCADE) + val school = reference("school_id", Schools, ReferenceOption.CASCADE, ReferenceOption.CASCADE) + val holiday = reference("holiday_id", Holidays, ReferenceOption.CASCADE, ReferenceOption.CASCADE) override val primaryKey = PrimaryKey(school, holiday) } object Schools : IntIdTable(name = "school") { - val name = varchar("name", 255).index(isUnique = true) - val region = reference("region_id", Regions) - val secondaryRegion = optReference("secondary_region_id", Regions) + val name = varchar("name", 255).index(isUnique = true) + val region = reference("region_id", Regions) + val secondaryRegion = optReference("secondary_region_id", Regions) } - class Region(id: EntityID): IntEntity(id) { + class Region(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(Regions) var name by Regions.name @@ -623,42 +620,40 @@ class EntityTests: DatabaseTestsBase() { override fun hashCode(): Int = id.hashCode() } - abstract class ComparableLongEntity(id: EntityID) : LongEntity(id) { + abstract class ComparableLongEntity(id: EntityID) : LongEntity(id) { override fun equals(other: Any?): Boolean { return (other as? T)?.id?.equals(id) ?: false } override fun hashCode(): Int = id.hashCode() } - class Student(id: EntityID): ComparableLongEntity(id) { + class Student(id: EntityID) : ComparableLongEntity(id) { companion object : LongEntityClass(Students) - var name by Students.name - var school by School referencedOn Students.school - val notes by Note.referrersOn(Notes.student, true) - val detentions by Detention.optionalReferrersOn(Detentions.student, true) + var name by Students.name + var school by School referencedOn Students.school + val notes by Note.referrersOn(Notes.student, true) + val detentions by Detention.optionalReferrersOn(Detentions.student, true) val bio by StudentBio.optionalBackReferencedOn(StudentBios.student) } - class StudentBio(id: EntityID): ComparableLongEntity(id) { + class StudentBio(id: EntityID) : ComparableLongEntity(id) { companion object : LongEntityClass(StudentBios) var student by Student.referencedOn(StudentBios.student) var dateOfBirth by StudentBios.dateOfBirth } - class Note(id: EntityID): ComparableLongEntity(id) { + class Note(id: EntityID) : ComparableLongEntity(id) { companion object : LongEntityClass(Notes) var text by Notes.text var student by Student referencedOn Notes.student } - - class Detention(id: EntityID): ComparableLongEntity(id) { + class Detention(id: EntityID) : ComparableLongEntity(id) { companion object : LongEntityClass(Detentions) - var reason by Detentions.reason - var student by Student optionalReferencedOn Detentions.student + var reason by Detentions.reason + var student by Student optionalReferencedOn Detentions.student } - class Holiday(id: EntityID) : ComparableLongEntity(id) { companion object : LongEntityClass(Holidays) @@ -666,7 +661,7 @@ class EntityTests: DatabaseTestsBase() { var holidayEnd by Holidays.holidayEnd } - class School(id: EntityID): IntEntity(id) { + class School(id: EntityID) : IntEntity(id) { companion object : IntEntityClass(Schools) var name by Schools.name @@ -690,17 +685,17 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val school2 = School.new { name = "Harrow" - region = region1 + region = region1 } val school3 = School.new { - name = "Winchester" - region = region2 + name = "Winchester" + region = region2 } commit() @@ -728,7 +723,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } commit() @@ -750,7 +745,7 @@ class EntityTests: DatabaseTestsBase() { } } - @Test fun preloadOptionalReferencesOnASizedIterable() { + @Test fun preloadOptionalReferencesOnASizedIterable() { withTables(Regions, Schools) { val region1 = Region.new { @@ -763,13 +758,13 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 secondaryRegion = region2 } val school2 = School.new { name = "Harrow" - region = region1 + region = region1 } commit() @@ -799,7 +794,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 secondaryRegion = region2 } @@ -830,17 +825,17 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val school2 = School.new { name = "Harrow" - region = region1 + region = region1 } val school3 = School.new { - name = "Winchester" - region = region2 + name = "Winchester" + region = region2 } val student1 = Student.new { @@ -866,7 +861,7 @@ class EntityTests: DatabaseTestsBase() { commit() inTopLevelTransaction(Connection.TRANSACTION_SERIALIZABLE, 1) { - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache School.all().with(School::students) assertEquals(true, cache.referrers.containsKey(school1.id)) @@ -887,10 +882,9 @@ class EntityTests: DatabaseTestsBase() { name = "United Kingdom" } - val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val student1 = Student.new { @@ -911,7 +905,7 @@ class EntityTests: DatabaseTestsBase() { commit() inTopLevelTransaction(Connection.TRANSACTION_SERIALIZABLE, 1) { - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache School.find { Schools.id eq school1.id }.first().load(School::students) assertEquals(true, cache.referrers.containsKey(school1.id)) @@ -931,7 +925,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val student1 = Student.new { @@ -954,12 +948,11 @@ class EntityTests: DatabaseTestsBase() { student = student1 } - commit() inTopLevelTransaction(Connection.TRANSACTION_SERIALIZABLE, 1) { School.all().with(School::students, Student::detentions) - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache School.all().with(School::students, Student::detentions) assertEquals(true, cache.referrers.containsKey(school1.id)) @@ -990,17 +983,17 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val school2 = School.new { name = "Harrow" - region = region1 + region = region1 } val school3 = School.new { - name = "Winchester" - region = region2 + name = "Winchester" + region = region2 } val holiday1 = Holiday.new { @@ -1049,7 +1042,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val holiday1 = Holiday.new { @@ -1088,7 +1081,7 @@ class EntityTests: DatabaseTestsBase() { Schools.id eq school1.id }.first().load(School::holidays) - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache assertEquals(true, cache.referrers.containsKey(school1.id)) assertEquals(true, cache.referrers[school1.id]?.get(SchoolHolidays.school)?.contains(holiday1)) @@ -1107,7 +1100,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val student1 = Student.new { @@ -1130,10 +1123,9 @@ class EntityTests: DatabaseTestsBase() { student = student2 } - School.all().with(School::students, Student::notes) - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache assertEquals(true, cache.referrers.containsKey(school1.id)) assertEquals(true, cache.referrers.containsKey(student1.id)) assertEquals(true, cache.referrers.containsKey(student2.id)) @@ -1154,7 +1146,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val student1 = Student.new { @@ -1181,7 +1173,7 @@ class EntityTests: DatabaseTestsBase() { inTopLevelTransaction(Connection.TRANSACTION_SERIALIZABLE, 1) { Student.all().with(Student::bio) - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache assertEquals(true, cache.referrers.containsKey(student1.id)) assertEquals(true, cache.referrers.containsKey(student2.id)) @@ -1201,7 +1193,7 @@ class EntityTests: DatabaseTestsBase() { val school1 = School.new { name = "Eton" - region = region1 + region = region1 } val student1 = Student.new { @@ -1228,7 +1220,7 @@ class EntityTests: DatabaseTestsBase() { inTopLevelTransaction(Connection.TRANSACTION_SERIALIZABLE, 1) { Student.all().first().load(Student::bio) - val cache = TransactionManager.current().entityCache + val cache = TransactionManager.current().entityCache assertEquals(true, cache.referrers.containsKey(student1.id)) @@ -1267,4 +1259,4 @@ class EntityTests: DatabaseTestsBase() { kotlin.test.assertEquals(bio1.student, student1) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ImmutableEntityTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ImmutableEntityTest.kt index e793b9b2ca..4580107063 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ImmutableEntityTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ImmutableEntityTest.kt @@ -97,4 +97,4 @@ class ImmutableEntityTest : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/LongIdTableEntityTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/LongIdTableEntityTest.kt index 4cf33f217d..e2b020177d 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/LongIdTableEntityTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/LongIdTableEntityTest.kt @@ -93,4 +93,4 @@ class LongIdTableEntityTest : DatabaseTestsBase() { assertEquals(false, allPeople.contains(Pair("Tanu Arora", "Pune"))) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/NonAutoIncEntities.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/NonAutoIncEntities.kt index 87b25a112a..5c2f298250 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/NonAutoIncEntities.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/NonAutoIncEntities.kt @@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicInteger class NonAutoIncEntities : DatabaseTestsBase() { - abstract class BaseNonAutoIncTable(name : String) : IdTable(name) { + abstract class BaseNonAutoIncTable(name: String) : IdTable(name) { override val id = integer("id").entityId() val b1 = bool("b1") } @@ -40,7 +40,6 @@ class NonAutoIncEntities : DatabaseTestsBase() { } } - @Test fun testDefaultsWithOverrideNew() { withTables(NotAutoIntIdTable) { @@ -101,4 +100,4 @@ class NonAutoIncEntities : DatabaseTestsBase() { } } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/SelfReferenceTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/SelfReferenceTest.kt index 8675e2155c..d322f67535 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/SelfReferenceTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/SelfReferenceTest.kt @@ -88,6 +88,5 @@ class SortByReferenceTest { assertTrue(SchemaUtils.checkCycle(TestTables.users)) assertTrue(SchemaUtils.checkCycle(TestTables.cities)) assertTrue(SchemaUtils.checkCycle(TestTables.strangeTable)) - } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/UuidTableEntityTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/UuidTableEntityTest.kt index c9c7c93713..7633072934 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/UuidTableEntityTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/UuidTableEntityTest.kt @@ -38,7 +38,6 @@ object UUIDTables { var city by City.referencedOn(Addresses.city) var address by Addresses.address } - } class UUIDTableEntityTest : DatabaseTestsBase() { @@ -136,4 +135,4 @@ class UUIDTableEntityTest : DatabaseTestsBase() { assertEquals("address2", address2.address) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ViaTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ViaTest.kt index a6557a8bf4..aba8191073 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ViaTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/entities/ViaTest.kt @@ -13,42 +13,41 @@ import org.junit.Test import java.util.* object ViaTestData { - object NumbersTable: UUIDTable() { + object NumbersTable : UUIDTable() { val number = integer("number") } - object StringsTable: IdTable("") { + object StringsTable : IdTable("") { override val id: Column> = long("id").autoIncrement().entityId() val text = varchar("text", 10) override val primaryKey = PrimaryKey(id) } - object ConnectionTable: Table() { + object ConnectionTable : Table() { val numId = reference("numId", NumbersTable, ReferenceOption.CASCADE) val stringId = reference("stringId", StringsTable, ReferenceOption.CASCADE) init { - index(true, numId, stringId) + index(true, numId, stringId) } } val allTables: Array
= arrayOf(NumbersTable, StringsTable, ConnectionTable) } -class VNumber(id: EntityID): UUIDEntity(id) { +class VNumber(id: EntityID) : UUIDEntity(id) { var number by ViaTestData.NumbersTable.number var connectedStrings: SizedIterable by VString via ViaTestData.ConnectionTable companion object : UUIDEntityClass(ViaTestData.NumbersTable) } -class VString(id: EntityID): Entity(id) { +class VString(id: EntityID) : Entity(id) { var text by ViaTestData.StringsTable.text companion object : EntityClass(ViaTestData.StringsTable) } - class ViaTests : DatabaseTestsBase() { @Test fun testConnection01() { withTables(*ViaTestData.allTables) { @@ -57,8 +56,8 @@ class ViaTests : DatabaseTestsBase() { n.connectedStrings = SizedCollection(listOf(s)) val row = ViaTestData.ConnectionTable.selectAll().single() - assertEquals (n.id, row[ViaTestData.ConnectionTable.numId]) - assertEquals (s.id, row[ViaTestData.ConnectionTable.stringId]) + assertEquals(n.id, row[ViaTestData.ConnectionTable.numId]) + assertEquals(s.id, row[ViaTestData.ConnectionTable.stringId]) } } @@ -73,8 +72,8 @@ class ViaTests : DatabaseTestsBase() { val row = ViaTestData.ConnectionTable.selectAll().toList() assertEquals(2, row.count()) - assertEquals (n1.id, row[0][ViaTestData.ConnectionTable.numId]) - assertEquals (n1.id, row[1][ViaTestData.ConnectionTable.numId]) + assertEquals(n1.id, row[0][ViaTestData.ConnectionTable.numId]) + assertEquals(n1.id, row[1][ViaTestData.ConnectionTable.numId]) assertEqualCollections(listOf(s1.id, s2.id), row.map { it[ViaTestData.ConnectionTable.stringId] }) } } @@ -101,12 +100,11 @@ class ViaTests : DatabaseTestsBase() { run { val row = ViaTestData.ConnectionTable.selectAll().toList() assertEquals(2, row.count()) - assertEquals (n2.id, row[0][ViaTestData.ConnectionTable.numId]) - assertEquals (n2.id, row[1][ViaTestData.ConnectionTable.numId]) + assertEquals(n2.id, row[0][ViaTestData.ConnectionTable.numId]) + assertEquals(n2.id, row[1][ViaTestData.ConnectionTable.numId]) assertEqualCollections(n1.connectedStrings, emptyList()) assertEqualCollections(n2.connectedStrings, listOf(s1, s2)) } - } } @@ -171,7 +169,6 @@ class ViaTests : DatabaseTestsBase() { assertEquals(root, child1.parents.singleOrNull()) assertEquals(root, child2.parents.singleOrNull()) } - } @Test fun testRefresh() { diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/types/CharColumnType.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/types/CharColumnType.kt index 49fe4e3175..be0ca5425a 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/types/CharColumnType.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/shared/types/CharColumnType.kt @@ -7,7 +7,7 @@ import org.jetbrains.exposed.sql.tests.DatabaseTestsBase import org.jetbrains.exposed.sql.tests.shared.assertEquals import org.junit.Test -class CharColumnType : DatabaseTestsBase() { +class CharColumnType : DatabaseTestsBase() { object CharTable : IntIdTable() { val charColumn = char("charColumn") } @@ -24,4 +24,4 @@ class CharColumnType : DatabaseTestsBase() { assertEquals('A', result?.get(CharTable.charColumn)) } } -} \ No newline at end of file +} diff --git a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/sqlite/MultipleDatabaseBugTest.kt b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/sqlite/MultipleDatabaseBugTest.kt index 604893c048..5acf7343dd 100644 --- a/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/sqlite/MultipleDatabaseBugTest.kt +++ b/exposed-tests/src/test/kotlin/org/jetbrains/exposed/sql/tests/sqlite/MultipleDatabaseBugTest.kt @@ -68,4 +68,4 @@ class MultipleDatabaseBugTest { println("Transaction connection url: ${connection.metadata { url }}") } } -} \ No newline at end of file +} diff --git a/spring-transaction/src/main/kotlin/org/jetbrains/exposed/spring/SpringTransactionManager.kt b/spring-transaction/src/main/kotlin/org/jetbrains/exposed/spring/SpringTransactionManager.kt index 611082a126..abed532499 100644 --- a/spring-transaction/src/main/kotlin/org/jetbrains/exposed/spring/SpringTransactionManager.kt +++ b/spring-transaction/src/main/kotlin/org/jetbrains/exposed/spring/SpringTransactionManager.kt @@ -16,9 +16,9 @@ import org.springframework.transaction.support.DefaultTransactionStatus import org.springframework.transaction.support.TransactionSynchronizationManager import javax.sql.DataSource - -class SpringTransactionManager(private val _dataSource: DataSource, - @Volatile override var defaultRepetitionAttempts: Int = DEFAULT_REPETITION_ATTEMPTS +class SpringTransactionManager( + private val _dataSource: DataSource, + @Volatile override var defaultRepetitionAttempts: Int = DEFAULT_REPETITION_ATTEMPTS ) : DataSourceTransactionManager(_dataSource), TransactionManager { init { @@ -140,5 +140,4 @@ class SpringTransactionManager(private val _dataSource: DataSource, } } } - } diff --git a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/EntityUpdateTest.kt b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/EntityUpdateTest.kt index 943b22f868..9eabe27ad0 100644 --- a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/EntityUpdateTest.kt +++ b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/EntityUpdateTest.kt @@ -45,4 +45,4 @@ open class EntityUpdateTest : SpringTransactionTestBase() { Assert.assertEquals("updated", entity.c1) SchemaUtils.drop(t1) } -} \ No newline at end of file +} diff --git a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/ExposedTransactionManagerTest.kt b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/ExposedTransactionManagerTest.kt index 931612df52..acac6328d7 100644 --- a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/ExposedTransactionManagerTest.kt +++ b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/ExposedTransactionManagerTest.kt @@ -25,7 +25,7 @@ open class ExposedTransactionManagerTest : SpringTransactionTestBase() { @Repeat(5) open fun testConnection() { val pm = ctx.getBean(PlatformTransactionManager::class.java) - if(pm !is SpringTransactionManager) error("Wrong txManager instance: ${pm.javaClass.name}") + if (pm !is SpringTransactionManager) error("Wrong txManager instance: ${pm.javaClass.name}") SchemaUtils.create(t1) t1.insert { @@ -72,4 +72,4 @@ open class ExposedTransactionManagerTest : SpringTransactionTestBase() { SchemaUtils.drop(t1) } } -} \ No newline at end of file +} diff --git a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringCoroutineTest.kt b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringCoroutineTest.kt index 4d94d25769..d486602ae0 100644 --- a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringCoroutineTest.kt +++ b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringCoroutineTest.kt @@ -3,16 +3,15 @@ package org.jetbrains.exposed.spring import kotlinx.coroutines.* import kotlinx.coroutines.debug.junit4.CoroutinesTimeout import org.jetbrains.exposed.sql.* +import org.jetbrains.exposed.sql.tests.RepeatableTest import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync import org.jetbrains.exposed.sql.transactions.transaction -import org.jetbrains.exposed.sql.tests.RepeatableTest import org.junit.Rule import org.junit.Test import org.springframework.test.annotation.Commit import org.springframework.transaction.annotation.Transactional import kotlin.test.assertEquals - open class SpringCoroutineTest : SpringTransactionTestBase() { @Rule @@ -35,7 +34,7 @@ open class SpringCoroutineTest : SpringTransactionTestBase() { val results = (1..5).map { indx -> suspendedTransactionAsync(Dispatchers.IO) { - Testing.insert { } + Testing.insert { } indx } }.awaitAll() @@ -77,4 +76,4 @@ open class SpringCoroutineTest : SpringTransactionTestBase() { mainJob.getCompletionExceptionOrNull()?.let { throw it } }*/ } -} \ No newline at end of file +} diff --git a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionEntityTest.kt b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionEntityTest.kt index 52fe5e3a16..7718696539 100644 --- a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionEntityTest.kt +++ b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionEntityTest.kt @@ -14,23 +14,22 @@ import java.util.* import kotlin.test.assertEquals import kotlin.test.assertNotNull - -private object CustomerTable: UUIDTable(name = "customer") { +private object CustomerTable : UUIDTable(name = "customer") { val name = varchar(name = "name", length = 255).uniqueIndex() } -class CustomerDAO(id: EntityID): UUIDEntity(id) { +class CustomerDAO(id: EntityID) : UUIDEntity(id) { companion object : UUIDEntityClass(CustomerTable) var name by CustomerTable.name } -object OrderTable: UUIDTable(name = "orders") { +object OrderTable : UUIDTable(name = "orders") { val customer = reference(name = "customer_id", foreign = CustomerTable) val product = varchar(name = "product", length = 255) } -class OrderDAO(id: EntityID): UUIDEntity(id) { +class OrderDAO(id: EntityID) : UUIDEntity(id) { companion object : UUIDEntityClass(OrderTable) var customer by CustomerDAO.referencedOn(OrderTable.customer) @@ -57,7 +56,7 @@ open class Service { return createOrder(createCustomer(name), product) } - open fun findOrderByProduct(product: String) : OrderDAO? { + open fun findOrderByProduct(product: String): OrderDAO? { return OrderDAO.find { OrderTable.product eq product }.singleOrNull() } } @@ -83,13 +82,13 @@ open class SpringTransactionEntityTest : SpringTransactionTestBase() { } @Test @Commit - fun test02(){ + fun test02() { service.doBoth("Bob", "Product2") val order = service.findOrderByProduct("Product2") assertNotNull(order) transaction { - assertEquals("Bob", order.customer.name) + assertEquals("Bob", order.customer.name) SchemaUtils.drop(CustomerTable, OrderTable) } } -} \ No newline at end of file +} diff --git a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionTestBase.kt b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionTestBase.kt index bfb42b0240..5c9f1e10f3 100644 --- a/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionTestBase.kt +++ b/spring-transaction/src/test/kotlin/org.jetbrains.exposed.spring/SpringTransactionTestBase.kt @@ -28,8 +28,7 @@ open class TestConfig : TransactionManagementConfigurer { override fun annotationDrivenTransactionManager(): PlatformTransactionManager? = SpringTransactionManager(ds()) @Bean - open fun service() : Service = Service() - + open fun service(): Service = Service() } /** @@ -42,4 +41,4 @@ abstract class SpringTransactionTestBase { @Autowired lateinit var ctx: ApplicationContext -} \ No newline at end of file +}