Skip to content

Commit

Permalink
Kotlin 1.0.0-beta-2423
Browse files Browse the repository at this point in the history
  • Loading branch information
laurentvdl committed Nov 16, 2015
1 parent ef555c7 commit 1b60933
Show file tree
Hide file tree
Showing 16 changed files with 62 additions and 123 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
buildscript {
ext.kotlin_version = '1.0.0-beta-1038'
ext.kotlin_version = '1.0.0-beta-2423'
repositories {
mavenCentral()
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/sqlbuilder/ResultSet.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package sqlbuilder

import sqlbuilder.impl.mappers.AnyMapper
import sqlbuilder.mapping.ToObjectMappingParameters
import java.io.Closeable
import java.sql.SQLException
Expand All @@ -13,8 +14,7 @@ class ResultSet(private val target: java.sql.ResultSet, private val configuratio
@Suppress("UNCHECKED_CAST")
@Throws(SQLException::class)
public fun <T> getObject(targetType: Class<T>, index: Int): T? {
val objectMapperForType = configuration.objectMapperForType(targetType) ?:
throw PersistenceException("unknown bean property, unable to find matching SQL variant: " + targetType.name)
val objectMapperForType = configuration.objectMapperForType(targetType) ?: AnyMapper()

return objectMapperForType.toObject(ToObjectMappingParameters(index, target, targetType)) as T
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/sqlbuilder/Select.kt
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ interface Select {

/**
* Override the cursor direction or concurrency to allow eg. updatable resultsets
* @param type one of
* @param cursorType one of
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
Expand All @@ -197,7 +197,7 @@ interface Select {
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @return the current Select statement
*/
fun resultSetType(`type`: Int, concurrency: Int): Select
fun resultSetType(cursorType: Int, concurrency: Int): Select

/**
* Specifiy group by statement, eg. <code>select.groupBy("group by aardvz")</code>
Expand Down
12 changes: 12 additions & 0 deletions src/main/kotlin/sqlbuilder/SqlBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,21 @@ public interface SqlBuilder {
* @return the same bean with the id set
*/
public fun <T : Any> save(bean: T, vararg excludedFields: String): T
/**
* Start a transaction with default isolation.
*/
public fun startTransaction()
/**
* Start a transaction using an isolationlevel other than TRANSACTION_READ_COMMITTED
* @param isolationLevel Connection.TRANSACTION_...
*/
public fun startTransaction(isolationLevel: Int, readonly: Boolean)
public fun commitTransaction()
/**
* This must be called in the a finally clause whenever you have started a transaction.
* <br/>If commitTransaction has already been called, it will only cleanup resources,
* else it will rollback the transaction.
*/
public fun endTransaction()
public fun purgeCache(cacheId: String)
public fun purgeAllCaches()
Expand Down
9 changes: 5 additions & 4 deletions src/main/kotlin/sqlbuilder/impl/DefaultConfiguration.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public open class DefaultConfiguration : Configuration {

protected fun registerDefaultMappers() {
val dualPurposeMappers = listOf(
AnyMapper(),
StringMapper(),
CharMapper(),
LongMapper(),
Expand All @@ -45,7 +44,7 @@ public open class DefaultConfiguration : Configuration {
}
}

override var metaResolver: MetaResolver = StaticJavaResolver()
override var metaResolver: MetaResolver = StaticJavaResolver(this)
var escapeCharacter: Char? = null

public fun setEscapeCharacter(escapeCharacter: Char): Configuration {
Expand All @@ -65,11 +64,13 @@ public open class DefaultConfiguration : Configuration {
}

override fun objectMapperForType(targetType: Class<*>): ToObjectMapper? {
return toObjectMappers.last { it.handles(targetType) }
val lastOrNull = toObjectMappers.lastOrNull { it.handles(targetType) }
println("mapper for type $targetType -> $lastOrNull")
return lastOrNull
}

override fun sqlMapperForType(targetType: Class<*>): ToSQLMapper? {
return toSQLMappers.last { it.handles(targetType) }
return toSQLMappers.lastOrNull { it.handles(targetType) }
}

override fun registerToObjectMapper(toObjectMapper: ToObjectMapper): DefaultConfiguration {
Expand Down
5 changes: 3 additions & 2 deletions src/main/kotlin/sqlbuilder/impl/InsertImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ class InsertImpl(val backend: Backend): Insert {
sql.append(")")

sqlString = sql.toString()

logger.info(sqlString)

cachedStatement = sqlCon.prepareStatement(sqlString, if (getkeys) Statement.RETURN_GENERATED_KEYS else java.sql.Statement.NO_GENERATED_KEYS)
Expand All @@ -103,7 +104,7 @@ class InsertImpl(val backend: Backend): Insert {


for ((index,property) in properties.withIndex()) {
logger.debug("setInsertParameter " + property.name + " <" + property.classType.getName() + ">")
logger.debug("setInsertParameter " + property.name + " <" + property.classType.name + ">")
sqlConverter.setParameter(cachedStatement!!, values[property], index + 1, property.classType, null)
}

Expand All @@ -112,7 +113,7 @@ class InsertImpl(val backend: Backend): Insert {
if (getkeys) {
try {
var key: Long = 0;
val keys = cachedStatement!!.getGeneratedKeys()
val keys = cachedStatement!!.generatedKeys
if (keys != null) {
if (keys.next()) {
key = keys.getLong(1)
Expand Down
10 changes: 5 additions & 5 deletions src/main/kotlin/sqlbuilder/impl/SelectImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class SelectImpl(val backend: Backend) : Select {
orderBy = column
orderAscending = ascending
} else {
throw IllegalArgumentException("can't order by <" + column + ">")
throw IllegalArgumentException("can't order by <$column>")
}
return this
}
Expand Down Expand Up @@ -120,7 +120,7 @@ class SelectImpl(val backend: Backend) : Select {
if (result.size > 1) {
throw IncorrectResultSizeException("more than 1 result")
}
return result.get(0)
return result[0]
}
return null
}
Expand Down Expand Up @@ -210,7 +210,7 @@ class SelectImpl(val backend: Backend) : Select {
if (list.size > 1) {
throw IncorrectResultSizeException("more than 1 result")
}
return list.get(0)
return list[0]
}
return null
}
Expand Down Expand Up @@ -388,8 +388,8 @@ class SelectImpl(val backend: Backend) : Select {
return this
}

override fun resultSetType(`type`: Int, concurrency: Int): Select {
this.cursorType = `type`
override fun resultSetType(cursorType: Int, concurrency: Int): Select {
this.cursorType = cursorType
this.cursorConcurrency = concurrency
return this
}
Expand Down
30 changes: 9 additions & 21 deletions src/main/kotlin/sqlbuilder/impl/SqlBuilderImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public class SqlBuilderImpl(private val dataSource: DataSource) : SqlBuilder, Ba
if (keys.size == 1 && keys[0] == "id") {
val idField = metaResolver.findField("id", bean.javaClass)
if (idField == null) throw IllegalArgumentException("bean <${bean.javaClass}> has no id field")
idField.setAccessible(true)
idField.isAccessible = true

val valueBefore = idField.get(bean)
if (valueBefore != null) {
Expand All @@ -64,7 +64,7 @@ public class SqlBuilderImpl(private val dataSource: DataSource) : SqlBuilder, Ba
try {
idField.set(bean, id)
} catch (e: Exception) {
throw PersistenceException("unable to set autogenerated id on " + bean.javaClass.getName(), e)
throw PersistenceException("unable to set autogenerated id on " + bean.javaClass.name, e)
}
}
} else {
Expand All @@ -78,7 +78,7 @@ public class SqlBuilderImpl(private val dataSource: DataSource) : SqlBuilder, Ba
try {
var connection = txConnections.get()
if (connection == null) {
connection = dataSource.getConnection()
connection = dataSource.connection
}
return connection!!
} catch (e: SQLException) {
Expand All @@ -87,27 +87,20 @@ public class SqlBuilderImpl(private val dataSource: DataSource) : SqlBuilder, Ba

}

/**
* Start a transaction with default isolation.
*/
override fun startTransaction() {
startTransaction(-1, false)
}

/**
* Start a transaction using an isolationlevel other than TRANSACTION_READ_COMMITTED
* @param isolationLevel Connection.TRANSACTION_...
*/
override fun startTransaction(isolationLevel: Int, readonly: Boolean) {
try {
var connection = txConnections.get()
if (connection == null) {
connection = dataSource.getConnection()
if (isolationLevel >= 0) connection!!.setTransactionIsolation(isolationLevel)
connection!!.setAutoCommit(false)
connection = dataSource.connection
if (isolationLevel >= 0) connection!!.transactionIsolation = isolationLevel
connection!!.autoCommit = false
txConnections.set(connection)
}
connection.setReadOnly(readonly)
connection.isReadOnly = readonly
} catch (e: SQLException) {
throw PersistenceException(e.message, e)
}
Expand All @@ -120,7 +113,7 @@ public class SqlBuilderImpl(private val dataSource: DataSource) : SqlBuilder, Ba
txConnections.set(null)
try {
connection.commit()
connection.setAutoCommit(true)
connection.autoCommit = true
} catch (ignore: SQLException) {
}

Expand All @@ -137,18 +130,13 @@ public class SqlBuilderImpl(private val dataSource: DataSource) : SqlBuilder, Ba
}
}

/**
* This must be called in the a finally clause whenever you have started a transaction.
* <br/>If commitTransaction has already been called, it will only cleanup resources,
* else it will rollback the transaction.
*/
override fun endTransaction() {
val connection = txConnections.get()
if (connection != null) {
txConnections.set(null)
try {
connection.rollback()
connection.setAutoCommit(true)
connection.autoCommit = true
} catch (ignore: SQLException) {}

closeConnection(connection)
Expand Down
41 changes: 5 additions & 36 deletions src/main/kotlin/sqlbuilder/impl/UpdateImpl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class UpdateImpl(private val backend: Backend): Update {
if (entity == null) entity = metaResolver.getTableName(bean.javaClass)
entity = backend.configuration.escapeEntity(entity)

if (keys.size == 0) {
if (keys.isEmpty()) {
throw PersistenceException("cannot update bean without a list of keys")
}

Expand Down Expand Up @@ -100,43 +100,25 @@ class UpdateImpl(private val backend: Backend): Update {
}

if (updates != 1) {
throw PersistenceException("updateBean resulted in " + updates + " updated rows instead of 1 using <" + sql + "> with bean " + bean)
throw PersistenceException("updateBean resulted in $updates updated rows instead of 1 using <$sql> with bean $bean")
}
} catch (sqlx: SQLException) {
throw PersistenceException("update <" + sql + "> failed", sqlx)
throw PersistenceException("update <$sql> failed", sqlx)
}

} finally {
backend.closeConnection(sqlCon)
}
}

/**
* Custom update that allows null parameters due to the types argument.
* @param sql statement
* @return updated rows
*/
public override fun updateStatement(sql: String): Int {
return updateStatement(sql, null, null)
}

/**
* Custom update that allows null parameters due to the types argument.
* @param sql statement
* @param parameters parameters objects
* @return updated rows
*/
public override fun updateStatement(sql: String, vararg parameters: Any): Int {
return updateStatement(sql, parameters, null)
}

/**
* Custom update that allows null parameters due to the types argument.
* @param sql statement
* @param parameters parameters objects
* @param types array of java.sql.Types
* @return updated rows
*/
public override fun updateStatement(sql: String, parameters: Array<out Any>?, types: IntArray?): Int {
logger.info(sql)

Expand Down Expand Up @@ -168,14 +150,14 @@ class UpdateImpl(private val backend: Backend): Update {
}
} catch (ignore: AbstractMethodError) {
} catch (sqlx: SQLException) {
throw PersistenceException("unable to retreive generated keys", sqlx)
throw PersistenceException("unable to retrieve generated keys", sqlx)
}

}
rows
}
} catch (px: PersistenceException) {
throw PersistenceException("update <" + sql + "> failed with parameters " + Arrays.toString(parameters), px)
throw PersistenceException("update <$sql> failed with parameters ${Arrays.toString(parameters)}", px)
}


Expand All @@ -186,13 +168,6 @@ class UpdateImpl(private val backend: Backend): Update {
}
}

/**
* Special updatestatement that throws PersistenceException if updated rows do not match.
* @param sql
* @param expectedUpdateCount
* @param parameters
* @return updated rows if matching the expected
*/
public override fun updateStatementExpecting(sql: String, expectedUpdateCount: Int, vararg parameters: Any): Int {
val updates = updateStatement(sql, parameters, null)
if (updates != expectedUpdateCount) {
Expand All @@ -204,12 +179,6 @@ class UpdateImpl(private val backend: Backend): Update {
return updates
}

/**
* store any generated id after executing the update statement (which should be an insert in this case)
* <br/>use <code>getGeneratedKey</code> to get the value afterwards
* @param cond
* @return
*/
public override fun getKeys(cond: Boolean): Update {
this.getkeys = cond
return this
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/sqlbuilder/impl/mappers/DoubleMapper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ public class DoubleMapper : BiMapper {
}

override fun handles(targetType: Class<*>): Boolean {
return targetType == Double::class.java
return targetType == Double::class.java || targetType == java.lang.Double::class.java
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/sqlbuilder/impl/mappers/FloatMapper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ public class FloatMapper : BiMapper {
}

override fun handles(targetType: Class<*>): Boolean {
return targetType == Double::class.java
return targetType == Float::class.java || targetType == java.lang.Float::class.java
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/sqlbuilder/impl/mappers/LongMapper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ public class LongMapper : BiMapper {
}

override fun handles(targetType: Class<*>): Boolean {
return Boolean::class.java == targetType
return Long::class.java == targetType || java.lang.Long::class.java == targetType
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/sqlbuilder/impl/mappers/ShortMapper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@ public class ShortMapper : BiMapper {
}

override fun handles(targetType: Class<*>): Boolean {
return Short::class.java == targetType
return Short::class.java == targetType || java.lang.Short::class.java == targetType
}
}
4 changes: 2 additions & 2 deletions src/main/kotlin/sqlbuilder/meta/JavaFieldPropertyReference.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import java.lang.reflect.Field
* Wrapper for bean property using java.lang.reflect.Field access.
*/
public class JavaFieldPropertyReference(override var name: String, private val field: Field, override var classType: Class<*>) : PropertyReference {
private val fieldType = field.getType()!!
private val fieldType = field.type!!

override fun set(bean: Any, value: Any?) {
try {
if (!(value == null && fieldType.isPrimitive())) {
if (!(value == null && fieldType.isPrimitive)) {
field.set(bean, value)
}
} catch (e: Exception) {
Expand Down
Loading

0 comments on commit 1b60933

Please sign in to comment.