getTableColumns gets the columns of a table.
(txn *sql.Tx)
| 338 | |
| 339 | // getTableColumns gets the columns of a table. |
| 340 | func getTableColumns(txn *sql.Tx) (map[db.TableKey][]*storepb.ColumnMetadata, error) { |
| 341 | columnsMap := make(map[db.TableKey][]*storepb.ColumnMetadata) |
| 342 | |
| 343 | query := ` |
| 344 | SELECT |
| 345 | cols.table_schema, |
| 346 | cols.table_name, |
| 347 | cols.column_name, |
| 348 | cols.data_type, |
| 349 | cols.character_maximum_length, |
| 350 | cols.ordinal_position, |
| 351 | cols.column_default, |
| 352 | cols.is_nullable, |
| 353 | cols.collation_name, |
| 354 | cols.udt_schema, |
| 355 | cols.udt_name, |
| 356 | pg_catalog.col_description(pc.oid, cols.ordinal_position::int) as column_comment |
| 357 | FROM |
| 358 | INFORMATION_SCHEMA.COLUMNS AS cols |
| 359 | JOIN pg_namespace AS pns ON pns.nspname = cols.table_schema |
| 360 | LEFT JOIN pg_class AS pc ON pc.relname = cols.table_name AND pns.oid = pc.relnamespace |
| 361 | WHERE cols.table_schema NOT IN ('pg_catalog', 'information_schema') |
| 362 | ORDER BY cols.table_schema, cols.table_name, cols.ordinal_position;` |
| 363 | rows, err := txn.Query(query) |
| 364 | if err != nil { |
| 365 | return nil, err |
| 366 | } |
| 367 | defer rows.Close() |
| 368 | for rows.Next() { |
| 369 | column := &storepb.ColumnMetadata{} |
| 370 | var schemaName, tableName, nullable string |
| 371 | var characterMaxLength, defaultStr, collation, udtSchema, udtName, comment sql.NullString |
| 372 | if err := rows.Scan(&schemaName, &tableName, &column.Name, &column.Type, &characterMaxLength, &column.Position, &defaultStr, &nullable, &collation, &udtSchema, &udtName, &comment); err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | if defaultStr.Valid { |
| 376 | // Store in Default field (migration from DefaultExpression to Default) |
| 377 | column.Default = defaultStr.String |
| 378 | } |
| 379 | isNullBool, err := util.ConvertYesNo(nullable) |
| 380 | if err != nil { |
| 381 | return nil, err |
| 382 | } |
| 383 | column.Nullable = isNullBool |
| 384 | switch column.Type { |
| 385 | case "USER-DEFINED": |
| 386 | column.Type = fmt.Sprintf("%s.%s", udtSchema.String, udtName.String) |
| 387 | case "ARRAY": |
| 388 | column.Type = udtName.String |
| 389 | case "character", "character varying", "bit", "bit varying": |
| 390 | if characterMaxLength.Valid { |
| 391 | // For character varying(n), the character maximum length is n. |
| 392 | // For character without length specifier, key character_maximum_length is null, |
| 393 | // we don't need to append the length. |
| 394 | // https://www.postgresql.org/docs/current/infoschema-columns.html. |
| 395 | column.Type = fmt.Sprintf("%s(%s)", column.Type, characterMaxLength.String) |
| 396 | } |
| 397 | default: |
no test coverage detected