Beispiel #1
0
int main_()
{
	printf("%d\n", sqlite3_complete("select * from emp;")); // output 1
	printf("%d\n", sqlite3_complete(";")); // output 1
	printf("%d\n", sqlite3_complete("f**k you;")); // output 1
	printf("%d\n", sqlite3_complete("select * from emp")); // output 0
	printf("%d\n", sqlite3_complete("select * from emp\0;")); // output 0
	
	return 0;
}
Beispiel #2
0
/* call-seq: complete?(sql)
 *
 * Return +true+ if the string is a valid (ie, parsable) SQL statement, and
 * +false+ otherwise.
 */
static VALUE complete_p(VALUE UNUSED(self), VALUE sql)
{
  if(sqlite3_complete(StringValuePtr(sql)))
    return Qtrue;

  return Qfalse;
}
Beispiel #3
0
/**
@SYMTestCaseID			SYSLIB-SQLITE3-UT-4002
@SYMTestCaseDesc		Statement handle SQLITE3 tests.
						List of called SQLITE3 functions:
						 - sqlite3_complete;
						 - sqlite3_complete16;
						 - sqlite3_prepare;
						 - sqlite3_finalize;
						 - sqlite3_column_count;
						 - sqlite3_db_handle;
						 - sqlite3_step;
						 - sqlite3_column_decltype;
						 - sqlite3_column_decltype16;
						 - sqlite3_column_name;
						 - sqlite3_column_name16;
						 - sqlite3_column_int;
						 - sqlite3_column_int64;
						 - sqlite3_column_double;
						 - sqlite3_column_text;
						 - sqlite3_column_text16;
						 - sqlite3_column_blob;
@SYMTestPriority		High
@SYMTestActions			Statement handle SQLITE3 tests.
@SYMTestExpectedResults Test must not fail
@SYMREQ					REQ8782
*/
static void TestStatement1()
	{
  	const char* tail = 0;
	int err;
	
	TEST(TheDb != 0);
	TEST(!TheStmt);

	err = sqlite3_complete("SELECT * FROM A;");
	TEST(err != 0);
	
	err = sqlite3_complete16(L"SELECT * FROM A;");
	TEST(err != 0);
	
	err = sqlite3_prepare(TheDb, "SELECT * FROM A", -1, &TheStmt, &tail);
	TEST2(err, SQLITE_OK);
	TEST((unsigned int)TheStmt);
	TEST(!tail || strlen(tail) == 0);
	
	DoTestStatement();
	
	err = sqlite3_finalize(TheStmt);
	TEST2(err, SQLITE_OK);
	TheStmt = 0;
	}
