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

int callback(void* option, int count, char** values, char** names) {
  for ( int i = 0; i < count; ++i ) {
    *static_cast<std::ostream*>(option) << names[i] << " = [" << values[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;
    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)", // 商品id, 商品名, 単価
    "INSERT INTO item VALUES ( 2 , 'りんご', 234)", 
    "INSERT INTO item VALUES ( 3 , 'みかん', 345)", 
    "INSERT INTO item VALUES ( 4 , 'なし',   456)", 
    "INSERT INTO item VALUES ( 5 , 'もも',   567)", 

    "CREATE TABLE sales (id INTEGER PRIMARY KEY, quantity NOT NULL )", 
    "INSERT INTO sales VALUES ( 1, 6 )", // 商品1が6個売れた
    "INSERT INTO sales VALUES ( 3, 4 )", // 商品3が4個売れた
    "INSERT INTO sales VALUES ( 5, 2 )", // 商品5が2個売れた

    /* 売り上げの小さい順に一覧を作れ */
    "SELECT name, price, quantity, price*quantity FROM item, sales "
      "WHERE item.id = sales.id ORDER BY price*quantity",
    0
  };
  for ( int i = 0; statements[i]; ++i ) {
    char* errmsg = 0;
    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;
    }
  }
  sqlite3_close(db);
  
  return 0;
}
