** Execute a statement or set of statements. Print ** any result rows/columns depending on the current mode ** set via the supplied callback. ** ** This is very similar to SQLite's built-in sqlite3_exec() ** function except it takes a slightly different callback ** and callback data argument. */
| 1355 | ** and callback data argument. |
| 1356 | */ |
| 1357 | static int shell_exec( |
| 1358 | sqlite3 *db, /* An open database */ |
| 1359 | const char *zSql, /* SQL to be evaluated */ |
| 1360 | int (*xCallback)(void*,int,char**,char**,int*), /* Callback function (not the same as sqlite3_exec) */ |
| 1361 | struct callback_data *pArg, /* Pointer to struct callback_data */ |
| 1362 | char **pzErrMsg /* Error msg written here */ |
| 1363 | ) |
| 1364 | { |
| 1365 | sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ |
| 1366 | int rc = SQLITE_OK; /* Return Code */ |
| 1367 | const char *zLeftover; /* Tail of unprocessed SQL */ |
| 1368 | |
| 1369 | if( pzErrMsg ){ |
| 1370 | *pzErrMsg = NULL; |
| 1371 | } |
| 1372 | |
| 1373 | while( zSql[0] && (SQLITE_OK == rc) ){ |
| 1374 | rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); |
| 1375 | if( SQLITE_OK != rc ){ |
| 1376 | if( pzErrMsg ){ |
| 1377 | *pzErrMsg = save_err_msg(db); |
| 1378 | } |
| 1379 | }else{ |
| 1380 | if( !pStmt ){ |
| 1381 | /* this happens for a comment or white-space */ |
| 1382 | zSql = zLeftover; |
| 1383 | while( isspace(zSql[0]) ) zSql++; |
| 1384 | continue; |
| 1385 | } |
| 1386 | |
| 1387 | /* save off the prepared statment handle and reset row count */ |
| 1388 | if( pArg ){ |
| 1389 | pArg->pStmt = pStmt; |
| 1390 | pArg->cnt = 0; |
| 1391 | } |
| 1392 | |
| 1393 | /* perform the first step. this will tell us if we |
| 1394 | ** have a result set or not and how wide it is. |
| 1395 | */ |
| 1396 | rc = sqlite3_step(pStmt); |
| 1397 | /* if we have a result set... */ |
| 1398 | if( SQLITE_ROW == rc ){ |
| 1399 | /* if we have a callback... */ |
| 1400 | if( xCallback ){ |
| 1401 | /* allocate space for col name ptr, value ptr, and type */ |
| 1402 | int nCol = sqlite3_column_count(pStmt); |
| 1403 | void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1); |
| 1404 | if( !pData ){ |
| 1405 | rc = SQLITE_NOMEM; |
| 1406 | }else{ |
| 1407 | char **azCols = (char **)pData; /* Names of result columns */ |
| 1408 | char **azVals = &azCols[nCol]; /* Results */ |
| 1409 | int *aiTypes = (int *)&azVals[nCol]; /* Result types */ |
| 1410 | int i; |
| 1411 | assert(sizeof(int) <= sizeof(char *)); |
| 1412 | /* save off ptrs to column names */ |
| 1413 | for(i=0; i<nCol; i++){ |
| 1414 | azCols[i] = (char *)sqlite3_column_name(pStmt, i); |
no test coverage detected