Giter Club home page Giter Club logo

sqlitedb's Introduction

SQLiteDB

SQLiteDB is a simple and lightweight SQLite wrapper for Swift. It allows all basic SQLite functionality including being able to bind values to parameters in an SQL statement. You can either include an SQLite database file with your project (in case you want to pre-load data) and have it be copied over automatically in to your documents folder, or have the necessary database and the relevant table structures created automatically for you via SQLiteDB.

SQLiteDB also provides an SQLTable class which allows you to use SQLiteDB as an ORM so that you can define your table structures via SQLTable sub-classes and be able to access the underlying data directly instead of having to deal with SQL queries, parameters, etc.

Update: (28 Mar 2018) The latest version of SQLiteDB changes the openDB() method to open() and changes the parameters for the method as well. Please be aware of this change when updating an existing project. The open method parameters have default values which should work for most general cases - so you probably will not need to modify existing code except to change the method name.

The row(number:filter:order:type:) method now takes 0-based row numbers instead of 1-based. This change was made to be in line with how the row number is used in all the use cases I've seen up to now.

Also do not try to use the cloud database functionality available with the latest code since that is not yet ready for prime time - that code is still a work in progress. However, the rest of SQLiteDB code will function as it should without any issues.

Adding to Your Project

  • If you want to pre-load data or have the table structures and indexes pre-created, or, if you are not using SQLTable sub-classes but are instead using SQLiteDB directly, then you need to create an SQLite database file to be included in your project.

    Create your SQLite database however you like, but name it data.db and then add the data.db file to your Xcode project. (If you want to name the database file something other than data.db, then set the DB_NAME property in the SQLiteDB class accordingly.)

    Note: Remember to add the database file above to your application target when you add it to the project. If you don't add the database file to a project target, it will not be copied to the device along with the other project resources.

    If you do not want to pre-load data and are using SQLTable sub-classes to access your tables, you can skip the above step since SQLiteDB will automatically create your table structures for you if the database file is not included in the project. However, in order for this to work, you need to pass false as the parameter for the open method when you invoke it, like this:

    swift db.open(copyFile: false) ​

  • Add all of the included source files (except for README.md, of course) to your project.

  • If you don't have a bridging header file, use the included Bridging-Header.h file. If you already have a bridging header file, then copy the contents from the included Bridging-Header.h file to your own bridging header file.

  • If you didn't have a bridging header file, make sure that you modify your project settings to point to the new bridging header file. This will be under Build Settings for your target and will be named Objective-C Bridging Header.

  • Add the SQLite library (libsqlite3.dylib or libsqlite3.tbd, depending on your Xcode version) to your project under Build Phases - Link Binary With Libraries section.

That's it. You're set!

Usage

There are several ways you can use SQLiteDB in your project:

Basic - Direct

You can use the SQLiteBase class to open one or more SQLite databases directly by passing the path to the database file to the open method like this:

let db = SQLiteBase()
_ = db.open(dbPath: path)

You can then use the db instance to query the database. You can have multiple instances of SQLiteBase be in existence at the same time and point to different databases without any issues.

Basic - Singleton

