#include <iostream>
#include <sqlite3.h>

int callback(void* option, int columnCount, char** columnValues, char** columnNames) {
  for ( int i = 0; i < columnCount; ++i ) {
    *static_cast<std::ostream*>(option) << columnNames[i] << " = [" << columnValues[i] << "] ";
  }
  std::cout << std::endl;
  return 0;
}

int main() {
  sqlite3* db;
  if ( sqlite3_open(":memory:", &db) ) {
    std::cerr << "Error " << __FILE__ << ' ' << __LINE__ 
              << ": Can't open database " << sqlite3_errmsg(db) 
              << std::endl;
    sqlite3_close(db);
    return 1;
  }

  const char* statements[] = {
    "CREATE TABLE item (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)", 
    "INSERT INTO item VALUES ( 1 , 'ばなな', 123)", 
    "INSERT INTO item VALUES ( 2 , 'りんご', 234)", 
    "INSERT INTO item VALUES ( 3 , 'みかん', 345)", 
    "INSERT INTO item VALUES ( 4 , 'なし',   456)", 
    "INSERT INTO item VALUES ( 5 , 'もも',   567)", 
    "INSERT INTO item VALUES ( 6 , 'びわ',   789)", 
    "INSERT INTO item VALUES ( 7 , 'くり',   891)",

    "CREATE TABLE sales (id INTEGER PRIMARY KEY, quantity NOT NULL )", 
    "INSERT INTO sales VALUES ( 1, 6 )",
    "INSERT INTO sales VALUES ( 3, 4 )",
    "INSERT INTO sales VALUES ( 5, 2 )",

    "SELECT item.id, name, price, quantity, price*quantity FROM item, sales WHERE item.id = sales.id ORDER BY price*quantity",

    "CREATE VIEW named_sales AS SELECT name, quantity FROM sales, item WHERE item.id = sales.id",
    "SELECT * FROM named_sales",
    0
  };
  for ( int i = 0; statements[i]; ++i ) {
    char* errmsg;
    std::cout << statements[i] << std::endl;
    if ( sqlite3_exec(db, statements[i], callback, &std::cout, &errmsg) != SQLITE_OK ) {
      std::cerr << "Error " << __FILE__ << ' ' << __LINE__ 
                << ": " << errmsg << std::endl;
      sqlite3_free(errmsg);
      sqlite3_close(db);
      return 1;
    }
  }
  
  return 0;
}
