// file      : odb/sqlite/connection.cxx
// license   : GNU GPL v2; see accompanying LICENSE file

#include <odb/sqlite/connection.hxx>

#ifdef _WIN32
#  include <odb/details/win32/windows.hxx> // Sleep()
#else
#  include <unistd.h> // usleep()
#endif

#include <new>    // std::bad_alloc
#include <string>

#include <odb/details/lock.hxx>

#include <odb/sqlite/database.hxx>
#include <odb/sqlite/transaction.hxx>
#include <odb/sqlite/statement.hxx>
#include <odb/sqlite/statement-cache.hxx>
#include <odb/sqlite/prepared-query.hxx>
#include <odb/sqlite/error.hxx>
#include <odb/sqlite/exceptions.hxx> // deadlock

using namespace std;

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
extern "C" void
odb_sqlite_connection_unlock_callback (void**, int);
#endif

namespace odb
{
  using namespace details;

  namespace sqlite
  {
    connection::
    connection (connection_factory& cf,
                int extra_flags,
                statement_translator* st)
        : odb::connection (cf),
          statement_translator_ (st),
#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
          unlock_cond_ (unlock_mutex_),
#endif
          active_objects_ (0)
    {
      database_type& db (database ());

      int f (db.flags () | extra_flags);
      const string& n (db.name ());

      // If we are opening a temporary database, then add the create flag.
      //
      if (n.empty () || n == ":memory:")
        f |= SQLITE_OPEN_CREATE;

      // A connection can only be used by a single thread at a time. So
      // disable locking in SQLite unless explicitly requested.
      //
#if defined(SQLITE_OPEN_NOMUTEX)
      if ((f & SQLITE_OPEN_FULLMUTEX) == 0)
        f |= SQLITE_OPEN_NOMUTEX;
#endif

      // sqlite3_open_v2() was only added in SQLite 3.5.0.
      //
      sqlite3* h (nullptr);
      const string& vfs (db.vfs ());
      int e (
        sqlite3_open_v2 (
          n.c_str (), &h, f, (vfs.empty () ? 0 : vfs.c_str ())));

      handle_.reset (h);

      if (e != SQLITE_OK)
      {
        if (h == nullptr)
          throw bad_alloc ();

        translate_error (e, *this);
      }

      init ();
    }

    connection::
    connection (connection_factory& cf,
                sqlite3* handle,
                statement_translator* st)
        : odb::connection (cf),
          handle_ (handle),
          statement_translator_ (st),
#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
          unlock_cond_ (unlock_mutex_),
#endif
          active_objects_ (0)
    {
      init ();
    }

    void connection::
    init ()
    {
      database_type& db (database ());

      // Configure the connection.
      //
      if (const auto& cc = db.connection_configurator ())
        cc (*this);

      // String lengths include '\0', as per the SQLite manual suggestion.
      //
      begin_statement_.reset (new generic_statement (*this, "BEGIN", 6));
      commit_statement_.reset (new generic_statement (*this, "COMMIT", 7));
      rollback_statement_.reset (new generic_statement (*this, "ROLLBACK", 9));

      // Create statement cache.
      //
      statement_cache_.reset (new statement_cache_type (*this));
    }

    connection::
    connection (attached_connection_factory& cf, statement_translator* st)
        : odb::connection (cf),
          handle_ (0),
          statement_translator_ (st),
#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
          unlock_cond_ (unlock_mutex_),
#endif
          active_objects_ (0)
    {
      // Copy relevant things over from the main connection.
      //
      connection& main (*cf.main_connection_);

      tracer_ = main.tracer_;

      // Create statement cache.
      //
      statement_cache_.reset (new statement_cache_type (*this));
    }

    connection::
    ~connection ()
    {
      // Destroy prepared query statements before freeing the connections.
      //
      recycle ();
      clear_prepared_map ();
    }

    generic_statement& connection::
    begin_statement ()
    {
      return static_cast<generic_statement&> (*begin_statement_);
    }

    generic_statement& connection::
    begin_immediate_statement ()
    {
      if (!begin_immediate_statement_)
        begin_immediate_statement_.reset (
          new generic_statement (*this, "BEGIN IMMEDIATE", 16));

      return static_cast<generic_statement&> (*begin_immediate_statement_);
    }

    generic_statement& connection::
    begin_exclusive_statement ()
    {
      if (!begin_exclusive_statement_)
        begin_exclusive_statement_.reset (
          new generic_statement (*this, "BEGIN EXCLUSIVE", 16));

      return static_cast<generic_statement&> (*begin_exclusive_statement_);
    }

    generic_statement& connection::
    commit_statement ()
    {
      return static_cast<generic_statement&> (*commit_statement_);
    }

    generic_statement& connection::
    rollback_statement ()
    {
      return static_cast<generic_statement&> (*rollback_statement_);
    }

    unique_ptr<odb::transaction_impl> connection::
    begin_ ()
    {
      return unique_ptr<odb::transaction_impl> (
        new transaction_impl (
          static_pointer_cast<connection> (this->shared_from_this ()),
          transaction_impl::deferred));
    }

    unique_ptr<transaction_impl> connection::
    begin_immediate ()
    {
      return unique_ptr<transaction_impl> (
        new transaction_impl (
          static_pointer_cast<connection> (this->shared_from_this ()),
          transaction_impl::immediate));
    }

    unique_ptr<transaction_impl> connection::
    begin_exclusive ()
    {
      return unique_ptr<transaction_impl> (
        new transaction_impl (
          static_pointer_cast<connection> (this->shared_from_this ()),
          transaction_impl::exclusive));
    }

    unsigned long long connection::
    execute (const char* s, std::size_t n)
    {
      generic_statement st (*this, s, n);
      return st.execute ();
    }

    static const unsigned char
    delays[] = { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };

    static const unsigned char
    totals[] = { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };

    int
    connection_busy_handler (void* arg, int scount)
    {
      // The protocol is as follows: Count is the number of times we have
      // already been called for this "locking event". If we return non-0,
      // then SQLite tries to grab the lock and calls us again if
      // unsuccessful. If we return 0, then SQLite immediately returns
      // SQLITE_BUSY to the application.
      //
      using busy_state = connection::busy_state;

      connection& c (*static_cast<connection*> (arg));

      assert (c.busy_state_ == busy_state::active && scount >= 0);

      // This waiting semantics was adopted from SQLite's default busy timeout
      // handler. Presumably it is adequate. Though one wonders if sleeping a
      // fraction of a millisecond the first few times would be better...
      //
      unsigned int count (static_cast<unsigned int> (scount));

      const unsigned int ndelay = sizeof (delays) / sizeof (delays[1]);
      unsigned int delay (count < ndelay ? delays[count] : delays[ndelay - 1]);

      if (c.busy_timeout_ >= 0) // If negative, wait indefinitely.
      {
        unsigned int timeout (static_cast<unsigned int> (c.busy_timeout_));

        unsigned int prior (
          count < ndelay
          ? totals[count]
          : totals[ndelay - 1] + delay * (count - (ndelay - 1)));

        if (prior + delay > timeout)
        {
          if (timeout > prior)
            delay = timeout - prior;
          else
          {
            c.busy_state_ = busy_state::timedout;
            return 0;
          }
        }
      }

      // Note that sqlite3_sleep() has to jump through some VFS hoops to get
      // to the sleep implementation which has an observable performance
      // impact.
      //
#if 0
      sqlite3_sleep (static_cast<int> (delay));
#else
#  ifdef _WIN32
      Sleep (delay);
#  else
      usleep (delay * 1000);
#  endif
#endif
      return 1;
    }

    void connection::
    busy_timeout (int ms)
    {
      if (handle_ == nullptr)
        main_connection ().busy_timeout (ms);
      else
      {
        assert (busy_state_ != busy_state::timedout);
        busy_state_ = busy_state::inactive;

        int e (sqlite3_busy_handler (handle (), &connection_busy_handler, this));

        if (e != SQLITE_OK)
          translate_error (e, *this);

        busy_timeout_ = ms;
        busy_state_ = busy_state::active;
      }
    }

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
    inline void
    connection_unlock_callback (void** args, int n)
    {
      for (int i (0); i < n; ++i)
      {
        connection* c (static_cast<connection*> (args[i]));
        details::lock l (c->unlock_mutex_);
        c->unlocked_ = true;
        c->unlock_cond_.signal ();
      }
    }

    void connection::
    wait ()
    {
      unlocked_ = false;

      // unlock_notify() returns SQLITE_OK or SQLITE_LOCKED (deadlock).
      //
      int e (sqlite3_unlock_notify (handle (),
                                    &odb_sqlite_connection_unlock_callback,
                                    this));
      if (e == SQLITE_LOCKED)
        throw deadlock ();

      details::lock l (unlock_mutex_);

      while (!unlocked_)
        unlock_cond_.wait (l);
    }
#endif // LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY

    void connection::
    clear ()
    {
      invalidate_results ();

      // The current first active_object may remove itself from the list and
      // make the second object (if any) the new first.
      //
      for (active_object** pp (&active_objects_); *pp != 0; )
      {
        active_object* p (*pp);
        p->clear ();

        // Move to the next object if this one decided to stay on the list.
        //
        if (*pp == p)
          pp = &p->next_;
      }
    }

    // connection_factory
    //
    connection_factory::
    ~connection_factory ()
    {
    }

    void connection_factory::
    database (database_type& db)
    {
      odb::connection_factory::db_ = &db;
      db_ = &db;
    }

    void connection_factory::
    attach_database (const connection_ptr& conn,
                     const std::string& name,
                     const std::string& schema)
    {
      conn->execute ("ATTACH DATABASE '" + name + "' AS \"" + schema + '"');
    }

    void connection_factory::
    detach_database (const connection_ptr& conn, const std::string& schema)
    {
      conn->execute ("DETACH DATABASE \"" + schema + '"');
    }
  }
}

#ifdef LIBODB_SQLITE_HAVE_UNLOCK_NOTIFY
extern "C" void
odb_sqlite_connection_unlock_callback (void** args, int n)
{
  odb::sqlite::connection_unlock_callback (args, n);
}
#endif