Beispiel #4
0
int main2()
{
	sqlite3 *db;
	int rc;

	rc = sqlite3_open("./employees.db", &db);
	if( rc != SQLITE_OK )
	{
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return(1);
	}

	int cols;
	sqlite3_stmt *stmt;
	const char* tail = NULL;
	//const char* sql = "create table emp(id, name);select * from emp;";
	const char* sql = "select * from emp;select * from emp where name like 'm%';";

	while (sqlite3_complete(sql))
	{
		printf("sql = %s\n", sql);
		rc = sqlite3_prepare_v2(db, sql, -1, &stmt, &tail);
		printf("after sqlite3_prepare_v2() called, rc = %d, tail = |%s|, tail = %p, *tail = %d\n", rc, tail, tail, *tail);
		if( rc != SQLITE_OK )
		{
			fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
		}
		
		cols = sqlite3_column_count(stmt);
		rc = sqlite3_step(stmt);
		while(rc == SQLITE_ROW)
		{
			int i;
			for (i = 0; i < cols; i++)
			{
				printf("%s    ", sqlite3_column_text(stmt, i));
			}
			printf("\n");
			rc = sqlite3_step(stmt);
		}
		if (sql == tail)
		{
			printf("please check you sql!\n");
			break;
		}
		else
		{
			sql = tail;
		}
		printf("\n\n");
	}
	
	sqlite3_finalize(stmt);
	sqlite3_close(db);

	return 0;
}
static void process_input(sqlite3 * db, FILE *in, int * lineErr){
  char *zLine;
  char *zSql = 0;
  char * zErrMsg = 0;
  int nSql = 0;
  int rc;
  while((zLine = sqlbrowser_getline(in))!=0 ){
    if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
    (*lineErr)++;
    if( zSql==0 ){
      int i;
      for(i=0; zLine[i] && isspace(zLine[i]); i++){}
      if( zLine[i]!=0 ){
        nSql = strlen(zLine);
        zSql = malloc( nSql+1 );
        strcpy(zSql, zLine);
      }
    }else{
      int len = strlen(zLine);
      zSql = realloc( zSql, nSql + len + 2 );
      /*if( zSql==0 ){
        fprintf(stderr,"%s: out of memory!\n", Argv0);
        exit(1);
      }*/
      strcpy(&zSql[nSql++], "\n");
      strcpy(&zSql[nSql], zLine);
      nSql += len;
    }
    free(zLine);
    if( zSql && _ends_with_semicolon(zSql, nSql) && sqlite3_complete(zSql) ){
      rc = sqlite3_exec(db, zSql, NULL, NULL, &zErrMsg);//&zErrMsg
      if( rc || zErrMsg ){
        //if( in!=0 && !p->echoOn ) printf("%s\n",zSql);
        if( zErrMsg!=0 ){
          /*printf("SQL error: %s\n", zErrMsg);*/
          free(zErrMsg);
          zErrMsg = 0;
          if( zSql ){
            free(zSql);
           }
           return;
        }/*else{
          printf("SQL error: %s\n", sqlite3_error_string(rc));
        }*/
      }
      free(zSql);
      zSql = 0;
      nSql = 0;
    }
  }
  if( zSql ){
    /*if( !_all_whitespace(zSql) ) printf("Incomplete SQL: %s\n", zSql);*/
    free(zSql);
  }
  /*normal exit, clear err*/
  *lineErr = 0;
}
Beispiel #6
0
/*
** Return true if zSql is a complete SQL statement.  Return false if it
** ends in the middle of a string literal or C-style comment.
*/
static int _is_complete(char *zSql, int nSql){
	int rc;
	if( zSql==0 ) return 1;
	zSql[nSql] = ';';
	zSql[nSql+1] = 0;
	rc = sqlite3_complete(zSql);
	zSql[nSql] = 0;
	return rc;
}
ikptr
ik_sqlite3_complete (ikptr s_sql_snippet)
{
#ifdef HAVE_SQLITE3_COMPLETE
  const char *	sql_snippet = IK_CHARP_FROM_BYTEVECTOR_OR_POINTER_OR_MBLOCK(s_sql_snippet);
  return (sqlite3_complete(sql_snippet))? IK_TRUE_OBJECT : IK_FALSE_OBJECT;
#else
  feature_failure(__func__);
#endif
}
/*
** This routine is the same as the sqlite3_complete() routine described
** above, except that the parameter is required to be UTF-16 encoded, not
** UTF-8.
*/
int sqlite3_complete16(const void *zSql){
  sqlite3_value *pVal;
  char const *zSql8;
  int rc = 0;

  pVal = sqlite3ValueNew();
  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  if( zSql8 ){
    rc = sqlite3_complete(zSql8);
  }
  sqlite3ValueFree(pVal);
  return rc;
}
SWIGEXPORT jint JNICALL Java_com_almworks_sqlite4java__1SQLiteSwiggedJNI_sqlite3_1complete(JNIEnv *jenv, jclass jcls, jstring jarg1) {
  jint jresult = 0 ;
  char *arg1 = (char *) 0 ;
  int result;
  
  (void)jenv;
  (void)jcls;
  arg1 = 0;
  if (jarg1) {
    arg1 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg1, 0);
    if (!arg1) return 0;
  }
  result = (int)sqlite3_complete((char const *)arg1);
  jresult = (jint)result; 
  if (arg1) (*jenv)->ReleaseStringUTFChars(jenv, jarg1, (const char *)arg1);
  return jresult;
}
Beispiel #10
0
/*
** This routine is the same as the sqlite3_complete() routine described
** above, except that the parameter is required to be UTF-16 encoded, not
** UTF-8.
*/
int sqlite3_complete16(const void *zSql){
  sqlite3_value *pVal;
  char const *zSql8;
  int rc = SQLITE_NOMEM;

#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite3_initialize();
  if( rc ) return rc;
#endif
  pVal = sqlite3ValueNew(0);
  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  if( zSql8 ){
    rc = sqlite3_complete(zSql8);
  }else{
    rc = SQLITE_NOMEM;
  }
  sqlite3ValueFree(pVal);
  return sqlite3ApiExit(0, rc);
}
static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
        kwargs)
{
    static char *kwlist[] = {"statement", NULL, NULL};
    char* statement;

    PyObject* result;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
    {
        return NULL; 
    }

    if (sqlite3_complete(statement)) {
        result = Py_True;
    } else {
        result = Py_False;
    }

    Py_INCREF(result);

    return result;
}
Beispiel #12
0
// read file
int database_loadFile ( database_state_t *pState, const char * pFileName )
{
  // local variables
  sqlite3 * database = pState->database;
  FILE    * file     = fopen ( pFileName, "rb" );
  int       result;

  if ( file == 0 )
  {
    error ( "SQL file failed to load!" );
    return 1;
  }
  else
  {
    char * errorMessage;
    char   buffer [ DATABASE_FILE_BUFFER_SIZE ];
    char * line;
    int    offset;
    int    size;

    offset = 0;
    line   = &buffer [ offset ];
    size   = sizeof ( buffer ) - offset;
    while ( NULL != fgets ( line, size, file ) )
    {
      switch ( sqlite3_complete ( buffer ) )
      {
        // SQLite3 memory allocation failed
        case SQLITE_NOMEM:
          error ( "No memory!  SQL file failed to load!" );
          fclose ( file );
          return 1;
          break;

        // incomplete statement, append next line
        case 0:
          if ( '-' == line[ 0 ] && '-' == line[ 1 ] )
          {
            // comment, ignore line
            // this comment detection is not robust!
          }
          else
          {
            // read next line
            offset = strlen ( buffer );
          }
          break;

        // complete statement, execute SQL and reset offset
        default:
          if ( SQLITE_OK != sqlite3_exec ( database, buffer, NULL, NULL, &errorMessage ) )
          {
            error ( errorMessage );
            sqlite3_free ( errorMessage );
          }
          offset = 0;
        break;
      }

      // update based on offset
      line   = &buffer [ offset ];
      size   = sizeof ( buffer ) - offset;
      if ( size <= 1 )
      {
        error ( "Buffer too small!  SQL file failed to load!" );
        fclose ( file );
        return 1;
      }
    }
    fclose ( file );
  }
  return result;
}
/*
 * This ist the Entry Function of this Mex-DLL
 */
