Adding a column to an existing table with values - ktor

I currently have a TABLE object, as below and existing table in DB. I am creating a webservice using KTOR.
object Arts: Table() {
val id : Column<Int> = integer("id").autoIncrement().primaryKey()
val title = varchar("title" , 256)
val description = varchar("desc", 512)
val price = double("price")
}
I would like to add a column, last_modified how to alter the current table.

First, add the column last_modified to your table.
object Arts: Table() {
val id : Column<Int> = integer("id").autoIncrement().primaryKey()
val title = varchar("title" , 256)
val description = varchar("desc", 512)
val price = double("price")
val lastModified = datetime("last_modified").defaultExpression(CurrentDateTime())
}
Then call the function
SchemaUtils.createMissingTablesAndColumns(Arts)

Related

How to join two tables on two fields using Exposed?

I have the following database Tables:
// CurrenciesTable
object CurrenciesTable : Table("currencies") {
val symbol = varchar("symbol", 48)
val name = varchar("name", 48)
override val primaryKey = PrimaryKey(symbol)
}
// OrdersTable
object OrdersTable : IntIdTable("orders") {
val baseCurrency = varchar("base_currency", 48)
val counterCurrency = varchar("counter_currency", 48)
val price = decimal("price", DECIMAL_PRECISION, DECIMAL_SCALE)
val createdAtEpochSecond = long("created_at_epoch_second")
}
In the OrdersTable, I have to fields which reference CurrenciesTable:
baseCurrency
counterCurrency
I want to select records from OrdersTable and join them with CurrenciesTable on two fields. So I get the symbol and name for each currency.
Here is my DSL query to join on baseCurrency field only.
// Exposed DSL
OrdersTable.join(CurrenciesTable, JoinType.INNER, OrdersTable.baseCurrency, CurrenciesTable.symbol)
.selectAll()
.forEach {
// Getting OrdersTable record data
it[OrdersTable.id].value
it[OrdersTable.price]
it[OrdersTable.createdAtEpochSecond]
// Getting CurrenciesTable record data (for baseCurrency only)
it[CurrenciesTable.symbol]
it[CurrenciesTable.name]
}
I tried to do a second join as follows:
// Exposed DSL
OrdersTable.join(CurrenciesTable, JoinType.INNER, OrdersTable.baseCurrency, CurrenciesTable.symbol)
.join(CurrenciesTable, JoinType.INNER, OrdersTable.counterCurrency, CurrenciesTable.symbol)
However, I get the following exception.
Caused by: java.sql.SQLSyntaxErrorException: Not unique table/alias: 'currencies'
Try to add alias for CurrenciesTable:
OrdersTable.innerJoin(CurrenciesTable.alias("baseCurrency"), { OrdersTable.baseCurrency }, { CurrenciesTable.symbol })
.innerJoin(CurrenciesTable, { OrdersTable.counterCurrency }, { CurrenciesTable.symbol })

How to get the index of a gson object?

I need to get the index of the array containing the member fileName = "Andres"
data class File(var fileName: String, var _id : String? = null)
data class Files(val files: Array<File>)
val miObjetG = Gson().fromJson(response_files, Files::class.java)
var indice = miObjetG.files.filterIndexed { index, file -> file.fileName == "Andres"}
I think indexOfFirst is what you are looking for:
val index = miObjetG.files.indexOfFirst{ it.fileName == "Andres" }

sum of arraylist elements getted by cursor

