// file      : odb/relational/schema.cxx
// author    : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009-2011 Code Synthesis Tools CC
// license   : GNU GPL v3; see accompanying LICENSE file

#include <odb/emitter.hxx>

#include <odb/relational/schema.hxx>
#include <odb/relational/generate.hxx>

using namespace std;

namespace relational
{
  namespace schema
  {
    struct schema_emitter: emitter, context
    {
      virtual void
      pre ()
      {
        first_ = true;
      }

      virtual void
      line (const std::string& l)
      {
        if (first_)
          first_ = false;
        else
          os << endl;

        os << l;
      }

      virtual void
      post ()
      {
        if (!first_) // Ignore empty statements.
          os << ';' << endl
             << endl;
      }

    private:
      bool first_;
    };

    static char const file_header[] =
    "/* This file was generated by ODB, object-relational mapping (ORM)\n"
    " * compiler for C++.\n"
    " */\n\n";

    void
    generate ()
    {
      context ctx;
      ostream& os (ctx.os);

      os << file_header;

      schema_emitter emitter;

      // Drop.
      //
      {
        traversal::unit unit;
        traversal::defines unit_defines;
        traversal::namespace_ ns;
        instance<class_drop> c (emitter);

        unit >> unit_defines >> ns;
        unit_defines >> c;

        traversal::defines ns_defines;

        ns >> ns_defines >> ns;
        ns_defines >> c;
        unit.dispatch (ctx.unit);
      }

      os << endl;

      // Create.
      //
      {
        traversal::unit unit;
        traversal::defines unit_defines;
        traversal::namespace_ ns;
        instance<class_create> c (emitter);

        unit >> unit_defines >> ns;
        unit_defines >> c;

        traversal::defines ns_defines;

        ns >> ns_defines >> ns;
        ns_defines >> c;
        unit.dispatch (ctx.unit);
      }
    }
  }
}
