Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Created August 31, 2019 18:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/b6e7e32de1f1c3d79d5c151eaa32643e to your computer and use it in GitHub Desktop.
Save robertmryan/b6e7e32de1f1c3d79d5c151eaa32643e to your computer and use it in GitHub Desktop.
func retrieveArticles(searchText: String) {
precondition(db != nil, "Database not open")
articles.removeAll()
let query = "SELECT * FROM articles WHERE title = ? "
var statement: OpaquePointer?
guard sqlite3_prepare(db, query, -1, &statement, nil) == SQLITE_OK else {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("error preparing Select: \(errmsg)")
return
}
defer { sqlite3_finalize(statement) }
guard sqlite3_bind_text(statement, 1, searchText, -1, nil) == SQLITE_OK else {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("failure binding title: \(errmsg)")
return
}
while sqlite3_step(statement) == SQLITE_ROW {
let id = sqlite3_column_int(statement, 0)
let author = sqlite3_column_text(statement, 1)
let title = sqlite3_column_int(statement, 2) // is title really an integer?
if let author = author {
articles.append(Article(id: Int(id), author: String(cString: author), title: "\(title)"))
} else {
print("Author is required")
}
}
print(articles.count)
print(articles)
}
@robertmryan
Copy link
Author

robertmryan commented Aug 31, 2019

A few observations:

  1. You should defer the sqlite3_finalize so that it's called, regardless of how you exit this routine.
  2. Method names should start with lowercase letters.
  3. For those errors that are hard stops, I'd suggest guard, in which the compiler verifies that you have returned.
  4. When retrieving the author name, you need to decide what you want to do if the name is missing in the table. But using String(describing:) is not what you want.
  5. I'd advise against using * is SQL SELECT statements because one's code should not be dependent upon the sequence of columns in the table. It's probably prudent to explicitly list the column names.
  6. It makes no sense to make the search string an optional (or, if you did, you'd need to handle it correctly ... the original code sample won’t do what you intended).
  7. I’d suggest changes to variable names (I’d suggest statement instead of stmt3; the ArticleList should also start with lowercase letter, and I’d personally just call it articles; etc.).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment