1/* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17import androidx.room.parser.SQLTypeAffinity 18import androidx.room.verifier.ColumnInfo 19import java.sql.PreparedStatement 20import java.sql.ResultSet 21import java.sql.ResultSetMetaData 22import java.sql.SQLException 23 24internal fun <T> ResultSet.collect(f: (ResultSet) -> T): List<T> { 25 val result = arrayListOf<T>() 26 try { 27 while (next()) { 28 result.add(f.invoke(this)) 29 } 30 } finally { 31 close() 32 } 33 return result 34} 35 36private fun <T> PreparedStatement.map(f: (Int, ResultSetMetaData) -> T): List<T> { 37 val columnCount = try { 38 metaData.columnCount 39 } catch (ex: SQLException) { 40 // ignore, no-result query 41 0 42 } 43 // return is separate than data creation because we want to know who throws the exception 44 return (1.rangeTo(columnCount)).map { f(it, metaData) } 45} 46 47internal fun PreparedStatement.columnNames(): List<String> { 48 return map { index, data -> data.getColumnName(index) } 49} 50 51private fun PreparedStatement.tryGetAffinity(columnIndex: Int): SQLTypeAffinity { 52 return try { 53 SQLTypeAffinity.valueOf(metaData.getColumnTypeName(columnIndex).capitalize()) 54 } catch (ex: IllegalArgumentException) { 55 SQLTypeAffinity.NULL 56 } 57} 58 59internal fun PreparedStatement.columnInfo(): List<ColumnInfo> { 60 //see: http://sqlite.1065341.n5.nabble.com/Column-order-in-resultset-td23127.html 61 return map { index, data -> ColumnInfo(data.getColumnName(index), tryGetAffinity(index)) } 62} 63