I've a table of Holidays, I'm trying to check if some specific one took any holidays before
This is my table construction:
db.execSQL("CREATE TABLE IF NOT EXISTS Holidays (HolidayID INTEGER PRIMARY KEY, Department TEXT NOT NULL, Profession TEXT NOT NULL, EmpName TEXT NOT NULL, DaysofHoliday TEXT NOT NULL, StartDay TEXT NOT NULL, StartMonth TEXT NOT NULL, StartYear TEXT NOT NULL, EndDay TEXT, EndMonth TEXT, EndYear TEXT, PresentedDay TEXT NOT NULL, PresentedMonth TEXT NOT NULL, PresentedYear TEXT NOT NULL, Engineer TEXT NOT NULL, ApproveDay TEXT NOT NULL, ApproveMonth TEXT NOT NULL, ApproveYear TEXT NOT NULL)")
My companion object:
companion object {
val DB_Name = "samalout.db"
val TABLE_HOL = "Holidays"
val COL_41 = "HolidayID"
val COL_42 = "Department"
val COL_43 = "Profession"
val COL_44 = "EmpName"
val COL_45 = "DaysofHoliday"
val COL_46 = "StartDay"
val COL_47 = "StartMonth"
val COL_48 = "StartYear"
val COL_49 = "EndDay"
val COL_410 = "EndMonth"
val COL_411 = "EndYear"
val COL_412 = "PresentedDay"
val COL_413 = "PresentedMonth"
val COL_414 = "PresentedYear"
val COL_415 = "Engineer"
val COL_416 = "ApproveDay"
val COL_417 = "ApproveMonth"
val COL_418 = "ApproveYear"
}
This my search function:
fun Game() {
var query1 = ""
var rv = ArrayList<String>()
val db = dbHelper.writableDatabase
query1 = "SELECT * FROM " + DBHelper.TABLE_HOL + " WHERE " + DBHelper.COL_44 + "='" + spin3.selectedItem.toString() + "'"
val c1 = db.rawQuery(query1, null)
while (c1.moveToNext()) {
rv.add(c1.getString(0))
textView13.text = rv.sum().toString()
}
}
Edit:
sum function can't b done to arraylist of strings, so I tried something else:
while (c1.moveToNext()) {
rv.add(c1.getString(0))
for (item in rv)
println(item)
}
but also it didn't get me result
I found the problem, It's the Column that I search .. I performed a select query on adb, it returned different columns .. for clarity: I assigned the following columns (HolidayID, Department, Profession, EmpName), when I made a select * from table Holidays; on adb it returned the following (HolidayID, EmpName, Department, Profession) .. I don't know what happened to reverse my initials but I changed search query in main activity to the second column of table and it worked for me.
Edit: It was the insertion statement, it's all my fault
fun insertDataHol(holid: Int, department: String, profession: String, empname: String, daysofholiday: String, startday: String, startmonth: String, startyear: String, endday: String, endmonth: String, endyear: String, presentedday: String, presentedmonth: String, presentedyear: String, engineer: String, approveday: String, approvemonth: String, approveyear: String) {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COL_41, holid)
contentValues.put(COL_42, empname)
contentValues.put(COL_43, department)
contentValues.put(COL_44, profession)
contentValues.put(COL_45, daysofholiday)
contentValues.put(COL_46, startday)
contentValues.put(COL_47, startmonth)
contentValues.put(COL_48, startyear)
contentValues.put(COL_49, endday)
contentValues.put(COL_410, endmonth)
contentValues.put(COL_411, endyear)
contentValues.put(COL_412, presentedday)
contentValues.put(COL_413, presentedmonth)
contentValues.put(COL_414, presentedyear)
contentValues.put(COL_415, engineer)
contentValues.put(COL_416, approveday)
contentValues.put(COL_417, approvemonth)
contentValues.put(COL_418, approveyear)
db.insert(TABLE_HOL, null, contentValues)
}
In the insert statement I defined to insert name as the second column, so it's my fault I tried to retrieve name from the forth column while it's inserted in second column.

kotlin SQLite database always writing default values, never new ones