You can use the SQLiteDB class, which is a singleton, to get a reference to one central database. Similar to the `SQLiteBase, instance above, you can then run queries (or execute statements) on the database using this reference.

Unlike with a SQLiteBase class instance, you cannot open multiple databases with SQLiteDB - it will only work with the database file specified via the DB_NAME property for the class.

  • You can gain access to the shared database instance as follows:
let db = SQLiteDB.shared
  • Before you make any SQL queries, or execute commands, you should open the SQLite database. In most cases, this needs to be done only once per application and so you can do it in your AppDelegate, for example:
db.open()
  • You can make SQL queries using the query method (the results are returned as an array of dictionaries where the key is a String and the value is of type Any):
let data = db.query(sql:"SELECT * FROM customers WHERE name='John'")
let row = data[0]
if let name = row["name"] {
	textLabel.text = name as! String
}

In the above, db is a reference to the shared SQLite database instance. You can access a column from your query results by subscripting a row of the returned results (the rows are dictionaries) based on the column name. That returns an optional Any value which you can cast to the relevant data type.

  • If you'd prefer to bind values to your query instead of creating the full SQL statement, then you can execute the above SQL also like this:
let name = "John"
let data = db.query(sql:"SELECT * FROM customers WHERE name=?", parameters:[name])
  • Of course, you can also construct the above SQL query by using Swift's string interpolation functionality as well (without using the SQLite bind functionality):
let name = "John"
let data = db.query(sql:"SELECT * FROM customers WHERE name='\(name)'")
  • You can execute all non-query SQL commands (INSERT, DELETE, UPDATE etc.) using the execute method:
let result = db.execute(sql:"DELETE FROM customers WHERE last_name='Smith'")
// If the result is 0 then the operation failed, for inserts the result gives the newly inserted record ID

Note: If you need to escape strings with embedded quotes, or other special strings which might not work with Swift string interpolation, you should use the SQLite parameter binding functionality as shown above.

Using SQLTable

If you would prefer to model your database tables as classes and do any data access via class instances instead of using SQL statements, SQLiteDB also provides an SQLTable class which does most of the heavy lifting for you.

If you create a sub-class of SQLTable, define properties where the names match the column names in your SQLite table, then you can use the sub-class to save to/update the database without having to write all the necessary boilerplate code yourself.

Additionally, with this approach, you don't need to include an SQLite database project with your app (unless you need/want to). Each SQLTable instance in your app will infer the structure for the underlying tables based on your SQLTable sub-classes and automatically create the necessary tables for you, if they aren't present.

In fact, while you develop your app, if you add new properties to your SQLTable sub-class instance, the necessary underlying SQLite columns will be added automatically to the database the next time the code is run. Again, SQLiteDB does all the work for you.

For example, say that you have a Categories table with just two columns - id and name. Then, the SQLTable sub-class definition for the table would look something like this:

class Category:SQLTable {
	var id = -1
	var name = ""
}

It's as simple as that! You don't have to write any insert, update, or delete methods since SQLTable handles all of that for you behind the scenese :) And on top of that, if you were to later add another property to the Category class later, say some sort of a usage count called count, that column would be added to the underlying table when you next run your code.

Note: Do note that for a table named Categories, the class has to be named Category - the table name has to be plural, and the class name has to be singular. The table names are plural while the classes are singular. Again, if you let SQLTable create the table structure for you, then it would all be handled correctly for you automatically. But if you create the tables yourself, do make sure that the table names are correct.

The only additional thing you need to do when you use SQLTable sub-classes and want the table structures to be automatically created for you is that you have to specify that you don't want to create a copy of a database in your project resources when you invoke open. So you have to have your open call be something like this:

db.open(copyFile:false)

Once you do that, you can run any SQL queries or execute commands on the database without any issues.

Here are some quick examples of how you use the Category class from the above example:

  • Add a new Category item to the table:
let category = Category()
category.name = "My New Category"
_ = category.save()

The save method returns a non-zero value if the save was successful. In the case of a new record, the return value is the id of the newly inserted row. You can check the return value to see if the save was sucessful or not since a 0 value means that the save failed for some reason.

  • Get a Category by id:
if let category = Category.rowBy(id: 10) {
	NSLog("Found category with ID = 10")
}
  • Query the Category table:
let array = Category.rows(filter: "id > 10")
  • Get a specific Category row (to display categories via a UITableView, for example) by row number. The row numbers start at 0, the same as UITableView row indexes:
if let category = row(number: 0) {
	NSLog("Got first un-ordered category row")
}
  • Delete a Category:
if let category = Category.rowBy(id: 10) {
	category.delete()
	NSLog("Deleted category with ID = 10")
}

You can refer to the sample iOS and macOS projects for more examples of how to implement data access using SQLTable.

Questions?

SQLiteDB is under DWYWPL - Do What You Will Public License :) Do whatever you want either personally or commercially with the code but if you'd like, feel free to attribute in your app.

sqlitedb's People

Contributors

fahimf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sqlitedb's Issues

Summer time zone

Hi, I think there's a problem with datetime fields.
I store a summer date (+3 in my country) 2017-06-15 02:00:00 +0000 and if i read it in winter (+2), i get 2017-06-15 01:00:00 +0000. If i store a winter date i get it back correctly, so somewhere at reading or writing i lose 1hr. I don't fully understand timezones but working with coredata i didn't had this problem. Do you know what might be the problem?
Thanks.

Update Table with 'SQLTables' - not working

Suppose, I've created a table with some columns and then I want to alter the table then I'm not able to alter it using 'SQLTable'.
Please add the guide to alter the tables using SQLTable.

string primaryKey

Hi, in the save method i noticed that the primary key is not unwrapped, so the query fails for optional string key.

func save() -> Int {
let db = SQLiteDB.shared!
let key = primaryKey()
let data = values()
var insert = true
if let rid = data[key] {
var val = "(rid)"
if let _rid = rid as? String {
val = "'(_rid)'"
}

Update Substring to Swift4

Hi

Could you please modify this line?

SQLiteDB.swift line 374

tmp = tmp.substring(to:pos.lowerBound)

to

tmp = String(tmp[..<pos.lowerBound])

Above code is Swift4

Sorry, I tried Pull requests, but I could not do.

About migrating to Swift 3 or Swift 4

Hello Fahim!,

First of all thank you very much for your fantastic library.. it helps me a lot.
Right now I am developing an app that was made using phonegap and now I have the work to migrate the app to Swift 3.

The app has this "migrationStore" where before launching the app it gathers all the information that was on the local database and uses it to generate a new CoreData model database..

Until now was working just fine.

This was the init process and an example of a method (previously working fine):

private init(){
        if PHONEGAP_MIGRATION {
            db = SQLiteDB.sharedInstance("file__0.localstorage")
            //   db = SQLiteDB.openRO(path: "file__0.localstorage")
        }
    }
public func getLocalStorageUrl() -> String{
        if PHONEGAP_MIGRATION {
            var url = [SQLRow]()
            url = db!.query("SELECT value FROM itemtable WHERE key = ?", parameters: [URL_FIELD])
            for v in url{
                if let value = v["value"]{
                    return value.asString().stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil).stringByReplacingOccurrencesOfString("\0", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                }
            }
            return NTXConfiguration.sharedInstance.serverUrl
        return ""
    }

I am having problems to use the init() method using swift 3

How can I open a database using a file name (string)?

Thank you so much

Regards

Its not working with swift 2.0

"Cannot invoke initializer for type 'sqlite3_destructor_type'with an argument list of type '(COparquePointer)'

for lines
private let SQLITE_STATIC = sqlite3_destructor_type(COpaquePointer(bitPattern:0))
private let SQLITE_TRANSIENT = sqlite3_destructor_type(COpaquePointer(bitPattern:-1))

on SQLiteDB.swift

SQL don't found table Xcode 9

Hello. I have an issue,

when I try to make a query, I got a response that has no such table found for example:

SQLiteDB opened!
2017-08-08 09:40:02.072893-0300 AJ3[73215:8322823] SQLiteDB - failed to prepare SQL: SELECT * from servers, Error: no such table: servers

but the data.db file is present and has the table servers. Could you help me with it?

how insert data TRANSACTION

how 300 record insert to sqlite

for item in data {

let resultQ = self.db.execute(sql: "INSERT INTO tabel ((key))VALUES ((value))")
}

Special characters like ąęźćżłó etc..

Hi, i've found a problem with my app. When I insert into db regular strings, without special characters like "ąęźćółż" there is everything okay. While trying to add some special chars there is an exception:

Terminating app due to uncaught exception 'NSCharacterConversionException', reason: 'Conversion to encoding 30 failed for string "INSERT INTO Osoby ('..."'

Could you help me with this issue?

Blob

How to save, retrieve blob ?

'SQLColumn?' does not have a member named `asString`

Here is a part of my code:

    var prizes = db.getPrizes(gameId!)

        for prize in prizes
        {

            var imageName = prize["image"]?.asString();

AsString gives this strange error, with xcode 6 gm seed. With 6.5 beta everything worked fine, I have also downloaded your latest updates.

How to create new table in github project

Hello sir when i am adding one more column(name) into Task table then an error has occure.

INSERT INTO tasks(name, categoryID, task) VALUES (?, ?, ?), Error: table tasks has no column named name

and please let me know that how do i create a new table in my project. what files i need to use in my project.

Regards
Nitesh

Dates

I notice that you're writing dates using NSDateFormatter. I'd really encourage you to specify a timezone for your formatter in case the timezone of the device changes at any point. As you've implemented the date logic, dates are stored in the device's then local time zone which can be problematic.

I'd suggest

  • using a date formatter that specifies time zone (e.g. store date strings as Zulu/GMT/UTC, NSTimeZone(forSecondsFromGMT: 0) and include the timezone in the date string, e.g. Z; and
  • locale (e.g. the one used for RFC 3339/ISO8601 dates is NSLocale(localeIdentifier: "en_US_POSIX"); see Q&A 1480).

You might even want to follow one of the established standards, such as ISO8601 format, e.g. 2015-02-03T15:29:00.000Z, in which the format is sortable and unambiguous.

Regarding Existing Database

Hello,

Can i use existing database suppose i have songs.sqlite which have lots of table and meta data inside can i used in your db wrapper ?

Because stephencelis has make a new copy of the database.

Please help me out i am very thankful

Thanks.

Error in Ipad IOS 10.1

When I test my app on Ipad with the version IOS 10.1 shows an error

let data = db.query(sql: "SELECT * FROM Catalog WHERE id=(id)") <--this line is null , in ihpone work fine

func query(sql:String, parameters:[Any]?=nil)->[[String:Any]] {
var rows = [String:Any]
queue.sync() {
if let stmt = self.prepare(sql:sql, params:parameters) {
rows = self.query(stmt:stmt, sql:sql)
}
}
return rows
}

my db file is on my folder path

help me pleasee
thank for your attention

About README.md

Hi ! first Thanks for your Lib !
you have a wrong SQL command in your README.md .
look here let result = db.execute("DELETE * FROM customers WHERE last_name='Smith'")
and it should be like this let result = db.execute("DELETE FROM customers WHERE last_name='Smith'")
the * is not proper here

Error handling while not initializing database

If I didn't call OpenDB() before and want to execute a query, my app fails and it says "assertion failed: Database has not been opened! Use the openDB() method before any DB queries".
I used do-catch and inside "do" I call db.execute(sql) but it failed again.
How can I use d-catch to handle errors?

Support for Int64

Hi,

It's look like Int64 is not supported in this database implementation ?

Getting data from SQLite in code form

I tried this :

let db = SQLiteDB.sharedInstance()

    let cat_id = 1
    let sql = "SELECT * FROM category"
    println(cat_id)

    let data = db.query("SELECT * FROM category")
    println(data)
    let row = data[0]
      println(row)
    let name  = row["cat_name"]
     println(name)

and get output like this.....

_TtC10SqliteDemo6SQLRow, _TtC10SqliteDemo6SQLRow, _TtC10SqliteDemo6SQLRow, _TtC10SqliteDemo6SQLRow]

XCode beta 3

Everything is not working anymore after the beta 3 due to Swift changes.

Warnning in code

'CFURLCreateStringByAddingPercentEscapes' was deprecated in iOS 9.0: Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid).

Swift 3 Xcode 8.0 (8A218a) don't compile

Hello.
While I'm trying to compile on swift 3 I have some issues.

Undefined symbols for architecture x86_64:
"_sqlite3_bind_blob", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_bind_double", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_bind_int", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_bind_null", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_bind_parameter_count", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_bind_text", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_changes", referenced from:
Guia_Itapipoca.SQLiteDB.(execute in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> Swift.Int32 in SQLiteDB.o
"_sqlite3_close", referenced from:
Guia_Itapipoca.SQLiteDB.(openDB in _2D93D55DF1AC88576925A27A6918D34B) (path : Swift.String) -> () in SQLiteDB.o
Guia_Itapipoca.SQLiteDB.(closeDB in _2D93D55DF1AC88576925A27A6918D34B) () -> () in SQLiteDB.o
"_sqlite3_column_blob", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnValue in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, type : Swift.Int32, stmt : Swift.OpaquePointer) -> Any? in SQLiteDB.o
"_sqlite3_column_bytes", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnValue in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, type : Swift.Int32, stmt : Swift.OpaquePointer) -> Any? in SQLiteDB.o
"_sqlite3_column_count", referenced from:
Guia_Itapipoca.SQLiteDB.(query in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> [[Swift.String : Any]] in SQLiteDB.o
"_sqlite3_column_decltype", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnType in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, stmt : Swift.OpaquePointer) -> Swift.Int32 in SQLiteDB.o
"_sqlite3_column_double", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnValue in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, type : Swift.Int32, stmt : Swift.OpaquePointer) -> Any? in SQLiteDB.o
"_sqlite3_column_int", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnValue in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, type : Swift.Int32, stmt : Swift.OpaquePointer) -> Any? in SQLiteDB.o
"_sqlite3_column_name", referenced from:
Guia_Itapipoca.SQLiteDB.(query in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> [[Swift.String : Any]] in SQLiteDB.o
"_sqlite3_column_text", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnValue in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, type : Swift.Int32, stmt : Swift.OpaquePointer) -> Any? in SQLiteDB.o
"_sqlite3_column_type", referenced from:
Guia_Itapipoca.SQLiteDB.(getColumnType in _2D93D55DF1AC88576925A27A6918D34B) (index : Swift.Int32, stmt : Swift.OpaquePointer) -> Swift.Int32 in SQLiteDB.o
"_sqlite3_errmsg", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
Guia_Itapipoca.SQLiteDB.(execute in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> Swift.Int32 in SQLiteDB.o
"_sqlite3_finalize", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
Guia_Itapipoca.SQLiteDB.(execute in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> Swift.Int32 in SQLiteDB.o
Guia_Itapipoca.SQLiteDB.(query in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> [[Swift.String : Any]] in SQLiteDB.o
"_sqlite3_last_insert_rowid", referenced from:
Guia_Itapipoca.SQLiteDB.(execute in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> Swift.Int32 in SQLiteDB.o
"_sqlite3_open", referenced from:
Guia_Itapipoca.SQLiteDB.(openDB in _2D93D55DF1AC88576925A27A6918D34B) (path : Swift.String) -> () in SQLiteDB.o
"_sqlite3_prepare_v2", referenced from:
Guia_Itapipoca.SQLiteDB.(prepare in _2D93D55DF1AC88576925A27A6918D34B) (sql : Swift.String, params : [Any]?) -> Swift.OpaquePointer? in SQLiteDB.o
"_sqlite3_step", referenced from:
Guia_Itapipoca.SQLiteDB.(execute in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> Swift.Int32 in SQLiteDB.o
Guia_Itapipoca.SQLiteDB.(query in _2D93D55DF1AC88576925A27A6918D34B) (stmt : Swift.OpaquePointer, sql : Swift.String) -> [[Swift.String : Any]] in SQLiteDB.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

query out of memory error

I'm just trying to do a simple query (app with Xcode 6 beta 7)

let db = SQLiteDB.sharedInstance()
let data = db.query("SELECT * FROM my_table")

but I'm getting:

SQLiteDB - failed to prepare SQL: SELECT * FROM my_table, Error: out of memory

I tried the query in SQLiteStudio and it works fine. Any ideas why I'm getting the out of memory error?

Thanks

SQLTable (upgrading from Swift 3 to Swift 4)

Using SQLTable to create the database in the app, I committed out the line
// if copyFile {
in SQLiteBase.swift
such that the database would appear in the Documents directory (to view in SQLite Manager) and data would remain after first launch from Xcode.
It was previously working correctly with the Swift 3 builds. Please advise.

Swift 2.0

Is there any plan to support swift-2.0 version?
swift2 now support throw exceptions so may be you would like to change some apis.

i see error

let pos = tmp.positionOf("(")

in SQLiteDB.swift line 315

Table Relations

Hi everyone,

Would like to know if this library there is a support to Table relationships?

For example:

class Employee:SQLTable {
	var id = -1
	var name = ""
        var address = Address()
}

class Address:SQLTable {
	var id = -1
	var street = ""
        var number = ""
}

Close and Reopen Database

Hi Fahim, i've adapted your code for a new iOS project.
Everything goes OK, but I have a problem when I want to reopen the database in another View.

The first time it opens with no problem. I´m getting the data this way:

    let db = SQLiteDB.sharedInstance()
    let cursor = db.query("SELECT * FROM DATOS")
    db.closeDatabase()

The I Close the View, and when I Try to reopen it, then it throws this error:

SQLiteDB - failed to prepare SQL: SELECT * FROM DATOS, Error: library routine called out of sequence
SQLiteDB - Launch count 482

How can I do so I can open and close the database multiple times?

table names

  1. table names should not be handled case sensitive, since they are forced to lowercase. so if there's an upper-case character, the select-statement from sqlite_master will fail because the operator '=' is used instead of 'like' or lower(/(tablename)) = lower(name).

  2. currently there is a suffix-replacement. table-names ending with "y" are replaced with "ies" and all other table-names are extended with "s". that's only useful for the english language and should be documented. of course it wasn't difficult to replace them, just wondered... :-)

e.g.
original tablename: tblPerson
variable: tnm = tblpersons
statement: SELECT * FROM sqlite_master WHERE type = 'table' AND name = 'tblpersons'; = 0 results

Generics? Nil support?

Hi! Have you thought about making the result rows generic, so it will be nicer to access properties inside of them?
Current syntax:
let id = rows[0]["id"] as! Int

Maybe something like
let id: Int? = rows[0]["id"]

return 0 instead of nil for NULL integer values

sqlite3_column_intreturns zero even if the value is NULL. I think you should check each field's type by calling sqlite3_column_type since SQLite uses a more general dynamic type system.

Support for Swift 3.0 ?

Hi,

Nice work providing abstraction on Sqlite.! I am trying to integrate SQLiteDB into Mac OS Project, that uses Swift 3.0. Is there any work around for that ?

update affected rows bug

  1. create table mytable(mykey INTEGER,myvalue INTEGER)
  2. insert into mytable("mykey","myvalue") values(100,10)
  3. update mytable set myvalue=20 where mykey=500
    nothing is changed in the table (as expected), but the return value is 1 instead of 0
    see SQLiteDB.swift: var cnt = sqlite3_changes(self.db)

WatchOS Compatibility

When I tried to compile on WatchOS shows that AppKit doesn't exists. What we need to do to compile on WatchOs 3 ?

Value of type String has no member "positionOf"

When i try to compile the Code (XCode 8) i get an Error for the Line
let pos = tmp.positionOf(sub:"(")

Value of type String has no member "positionOf".
Is something wrong with the Code or with my setup?
Anyone else have this issue?

// NSLog("SQLiteDB - Got column type: \(buf)") if buf != nil { var tmp = String(validatingUTF8:buf!)!.uppercased() // Remove brackets let pos = tmp.positionOf(sub:"(") if pos > 0 { tmp = tmp.subString(start:0, length:pos) }

Db versioning help

Hi Fahim,

First off, huge thanks for a great library!

My scenario is that I have an onboard db that is copied to the device as per your library.
All the sql query functions work perfectly.
I run the db.getDBVersion() function and it correctly pulls in the user_pragma version.

Now I run into a the problems.

When I update my .db file and add the new .db to the xcode project and install the new version of the app on my device the db.getDBVersion() comes back with the original version that is copied to the device.

Was just wondering if you had any ideas on identifying the new version and overwriting the already copied version / or have i missed something in your library.

Hope this makes sense and hope to hear from you.

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.