Skip to content

Commit f5f02d4

Browse files
committed
Fix not handling temp file request from sqlite
1 parent 15b74c0 commit f5f02d4

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/esp32.cpp

+38-6
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,8 @@ static int ESP32Access(
383383
return SQLITE_OK;
384384
}
385385

386+
static char dbrootpath[MAXPATHNAME+1];
387+
386388
/*
387389
** Open a file handle.
388390
*/
@@ -416,9 +418,6 @@ static int ESP32Open(
416418
//Serial.println("fn: Open");
417419

418420
strcpy(mode, "r");
419-
if( zName==0 ){
420-
return SQLITE_IOERR;
421-
}
422421

423422
if( flags&SQLITE_OPEN_MAIN_JOURNAL ){
424423
aBuf = (char *)sqlite3_malloc(SQLITE_ESP32VFS_BUFFERSZ);
@@ -431,7 +430,7 @@ static int ESP32Open(
431430
|| flags&SQLITE_OPEN_MAIN_JOURNAL ) {
432431
struct stat st;
433432
memset(&st, 0, sizeof(struct stat));
434-
int rc = stat( zName, &st );
433+
int rc = (zName == 0 ? -1 : stat( zName, &st ));
435434
//Serial.println(zName);
436435
if (rc < 0) {
437436
strcpy(mode, "w+");
@@ -446,8 +445,41 @@ static int ESP32Open(
446445
memset(p, 0, sizeof(ESP32File));
447446
//p->fd = open(zName, oflags, 0600);
448447
//p->fd = open(zName, oflags, S_IRUSR | S_IWUSR);
449-
p->fp = fopen(zName, mode);
450-
if( p->fp == (void *)NULL ) {
448+
if (zName == 0) {
449+
//generate a temporary file name
450+
char *tName = tmpnam(NULL);
451+
tName[4] = '_';
452+
size_t len = strlen(dbrootpath);
453+
memmove(tName + len, tName, strlen(tName) + 1);
454+
memcpy(tName, dbrootpath, len);
455+
p->fp = fopen(tName, mode);
456+
//https://stackoverflow.com/questions/64424287/how-to-delete-a-file-in-c-using-a-file-descriptor
457+
//for temp file, then no need to handle in esp32close
458+
unlink(tName);
459+
//Serial.println("Temporary file name generated: " + String(tName) + " mode: " + String(mode));
460+
} else {
461+
//detect database root as folder for temporary files, every newly openened db will change this path
462+
//this mainly fixes that vfs's have their own root name like /sd
463+
char *ext = strrchr(zName, '.');
464+
bool isdb = false;
465+
if (ext) {
466+
isdb = (strcmp(ext+1,"db") == 0);
467+
}
468+
if (isdb) {
469+
char zDir[MAXPATHNAME+1];
470+
int i=0;
471+
strcpy(zDir,zName);
472+
473+
for(i=1; zDir[i]!='/'; i++) {};
474+
zDir[i] = '\0';
475+
476+
strcpy(dbrootpath, zDir);
477+
}
478+
479+
p->fp = fopen(zName, mode);
480+
}
481+
482+
if( p->fp<=0){
451483
if (aBuf)
452484
sqlite3_free(aBuf);
453485
//Serial.println("Can't open");

0 commit comments

Comments
 (0)