scalajdbcscalikejdbc

ScalikeJDBC wrong order of columns in the result string


I am using ScalikeJDBC to get the results of queries. However, the problem is that the order of columns in the output does not conform to the one I define in queries. For me, the order of columns is very important. So how can it be fixed?

My query looks like this:

def getAllRecords():List[String] = {
    sql"SELECT random_pk,random_string, code,random_bool,random_int,random_float,random_double, random_enum,random_date,random_decimal,update_database_time,update_database_time_tz,random_money FROM TestAllData"
      .map(records => records.toMap.values.mkString(", "))
      .list()
      .apply()
}

The columns order in the result looks like this:

random_float, random_money, random_int,random_string,update_database_time_tz,code,random_date,update_database_time,random_pk,random_bool,random_enum,random_decimal,random_double

Solution

  • You are mapping your result records to a Map. A Map does not guarantee the order of the keys, hence every call will return result-set in different order.

    You can map your result-set to a case class in the following way:

    case class ResultSet(
    random_pk_string: Option[String],
    random_string: Option[String],
    code: Option[String],
    random_bool: Option[Boolean],
    random_int: Option[Int],
    random_float: Option[Float],
    random_double: Option[Double],
    random_enum: Option[String],
    random_date: Option[String],
    random_decimal: Option[Double],
    update_database_time: Option[String],
    update_database_time_tz: Option[String],
    random_money:Int)
    
    def getAllRecords():List[String] = {
        sql"SELECT random_pk],random_string], code],random_bool],random_int],random_float],random_double], random_enum],random_date],random_decimal],update_database_time],update_database_time_tz],random_money FROM TestAllData"
          .map(rs => ResultSet(
            rs.string("random_pk_string"),
            rs.string("random_string"),
            rs.string("code"),
            rs.boolean("random_bool"),
            rs.int("random_int"),
            rs.float("random_float"),
            rs.double("random_double"),
            rs.string("random_enum"),
            rs.string("random_date"),
            rs.double("random_decimal"),
            rs.string("update_database_time"),
            rs.string("update_database_time_tz"),
            rs.int("random_money")))
          .list.apply()
    }
    

    You can follow this example to get more clarity.