pgLab/pglablib/catalog/PgAttribute.cpp

74 lines
2.1 KiB
C++
Raw Permalink Normal View History

#include "PgAttribute.h"
#include "QStringBuilder"
#include "SqlFormattingUtils.h"
#include "PgClass.h"
#include "PgDatabaseCatalog.h"
#include "PgTypeContainer.h"
#include "PgCollation.h"
#include "PgCollationContainer.h"
#include "Pgsql_oids.h"
QString PgAttribute::columnDefinition(const PgDatabaseCatalog &cat) const
{
// create: column_name data_type [ COLLATE collation ] [ column_constraint [ ... ]
// alter: column_name data_type [ COLLATE collation ] [ column_constraint [ ... ]
// constraints NULL/NOT NULL, DEFAULT, GENERATED other constraints will be ignored here a
QString type_str;
if (isSerial()) {
if (typid == Pgsql::int4_oid)
type_str = "SERIAL";
else if (typid == Pgsql::int8_oid)
type_str = "BIGSERIAL";
}
else {
type_str = getTypeDisplayString(cat, typid, typmod);
}
QString sql = quoteIdent(name) % " " % type_str;
if (collation != InvalidOid) {
auto&& col = cat.collations()->getByKey(collation);
QString oname = col->objectName();
if (oname != "default")
sql += " COLLATE " % quoteIdent(oname);
}
if (notnull)
sql += " NOT NULL";
if (hasdef && !isSerial())
sql += " DEFAULT " % defaultValue;
if (identity != '\0') {
sql += " GENERATED ";
if (identity == 'a') sql += "ALWAYS";
else if (identity == 'd') sql += "BY DEFAULT";
sql += " AS IDENTITY";
}
// TODO sequence options might be missing
return sql;
}
QString PgAttribute::alterTableAddColumn(const PgDatabaseCatalog &cat, const PgClass &table) const
{
QString sql = "ALTER TABLE " % table.fullyQualifiedQuotedObjectName()
% " ADD COLUMN " % columnDefinition(cat) % ";";
return sql;
}
QString PgAttribute::alterTableDropColumn(const PgDatabaseCatalog &cat, const PgClass &table) const
{
QString sql = "ALTER TABLE " % table.fullyQualifiedQuotedObjectName()
% " DROP COLUMN " % quoteIdent(name) % ";";
return sql;
}
QString PgAttribute::commentStatement(const PgDatabaseCatalog &cat, const PgClass &table) const
{
if (description.isEmpty())
return {};
return "COMMENT ON COLUMN " % table.fullyQualifiedQuotedObjectName() % "."
% quoteIdent(name) % " IS " % escapeLiteral(description) % ";";
}