mike@159: /* mike@159: * Copyright 2020 Mike Becker. All rights reserved. mike@159: * mike@159: * Redistribution and use in source and binary forms, with or without mike@159: * modification, are permitted provided that the following conditions are met: mike@159: * mike@159: * 1. Redistributions of source code must retain the above copyright mike@159: * notice, this list of conditions and the following disclaimer. mike@159: * mike@159: * 2. Redistributions in binary form must reproduce the above copyright mike@159: * notice, this list of conditions and the following disclaimer in the mike@159: * documentation and/or other materials provided with the distribution. mike@159: * mike@159: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" mike@159: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE mike@159: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE mike@159: * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE mike@159: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL mike@159: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR mike@159: * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER mike@159: * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, mike@159: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE mike@159: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mike@159: * mike@159: */ mike@159: mike@159: package de.uapcore.lightpit.dao mike@159: mike@159: import java.sql.PreparedStatement mike@159: import java.sql.ResultSet mike@159: import java.sql.Types mike@159: mike@159: abstract class AbstractDao { mike@159: mike@159: abstract fun mapResult(rs: ResultSet): T mike@159: mike@159: protected fun list(stmt: PreparedStatement): List { mike@159: return sequence { mike@159: stmt.executeQuery().use { result -> mike@159: while (result.next()) yield(mapResult(result)) mike@159: } mike@159: }.toList() mike@159: } mike@159: mike@159: protected fun find(stmt: PreparedStatement): T? { mike@159: stmt.executeQuery().use { result -> mike@159: return if (result.next()) { mike@159: mapResult(result) mike@159: } else { mike@159: null mike@159: } mike@159: } mike@159: } mike@159: mike@159: // TODO: create PreparedStatement abstraction that provides some features mike@159: mike@159: // TODO: remove the following legacy code helper function mike@159: protected fun setForeignKeyOrNull(stmt: PreparedStatement, index: Int, instance: T?, keyGetter: (obj: T) -> Int) { mike@159: if (instance == null) { mike@159: stmt.setNull(index, Types.INTEGER) mike@159: } else { mike@159: stmt.setInt(index, keyGetter(instance)) mike@159: } mike@159: } mike@159: }