Hope you're well !
I have a question. How can I prevent the following error after a db reset (sync force true) please ?
SequelizeDatabaseError: type "enum_coverLists_supportingDocument"
already exists
Here is what my model look like :
export const SUPPORTING_DOCUMENT = {
MEDIATION_FEES: 'MEDIATION_FEES',
LEGAL_COUNSEL_FEES: 'LEGAL_COUNSEL_FEES',
FILING_COMPLAINT: 'FILING_COMPLAINT'
};
export const TYPE = {
BUDGET: 'BUDGET',
QUANTITY: 'QUANTITY',
UNLIMITED: 'UNLIMITED'
};
const coverList = function (sequelize, Sequelize) {
const coverList = sequelize.define('coverList',
{
id: {
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4
},
title: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: true
},
supportingDocument: {
type: Sequelize.ARRAY(Sequelize.ENUM({
values: [...Object.values(SUPPORTING_DOCUMENT)]
})),
validate: {
isIn: [...Object.values(SUPPORTING_DOCUMENT)],
},
allowNull: true
},
type: {
type: Sequelize.ENUM,
values: Object.values(TYPE),
validate: {
isIn: [Object.values(TYPE)],
},
allowNull: false
}
});
return coverList;
};
export default coverList;
Stack :
Node.js
PostgreSQL
Sequelize
Thanks in advance for your help.
So, Whenever you create an "enum" it will store in the database. if you are using pgAdmin it stores all enums in the "Types" folder and if you use dbeaver there it is stored in "dataTypes" folder. so from there, you can delete it...
you can see here...
Related
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Characters' AND TABLE_SCHEMA = 'dev'
D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\utils.js:364
return s.replace(new RegExp(tickChar, 'g'), '');
^
TypeError: Cannot read properties of undefined (reading 'replace')
at Object.removeTicks (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\utils.js:364:12)
at MySQLQueryGenerator.quoteIdentifier [as _quoteIdentifier] (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\mysql\query-generator.js:590:33)
at MySQLQueryGenerator.quoteIdentifier (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\abstract\query-generator.js:954:19)
at MySQLQueryGenerator.quoteTable (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\abstract\query-generator.js:1037:20)
at MySQLQueryGenerator.attributeToSQL (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\mysql\query-generator.js:416:39)
at MySQLQueryGenerator.attributesToSQL (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\mysql\query-generator.js:441:45)
at MySQLQueryInterface.createTable (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\abstract\query-interface.js:222:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Function.sync (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\model.js:1353:7)
While creating a new table, I'm having this error.
All referenced types are fine. userId in Users is defined as MEDIUMINT.UNSIGNED, titleId and fieldId as TINYINT.UNSIGNED
I can't see any typos nor can find any similar issue from others.
Does anybody have an idea, please?
below is my charater model code
import sequelize from '../config/connection';
import { Fields, Titles, Users } from '../models';
import {
Model, DataTypes,
InferAttributes, InferCreationAttributes,
CreationOptional, ForeignKey
} from 'sequelize'
class Characters extends Model<
InferAttributes<Characters>, InferCreationAttributes<Characters>
>{
declare characterId: CreationOptional<number>;
declare userId: ForeignKey<number>;
declare titleId: ForeignKey<number>;
declare fieldId: ForeignKey<number>;
declare name: string;
declare job: string;
declare level: number;
declare attack: number;
declare defense: number;
declare hit: number;
declare mana: number;
declare exp: number;
declare createdAt: CreationOptional<number>;
declare updatedAt: CreationOptional<number>;
// declare User: NonAttribute<Users>
// declare Title: NonAttribute<>;
// declare Field: NonAttribute<>;
};
Characters.init({
characterId: {
type: DataTypes.MEDIUMINT.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
userId: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false,
references: {
model: Users,
key: 'userId'
}
},
titleId: {
type: DataTypes.TINYINT.UNSIGNED,
allowNull: false,
references: {
model: Titles,
key: 'titleId'
}
},
fieldId: {
type: DataTypes.TINYINT.UNSIGNED,
allowNull: false,
references: {
model: Fields,
key: 'fieldId'
}
},
name: {
type: DataTypes.STRING(40),
allowNull: false,
unique: true
},
job: {
type: DataTypes.STRING(40),
allowNull: false
},
level: {
type: DataTypes.TINYINT.UNSIGNED,
allowNull: false
},
attack: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
defense: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
hit: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
mana: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
exp: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
createdAt: {
type: DataTypes.INTEGER,
defaultValue: (Date.now()/1000)|0 + 60 * 60 * 9
},
updatedAt: {
type: DataTypes.INTEGER,
defaultValue: (Date.now()/1000)|0 + 60 * 60 * 9
}
}, {
sequelize,
modelName: 'Characters'
});
export default Characters;
The problem is that maybe your tables were not created/synced with the sequelize instance
I had the same issue and when I synced my database connection the problem was solved. Thats why maybe when you created the file again, it worked
Update 1/10/2022:
Here's an axemple of my code:
// your sequelize instance connected with your database
const sequelize = await new Sequelize({
dialect: 'foo',
storage: 'bar'
});
// initialization of your models...
YourModel.init(
{
foo: {
type: DataTypes.STRING(128),
allowNull: true
}
},
{
sequelize,
tableName: 'bar',
timestamps: true
}
);
...
// and then: synchronize the sequelize instance with your database and the needed data for sequelize to properly work will be available
await sequelize.sync();
Also check the official documentation for reference: https://sequelize.org/docs/v6/core-concepts/model-basics/#model-synchronization
i am new to sequelize, i have a user table , address table and address type table as given below.
A user can have 2 a different address , permanent and current address, and the type of address (permanent or current ) is specified in the table address type.
I have tried to access the data from mapping table (address_type) in the resolver based on schema and set hasMany relation from user -> address table , but graphql shows association not found error.
How can we get the relation properly in order to get the mapping address type name.
type User{
id:Int
name:String
}
type Address {
id: ID!
user_id:Int
city: String
addr_type:AddressType
}
type AddressType{
id : Int
name:String (permanent|current)
}
table definition
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
name: {
type: DataTypes.INTEGER, allowNull: false,
},
}, {
tableName: 'user',
timestamps: false
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('address', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER, allowNull: false, field:"addr_type"
},
addr_type: {
type: DataTypes.INTEGER, allowNull: false, field:"addr_type"
},
city: {
type: DataTypes.STRING, allowNull: false,
},
}, {
tableName: 'address',
timestamps: false
});
};
module.exports = function(sequelize, DataTypes) {
return sequelize.define('address_types', {
id: {
type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true
},
name: {
type: DataTypes.STRING, allowNull: false,
},
}, {
tableName: 'address_type',
timestamps: false
});
};
relationship
db.user.hasMany(db.address,{foreignKey: 'user_id'});
db.address.belongsTo(db.user,{foreignKey: 'user_id'});
db.address.belongsTo(db.address_types,{foreignKey: 'addr_type'});
resolver code
userts: async (obj, args, context, info ) => User.findAll( {
where: { user_status: 1 },
,
raw: true,
nest: true,
} ).then(userts => {
const response = userts.map(usert => {
return{
// i have 15 fields for a user, if i can access the schema of the corresponsing resolver i can dynamically build the response out put
id: usert.id,
firstName: usert.firstName,
lastName: usert.lastName,
middleName: usert.middleName,
}
})
return response;
}),
You should turn off the option raw in order to get associated objects and use the include option to indicate what associated models you wish to load.
User.findAll( {
where: { user_status: 1 },
include: [{
model: Address,
include: AddressType
}],
raw: false,
nest: true,
}
I'm using sequelize 4.32 and I was trying to write a self-association in one of the tables, I'm not sure if there is something else that I need to do to solve this relation, my goal is to get all the records in my table and include all the records associated with each one
this is the error that I'm getting in the console:
You have used the alias adjucent_stands in two separate associations. Aliased associations must have unique aliases
below you'll find my model:
module.exports = (sequelize, DataTypes) => {
const stands = sequelize.define('stands', {
id: {
type: DataTypes.INTEGER,
unique: true,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
field: 'name',
unique: {
args: true,
msg: 'Name already exists ',
},
},
location: {
type: DataTypes.JSON,
field: 'location',
},
remote: {
type: DataTypes.BOOLEAN,
field: 'remote',
defaultValue: false,
},
created_at: {
type: DataTypes.DATE(3),
defaultValue: sequelize.literal('CURRENT_TIMESTAMP(3)'),
},
updated_at: {
type: DataTypes.DATE(3),
defaultValue: sequelize.literal('CURRENT_TIMESTAMP(3)'),
},
}, { freezeTableName: true, timestamps: true, underscored: true });
stands.associate = (models) => {
stands.hasMany(stands, { as: 'adjucent_stands' });
};
return stands;
};
I use Sequelize to communicate with my postgres database. I want to use the upsert functionality, but with custom where clause. For example I have this model for volunteers location
module.exports = function (sequelize, DataTypes) {
var volunteer_location = sequelize.define('volunteer_location', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
deviceId: {
allowNull: false,
type: Sequelize.STRING
},
latitude: {
allowNull: false,
type: Sequelize.DECIMAL(18, 14)
},
longitude: {
allowNull: false,
type: Sequelize.DECIMAL(18, 14)
},
city: {
allowNull: false,
type: Sequelize.STRING(90)
},
state: {
type: Sequelize.STRING(90)
},
postalCode: {
type: Sequelize.STRING(16)
},
country: {
allowNull: false,
type: Sequelize.STRING(70)
}
}, {
instanceMethods: {
insertOrUpdate: function (requestBody, res) {
volunteer_location.upsert(requestBody).then(function () {
res.sendStatus(200);
});
}
}
});
return volunteer_location;
};
In the insertOrUpdate method I try to use the upsert by giving a json like
location = {
deviceId: req.body.deviceId,
latitude: req.body.latitude,
longitude: req.body.longitude,
city: req.body.city,
state: req.body.state,
postalCode: req.body.postalCode,
country: req.body.country,
volunteer: req.decoded.id
};
where volunteer is a foreign key from table users.
Now the executing says:
CREATE OR REPLACE FUNCTION pg_temp.sequelize_upsert() RETURNS integer
AS $func$ BEGIN INSERT INTO "volunteer_locations" some values RETURN
1; EXCEPTION WHEN unique_violation THEN UPDATE "volunteer_locations"
SET some values WHERE (("id" IS NULL AND "volunteer" = 1));
RETURN 2; END; $func$ LANGUAGE plpgsql; SELECT * FROM
pg_temp.sequelize_upsert();
id and volunteer is a set of primary keys. I want to change the WHERE clause on the UPDATE by checking only the volunteer value, because I don't know the value of the id.
Is this possible? Or I have to use
findOne(...).then(function () {
//update
});
EDIT
I set volunteer with the attribute unique: true and it replaced the where clause with WHERE (("id" IS NULL AND "volunteer" = 1) OR "volunteer" = 1);, which means that the update works. But I don't know if this is very efficient. If anyone knows a better solution please let me know.
I'm newbie of Sails and I've got a problem with one to one association.
First, I have model User:
module.exports = {
schema: true,
identity : "User",
tableName: "user",
attributes: {
email: {
type: 'email',
unique: true,
required: true
},
password: {
type: 'string'
},
salt: {
type: 'string'
},
merchant: {
model: 'merchant',
defaultsTo: null
},
removed: {
type: 'boolean',
required: true,
defaultsTo: false
}
}
}
And my Merchant model:
module.exports = {
schema: true,
identity : "Merchant",
tableName: "merchant",
attributes: {
name: {
type: 'string',
unique: true,
required: true
},
code: {
type: 'string',
unique: true,
required: true
},
security_key: {
type: 'string',
required: true
},
active: {
type: 'boolean',
defaultsTo: false,
required: true
},
user: {
model: 'user'
}
}
}
So when I need to find records where merchant.active = true, I write this query:
var findUser = User.find(query).populate('merchant', {active: true});
return findUser;
But it was not working at all.
Anyone any ideas to solve this properly?
P.S. my Sails version is: 0.11.1. My DB is MongoDB
First of all, remove defaultsTo from your association attributes. I don't like this :) I don't know if it makes the problem, but in documentation I never see this.
Also you need to execute your query, not just return it. If I take your models' declarations then I can write populate query like this.
var findUser = User.find(query).populate('merchant', {active: true});
findUser.then(function(user) {
console.log('Your user is ' + user);
}).catch(function(error) {
console.log('Your error is ' + error);
});