3 ms·
They mention transactions so I would assume they are using InnoDB in which case you have to have a primary key, if you don't define one InnoDB will either use t
by mbell 14y ago
They mention transactions so I would assume they are using InnoDB in which case you have to have a primary key, if you don't define one InnoDB will either use the first unique not null column it finds or failing that, create one using the internal 6 byte rowID. They could have used a composite primary key on (project_id, backer_id) but that can create other problems such as blowing up the size of your secondary indexes (primary index is included in all secondary indexes in innoDB). So I doubt they were too worried about the storage space compared to other options and probably already had a unique ID column for every row.
If I had to guess, they wanted this column so they could use it to get the number of the backers on any project very quickly. InnoDB's COUNT() performance historically is pretty terrible, especially with large tables, I'm guessing they were trying to avoid that, in addition to being able to provide the project owners with a 'backer ID' that is more human digestible.
That said, the count could be handled with a trigger and there is a trick using LAST_INSERT_ID(expr) for generating the sequence:
Create a column somewhere to hold the sequence value, for example in a backer_sequence_id column in the project table then:
UPDATE project SET backer_sequence_id=LAST_INSERT_ID(backer_sequence_id+1) WHERE id = ?;
SELECT LAST_INSERT_ID(); <----returns the sequence ID that was created
It does lock the row in the project table if this is inside a larger transaction but that shouldn't be too hard to avoid. LAST_INSERT_ID is handled per client, so its multi-connection safe. The above works inside a trigger also so the client code wouldn't need to think about it.