Skip to content

Commit

Permalink
Fix not handling temp file request from sqlite
Browse files Browse the repository at this point in the history
  • Loading branch information
siara-cc committed Dec 31, 2023
1 parent 15b74c0 commit f5f02d4
Showing 1 changed file with 38 additions and 6 deletions.
44 changes: 38 additions & 6 deletions src/esp32.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,8 @@ static int ESP32Access(
return SQLITE_OK;
}

static char dbrootpath[MAXPATHNAME+1];

/*
** Open a file handle.
*/
Expand Down Expand Up @@ -416,9 +418,6 @@ static int ESP32Open(
//Serial.println("fn: Open");

strcpy(mode, "r");
if( zName==0 ){
return SQLITE_IOERR;
}

if( flags&SQLITE_OPEN_MAIN_JOURNAL ){
aBuf = (char *)sqlite3_malloc(SQLITE_ESP32VFS_BUFFERSZ);
Expand All @@ -431,7 +430,7 @@ static int ESP32Open(
|| flags&SQLITE_OPEN_MAIN_JOURNAL ) {
struct stat st;
memset(&st, 0, sizeof(struct stat));
int rc = stat( zName, &st );
int rc = (zName == 0 ? -1 : stat( zName, &st ));
//Serial.println(zName);
if (rc < 0) {
strcpy(mode, "w+");
Expand All @@ -446,8 +445,41 @@ static int ESP32Open(
memset(p, 0, sizeof(ESP32File));
//p->fd = open(zName, oflags, 0600);
//p->fd = open(zName, oflags, S_IRUSR | S_IWUSR);
p->fp = fopen(zName, mode);
if( p->fp == (void *)NULL ) {
if (zName == 0) {
//generate a temporary file name
char *tName = tmpnam(NULL);
tName[4] = '_';
size_t len = strlen(dbrootpath);
memmove(tName + len, tName, strlen(tName) + 1);
memcpy(tName, dbrootpath, len);
p->fp = fopen(tName, mode);
//https://stackoverflow.com/questions/64424287/how-to-delete-a-file-in-c-using-a-file-descriptor
//for temp file, then no need to handle in esp32close
unlink(tName);
//Serial.println("Temporary file name generated: " + String(tName) + " mode: " + String(mode));
} else {
//detect database root as folder for temporary files, every newly openened db will change this path
//this mainly fixes that vfs's have their own root name like /sd
char *ext = strrchr(zName, '.');
bool isdb = false;
if (ext) {
isdb = (strcmp(ext+1,"db") == 0);
}
if (isdb) {
char zDir[MAXPATHNAME+1];
int i=0;
strcpy(zDir,zName);

for(i=1; zDir[i]!='/'; i++) {};
zDir[i] = '\0';

strcpy(dbrootpath, zDir);
}

p->fp = fopen(zName, mode);
}

if( p->fp<=0){
if (aBuf)
sqlite3_free(aBuf);
//Serial.println("Can't open");
Expand Down

0 comments on commit f5f02d4

Please sign in to comment.