//
// Copyright (c) 2009-2010 Ronald Kluth
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

/**
 * @file Example_DatabaseAccessor.cpp
 * @author Ronald Kluth
 * @date 2009/11/29
 * @brief Example showing the usage of DatabaseAccessor with SQLite
 * @since 0.1
 */

/**
 * @example Example_DatabaseAccessor.cpp
 *
 * This example demonstrates how to use class @c DatabaseAccessor for writing
 * data to an SQLite database. The record type is a pair of ID and string.
 * The function @c insertRow defines how to write a single record to the
 * database by using the accessor's method @c insertIntoTable.
 *
 * In the main program we first use the method @c tableExists to check if 
 * the table is already contained in the database. If not, it is created 
 * via the method @c createTable. We then retrieve the current maximum ID 
 * value in order to create valid primary keys for new records. After that,
 * two records are added to a buffer and finally, the buffer is written to 
 * the database by calling @c storeData and providing the buffer and the
 * function @c insertRow, which is called for every buffered record.
 */

#define CPPLOG_USE_SQLITE

#include <CppLog.h>
#include <string>
#include <utility>
#include <vector>
using namespace std;

Log::DatabaseAccessor db( "example.db" );

void createTable()
{
	if( ! db.tableExists( "example_table" ) )
	{
		db.createTable( "example_table" )
			.column( "id", "INTEGER" )
			.column( "text", "VARCHAR" )
			.primaryKey( "id" );
	}
}

void insertRow( const pair< int, string >& record )
{
	db.insertIntoTable( "example_table" )
		.columnValue( "id", record.first )
		.columnValue( "text", record.second );
}

int main()
{
	createTable();

	int maxId;
	db.getMaxColumnValue( "example_table", "id", maxId );

	vector< pair< int, string > > buffer;
	buffer.push_back( make_pair( maxId + 1, "first_example_string" ) );
	buffer.push_back( make_pair( maxId + 2, "second_example_string" ) );

	db.storeData( buffer, &insertRow );
}
