Skip to content

Foreign key labels for tables with unique indexes on multiple columns #2413

@simonw

Description

@simonw

While hacking around with https://github.com/datasette/datasette-acl I noticed this table:

CleanShot 2024-08-30 at 17 01 07@2x

Those resource_id integers link to this table:

CleanShot 2024-08-30 at 17 01 17@2x

CREATE TABLE acl_resources (
    id integer primary key autoincrement,
    database text not null,
    resource text,
    unique(database, resource)
);

In this particular case, showing the database and then the resource as the foreign key label would make sense - both of those are strings and they are unique together, which makes them a valid label.

I poked around with Claude and came up with this query:

select
  m.name as table_name,
  json_group_array(ii.name) as unique_column_names
from
  sqlite_master as m,
  pragma_index_list(m.name) AS il,
  pragma_index_info(il.name) AS ii
where
  m.type = 'table'
  and il.origin = 'u'
group by
  il.name;

Which returns this for that schema:

CleanShot 2024-08-30 at 17 03 14@2x

This could be a useful alternative way to determine default foreign key labels.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions