简体   繁体   English

续集错误:关系不存在

[英]Sequelize Error: Relation does not exist

I am able to use sequelize.js to do an INSERT INTO command for a table in my development database, but not in my test database.我可以使用sequelize.js对我的开发数据库中的表执行INSERT INTO命令,但不能在我的测试数据库中执行。

Despite researching thoroughly, I have not been able to resolve the issue.尽管进行了彻底的研究,但我还是无法解决这个问题。

A similar question has been posted here, though I have not been able to answer my question with the answers: sequelize with postgres database not working after migration from mysql这里已经发布了一个类似的问题,尽管我无法用答案回答我的问题: 从 mysql 迁移后,使用 postgres 数据库进行续集不起作用

Here is my relevant migration file:这是我的相关迁移文件:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Trees', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      title: {
        type: Sequelize.STRING,
        allowNull: false
      },
      content: {
        type: Sequelize.STRING(10000),
        allowNull: false
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Trees');
  }
};

Here is the model file:这是模型文件:

'use strict';
module.exports = (sequelize, DataTypes) => {
  var Tree = sequelize.define('Tree', {
    title: {
      type: DataTypes.STRING,
      allowNull: false
    },
    content: {
      type: DataTypes.STRING(10000),
      allowNull: false
    }
  }, {});
  Tree.associate = function(models) {
    // associations can be defined here
  };
  return Tree;
};

Here is the code that accesses the database:下面是访问数据库的代码:

const setTree = (treeVal, callback) => {
  console.log(`this would be the part`);
  Tree.create({
    title: 'Tree',
    content: JSON.stringify(treeVal)
  })
  .then((treeStr) => {
    let primaryTopics = JSON.parse(treeStr.content);
    callback(null, primaryTopics);
  })
  .catch((err) => {
    callback(err);
  });
}

This is exported in the module.exports method:这是在module.exports方法中导出的:

  callTree(callback) {
    return Tree.findOne({
      where: {
        title: 'Tree'
      }
    })
    .then((treeStr) => {
      if (treeStr === null) {
        return callback(`not defined yet`);
      }
      let primaryTopics = treeStr.content;
      primaryTopics = JSON.parse(primaryTopics);
      callback(null, primaryTopics);
    })
    .catch((err) => {
      callback(err);
    });
  }

And I'm pulling this method for an integration test here (the PrimaryTopic table is in the same database, and I receive no errors trying to run it):我在此处提取此方法进行集成测试(PrimaryTopic 表位于同一个数据库中,我在尝试运行它时没有收到任何错误):

  beforeEach((done) => {
    this.primaryTopic;
    sequelize.sync({force: true}).then((res) => {

      PrimaryTopic.create({
        title: 'Title: Hello World',
        content: '<p>Content: Hello World</p>'
      })
      .then((primaryTopic) => {
        this.primaryTopic = primaryTopic;
        treeQueries.buildTree((err, res) => {
          if (err) {
            console.error(err);
          }
        });
        done();
      })
      .catch((err) => {
        console.log(err);
        done();
      });

    });
  });

I've searched through all the code for possible errors, but haven't found anything yet.我已经搜索了所有代码以查找可能的错误,但还没有找到任何东西。

I can use psql to access the Trees table in the test database, though it is empty.我可以使用psql访问测试数据库中的Trees表,尽管它是空的。

I can use the same code to insert a value into the Trees table in the development database with no issues.我可以使用相同的代码在开发数据库的Trees表中插入一个值,没有任何问题。

Here is the error I receive when I try to run a test (using jasmine.js for testing):这是我尝试运行测试时收到的错误(使用 jasmine.js 进行测试):

