| 116 | } |
| 117 | |
| 118 | func getPostgresqlTableFields(db *gorm.DB, tableName string) (PGFields, error) { |
| 119 | query := fmt.Sprintf(`SELECT |
| 120 | a.attname AS name, |
| 121 | t.typname AS type, |
| 122 | a.attlen AS length, |
| 123 | a.atttypmod AS lengthvar, |
| 124 | a.attnotnull AS notnull, |
| 125 | b.description AS comment, |
| 126 | CASE |
| 127 | WHEN pk.constraint_type = 'PRIMARY KEY' THEN true |
| 128 | ELSE false |
| 129 | END AS is_primary_key |
| 130 | FROM pg_class c |
| 131 | JOIN pg_attribute a ON a.attrelid = c.oid |
| 132 | LEFT JOIN pg_description b ON a.attrelid = b.objoid AND a.attnum = b.objsubid |
| 133 | JOIN pg_type t ON a.atttypid = t.oid |
| 134 | LEFT JOIN ( |
| 135 | SELECT |
| 136 | kcu.column_name, |
| 137 | con.constraint_type |
| 138 | FROM information_schema.table_constraints con |
| 139 | JOIN information_schema.key_column_usage kcu |
| 140 | ON con.constraint_name = kcu.constraint_name |
| 141 | WHERE con.constraint_type = 'PRIMARY KEY' |
| 142 | AND con.table_name = '%s' |
| 143 | ) AS pk ON a.attname = pk.column_name |
| 144 | WHERE c.relname = '%s' |
| 145 | AND a.attnum > 0 |
| 146 | ORDER BY a.attnum;`, tableName, tableName) |
| 147 | |
| 148 | var fields PGFields |
| 149 | result := db.Raw(query).Scan(&fields) |
| 150 | if result.Error != nil { |
| 151 | return nil, fmt.Errorf("failed to get table fields: %v", result.Error) |
| 152 | } |
| 153 | |
| 154 | return fields, nil |
| 155 | } |
| 156 | |
| 157 | func getType(field *PGField) string { |
| 158 | switch field.Type { |