#Primary key composed of multiple columns

3 messages · Page 1 of 1 (latest)

gusty seal
#

Basically I'm trying to re-create this SQL script:

CREATE TABLE ArticleThemes (
  articleId INTEGER,
  theme TEXT,
  FOREIGN KEY (articleId) REFERENCES Article(id),
  FOREIGN KEY (theme) REFERENCES Theme(theme),
  PRIMARY KEY (articleId, theme)
);

But it's just not possible to declare a primary key composed of several columns. Am I missing something?

tropic copperBOT
#

Hi @gusty seal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the provided knowledge sources, Astro's defineTable function does not currently support composite primary keys. In Astro, you can define a primary key for a column using the primaryKey property, but this is only applicable to a single column.

Here's an example of how you would typically define a primary key in Astro:

const Author = defineTable({ 
  columns: { 
    id: column.number({ primaryKey: true }), 
    name: column.text(), 
  }
});

In the above example, the id column is set as the primary key. However, there's no provided way to set multiple columns as a composite primary key.

For more complex relationships between tables, Astro provides the foreignKeys API, which allows you to relate multiple table columns. But this is not the same as a composite primary key.

Here's an example of how you would use the foreignKeys API:

const Author = defineTable({ 
  columns: { 
    firstName: column.text(), 
    lastName: column.text(), 
  },
});

const Comment = defineTable({ 
  columns: { 
    authorFirstName: column.text(), 
    authorLastName: column.text(), 
    body: column.text(), 
  }, 
  foreignKeys: [ 
    { 
      columns: ["authorFirstName", "authorLastName"], 
      references: () => [Author.columns.firstName, Author.columns.lastName], 
    }, 
  ],
});

In the above example, the Comment table has a foreign key that references the firstName and lastName columns in the Author table.

For more information, you can refer to the Astro documentation (https://docs.astro.build/en/guides/integrations-guide/db#foreignkeys).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: