On 3/18/15, Scott Hess <shess at google.com> wrote:
> I'm thinking I could use something like:
>
> SQLITE_API int sqlite3_attach(sqlite3* db, const char* zPath, const
> char* dbname);
> SQLITE_API int sqlite3_detach(sqlite3* db, const char* dbname);
>
> Right now, I have a helper in Chromium which does "ATTACH DATABASE ?
> AS ?". This works, but AFAICT this page:
> https://www.sqlite.org/lang_keywords.html
> implies that the dbname _probably_ should not be a string literal but
> instead an identifier. So it should be "dbname" with embedded "
> characters doubled (nobody should ever do that, but *shrug*).
Though undocumented, the arguments to ATTACH and DETACH can be
arbitrary expressions. For example:
ATTACH 'xyzzy' || '.txt' AS printf('abc-%d',12345');
So bound parameters are also supported. We have test cases that
verify this behavior.
>
> WDYT? Mostly this just came up because I saw someone writing code
> which constructed things sprintf-style, without quoting, which was
> clearly error-prone. But in describing the right way to do it, I had
> to do notable hand-waving.
>
Seems like an implementation of your requested functions would be fairly simple:
int sqlite3_attach(sqlite3* db, const char* zPath, const char* dbname){
char *zSql = sqlite3_mprintf("ATTACH %Q AS %Q", zPath, dbname);
int rc = sqlite3_exec(db, zSql, 0, 0, 0);
sqlite3_free(zSql);
return rc;
}
int sqlite3_detach(sqlite3* db, const char* dbname){
char *zSql = sqlite3_mprintf("DETACH %Q", dbname);
int rc = sqlite3_exec(db, zSql, 0, 0, 0);
sqlite3_free(zSql);
return rc;
}
--
D. Richard Hipp
drh at sqlite.org