SeaQL / sea-query

🔱 A dynamic SQL query builder for MySQL, Postgres and SQLite
https://www.sea-ql.org
Other
1.12k stars 182 forks source link

Support for Postgres comments when creating tables and columns #761

Open reivilibre opened 5 months ago

reivilibre commented 5 months ago

Motivation

When I create tables in Postgres I typically add comments to the table and the columns in order to make it easier to identify what they are for.

Currently in Sea-Query it seems this is not supported in Postgres (but might be in MySQL) and I'd have to escape to raw SQL to do this.

Proposed Solutions

I think the most natural solution would be if the create_table method would in some way emit the statements required in Postgres to set the comments.

e.g:

        manager
            .create_table(
                Table::create()
                    .comment("Tracks classes of items. In the normal case you should expect to be able to search the items in the class parametrically.")
                    .table(ItemClass::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ItemClass::ClassPath)
                            .text()
                            .not_null()
                            .primary_key()
                            .comment("slash-separated path that represents the item class"),
                    )
                    .col(
                        ColumnDef::new(ItemClass::Description)
                            .text()
                            .not_null()
                            .default("")
                            .comment("markdown comment for the item class"),
                    )
                    .to_owned(),
            )
            .await?;

would emit

COMMENT ON TABLE item_class IS 'Tracks classes of items. In the normal case you should expect to be able to search the items in the class parametrically.';
COMMENT ON COLUMN item_class.class_path IS 'slash-separated path that represents the item class';
COMMENT ON COLUMN item_class.description IS 'markdown comment for the item class';

after the CREATE TABLE statement.

Especially since the Postgres syntax for this is awkward, it would make things a lot easier as well :-)

Additional Information

I think this syntax has been available in Postgres for more or less forever, so there should be no harm in supporting it.

reivilibre commented 5 months ago

(as an aside, the equivalent in SQLite would be to emit SQL comments in the CREATE TABLE statement, since SQLite tracks the whole SQL text of the table creation. But I'm not sure how conventional it is for people to use that.)