1

We recently discovered that one of our foreign keys was of type varchar instead of bigInt. It was a huge bottleneck and was consuming something like 75% of our RDS and had been in the codebase for 3 years...

I wondered if there was any kind of command I could run against our schema to check if other columns have the wrong type assigned? Something like:

// pseudo AF but:
select columns.* from our_schema where column.name LIKE '_id' and column.type = 'varChar'
James Stewart
  • 869
  • 12
  • 33
  • 1
    Wouldn't it just be simpler to Eye Ball your schema. – RiggsFolly May 10 '22 at 13:42
  • [INFORMATION_SCHEMA Tables](https://dev.mysql.com/doc/refman/8.0/en/information-schema.html). Query KEY_COLUMN_USAGE Table for columns names used in PRIMARY key constraint. Then query COLUMNS Table and check the datatype. – Akina May 10 '22 at 13:43
  • Be kind, let the programmers create poor performance foreign keys... (I'd rather prefer the opposite, require matching data types.) – jarlh May 10 '22 at 14:07

1 Answers1

0

I was able to achieve this within my Laravel environment like so:

    $schema = collect(DB::connection()->getDoctrineSchemaManager()->listTableNames())->map(function ($item, $key) {
        return [
          'name' => $item,
          'columns' => DB::getSchemaBuilder()->getColumnListing($item)
        ];
      });

    foreach ($schema as $table) {
        foreach ($table['columns'] as $columnName) {
            if (!strpos($columnName, '_id')) {
                continue;
            }
            try {

                $columnType = DB::getSchemaBuilder()->getColumnType($table['name'], $columnName);

                if ($columnType !== 'bigint') {
                    logger(["column name" => $columnName, "table name" => $table['name'], "column type" => $columnType]);
                }
            } catch (\Exception $e) {
                // do nothing
            }
        }
    }
James Stewart
  • 869
  • 12
  • 33
  • You should read [this](https://stackoverflow.com/questions/201621/how-do-i-see-all-foreign-keys-to-a-table-or-column) and its answers so that you can solve this type of problem regardless of the names of the columns. – Jeff Holt May 10 '22 at 14:00