Getting the size of an sqlite database

December 23rd, 2010 | No Comments »

Sometimes you need a way (probably a multi-platform way) to get the size of an sqlite database and inside the cubesql server we really need to know that information a lot of times.
In C we use a function like:

sqlite3_int64 file_size (const char *path)
{
	#ifdef WIN32
	WIN32_FILE_ATTRIBUTE_DATA   fileInfo;
	if (GetFileAttributesExA(path, GetFileExInfoStandard, (void*)&fileInfo) == 0) return 0;
	// combine two 32bit values fileInfo.nFileSizeHigh and fileInfo.nFileSizeLow to one 64 bit value
	return (((__int64)fileInfo.nFileSizeHigh) << 32 ) + fileInfo.nFileSizeLow;
	#else
	struct stat sb;
	if (stat(path, &sb) == -1) return 0;
	return sb.st_size;
	#endif
}

and it works pretty well.

In REAL Studio you can simply use the FolderItem class to get that value (using the Length property).

But there is another powerful way that’s is multi-platform and language independent, you just need the sqlite SQL language itself.

sqlite3_int64 cubesql_dbsize (sqlite3 *db)
{
	sqlite3_int64 n1, n2;
	
	n1 = cubesql_singlecolumn_select_int64 (db, "PRAGMA page_count;", 0, 0);
	n2 = cubesql_singlecolumn_select_int64 (db, "PRAGMA page_size;", 0, 0);
	
	// PRAGMA page_count * PRAGMA page_size;
	return n1 * n2;
}

Obviously the values returned by PRAGMA page_count; and PRAGMA page_size; can be used inside every application that have access to an sqlite3 database and multiplying these values represents a very easy way to get the database file without the needs to use the underline OS system calls.

Leave a Reply

This field is required

This field is required