here is the class I set up for my database. database handler being the inner class.
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.ContentValues
import android.util.Log
import java.sql.Date
class Scores {
var id : Int = 0
var dataBaseName = "ScoreDatabase"
var averageTime = 0.0f
val date = Date(System.currentTimeMillis()).toString()
constructor(averageTime:Float) {
this.averageTime = averageTime
Log.d("Poop", averageTime.toString())
}
constructor()
inner class DataBaseHandler(var context:Context, tableName:String): SQLiteOpenHelper(context, dataBaseName, null,1){
val TABLE_NAME = tableName
val COL_ID = "id"
val COL_AVG = "Average_Time"
val COL_DATE = "Date"
override fun onCreate(db: SQLiteDatabase?) {
val createTable = "CREATE TABLE " + TABLE_NAME +" (" +
COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_AVG + " VARCHAR(256)," +
COL_DATE +" VARCHAR(256)"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun insertData(score: Scores){
val db = this.writableDatabase
var cv = ContentValues()
cv.put(COL_AVG,score.averageTime)
cv.put(COL_DATE,score.date)
var result = db.insert(TABLE_NAME,null,cv)
if(result == -1.toLong())
Log.d("POOP", "fail score table in addition")
else
Log.d("POOP", "Success score table in addition" )
}
fun readData(): MutableList<Scores>{
var list: MutableList<Scores> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query,null)
if (result.moveToFirst()){
do {
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
}while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
}
I tried this where the scores class and the handler were two separate classes, but it generated the same results.
here is how I write to the database (from 4 separate activities. in each activity the tablename is different. in this one for example it is 'additionDataBase')
val scores = Scores("%.3f".format(timeKeeper.averageNumber).toFloat())
val db = scores.DataBaseHandler(context, "additionDataBase")
db.insertData(scores)
and here is how I read from the database which is in a different activity that shows the averageTime from each table. here is the code for one of them
val context: Context? = activity
val adb = Scores().DataBaseHandler(context!!,"additionDataBase")
val data = adb.readData()
TextViewAdScore.text = data[0].averageTime.toString() + " " + data[1].date
I think I am missing something, but I can't seem to find what it is.
so far, no matter how many times I do this. the output is always 0.0f
Look at what you do in readData:
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
id, AvgTime, and date are retrieved but not used in any way, so your code is equivalent to just writing list.add(Scores()). (Side note: there's no reason for them to be var, and why the case inconsistency between AvgTime and the rest?)

Remove item of record without knowing all item

I have this simulation:
init : (Model, Cmd Msg)
init = ({ dog = List Dog }, Cmd.none)
type alias Dog =
{ name : String
, age : Int
, price : Float
, extra = List Extra
}
type alias Extra =
{ allergies : List String
, wishes : List String
}
[{ name = "Hot"
, age = 1
, price = 300.5
, extra = [{...}]
},
{ name = "Dog"
, age = 3
, price = 150.0
, extra = [{...}]
}]
And I want to remove only 'extras' of Dog, in determined part of the code:
[{ name = "Hot"
, age = 1
, price = 300.5
},
{ name = "Dog"
, age = 3
, price = 150.0
}]
I can do this by mapping the entire list and generating a new one by removing 'extra' occurrence:
removeExtraOfDogs dogList =
(dogList |> List.map (\dog ->
{ name = dog.name
, age = dog.age
, price = dog.price
}
))
but I want to make it dynamic to just pass the extra to remove, without having to know what variables there are in the type and recreate it
Elm used to have this feature but it was removed a while ago. But, based on your use case described in a comment, I don't think you need this feature. You can instead use extensible record feature of Elm to allow passing different records into a function as long as they contain a fixed set of fields.
For example, let's say you have two types with name and age fields and having an extra incompatible field:
type alias Foo = { name : String, age : Int, extra : List String }
type alias Bar = { name : String, age : Int, extra : Int }
You can define a function that takes a record with a name field of type String and age of type Int and any extra fields:
encode : { r | name : String, age : Int } -> String
encode record = record.name ++ "," ++ toString record.age
You'll can now pass both Foo and Bar to this function because they both satisfy the requirements of the type signature.