nerdyc / squeal Goto Github PK
View Code? Open in Web Editor NEWA Swift wrapper for SQLite databases
License: MIT License
A Swift wrapper for SQLite databases
License: MIT License
Xcode 6.3 (6D570) - Swift 1.2
File "Squeal/Squeal/Statement.swift"
Here's the patch:
65c65
< columnNames.append(columnNameString)
---
> columnNames.append(columnNameString as String)
767c767
< return NSString(UTF8String:columnTextI)
---
> return NSString(UTF8String:columnTextI) as String?
Ciao.
The snippet provided in the README:
database.selectFrom("people") { (statement:Statement) -> Person in
Results in the error
Missing argument for parameter 'collector'
Modifying this to
database.selectFrom("people", collector: { (statement:Statement) -> Person in
...
})
Appears to resolve the error.
Supporting the Online Backup API for SQLite will make it easier to create copies of databases. In particular, this is helpful for situations when working with in-memory or temporary databases that need to be persisted to disk.
Further info: https://www.sqlite.org/backup.html
When I try to build a unit test that does an import of the whole project, it fails to compile with the error message given in the title. I added $(PROJECT_DIR)/Externals/Squeal/modules to the Swift import paths list, so don't know why this is happening.
I've tried googling this to see if there's a way to do it, but I'm currently trying to make the database for my App in ~/STEiN/(AppName)/(db) - I've tried setting the database string to be the full directory, I've tried making a temporary database, then using system() to move it to where I want it (which got it where I wanted it!) BUT then when I go to use it I keep getting nil. Any help would be greatly appreciated!!
I have added an sqlite3 db file to my project. However, when I try to access the database via Database(path: "myDB.db") I receive the following error upon calling the open() method:
Error Domain=sqlite3 Code=14 "out of memory"
Any ideas as to what I am doing incorrectly?
Code:
let database = Database(path:"brynkaTest.db")
var error : NSError?
if !database.open(&error) {
// handle error
var test = error!.description;
}
database.close(&error)
Legacy Objective-C codebases should be able to integrate Squeal at some level.
I'm just going to throw this out there but I kinda cringed when I saw that the main Squeal interface was just called "Database." Keep in mind that I'm new to Swift (and most of my background is Ruby, which has a more-than-healthy obsession with namespacing) so there might be things I can do to namespace/locally rename the Squeal Database class or whatnot, so please correct me if I'm making a mountain out of a molehill (In ESCMAScript 6, for instance, any imported module can be opaquely aliased in the client code). That said, I believe there are a couple problems with this naming:
(1) It's just not descriptive. When I inject a Squeal instance into my repository class at runtime, and a mock in-memory instance into the class for tests, they're both "Database" from the perspective of what they do in relation to the code that is using them, but they need easily distinguishable names. I'd much rather be dealing with instances of Squeal() (or Squeal::Database() would be ideal, but my understanding is that swift namespacing is way too clever to allow that), and MemoryStore() or whatever, simply for readability.
(2) Other than the testing case, one could conceivably have multiple database interfaces, with Squeal being but one. No one library should assume that it is used in a vacuum.
(3) Collisions with app code are not impossible by any means. Another (not iOS related) project I'm working on deals with databases and all the associated rigmarole as data objects, not code. Think a control panel or whatnot. Now my Database model class and my internal SQL connection library are at best very similarly named.
Other than the naming thing, I have no complaints :)
The latest version of Squeal doesn't build on iOS, because of "unresolved identifier 'sqlite3_close_v2'" or "unresolved identifier 'sqlite3_errstr'".
This is caused by the older versions of sqlite shipped with iOS, and probably affects pre-Yosemite builds of OS X too.
In the README.md example of creating a table invalid SQL is used in the definitions line of database.createTable. It reads
"personId INTEGER NOT NULL AUTOINCREMENTING PRIMARY KEY"
And should be changed to
"personId INTEGER NOT NULL AUTOINCREMENT PRIMARY KEY"
Everytime I try to use one of the query methods as stated in the Readme I get an error saying StepSequence? does not have a member named Generator
in the for loop
ex:
var rows2 = db?.query(sqlString!, error: err)
for image in rows2{ //error points to the rows2 variable
}
I have this problem with all the query methods. Am I doing something wrong?
Spent a few hours trying to get the app running on my iPad (real device). I was getting a crash when app was trying to load, see the attached image.
Finally was able to get it to work. The solution was to add Squeal for iOS not to Linked Frameworks and Libraries, but rather to Embedded Binaries (in the General section of project settings). Also, setting import module path was not necessary.
Please update installation instructions accordingly. Thanks.
Hi,
I can't install Squeal to my Swift project. I followed all installation instructions, but I still get "Use of unresolved identifier 'Database'
" error.
Thanks for any help.
When I tried to use Database.selectFrom function and I pass in the Limit parameter, I got an error says "No such function: Optional", then I found in this selectFrom function, the limit was append as "Optional(20)".
My code:
let rows = db.selectFrom("Merchandise", orderBy: "created desc", offset: start, limit: page, error: &error)
The SQL after parsed:
"SELECT * FROM Merchandise ORDER BY created desc LIMIT Optional(20) OFFSET 0"
Then I found in line 48 of SelectHelpers.swift, there is a missing "!":
if limit != nil {
fragments.append("LIMIT")
fragments.append("(limit)")
}
After I changed it to:
if limit != nil {
fragments.append("LIMIT")
fragments.append("(limit!)")
}
It works fine, do you think it is a bug in the code?
Thanks
JJ
Hi ! i'm a beginner in Swift and i'm trying to launch my app on my iphone for the first time.
I have just got my AppDev account and i create my certificate, my AppID, and my provisioning profiles.
I added my account in xcode preferences, and link my project with my team (in general option).
But when i try to launch my app on my device, i have this message:
This is not my team id... Do you know how i can fix it ?
Regards and thank fou your help
Squeal should provide simple methods for executing transactions
I'm creating a DAO class in swift using Squeal, however, when I try to create a database using the example in the documentation, I run into the "unable to open database file" error with SQLite.
Is there a particular way I am supposed to pass in the file path to the constructor?
when I try to use insertInto(tableName:values:error:)
xcode throws an error saying Missing argument for parameter 'columns' in call
If I use db?.insertInto(tableName, columns:, values:, error: err)
it builds fine
I followed your installation instructions and added the call let onDiskDatabase = Database(...) and it does not find the Database class. Am I missing an import or a framework setup on my project?
Receiving the error "Missing argument for parameter 'collector' in call" upon trying to call the Database.selectFrom method
Code:
let database = Database(path:DBPath)
var error : NSError?
if !database.open(&error) {
// handle error
var test = error!.description;
}
//var s = Statement()
var events = database.selectFrom("admEvents") { (statement:Statement) -> Event in // ERROR
// this block is called to process each row.
return Event(
id: statement.int64Value("id"),
name: statement.stringValue("name")
)
}
if events != nil {
// ...
return events
} else {
// handle error
return []
}
database.close(&error)
Forgive me, I'm new to IOS development and may be doing (or not doing) something stupid. I have followed all of the installation instructions you listed. I have also linked the Squeal framework in the Build Phases section of the project after reading other comments. However, when I try to import Squeal at the top of my Swift file I get the following error: "Could not build Objective-C module 'Squeal'.
Is there something that I'm missing? It seemed like maybe Squeal needed an Objective-C Bridging Header to function properly. I tried to create one and import the Squeal.h file at the top of it but it did not rectify my issue. Perhaps I have the directory path wrong for the import statement in the Bridging-Header???
Any insight you could provide would be greatly appreciated. Looks like it will be an awesome wrapper when I can get it up and running.
Xcode 6.0.1 (6A317)
when trying to clone as per step 1 I receive the following. Are there protections you need to set to allow a clone?
Brians-Mac-mini:Externals Brian$ git clone [email protected]:nerdyc/Squeal.git Externals/Squeal
Cloning into 'Externals/Squeal'...
Warning: Permanently added the RSA host key for IP address '192.30.252.130' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
I have been working on building a simple ORM on top of Squeal, and overall it has been working great. But as I have been making and testing swift optional parameters I noticed that inserts are no longer being handled correctly. When I pass in a [String, Bindable?]
Dictionary, if any of the values are nil(NULL
), subsequent values are not being handled correctly.
For example, if I have a table that looks like:
CREATE TABLE Items (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
title VARCHAR,
externalKey INTEGER
);
And I do an insert like:
var values = ["title": nil, "externalKey":35]
db.insertInto("Items", values: values, error:&error)
The externalKey
field will be NULL
.
If instead I do:
var values = ["externalKey":35, "title": nil]
db.insertInto("Items", values: values, error:&error)
The externalKey
field will be 35
. So, order in this case makes the difference on whether it works.
To reproduce, you just need these 4 lines of code:
var error : NSErrorPointer = nil
db.execute("CREATE TABLE Items (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR,externalKey INTEGER);", error:error)
var values : Dictionary<String, Bindable?> = ["title": nil, "externalKey":35]
self.db!.insertInto("Items", values: values, error: error)
Since I found this issue, I also tried testing it with updates. Updates also had issues, but in some ways more substantive because if there were any nil values, they would just not update any of the values.
Is there something additional that I am missing in how to handle nil values on an insert or update?
Squeal doesn't support BLOBs yet.
Trying out Xcode 7 and there are a lot of Swift 2.0 compatibility issues, some are easily fixable but others I am not sure what to do.
for example
public func bindStringValue(stringValue:String, atIndex index:Int, error:NSErrorPointer = nil) -> Bool {
let cString = stringValue.cStringUsingEncoding(NSUTF8StringEncoding)
let negativeOne = UnsafeMutablePointer<Int>(bitPattern: -1)
let opaquePointer = COpaquePointer(negativeOne)
let transient = CFunctionPointer<((UnsafeMutablePointer<()>) -> Void)>(opaquePointer)
let resultCode = sqlite3_bind_text(sqliteStatement, Int32(index), cString!, -1, transient)
if resultCode != SQLITE_OK {
if error != nil {
error.memory = database.sqliteError
}
return false
}
return true
}
gives an error CFunctionPointer is unavailable, use a function type @convention(c) (T)->U
Hello,
I followed the instructions on your documentation:
struct Person {
let id:Int64?
let name:String?
let email:String?
}
var people = database.selectFrom("people") { (statement:Statement) -> Person in
// this block is called to process each row.
return Person(id: statement.int64Value("personId"),
name: statement.stringValue("name"),
email:statement.stringValue("email"))
}
if people != nil
{
// here I might need to do a loop through people?????
}
How should I loop through the people variable? I tried few things with no luck....
Thanks!
Project using squeal-ios framework builds and runs without any issues on my mac, but on another mac I'm getting Library not found for -lsqlite3 error. I tried to delete and add framework but I'm getting the same error.
Xcode 6.0 OS X 10.10 Swift Compiler Error: Could not build Objective-C module 'sqlite3'
I have an insert into sentence, its 100% functional in develop with xcode, but after that i uploaded to testflight, i received the next error:
Error Domain=sqlite3 Code=1 "near"=":syntax error"
In my example, the data never have a character "="
I use the same data always
My code is:
var _values = String: Bindable?
_values["promotion_id"] = json["promotions"][index]["id"].stringValue
_values["name"] = json["promotions"][index]["name"].stringValue
_values["description"] = json["promotions"][index]["description"].stringValue
_values["image"] = json["promotions"][index]["image"].stringValue
_values["valid_from"] = json["promotions"][index]["valid_from"].stringValue
_values["valid_to"] = json["promotions"][index]["valid_to"].stringValue
_values["restaurant_id"] = json["promotions"][index]["restaurant"]["id"].stringValue
_values["restaurant_branch_id"] = json["promotions"][index]["restaurant"]["branch_id"].stringValue
_values["restaurant_name"] = json["promotions"][index]["restaurant"]["name"].stringValue
_values["restaurant_description"] = json["promotions"][index]["restaurant"]["description"].stringValue
_values["restaurant_location_latitude"] = json["promotions"][index]["restaurant"]["location_latitude"].stringValue
_values["restaurant_location_longitude"] = json["promotions"][index]["restaurant"]["location_longitude"].stringValue
_values["restaurant_logo"] = json["promotions"][index]["restaurant"]["logo"].stringValue
_values["restaurant_cover"] = json["promotions"][index]["restaurant"]["cover"].stringValue
_values["restaurant_distance"] = json["promotions"][index]["restaurant"]["distance"].stringValue
_values["restaurant_color"] = json["promotions"][index]["restaurant"]["color"].stringValue
_values["restaurant_open"] = json["promotions"][index]["restaurant"]["open"].stringValue
_values["restaurant_ticket"] = json["promotions"][index]["restaurant"]["ticket"].stringValue
var error: NSError?
self.db.insertInto("promotions", values: _values, error: &error)
Hello,
First off - thank you for making Squeal. I've been working on a relatively simple app that makes heavy use of an existing sqlite database, and I've found Squeal to be very intuitive and fast.
I'm running into an issue now where I appear to need to be on the Squeal team in order to include the framework as part of my project. When I go to Build Phases -> Embed Frameworks and add Squeal.framework, I am told I need to code sign the Squeal.xcodeproj. When I try to do this, I am told I can't because I am not a part of team D7K65AYKY9. I have tried hitting "Fix Issue" and changing the team and signing types within xcode, but to no avail. I am currently unable to build due to this issue, which I suspect may be related to an update of xcode. I was wondering if this is an issue anyone else is experiencing, or whether anyone has any advice on how I should proceed.
Any help is very much appreciated.
Best,
Marvin
follow Installation to install but not work, can not import squeal
when I have a class that imports the library, the import has an error saying
Missing required module 'sqlite3_ios'
I installed Command line tools for xcode but that didnt seem to help
I have my Bridging header setup, module.map seems to be setup. I dont know what else to check
This patch fixes some typos in "README.md".
It's useful for those, like me, copy & paste to try to understand ;-)
166c166
< if let rowId = database.insertInto("people", values:["email":"[email protected]"], error:&error]) {
---
> if let rowId = database.insertInto("people", values:["email":"[email protected]"], error:&error) {
183c183
< error: &error]) {
---
> error: &error) {
201c201
< error: &error]) {
---
> error: &error) {
219,220c219,220
< for row in db.query("SELECT * FROM people", error:&error) {
< if row == nil? {
---
> for row in database.query("SELECT * FROM people", error:&error) {
> if row == nil {
235c235
< for row in db.selectFrom("people", error:&error) {
---
> for row in database.selectFrom("people", error:&error) {
251c251
< if peopleCount == nil
---
> if peopleCount == nil {
273c273
< let insertedId = db.insertInto("people", values:["name":"Audrey"], error:&error)
---
> let insertedId = database.insertInto("people", values:["name":"Audrey"], error:&error)
275c275
< return .Failed(error:error)
---
> return .Failed(error!)
289c289
< return .Failed(error:error)
---
> return .Failed(error!)
320c320
< if db.execute("VACUUM", error:&error) {
---
> if database.execute("VACUUM", error:&error) {
335c335
< let statement = database.prepareStatement("SELECT * FROM contacts WHERE email = ?")!
---
> if let statement = database.prepareStatement("SELECT * FROM people WHERE email = ?") {
337c337,338
< ...
---
> // ...
> }
344,345c345,347
< let statement = database.prepareStatement("INSERT INTO contacts (name,email) VALUES (?, ?)")!
< statement.execute(parameters:["Harry Potter", "[email protected]"])
---
> if let statement = database.prepareStatement("INSERT INTO people (name,email) VALUES (?, ?)") {
> // statement.execute(parameters:["Harry Potter", "[email protected]"]) It's not yet implemented (Request/ToDo ?)
> }
Ciao.
It would be nice to be able to use subscripting with a Statement, if possible. Something like:
var name : String? = statement["name"]
The type of the returned value probably needs to be declared so the appropriate type method can be called on sqlite.
Why don't create a Podfile in order to install Squeal as a pod? I would be very useful considering that CocoaPods 0.36.0 is now supporting Swift.
SQLite provides Full Text Search extensions. Squeal should provide helpers to make setting this up simple, and perhaps help with constructing optimized FTS queries.
Hi,
I used the query(string) method to make a generic method for select data.
With the update of Squeal for Swift2, i cant use this method.
var rows = try db.query(request)
for row in rows{
//Treat row
}
I dont find equivalent of this...
Regards
Squeal should provide basic ability to query the database schema, and perform core modifications. Including:
Squeal should keep migration management very minimal, so app developers can decide how to manage schema changes themselves.
Interacting directly with a database through Squeal gives app developers a lot of power, but writing basic SELECT statements is still boilerplate.
Squeal should provide extensions for basic SQL operations, including:
Support for joins and complex queries should be avoided and left up to higher-level frameworks.
Squeal works on iOS 7.1 but won't pass AppStore validator. Any suggestions how to use squeal, so it will pass validator for iOS 7.1.
“execute” with parameters and “execute” with named parameters are not yet implemented.
I suggest this patch for “Statement.swift":
500a501,532
> /// Replaces the parameters and executes the statement. This is useful for statements like `INSERT` which return no results.
> ///
> /// :param: error An error pointer.
> ///
> /// :returns: `true` if the statement succeeded, `false` if it failed.
> ///
> public func execute(#parameters:[Bindable?], error:NSErrorPointer = nil) -> Bool {
> reset()
> clearParameters()
> if self.bind(parameters, error:error) {
> return execute(error:error)
> } else {
> return false
> }
> }
>
> /// Replaces the named parameters and executes the statement. This is useful for statements like `INSERT` which return no results.
> ///
> /// :param: error An error pointer.
> ///
> /// :returns: `true` if the statement succeeded, `false` if it failed.
> ///
> public func execute(#namedParameters:[String:Bindable?], error:NSErrorPointer = nil) -> Bool {
> reset()
> clearParameters()
> if self.bind(namedParameters:namedParameters, error:error) {
> return execute(error:error)
> } else {
> return false
> }
> }
>
Ciao.
SQLite provides the ability to define custom functions in C. Squeal should provide a similar way to do so in Swift.
This would allow complex or domain-specific operations to be performed in code, and accessed via SQL.
Followed installation instructions. Works great on a simulator. Crashes on a device with following error:
dyld: Library not loaded: @rpath/Squeal.framework/Squeal
Referenced from: /private/var/mobile/Containers/Bundle/Application/91F3700E-F93C-4259-9E47-861E0B6069B7/MyApp.app/MyApp
Reason: image not found
I know it's not an issue with a framework itself, but I could not find any fix for it. Any advice?
Thanks.
I would like to know , if there is any documentation update for swift 2.0
Are there any informations about how to do the select, insert or update commands, as it is described in the documentation for the previous swift versions
All my commands and connections are no more valid in swift 2.0 and I habe absolutely no idea how to solve that
It would be so nice to read an updated documentation.
Thanks a lot
Upgraded to Yosemite and now Squeal will not compile. The following error is being thrown in the Squeal/Helpers/TransactionHelpers.swift file:
"No such module 'sqlite3'"
Any ideas on how to fix this?
It would be really nice if we didn't need to configure a module.map to compile and use Squeal.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.