Skip to content

Instantly share code, notes, and snippets.

@d3x0r
Created December 26, 2017 04:47
Show Gist options
  • Save d3x0r/85d1b5af3350814f942e047cae9eb6f4 to your computer and use it in GitHub Desktop.
Save d3x0r/85d1b5af3350814f942e047cae9eb6f4 to your computer and use it in GitHub Desktop.
test getting expanded statement from sqlite3 with bound parameter.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
sqlite3 *db; /* The SQLite database connection */
const char *zLastError;
const char testStatements1[] = "create table test (a char);";
const char testStatements2[] = "insert into test (a) values (?);";
/* Print an error message and exit */
static void fatal_error(const char *zMsg, ...){
va_list ap;
va_start(ap, zMsg);
vfprintf(stderr, zMsg, ap);
va_end(ap);
exit(1);
}
void ExpectSuccess( const char *sql, int len, int nLine ) {
int rc;
sqlite3_stmt *pStmt;
rc = sqlite3_prepare_v2(db, sql, len, &pStmt, 0);
if( rc != SQLITE_OK ) {
zLastError = sqlite3_errmsg( db );
fatal_error( "(%d-prep)unexpected error: [%s]\n", nLine, zLastError );
}
rc = sqlite3_step( pStmt );
if( rc != SQLITE_OK && rc != SQLITE_DONE ) {
zLastError = sqlite3_errmsg( db );
fatal_error( "(%d-step)unexpected error: %d[%s]\n", nLine, rc, zLastError );
}
{
const char *_sql = sqlite3_sql( pStmt );
printf( "got:" );
fwrite( _sql, 1, strlen(_sql), stdout );
printf( "\n" );
}
sqlite3_finalize( pStmt );
}
void ExpectBindSuccess( const char *sql, int len, int nLine, char *param, int paramLen ) {
int rc;
sqlite3_stmt *pStmt;
rc = sqlite3_prepare_v2(db, sql, len, &pStmt, 0);
if( rc != SQLITE_OK ) {
zLastError = sqlite3_errmsg( db );
fatal_error( "(%d-prep)unexpected error: [%s]\n", nLine, zLastError );
}
sqlite3_bind_text( pStmt, 1, param, paramLen, NULL );
rc = sqlite3_step( pStmt );
if( rc != SQLITE_OK && rc != SQLITE_DONE ) {
zLastError = sqlite3_errmsg( db );
fatal_error( "(%d-step)unexpected error: %d[%s]\n", nLine, rc, zLastError );
}
{
const char *_sql = sqlite3_expanded_sql( pStmt );
printf( "got:" );
fwrite( _sql, 1, strlen(_sql), stdout );
printf( "\n" );
}
sqlite3_finalize( pStmt );
}
int main( void ) {
int rc; /* sqlite3 result code */
unlink( "testdir/nultest.db" );
rc = sqlite3_open( "testdir/nultest.db", &db);
ExpectSuccess( testStatements1, sizeof( testStatements1 ), __LINE__ );
ExpectBindSuccess( testStatements2, sizeof( testStatements2 ), __LINE__, "Another\0Test", 12 );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment