Prisma - ConnectorError - mysql

I'm trying to learn Prisma on my hobby project so I started with basics.
The first thing I tried was a simple GET request which should list all results in a table.
// Using "#prisma/client": "^3.8.1",
const position = await prisma.position.findMany();
It worked fine but obviously, I don't have any data so it return an empty array. If I try to add some items to the Position table I'm getting error (mentioned below). Same error I'm getting also from Prisma Studio so I wonder If I did something wrong or what can I do to fix it.
Prisma schema
model Position {
id Int #id #default(autoincrement())
name String #db.VarChar(255)
externalId String #db.VarChar(255)
benefits String #db.Text()
}
MySQL Schema
CREATE TABLE `Position` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`externalId` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`benefits` text COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Query:
await prisma.position.create({
data: {
name: 'Position Name',
externalId: '321',
benefits: 'My benefits',
},
});
Error:
Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Server(ServerError { code: 1064, message: "target: referral.-.primary: vttablet: (errno 1064) (sqlstate 42000) (CallerID: unsecure_grpc_client): Sql: \"insert into Position(`name`, externalId,
benefits) values (:v1, :v2, :v3)\", BindVars: {}", state: "42000" })) })
at cb (C:\Develop\referral-nextjs-prisma\node_modules\#prisma\client\runtime\index.js:38695:17)
at async assetHandler (webpack-internal:///./pages/api/position/index.tsx:12:34)
at async Object.apiResolver (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\api-utils.js:102:9)
at async DevServer.handleApiRequest (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\base-server.js:1076:9)
at async Object.fn (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\base-server.js:963:37)
at async Router.execute (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\router.js:222:32)
at async DevServer.run (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\base-server.js:1103:29)
at async DevServer.run (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\dev\next-dev-server.js:444:20)
at async DevServer.handleRequest (C:\Develop\referral-nextjs-prisma\node_modules\next\dist\server\base-server.js:319:20) {
clientVersion: '3.8.1'
}

Related

Why when I query information in a table the updateDateColumn gets updated?

I am making a get request to my API and I want to use the table's changeDate field to run some logic, but the problem is that when I request the data this field gets updated and that's not the behavior I expected from the #UpdateDateColumn decorator since I'm just doing a simple get query with the Repository API. Why does this happens? Did I miss something in the docs?
I know this because I gave read only permissions (mysql) to my API, when I make a request it failed because of this.
This is the error:
QueryFailedError: The MySQL server is running with the --read-only option so it cannot execute this statement
This is my entity (part of it):
export class Cake{
#PrimaryGeneratedColumn()
id: number;
#Index()
#Column()
#Generated('uuid')
GUID: string;
#Column({ nullable: true })
flavor: string;
#UpdateDateColumn({ nullable: true })
changeDate: Date;
}
This is my query:
const cake= await this.cakeRepository.findOne({where: {GUID: guid}, select: ['id', 'GUID', 'changeDate']})
SQL for table creation
CREATE TABLE `Cake` (
`id` int NOT NULL AUTO_INCREMENT,
`GUID` varchar(36) NOT NULL,
`changeDate` datetime(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
`flavor` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_6aeaf4ee4a4e43e805a15c4738` (`GUID`),
) ENGINE=InnoDB AUTO_INCREMENT=362 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Error: ER_INVALID_JSON_TEXT: Invalid JSON text: "Invalid value." at position 1 in value for column '._data'. IN NODE JS

I want to insert JOSN data/object into mysql using stored procedure using node js. First of all I know there are some similar question out there but I tried them and but still didn't get the result.
This is the first time I am using stored procedure and node js, So I have table name test_data
test_data
CREATE TABLE `test_data` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL DEFAULT NULL,
`address` VARCHAR(255) NULL DEFAULT NULL,
`city` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2
;
This is stored procedure insert_data:
insert_data
CREATE DEFINER=`root`#`localhost` PROCEDURE `insert_data`(
IN `_data` JSON
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
declare p_name varchar(255) default null;
declare p_address varchar(255) default null;
declare p_city varchar(255) default null;
set p_name= json_unquote(json_extract(_data, '$.name'));
set p_address= json_unquote(json_extract(_data, '$.address'));
set p_city= json_unquote(json_extract(_data, '$.city'));
insert into test_data(name, address, city) values(p_name, p_address, p_city);
END
here is my node js code :
const con = require('./db/connection');
const _data = {
"name": "Ironman",
"address": "ani#gamil.com",
"city": "bhilai"
}
const sql = "CALL insert_data('"+_data +"')"
con.query(sql, _data,(error, result) => {
if(error){
return console.log("There is error in the query: " + error)
}
console.log(result)
})
ERROR
There is error in the query: Error: ER_INVALID_JSON_TEXT: Invalid JSON text: "Invalid value." at position 1 in value for column '._data'.
please help me out here, what am i doing wrong ?
Thanks
It seems to me that you are not actually passing a JSON value?
const _data = {
"name": "Ironman",
"address": "ani#gamil.com",
"city": "bhilai"
};
The above is a Javascript object, not its JSON representation. So here
const sql = "CALL insert_data('"+_data +"')"
the actual value of sql will be "CALL insert_data('[object Object]')" which is in fact not valid. Try dumping sql to console to verify that this is indeed the case.
Try with:
const sql = "CALL insert_data('"+ JSON.stringify(_data) +"')"

Incorrect string value for column

I'm getting this error while trying to save an entry from my application to mysql DB
Hibernate operation: could not execute statement; uncategorized
SQLException for SQL [n/a]; SQL state [HY000]; error code [1366];
Incorrect string value: '\xE2\x80\x8BShe...' for column
'extracted_text' at row 1; nested exception is java.sql.SQLException:
Incorrect string value: '\xE2\x80\x8BShe...' for column
'extracted_text' at row 1
at com.some.scanner.RequestService.$tt__handleMessage(RequestService.groovy:67)
My Table is created as below:
CREATE TABLE `request` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`doc_hash` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`extracted_text` longtext COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`),
KEY `FK414EF28FD3E87920` (`batch_id`),
) ENGINE=InnoDB AUTO_INCREMENT=20025 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
my entity mapping is quite simple in Grails
class Request {
String docHash
String extractedText
static mapping = {
extractedText type: 'text'
}
}
Do I need to change the encoding type? If so, to what?
Set the database properties useUnicode and characterEncoding. These are passed directly to your JDBC driver: https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/tomcat/jdbc/pool/PoolConfiguration.html#getDbProperties%28%29
dataSource {
url = 'jdbc:mysql://...'
properties {
dbProperties {
useUnicode=true
characterEncoding='UTF-8'
}
}
}
A little more about MySQL Connect charsets (which includes the spelling of UTF-8): http://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-charsets.html
MySQL-specific config properties go in dbProperties: http://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
...unless they are already covered by the main dataSource properties from: http://docs.grails.org/latest/guide/conf.html#dataSource
or are in the "extra" properties from: http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#Common_Attributes

ExpressJS - Sequelize - Column Missing Error

I'm trying to properly query all images that fit my sequelize query in addition to the description that is connected to the specific query, but I receive an error for a createdAt column, which is not located in my table. How can I specify the columns I want to use within my query?
Here is the query (The pattern and color are correctly pulled into the query):
router.get('/:pattern/:color/result', function(req, res){
console.log(req.params.color);
console.log(req.params.pattern);
Images.findAll({
where: {
pattern: req.params.pattern,
color: req.params.color
}
});
//console.log(image);
//console.log(doc.descriptions_id);
res.render('pages/result.hbs', {
pattern : req.params.pattern,
color : req.params.color,
image : image
});
});
Here is my table:
CREATE TABLE `images` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`pattern` varchar(225) DEFAULT NULL,
`color` varchar(225) DEFAULT NULL,
`imageUrl` varchar(225) DEFAULT NULL,
`imageSource` varchar(225) DEFAULT NULL,
`description_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `description_id` (`description_id`),
CONSTRAINT `images_ibfk_1` FOREIGN KEY (`description_id`) REFERENCES `description` (`description_id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;
Here is the error:
Executing (default): SELECT `id`, `pattern`, `color`, `imageUrl`, `imageSource`, `description_id`, `createdAt`, `updatedAt` FROM `images` AS `images` WHERE `images`.`pattern` = 'solid' AND `images`.`color` = 'navy-blue';
Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'createdAt' in 'field list'
at Query.formatError (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/dialects/mysql/query.js:160:14)
By default, sequelize assumes that you have timestamps in your table. This can be disabled either globally
new Sequelize(..., { define: { timestamps: false }});
Or per model:
sequelize.define(name, attributes, { timestamps: false });
Or if you only have some timesstamps (fx updated, but not created)
sequelize.define(name, attributes, { createdAt: false });
In case your column is called something else:
sequelize.define(name, attributes, { createdAt: 'make_at' });
http://docs.sequelizejs.com/en/latest/api/sequelize/
In this way, you don't have to specify all attributes each time - sequelize knows which attributes it can actually select.
If you really wanted to specify which attributes should be selected by
default you could use a scope
sequelize.define(name, attributes, { defaultScope { attributes: [...] }});
And that will be applied to each find call
You can explicitly set which attributes (column names) you want to retrieve in your query. For example, if you wanted to retrieve the id, pattern, color, imageUrl, and imageSource columns you can use the following code:
Images.findAll({
where : {
pattern: req.params.pattern,
color: req.params.color
},
attributes : ['id', 'pattern', 'color', 'imageUrl', 'imageSource']
})

Waterline ORM Foreign Key Error

I'm completely new to NodeJS. I'm trying to build my first express app with mysql database. I'm not using Sails, but I read some suggestions to use the Waterline ORM. However, I'm having problems trying to initialize my ORM. Here's my database schema in mysql:
CREATE TABLE IF NOT EXISTS `c` (
`c_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`d_id` int(11) UNSIGNED NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`c_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `d` (
`d_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`c_id` int(11) UNSIGNED NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`d_id`),
CONSTRAINT `d_ibfk_1` FOREIGN KEY (`c_id`) REFERENCES `c`(`c_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE c ADD CONSTRAINT `c_ibfk_1` FOREIGN KEY (`d_id`) REFERENCES `d`(`d_id`) ON DELETE CASCADE;
Here is my Node JS code
var express = require("express");
var app = express();
var Waterline = require("waterline");
//console.log(new homer());
var orm = new Waterline();
//////////////////////////////////////////////////////////////////
// WATERLINE CONFIG
//////////////////////////////////////////////////////////////////
// Require any waterline compatible adapters here
var diskAdapter = require('sails-disk'),
mysqlAdapter = require('sails-mysql');
// Build A Config Object
var config = {
// Setup Adapters
// Creates named adapters that have have been required
adapters: {
'default': diskAdapter,
disk: diskAdapter,
mysql: mysqlAdapter
},
// Build Connections Config
// Setup connections using the named adapter configs
connections: {
myLocalDisk: {
adapter: 'disk'
},
myLocalMySql: {
adapter: 'mysql',
host: 'localhost',
database: 'waterline_error',
user: 'weruser',
password: 'migjiii322'
}
}
};
var C = Waterline.Collection.extend({
tableName: 'c',
identity: 'c',
connection: 'myLocalMySql',
attributes: {
c_id: {type:'integer'},
name: {type:'string'}
}
});
orm.loadCollection(C);
app.listen(3000,function(){
console.log("Running Server on Port 3000.");
orm.initialize(config, function(err, models) {
if(err) throw err;
app.models = models.collections;
app.connections = models.connections;
app.models.c.find().exec(function(err,models){
if(err) return res.json({ err: err }, 500);
console.log(models);
});
});
});
When I run this code, I get the following error:
if(err) throw err;
^
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails
How do I get around this error such that the .find() function near the bottom actually gets fired?