1

I want to be able to either set a sorting condition for my SQLite Table or sort it every time a new entry is inserted.

The SQlite docs say to use query.order(expression)

Currently this is what I have:

class SQLiteData {
    var fileURL : URL
    var tasks : Table
    var titleDb : Expression<String>
    var descriptionDb : Expression<String>
    var dateDb : Expression<String>

    init() {
        //...  
        tasks = Table("Tasks")
        titleDb = Expression<String>("Title")
        descriptionDb = Expression<String>("Description")
        dateDb = Expression<String>("Date")
        tasks.order(dateDb)
    }

but the line tasks.order(dateDb) doesn't seem to have any effect...

I also tried it in my uploadData function:

    func uploadData(_ title: String, _ description: String, _ date: String) {
        do {
            let db = try Connection(fileURL.path)

            try db.run(tasks.create(ifNotExists: true) { t in
                t.column(titleDb, unique : true)
                t.column(descriptionDb)
                t.column(dateDb)
            })

            let insert = tasks.insert(titleDb <- title,  descriptionDb <- description,
                                      dateDb <- date)
            _ = tasks.order(dateDb)

            let rowid = try db.run(insert)

        }

        catch {
            print(error)
        }
    }

but alas have not had any success doing this either. Any ideas how would I setup the table to always be sorted by dateDb? Thank you.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
koza
  • 71
  • 1
  • 2
  • 13

1 Answers1

1

.order is not an attribute of the table. It is a feature of a query. The sortedTasks query below may be what you need.

tasks = Table("Tasks")

 sortedTasks = Table("Tasks").order(dateDb)
adamek
  • 2,324
  • 3
  • 24
  • 38