115 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-06-17 16:17:15 +02:00
'use strict';
2021-06-24 18:28:36 +02:00
const errors = require('../errors');
2021-06-17 16:17:15 +02:00
class Dialect {
2021-06-28 12:34:29 +02:00
constructor(db) {
this.db = db;
}
2021-06-28 21:37:44 +02:00
usesForeignKeys() {
2021-06-17 16:17:15 +02:00
return false;
}
2021-06-24 18:28:36 +02:00
2021-06-28 21:37:44 +02:00
useReturning() {
return false;
2021-06-24 18:28:36 +02:00
}
// TODO: pass query info to display some more metadata
transformErrors(error) {
throw error;
}
2021-06-17 16:17:15 +02:00
}
2021-06-24 18:28:36 +02:00
class PostgresDialect extends Dialect {
2021-06-17 16:17:15 +02:00
useReturning() {
return true;
}
2021-06-24 18:28:36 +02:00
2021-06-28 12:34:29 +02:00
initialize() {
2021-06-28 21:37:44 +02:00
// console.log(this.db.connection)
// this.db.connection.context.client.types.setTypeParser(1700, 'text', parseFloat);
}
usesForeignKeys() {
return false;
2021-06-28 12:34:29 +02:00
}
2021-06-24 18:28:36 +02:00
transformErrors(error) {
switch (error.code) {
case '23502': {
throw new errors.NotNullConstraint({ column: error.column });
}
default: {
throw error;
}
}
}
}
class MysqlDialect extends Dialect {
2021-06-28 12:34:29 +02:00
initialize() {
this.db.connection.supportBigNumbers = true;
this.db.connection.bigNumberStrings = true;
this.db.connection.typeCast = (field, next) => {
if (field.type == 'DECIMAL' || field.type === 'NEWDECIMAL') {
var value = field.string();
return value === null ? null : Number(value);
}
if (field.type == 'TINY' && field.length == 1) {
let value = field.string();
return value ? value == '1' : null;
}
return next();
};
}
2021-06-28 21:37:44 +02:00
usesForeignKeys() {
return false;
}
2021-06-24 18:28:36 +02:00
transformErrors(error) {
throw error;
}
}
class SqliteDialect extends Dialect {
2021-06-28 12:34:29 +02:00
async initialize() {
// Create the directory if it does not exist.
// options.connection.filename = path.resolve(strapi.config.appPath, options.connection.filename);
await this.db.connection.raw('PRAGMA foreign_keys = ON');
}
2021-06-24 18:28:36 +02:00
transformErrors(error) {
switch (error.errno) {
case 19: {
throw new errors.NotNullConstraint();
}
default: {
throw error;
}
}
}
2021-06-17 16:17:15 +02:00
}
2021-06-28 12:34:29 +02:00
const getDialect = db => {
const { client } = db.connection.client.config;
2021-06-17 16:17:15 +02:00
switch (client) {
case 'postgres':
2021-06-28 12:34:29 +02:00
return new PostgresDialect(db);
2021-06-24 18:28:36 +02:00
case 'mysql':
2021-06-28 12:34:29 +02:00
return new MysqlDialect(db);
2021-06-24 18:28:36 +02:00
case 'sqlite':
2021-06-28 12:34:29 +02:00
return new SqliteDialect(db);
2021-06-17 16:17:15 +02:00
default:
2021-06-28 12:34:29 +02:00
return new Dialect(db);
2021-06-17 16:17:15 +02:00
}
};
module.exports = {
getDialect,
};