/*
** sqtables: Sample C application using sqlite database library.
** This outputs a list of the tables and views in an sqlite database to stdout.
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
 */

#include <stdio.h>
#include "sqlite.h"
#include "sqliteInt.h"


/* All uses of sqlite_exec() REQUIRE a callback function.
 * This function outputs the row data to stdout with tab delimiters.
 * <pArg> is an app-supplied argument passed into sqlite_exec().
 * <argc> is the number of columns of data.
 * <argv> is an array of the column data.
 * <azColName> is an array of the column names.
 */
static int callback_output_tabbed(void *pArg, int argc, char **argv, char **azColName)
{
	int i;
	for (i = 0; i < argc; i++)
	{
		puts(argv[i]);
		if (i < argc-1)
			putchar('\t');
	}
	putchar('\n');

	return 0; /* okay */
}


int main(int argc, char **argv)
{
	sqlite *db;
	char *zErrMsg = NULL;
	int rc;
	int mode = 0;
	const char* zSql = "SELECT type AS 'Type', name AS 'Name' FROM SQLITE_MASTER WHERE type='table' OR type='view'; ";

	/* Validate command-line arguments.
	 * argv[0] will be the application name.
	 */
	if (argc != 2 || !argv[1])
	{
		fprintf(stderr, "usage: %s database\n", argv[0]);
		return -1; /* error */
	}

	/* Open the database connection. The mode flag is unused (as of 2.7.3) */
	db = sqlite_open(argv[1], mode, &zErrMsg);
	if (!db)
	{
		fprintf(stderr, "%s: failed to open database '%s'.\n%s", argv[0], argv[1], zErrMsg);
		sqliteFree(zErrMsg);
		return -1; /* error */
	}

	/* Execute the query. The work is done in the callback function. */
	rc = sqlite_exec(db, zSql, callback_output_tabbed, NULL, &zErrMsg);
	if (rc != SQLITE_OK)
	{
		fprintf(stderr, "%s: failed to execute query.\n%s", argv[0], zErrMsg);

		/* The error message must be freed. This only needs to be done if rc != SQLITE_OK. */
		sqliteFree(zErrMsg);
	}

	sqlite_close(db);

	return (rc == SQLITE_OK)? 0: -1;
}