void mexFunction(int nlhs, mxArray*plhs[], int nrhs, const mxArray*prhs[])
{
    mexAtExit(CloseDBs);
    
    /*
     * Get the current Language
     */
    if (Language == -1)
    {
#ifdef _WIN32        
        switch(PRIMARYLANGID(GetUserDefaultLangID()))
        {
            case LANG_GERMAN:
                Language = 1;
                break;
                
            default:
                Language = 0;
        }
#else
        Language = 0;
#endif
    }
    
	/*
	 * Print Version Information
	 */
	if (! FirstStart)
    {
    	FirstStart = true;

        mexPrintf (MSG_HELLO, sqlite3_libversion());
    }
    
    /*
     * Check if the first argument is a number, then we have to use
	 * this number as an database id.
     */
    int db_id = 0;
    int FirstArg = 0;
    int NumArgs = nrhs;
    
    if (nrhs >= 1 && mxIsNumeric(prhs[0]))
    {
        db_id = (int) *mxGetPr(prhs[0]);
        if (db_id < 0 || db_id > MaxNumOfDbs)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        db_id --;
        FirstArg ++;
        NumArgs --;
    }

	/*
	 * All remaining arguments have to be strings
	 */
    bool isNotOK = false;
    int  i;
    
    for (i = FirstArg; i < nrhs; i++)
    {
        if (! mxIsChar(prhs[i]))
        {
            isNotOK = true;
            break;
        }
    }
    if (NumArgs < 1 || isNotOK)
    {
        mexPrintf(MSG_USAGE);
        mexErrMsgTxt(MSG_INVALIDARG);
    }

	/*
	 * Get the first string argument, this is the command string
	 */
    char *command = getstring(prhs[FirstArg]);
    
    if (! strcmp(command, "open"))
    {
		/*
		 * open a database. There have to be two string arguments.
		 * The command 'open' and the database filename
		 */
        if (NumArgs != 2)
        {
            mexPrintf(MSG_NOOPENARG, mexFunctionName());
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		// TODO: Memoryleak 'command not freed' when getstring fails
        char* dbname = getstring(prhs[FirstArg +1]);

		/*
		 * Is there an database ID? The close the database with the same id 
		 */
        if (db_id > 0 && g_dbs[db_id])
        {
            sqlite3_close(g_dbs[db_id]);
            g_dbs[db_id] = 0;
        }

		/*
		 * If there isn't an database id, then try to get one
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i] == 0)
                {
                    db_id = i;
                    break;
                }
            }
        }
		/*
		 * no database id? sorry, database id table full
		 */
        if (db_id < 0)
        {
            plhs[0] = mxCreateScalarDouble((double) 0);
            mexPrintf(MSG_NOFREESLOT);
			mxFree(command);
        	mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
       
		/*
		 * Open the database
		 */
        int rc = sqlite3_open(dbname, &g_dbs[db_id]);
        
        if (rc)
        {
			/*
			 * Anything wrong? free the database id and inform the user
			 */
            mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
            sqlite3_close(g_dbs[db_id]);

            g_dbs[db_id] = 0;
            plhs[0] = mxCreateScalarDouble((double) 0);
            
			mxFree(command);
	        mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
		/*
		 * return value will be the used database id
		 */
        plhs[0] = mxCreateScalarDouble((double) db_id +1);
        mxFree(dbname);
    }
    else if (! strcmp(command, "close"))
    {
		/*
		 * close a database
		 */

		/*
		 * if the database id is < 0 than close all open databases
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i])
                {
                    sqlite3_close(g_dbs[i]);
                    g_dbs[i] = 0;
                }
            }
        }
        else
        {
			/*
			 * If the database is open, then close it. Otherwise
			 * inform the user
			 */
            if (! g_dbs[db_id])
            {
				mxFree(command);
                mexErrMsgTxt(MSG_DBNOTOPEN);
            }
            else
            {
                sqlite3_close(g_dbs[db_id]);
                g_dbs[db_id] = 0;
            }
        }
    }
    else if (! strcmp(command, "status"))
    {
    	for (i = 0; i < MaxNumOfDbs; i++)
        {
            mexPrintf("DB Handle %d: %s\n", i, g_dbs[i] ? "OPEN" : "CLOSED");
        }
    }
    else
    {
		/*
		 * Every unknown command is treated as an sql query string
		 */

		/*
		 * database id < 0? Thats an error...
		 */
        if (db_id < 0)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
			mxFree(command);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
		/*
		 * database not open? -> error
		 */
        if (!g_dbs[db_id])
        {
			mxFree(command);
            mexErrMsgTxt(MSG_DBNOTOPEN);
        }

		const char* query = command;

		/*
		 * emulate the "show tables" sql query
		 */
        if (! strcmpi(query, "show tables"))
        {
            query = "SELECT name as tablename FROM sqlite_master "
                    "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
                    "UNION ALL "
                    "SELECT name as tablename FROM sqlite_temp_master "
                    "WHERE type IN ('table','view') "
                    "ORDER BY 1";
        }

		/*
		 * complete the query
		 */
        if (sqlite3_complete(query))
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVQUERY);
        }
        
        sqlite3_stmt *st;
        
		/*
		 * and prepare it
		 * if anything is wrong with the query, than complain about it.
		 */
        if (sqlite3_prepare_v2(g_dbs[db_id], query, -1, &st, 0))
        {
            if (st)
                sqlite3_finalize(st);
            
			mxFree(command);
            mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
        }

		/*
		 * Any results?
		 */
        int ncol = sqlite3_column_count(st);
        if (ncol > 0)
        {
            char **fieldnames = new char *[ncol];   /* Column names */
            Values* allrows = 0;                    /* All query results */
            Values* lastrow = 0;					/* pointer to the last result row */
            int rowcount = 0;						/* number of result rows */
            
			/*
			 * Get the column names of the result set
			 */
            for(i=0; i<ncol; i++)
            {
                const char *cname = sqlite3_column_name(st, i);
                
                fieldnames[i] = new char [strlen(cname) +1];
                strcpy (fieldnames[i], cname);
				/*
				 * replace invalid chars by '_', so we can build
				 * valid MATLAB structs
				 */
                char *mk_c = fieldnames[i];
                while (*mk_c)
                {
                	if ((*mk_c == ' ') || (*mk_c == '*') || (*mk_c == '?'))
                    	*mk_c = '_';
                    mk_c++;
                }
            }
            
            /*
			 * get the result rows from the engine
			 *
			 * We cannot get the number of result lines, so we must
			 * read them in a loop and save them into an temporary list.
			 * Later, we can transfer this List into an MATLAB array of structs.
			 * This way, we must allocate enough memory for two result sets,
			 * but we save time by allocating the MATLAB Array at once.
			 */
            for(;;)
            {
				/*
				 * Advance to teh next row
				 */
                int step_res = sqlite3_step(st);

				/*
				 * no row left? break out of the loop
				 */
                if (step_res != SQLITE_ROW)
                    break;

				/*
				 * get new memory for the result
				 */
                Values* RecordValues = new Values(ncol);
                
                Value *v = RecordValues->m_Values;
                for (int j = 0; j < ncol; j++, v++)
                {
                     int fieldtype = sqlite3_column_type(st,j);

                     v->m_Type = fieldtype;
                        
                     switch (fieldtype)
                     {
                         case SQLITE_NULL:      v->m_NumericValue = g_NaN;                                   break;
                         case SQLITE_INTEGER:	v->m_NumericValue = (double) sqlite3_column_int(st, j);      break;
                         case SQLITE_FLOAT:     v->m_NumericValue = (double) sqlite3_column_double(st, j);	 break;
                         case SQLITE_TEXT:      v->m_StringValue  = strnewdup((const char*) sqlite3_column_text(st, j));   break;
                                
                         default:	
							mxFree(command);
							mexErrMsgTxt(MSG_UNKNWNDBTYPE);
                     }
                }
				/*
				 * and add this row to the list of all result rows
				 */
                if (! lastrow)
                {
                    allrows = lastrow = RecordValues;
                }
                else
                {
                    lastrow->m_NextValues = RecordValues;
                    lastrow = lastrow->m_NextValues;
                }
				/*
				 * we have one more...
				 */
                rowcount ++;
            }
            
			/*
			 * end the sql engine
			 */
            sqlite3_finalize(st);

			/*
			 * got nothing? return an empty result to MATLAB
			 */
            if (rowcount == 0 || ! allrows)
            {
                if (!( plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL) ))
				{
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
				}
            }
            else
            {
				/*
				 * Allocate an array of MATLAB structs to return as result
				 */
                int ndims[2];
                
                ndims[0] = rowcount;
                ndims[1] = 1;
                
                if (( plhs[0] = mxCreateStructArray (2, ndims, ncol, (const char**)fieldnames)) == 0)
                {
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
                }
                
				/*
				 * transfer the result rows from the temporary list into the result array
				 */
                lastrow = allrows;
                i = 0;
                while(lastrow)
                {
                    Value* recordvalue = lastrow->m_Values;
                    
                    for (int j = 0; j < ncol; j++, recordvalue++)
                    {
                        if (recordvalue -> m_Type == SQLITE_TEXT)
                        {
                            mxArray* c = mxCreateString(recordvalue->m_StringValue);
                            mxSetFieldByNumber(plhs[0], i, j, c);
                        }
                        else if (recordvalue -> m_Type == SQLITE_NULL && !NULLasNaN)
                        {
                            mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                        else
                        {
                            mxArray* out_double = mxCreateDoubleScalar(recordvalue->m_NumericValue);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                    }
                    allrows = lastrow;
                    lastrow = lastrow->m_NextValues;
                    delete allrows;
                    i++;
                }
            }
            for(int i=0; i<ncol; i++)
                delete [] fieldnames[i];
            delete [] fieldnames;
        }
        else
        {
			/*
			 * no result, cleanup the sqlite engine
			 */
            int res = sqlite3_step(st);
            sqlite3_finalize(st);

            if (res != SQLITE_DONE)
            {
				mxFree(command);
                mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
            }            
        }
    }
	mxFree(command);
}
Beispiel #14
0
DLL_FUNCTION(int32_t) BU_SQLite_Complete(const char* sql) {
#pragma comment(linker, "/EXPORT:BU_SQLite_Complete=_BU_SQLite_Complete@4")
	return sqlite3_complete(sql);
}
Beispiel #15
0
int sqlite3_complete_idr(const char *sql){
	
	int rc = sqlite3_complete(sql);
	return rc;
}
Beispiel #16
0
__declspec(dllexport) int WINAPI sqlite3_complete_interop(const char *sql)
{
  return sqlite3_complete(sql);
}
int main(int argc, char *argv[]) {
    sqlite3         *db = NULL;
    sqlite3_stmt    *stmt = NULL;
    int             res = 0;
    int             flags = SQLITE_OPEN_READONLY;
    const char      *colnms[4] = {NULL};     // Nomi delle colonne
    const char      *tail = NULL;
    const char            *sql_str = 
        "SELECT * FROM addressbook ORDER by id;"
        "SELECT * FROM addressbook ORDER by fullname;"
        "SELECT * FROM addressbook ORDER by alias;"
        "SELECT * FROM addressbook ORDER by email;";

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <database name>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // Inizializzazione della libreria
    if (sqlite3_initialize() != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to initialize the library.\n");
        exit(EXIT_FAILURE);
    }

    /* Creazione della connessione al database */
    res = sqlite3_open_v2(argv[1], &db, flags, NULL);

    if (res != SQLITE_OK) {
        fprintf(stderr, "Err. can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        exit(EXIT_FAILURE);
    }

    /* Si utilizza la funzione sqlite3_complete() per la verifica della query,
    si basa essenzialmente sul riconoscimento del punto e virgola - semicolon -
    finale */
    while(sqlite3_complete(sql_str)) {
        if (sqlite3_prepare_v2(db, sql_str,-1, &stmt, &tail) != SQLITE_OK) {
            fprintf(stderr, "Err. Unable to create Prepared Statement.\n");
            exit(EXIT_FAILURE);
        }

        // Stampa il nome di ciascuna colonna.
        for (int i=0; i<sqlite3_column_count(stmt); i++)
            colnms[i] = sqlite3_column_name(stmt, i);
    
            printf("%2s %10s %8s %14s\n", \
                    colnms[0], colnms[1], colnms[2], colnms[3]);

        // Estrazione dei dati riga per riga
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            printf("%2d %10s %5s %20s (byte: %3d)\n",                \
                    sqlite3_column_int(stmt, 0),                    \
                    (const char*)sqlite3_column_text(stmt, 1),      \
                    (const char*)sqlite3_column_text(stmt, 2),      \
                    (const char*)sqlite3_column_text(stmt, 3),      \
                    sqlite3_column_bytes(stmt, 3));
        }
        puts("\n");
        
        // L'istruzione successiva da eseguire e' conservata in 'tail'
        sql_str = tail;
    }


    // Rilascio delle risorse relative alla Prepared Statement
    if (sqlite3_finalize(stmt) != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to finalize.\n");
        exit(EXIT_FAILURE);
    }

    // Close database connection
    if (sqlite3_close_v2(db) != SQLITE_OK) {
        fprintf(stderr, "Err. Unable to close connection.\n");
        exit(EXIT_FAILURE);
    }

    // Rilascio delle risorse di inizializzazione
    sqlite3_shutdown();

    return(EXIT_SUCCESS);
}
	int Database::IsSQLComplete( LPCTSTR strSQL )
	{
		return sqlite3_complete( UTF8MBSTR(strSQL) );
	}
Beispiel #19
0
/*
** Read input from *in and process it.  If *in==0 then input
** is interactive - the user is typing it it.  Otherwise, input
** is coming from a file or device.  A prompt is issued and history
** is saved only if input is interactive.  An interrupt signal will
** cause this routine to exit immediately, unless input is interactive.
**
** Return the number of errors.
*/
static int process_input(struct callback_data *p, FILE *in){
	char *zLine = 0;
	char *zSql = 0;
	int nSql = 0;
	int nSqlPrior = 0;
	char *zErrMsg;
	int rc;
	int errCnt = 0;
	int lineno = 0;
	int startline = 0;

	while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
		//fflush(p->out);
		free(zLine);
		zLine = one_input_line(in);
		if( zLine==0 ){
			break;  /* We have reached EOF */
		}
		if( seenInterrupt ){
			if( in!=0 ) break;
			seenInterrupt = 0;
		}
		lineno++;
		if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
		if( zLine && zLine[0]=='.' && nSql==0 ){
			continue;
		}
		if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
			memcpy(zLine,";",2);
		}
		nSqlPrior = nSql;
		if( zSql==0 ){
			int i;
			for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){}
			if( zLine[i]!=0 ){
				nSql = strlen30(zLine);
				zSql = (char*)malloc( nSql+3 );
				if( zSql==0 ){
					fprintf(stderr, "Error: out of memory\n");
					exit(1);
				}
				memcpy(zSql, zLine, nSql+1);
				startline = lineno;
			}
		}else{
			int len = strlen30(zLine);
			zSql = (char*)realloc( zSql, nSql + len + 4 );
			if( zSql==0 ){
				fprintf(stderr,"Error: out of memory\n");
				exit(1);
			}
			zSql[nSql++] = '\n';
			memcpy(&zSql[nSql], zLine, len+1);
			nSql += len;
		}
		if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
			&& sqlite3_complete(zSql) ){
				p->cnt = 0;
				//
				rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);

				if( rc || zErrMsg ){
					char zPrefix[100];
					if( in!=0 || !stdin_is_interactive ){
						sqlite3_snprintf(sizeof(zPrefix), zPrefix, 
							"Error: near line %d:", startline);
					}else{
						sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
					}
					if( zErrMsg!=0 ){
						fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
						sqlite3_free(zErrMsg);
						zErrMsg = 0;
					}else{
						fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
					}
					errCnt++;
				}
				free(zSql);
				zSql = 0;
				nSql = 0;
		}
	}
	if( zSql ){
		if( !_all_whitespace(zSql) ){
			fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
		}
		free(zSql);
	}
	free(zLine);
	return errCnt;
}