#include "PgSequence.h"
#include "PgDatabaseCatalog.h"
#include "PgTypeContainer.h"
#include <QStringBuilder>

QString PgSequence::createSql() const
{
	QString sql;
	sql = "CREATE";
	//	[ TEMPORARY | TEMP ]
	sql += " SEQUENCE " % fullyQualifiedQuotedObjectName();
	if (catalog().serverVersion() >= 100000)
		sql +=  "\n   AS " % catalog().types()->getByKey(typid)->objectName();
	sql += QString("\n  INCREMENT %1\n  MINVALUE %2"
		" MAXVALUE %3\n  START %4 CACHE %5")
			.arg(increment).arg(min).arg(max).arg(start).arg(cache);
	if (cycled)
		sql += "\n  CYCLE";

	// [ OWNED BY { table_name.column_name | NONE } ]
	sql += ";";
    return sql;
}

int64_t PgSequence::defaultMin() const
{
    if (direction() == Ascending)
        return 1;

    if (typid == Pgsql::int8_oid)
        return std::numeric_limits<int64_t>::min();
    return std::numeric_limits<int32_t>::min();
}

int64_t PgSequence::defaultMax() const
{
    if (direction() == Descending)
        return -1;

    if (typid == Pgsql::int8_oid)
        return std::numeric_limits<int64_t>::max();
    return std::numeric_limits<int32_t>::max();
}

int64_t PgSequence::defaultStart() const
{
    if (direction() == Descending)
        return max;
    return min;
}

int64_t PgSequence::defaultIncrement() const
{
    // Direction should not be considered here
    // a negative increment is what makes it a descending sequence
    return 1;
}

int64_t PgSequence::defaultCache() const
{
    return 1;
}

QString PgSequence::nonDefaultOptionsString() const
{
    QString options;
    if (increment != defaultIncrement())
        options += QString("INCREMENT %1 ").arg(increment);
    if (min != defaultMin())
        options += QString("MINVALUE %1 ").arg(min);
    if (max != defaultMax())
        options += QString("MAXVALUE %1 ").arg(max);
    if (start != defaultStart())
        options += QString("START %1 ").arg(start);
    if (cache != defaultCache())
        options += QString("CACHE %1 ").arg(cache);
    return options.trimmed();
}
