daichirata / hammer

🛠 hammer is a command-line tool to schema management for Google Cloud Spanner.
MIT License
83 stars 24 forks source link

Table Creation Order matters for Foreign Keys #26

Open dlazares opened 3 years ago

dlazares commented 3 years ago

When I applied diff on my dev db, the generated sql diff did not execute correctly to my prod db. When I applied it I got Error: rpc error: code = NotFound desc = Table not found: Images.

Example failure:

CREATE TABLE Posts (
  PostId STRING(2048) NOT NULL,
  Text STRING(MAX),
  FOREIGN KEY (ImageId) REFERENCES Images (ImageId),
) PRIMARY KEY(PostId);

CREATE TABLE Images (
  ImageId STRING(2048) NOT NULL,
  URL STRING(2048),
) PRIMARY KEY(ImageId);

Order matters here due to foreign key so should be:


CREATE TABLE Images (
  ImageId STRING(2048) NOT NULL,
  URL STRING(16),
) PRIMARY KEY(ImageId);

CREATE TABLE Posts (
  PostId STRING(2048) NOT NULL,
  PairSymbol STRING(16),
  FOREIGN KEY (ImageId) REFERENCES Images (ImageId),
) PRIMARY KEY(PostId);

I verified by switching manually that this solved the problem. I think we just need some clever ordering in the library to handle this case.