/*
 Copyright 2019 Florian Dold

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 or implied. See the License for the specific language governing
 permissions and limitations under the License.
 */

import test from "ava";
import { createNodeHelperSqlite3Impl } from "./node-helper-sqlite3-impl.js";

// Serial test as it touches the FS.
test.serial("sqlite3 helper", async (t) => {
  const filename = ":memory:";
  const impl = await createNodeHelperSqlite3Impl();

  const db = await impl.open(filename);

  await db.exec(`CREATE TABLE person(firstname, lastname, age);
    CREATE TABLE book(title, author, published);
    CREATE TABLE publisher(name, address);`);

  const stmt1 = await db.prepare(
    "INSERT INTO book (title, author, published) VALUES ($title, $author, $published)",
  );

  const stmt2 = await db.prepare(
    "SELECT author, title, NULL as foobar, 42, published FROM book WHERE published=$published ORDER BY author",
  );

  const stmtBegin = await db.prepare("BEGIN");

  const stmtCommit = await db.prepare("COMMIT");

  await stmtBegin.run();

  const r1 = await stmt1.run({
    title: "foo",
    author: "bar",
    published: 1995,
  });

  const r2 = await stmt1.run({
    title: "foo2",
    author: "bar2",
    published: 1998,
  });

  await stmt1.run({
    title: "foo4",
    author: "bar4",
    published: 1995,
  });

  t.deepEqual(r1.lastInsertRowid, 1n);
  t.deepEqual(r2.lastInsertRowid, 2n);

  const r3 = await stmtCommit.run();

  const getRes1 = await stmt2.getAll({
    published: 1995,
  });

  t.deepEqual(getRes1.length, 2);
  t.deepEqual(getRes1[0].title, "foo");
  t.deepEqual(getRes1[1].title, "foo4");

  t.pass();
});
