Skip to content

Commit

Permalink
fix sqlite API error handling
Browse files Browse the repository at this point in the history
- call sqlite3_errmsg(db) before closing the db, not after
- sqlite3_errmsg() can only be used when sqlite3_step() returns SQLITE_ERROR
- check for errors from sqlite3_finalize()
- close db handle even when an error occurred during sqlite3_open()

with suggestions from chris
testing + ok tom
  • Loading branch information
stspdotname committed Sep 18, 2023
1 parent dd054fe commit eb5d12f
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions sqlite3.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Expand Down Expand Up @@ -213,20 +214,23 @@ db_select_name_rtable(StringList *words, int rtableid)
int
sq3simple(char *sql, StringList *words)
{
sqlite3 *db;
sqlite3 *db = NULL;
sqlite3_stmt *stmt;
char *result, *new = NULL;
int rv, len, tlen = 0;

if (sqlite3_open(SQ3DBFILE, &db)) {
printf("%% database file open failed: %s\n", sqlite3_errmsg(db));
return -1;
printf("%% database file open failed: %s\n",
db ? sqlite3_errmsg(db) : strerror(ENOMEM));
tlen = -1;
goto done;
}
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL)
!= SQLITE_OK) {
printf("%% sqlite3_prepare_v2 failed: %s (%s)\n",
sqlite3_errmsg(db), sql);
return -1;
tlen = -1;
goto done;
}

while ((rv = sqlite3_step(stmt)) == SQLITE_ROW) {
Expand All @@ -240,12 +244,20 @@ sq3simple(char *sql, StringList *words)
strlcpy(new, result, len);
sl_add(words, new);
}
sqlite3_finalize(stmt);
sqlite3_close(db);

if (rv != SQLITE_DONE) {
printf("%% sq3simple: error: %s\n", sqlite3_errmsg(db));
return -1;
if (rv == SQLITE_ERROR) {
printf("%% sqlite3_step: %s\n", sqlite3_errmsg(db));
tlen = -1;
}

rv = sqlite3_finalize(stmt);
if (rv != SQLITE_OK) {
printf("%% sqlite3_finalize: %s\n", sqlite3_errstr(rv));
tlen = -1;
}
done:
if (db)
sqlite3_close(db);

return tlen;
}

0 comments on commit eb5d12f

Please sign in to comment.