{ SequelizeDatabaseError: relation "Trees" does not exist
    at Query.formatError (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/sequelize/lib/dialects/postgres/query.js:363:16)
    at query.catch.err (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/sequelize/lib/dialects/postgres/query.js:86:18)
    at tryCatcher (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/promise.js:689:18)
    at Async._drainQueue (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:756:18)
    at tryOnImmediate (timers.js:717:5)
    at processImmediate [as _immediateCallback] (timers.js:697:5)
  name: 'SequelizeDatabaseError',
  parent: 
   { error: relation "Trees" does not exist
    at Connection.parseE (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/pg/lib/connection.js:553:11)
    at Connection.parseMessage (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/pg/lib/connection.js:378:19)
    at Socket.<anonymous> (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/pg/lib/connection.js:119:22)
    at Socket.emit (events.js:160:13)
    at addChunk (_stream_readable.js:269:12)
    at readableAddChunk (_stream_readable.js:256:11)
    at Socket.Readable.push (_stream_readable.js:213:10)
    at TCP.onread (net.js:599:20)
     name: 'error',
     length: 104,
     severity: 'ERROR',
     code: '42P01',
     detail: undefined,
     hint: undefined,
     position: '13',
     internalPosition: undefined,
     internalQuery: undefined,
     where: undefined,
     schema: undefined,
     table: undefined,
     column: undefined,
     dataType: undefined,
     constraint: undefined,
     file: 'parse_relation.c',
     line: '1160',
     routine: 'parserOpenTable',
     sql: 'INSERT INTO "Trees" ("id","title","content","createdAt","updatedAt") VALUES (DEFAULT,\'Tree\',\'[{"title":"Title: Hello World","id":1,"secondaryTopics":[]}]\',\'2018-08-14 06:38:37.243 +00:00\',\'2018-08-14 06:38:37.243 +00:00\') RETURNING *;' },
  original: 
   { error: relation "Trees" does not exist
    at Connection.parseE (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/pg/lib/connection.js:553:11)
    at Connection.parseMessage (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/pg/lib/connection.js:378:19)
    at Socket.<anonymous> (/home/siddhartha/Documents/01-Studio/01-Commercial-Public/01-Komodo/2018-resources/node_modules/pg/lib/connection.js:119:22)
    at Socket.emit (events.js:160:13)
    at addChunk (_stream_readable.js:269:12)
    at readableAddChunk (_stream_readable.js:256:11)
    at Socket.Readable.push (_stream_readable.js:213:10)
    at TCP.onread (net.js:599:20)
     name: 'error',
     length: 104,
     severity: 'ERROR',
     code: '42P01',
     detail: undefined,
     hint: undefined,
     position: '13',
     internalPosition: undefined,
     internalQuery: undefined,
     where: undefined,
     schema: undefined,
     table: undefined,
     column: undefined,
     dataType: undefined,
     constraint: undefined,
     file: 'parse_relation.c',
     line: '1160',
     routine: 'parserOpenTable',
     sql: 'INSERT INTO "Trees" ("id","title","content","createdAt","updatedAt") VALUES (DEFAULT,\'Tree\',\'[{"title":"Title: Hello World","id":1,"secondaryTopics":[]}]\',\'2018-08-14 06:38:37.243 +00:00\',\'2018-08-14 06:38:37.243 +00:00\') RETURNING *;' },
  sql: 'INSERT INTO "Trees" ("id","title","content","createdAt","updatedAt") VALUES (DEFAULT,\'Tree\',\'[{"title":"Title: Hello World","id":1,"secondaryTopics":[]}]\',\'2018-08-14 06:38:37.243 +00:00\',\'2018-08-14 06:38:37.243 +00:00\') RETURNING *;' }

Here's a link to the full repository.这是完整存储库的链接。

I know this is old but it could help somebody else facing same issue.我知道这是旧的,但它可以帮助其他人面临同样的问题。 I migrated from mysql to postgres and got same issue because the name of my table started with upper case ("Home") and I was trying to add a constraint with table name "home" which starts with lowercase.我从 mysql 迁移到 postgres 并遇到了同样的问题,因为我的表名以大写(“Home”)开头,我试图添加一个以小写开头的表名“home”的约束。

You need to set freezeTableName to true in the options of the data model.您需要在数据模型的选项中将 freezeTableName 设置为 true。 otherwise sequelize will try to search for Trees table否则 sequelize 将尝试搜索 Trees 表

module.exports = (sequelize, DataTypes) => {
  var Tree = sequelize.define('Tree', {
    title: {
      type: DataTypes.STRING,
      allowNull: false
    },
    content: {
      type: DataTypes.STRING(10000),
      allowNull: false
    }
  }, {
freezeTableName: true
});
  Tree.associate = function(models) {
    // associations can be defined here
  };
  return Tree;
};

for full documentation: https://sequelize.org/v3/docs/models-definition/#configuration完整文档: https : //sequelize.org/v3/docs/models-definition/#configuration

If you use the extend model interface, you can simply append tableName: "Trees" to your model configuration.如果您使用扩展模型接口,您可以简单地将tableName: "Trees"附加到您的模型配置中。

The easiest way I found to solve, is to explicitly set the tableName on the model.我发现解决的最简单方法是在模型上显式设置tableName As others have mentioned, sequelize defaults to the plural form of a model as the table name.正如其他人所提到的,sequelize 默认使用模型的复数形式作为表名。 For instance Tree, becomes Trees.例如Tree,变成Trees。

When you query, sequelize looks after a table with the same name as your model Tree .查询时,sequelize 会处理与模型Tree同名的表。 By defining the tableName in the model, sequelize should search the correct table.通过在模型中定义tableName ,sequelize 应该搜索正确的表。 Append tableName: "Trees" to your model configuration ie:tableName: "Trees"到您的模型配置中,即:

module.exports = (sequelize, DataTypes) => {
    class Tree extends Model {
        ...
    }
    Tree.init(
        {
            title: DataTypes.STRING,
            ...
        },
        {
            sequelize,
            modelName: 'Tree',
            tableName: 'Trees',
        }
    );
    return Tree;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM