Home > Software design >  I'm trying to create Two Tables in sql.js but there is an error regarding foreign key constrain
I'm trying to create Two Tables in sql.js but there is an error regarding foreign key constrain

Time:03-28

Sample Code

<script>
config = {
    locateFile: filename => `sql-wasm.wasm`
  }
initSqlJs(config).then(function(SQL)
{
    //Create the database
    const db = new SQL.Database();

    //create first table - Questions (Parent Table)
    let question = "CREATE TABLE Questions(qid INT NOT NULL, qdesc CHAR, PRIMARY KEY(qid));\
        INSERT INTO Questions VALUES(1, 'set1');\
        INSERT INTO Questions VALUES(2, 'set2');\
        INSERT INTO Questions VALUES(3, 'set3');\
        INSERT INTO Questions VALUES(4, 'set4');\
        INSERT INTO Questions VALUES(5, 'set5');";
    db.run(question);
    const result = db.exec("SELECT * FROM Questions");
    console.log(result);
    
    //create second Table - Qimages (Child Table)
    let qimage = "CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,FOREIGN KEY (qid) REFERENCES Questions(qid));\
        INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_woods.jpg',1);\
        INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_5terre.jpg',1);\
        INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_mountains.jpg',2);";
    db.run(qimage);
    const res = db.exec("SELECT * FROM Qimages");
    console.log(res);
</script>

Below is the Error I'm Getting

uncaught (in promise) Error: unknown column "qid" in foreign key definition

CodePudding user response:

As the message says, there is no qid column in the Qimages table. I suspect that you want:-

CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,qid INTEGER REFERENCES Questions(qid));

Thus the value of the qid column (now defined), that uses the column level version of the Foreign Key constraint declaration, must have a corresponding value in the qid column of the Question table.

Alternately you could use:-

CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,qid INTEGER, FOREIGN KEY (qid) REFERENCES Questions(qid));
  • Related