Skip to content

Support FK on composite PK #235

@hrothwell

Description

@hrothwell

Is your feature request related to a problem? Please describe.
create_table supports a composite primary key, but trying to define a foreign key on said composite key does not behave correctly

Describe the solution you'd like
specifying two values as foreign_key as a composite key from another table should be doable via the create_table method's table_data dictionary

Describe alternatives you've considered
using query straight up to create a table, assuming that essentially acts as a DB shell

Additional context

example table schemas

func create_word_bank_table():
	var schema := {
		"word" = {
			"data_type" = "text",
			"not_null" = true,
			"primary_key" = true
		},
		"pos" = {
			"data_type" = "text",
			"not_null" = true,
			"primary_key" = true
		}
	}
	var result := db.create_table(word_table, schema)
	if !result:
		printerr("Failed to create table: ", db.error_message)

func create_definitions_table() -> void:
	var schema := {
		"word" = {
			"data_type" = "text",
			"not_null" = true,
			"foreign_key" = "%s.word" % [word_table]
		},
		"pos" = {
			"data_type" = "text",
			"not_null" = true,
			"foreign_key" = "%s.pos" % [word_table]
		},
		"definition" = {
			"data_type" = "text",
			"not_null" = true,
		}
	}
	var result := db.create_table(definition_table, schema)
	if !result:
		printerr("Failed to create table: ", db.error_message)

this generates output like:

Image

This should instead produce output like:

Image

Working solution is to use query to build the table using composite foreign key

func create_word_bank_table():
	var schema := {
		"word" = {
			"data_type" = "text",
			"not_null" = true,
			"primary_key" = true
		},
		"pos" = {
			"data_type" = "text",
			"not_null" = true,
			"primary_key" = true
		}
	}
	var result := db.create_table(word_table, schema)
	if !result:
		printerr("Failed to create table: ", db.error_message)

func create_definitions_table() -> void:
	var result = db.query("CREATE TABLE definitions (word text NOT NULL,pos text NOT NULL, definition text NOT NULL, FOREIGN KEY (word, pos) REFERENCES word_bank(word, pos))")
	
	if !result:
		printerr("Failed to create table: ", db.error_message)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions