MariaDB connection with Sequelize - javascript

I have been checking for the connectivity of MariaDB, with Sequelize.
const Sequelize = require('sequelize');
// Setting up database (MariaDB) connection
const sequelize = new Sequelize('dbName', 'usr', 'pass', {
host: 'localhost',
dialect: 'mariadb'
});
But I am getting the following error:
/home/lt-196/api/node_modules/sequelize/lib/sequelize.js:236
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.');
^
Error: The dialect mariadb is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.
at new Sequelize (/home/lt-196/api/node_modules/sequelize/lib/sequelize.js:236:15)
at Object.<anonymous> (/home/lt-196/api/app.js:21:19)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3

MariaDB
For MariaDB compatibility you have to install the package mariasql#0.1.20, or higher.
The configuration needs to look like this:
var sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mariadb'
})
Or Try this:
MariaSQL: https://www.npmjs.com/package/mariasql
A node.js binding to MariaDB's non-blocking (MySQL-compatible) client library.
var Client = require('mariasql');
var c = new Client({
host: '127.0.0.1',
user: 'foo',
password: 'bar'
});
c.query('SHOW DATABASES', function(err, rows) {
if (err)
throw err;
console.dir(rows);
});
c.end();
MariaSQL is recommended.

https://github.com/MariaDB/mariadb-connector-nodejs
NPM
npm install --save mariadb
npm install --save sequelize#next
Yarn
yarn add mariadb
yarn add sequelize#next
const Sequelize = require('sequelize'),
sequelize = new Sequelize(process.env.db_name, process.env.db_user, process.env.db_pass, {
dialect: 'mariadb',
dialectOptions: {
socketPath: process.env.db_socket,
timezone: process.env.db_timezone
},
pool: {
min: 0,
max: 5,
idle: 10000
},
define: {
charset: 'utf8',
timestamps: false
},
benchmark: false,
logging: false
})

Related

AssertionError [ERR_ASSERTION]: PORT is required (when starting node js as a windows service)

The project runs without any errors when run from Visual Studio Code by runung the cmd : npm start.
But when runing the project as a windows service I´m getting an error about the PORT.
The PORT=8080 is initialized in the (Environment file) env. file.
Bellow is the env. file:
NODE_ENV=production
# hapi server config
PORT=8080
HOST=localhost
HOST_URL=http://localhost:8080
COOKIE_ENCRYPT_PWD=xxxxxxxxxx...
#sql server config
SQL_USER=xxxxx
SQL_PASSWORD=xxxxxxxx
SQL_DATABASE=xxxxxxxx
SQL_SERVER=computer\SQLEXPRESS
SQL_ENCRYPT=false
#okta config
OKTA_ORG_URL=https://dev-000000.okta.com
OKTA_CLIENT_ID=xxxxxxxx
OKTA_CLIENT_SECRET=xxxxxxxxxxx
Bellow is the config file:
"use strict";
const dotenv = require( "dotenv" );
const assert = require( "assert" );
dotenv.config();
const {
PORT,
HOST,
HOST_URL,
COOKIE_ENCRYPT_PWD,
SQL_SERVER,
SQL_PORT,
SQL_DATABASE,
SQL_USER,
SQL_PASSWORD,
OKTA_ORG_URL,
OKTA_CLIENT_ID,
OKTA_CLIENT_SECRET
} = process.env;
const sqlEncrypt = process.env.SQL_ENCRYPT === "false";
assert( PORT, "PORT is required" );
assert( HOST, "HOST is required" );
module.exports = {
port: PORT,
host: HOST,
url: HOST_URL,
cookiePwd: COOKIE_ENCRYPT_PWD,
sql: {
server: SQL_SERVER,
port: SQL_PORT,
database: SQL_DATABASE,
user: SQL_USER,
password: SQL_PASSWORD,
options: {
encrypt: sqlEncrypt,
enableArithAbort: true
}
},
okta: {
url: OKTA_ORG_URL,
clientId: OKTA_CLIENT_ID,
clientSecret: OKTA_CLIENT_SECRET
}
};
the error is as follows:
assert.js:386
throw err;
^
AssertionError [ERR_ASSERTION]: PORT is required
at Object.<anonymous> (C:\inetpub\apis\routis\src\config.js:25:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:903:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\inetpub\apis\routis\src\index.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: undefined,
expected: true,
operator: '=='
}
extension of dotenv file is .env, Check once for that.

how to connect to MySQL(phphmyadmin) from Node.js?

When installing a fresh version of xampp I'm able to connect my js script to MySQL through the terminal.
const mysql = require('mysql');
let con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
port:3307
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
PS C:\login> node connection.js
Connected!
I've been trying another db which I have credentials for but it seems to be a problem when you have a password property in the con object. That it will not connect with a password :P What Im I doing wrong here?
C:\login\connection.js:13
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16)
--------------------
at Protocol._enqueue (C:\login\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\login\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\login\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\login\connection.js:12:7)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"xyz"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
PS C:\login> node connection.js
Connected!

How to do testing with Jest and Knex in TypeScript?

I'm trying to test GraphQL server with Jest and Knex. I had a hard time figuring out how to use knexfile in typescript. But now everything is working fine for development and production envs, except for testing.
Here's my current knexfile.ts:
// knexfile.ts
const defaults = {
client: 'pg',
connection: {
host: DB_HOST,
user: DB_USER,
password: DB_PASSWORD,
database: DB_DATABASE
},
pool: {
min: 2,
max: 10
},
migrations: {
extension: 'ts',
directory: './migration',
tableName: 'knex_migrations'
},
seeds: {
extension: 'ts',
directory: './seed'
}
};
interface KnexConfig {
[key: string]: object;
}
const knexConfig: KnexConfig = {
local: {
client: 'sqlite3',
connection: {
filename: './dev.sqlite3'
}
},
development: {
...defaults,
debug: true,
useNullAsDefault: true
},
production: {
...defaults
}
};
/**
* `export default` does not work, causes `client` missing problem
* at database migration.
*/
export = knexConfig;
This is global setup for Jest:
// globalSetup.ts
export = async () => {
try {
// Start http server
await httpServer.listen(PORT);
// Rollback and migrate
// await knex.migrate.rollback().then(() => knex.migrate.latest());
knex.migrate.latest();
} catch (err) {
// Log the error
logger.error('', err);
}
};
This is global teardown:
// globalTeardown.ts
export = async () => {
try {
await knex.migrate.rollback();
// Shutdown server
httpServer.close(() => logger.info('Server closed'));
} catch (err) {
// Log the error
logger.error('', err);
}
};
It keeps giving me error:
Unhandled rejection SyntaxError: Unexpected token *
/home/my/knex-graphql/migration/20190821235716_create_user.ts:1
import * as Knex from 'knex';
^
SyntaxError: Unexpected token *
at Module._compile (internal/modules/cjs/loader.js:872:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Function.<anonymous> (/home/my/knex-graphql/node_modules/#sentry/node/src/integrations/console.ts:37:43)
at Function._load (/home/my/knex-graphql/node_modules/#sentry/node/src/integrations/http.ts:73:43)
at Module.require (internal/modules/cjs/loader.js:830:19)
at require (internal/modules/cjs/helpers.js:68:18)
at FsMigrations.getMigration (/home/my/knex-graphql/node_modules/knex/lib/migrate/sources/fs-migrations.js:84:12)
at /home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:82:69
at arrayFilter (/home/my/knex-graphql/node_modules/lodash/lodash.js:582:11)
at filter (/home/my/knex-graphql/node_modules/lodash/lodash.js:9173:14)
at /home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:81:13
at tryCatcher (/home/my/knex-graphql/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/my/knex-graphql/node_modules/bluebird/js/release/promise.js:517:31)
at Promise._settlePromise (/home/my/knex-graphql/node_modules/bluebird/js/release/promise.js:574:18)
From previous event:
at Migrator.latest (/home/my/knex-graphql/node_modules/knex/lib/migrate/Migrator.js:71:8)
at /home/my/knex-graphql/test/global/setup.ts:24:32
at Generator.next (<anonymous>)
at fulfilled (/home/my/knex-graphql/test/global/setup.ts:5:58)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
Tech stack: Apollo-server-express, TypeScript, Knex.js, PostgreSQL, Jest
You need to add ts-jest, which will transpile your ts files for jest.
Install it
npm install --save-dev ts-jest
Add default ts-jest config
npx ts-jest config:init
we use something a bit like this in our knexfile.js
require('ts-node/register');
require('dotenv').config();
const {
SERVER_HOST,
SERVER_USER,
SERVER_PASSWORD,
SERVER_DATABASE,
SERVER_DATABASE_TEST,
} = process.env;

Node js unexpected token

i'm trying to run my project on centos 7 OS, i'm trying to install my project by writing node install_server.js
and the terminal returns me an error
install_server.js:26
fs.readFile(`${__dirname}/config/config.sql`, (err, data) => {
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
And my source code of this file is found below
const cfg = require('./config/config.json');
const knex = require('knex');
const fs = require('fs');
const mysql = require('mysql');
var db = knex({
client: 'mysql',
pool: {
min: 0,
max: 1
},
connection: {
host: cfg.database.db_server,
user: cfg.database.db_user,
password: cfg.database.db_password
}
});
var myCon = mysql.createConnection({
multipleStatements: true,
host: cfg.database.db_server,
user: cfg.database.db_user,
password: cfg.database.db_password
});
fs.readFile(`${__dirname}/config/config.sql`, (err, data) => {
if (err)
throw err;
myCon.query(data.toString(), function(err, results) {
if (err)
throw err;
console.log('complete')
});
});
Cant seem to figure it out, could i get a helphand?
Template Literals are not supported until version 4.8.4 according to
http://node.green/
which is a great resource.

Runner is undefined in query of Knex.js

I tried to use Knex.js on Node.js by following code:
var Promise = require("bluebird");
var knex = require("knex")({
client: 'pg',
user : 'username',
database : 'database',
password: "password",
migrations: {
tableName: 'knex_migrations'
},
pool: {
min: 0,
max: 7
}
});
knex.select("*").from("users").then(function(rows){
console.log(rows);
});
But, it threw an error about Runner object as follows:
/path/to/myapp/node_modules/knex/lib/interface.js:27
return new Runner(this).run().then(onFulfilled, onRejected);
^
TypeError: undefined is not a function
at QueryBuilder_PG.Target.then (/path/to/myapp/node_modules/knex/lib/interface.js:27:12)
at Object.<anonymous> (/path/to/myapp/test.js:14:32)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
When I try to use stream, pipe, exec and transaction, same error occurred.
Please tell me how to solve this problem...
I was really careless about configuration of client.
I have mistaken in description of "connection". It have to be written as follows:
var Promise = require("bluebird");
var knex = require("knex")({
client: 'pg',
connection: {
host : '127.0.0.1',
user: 'username',
database: 'database',
password: 'password'
},
migrations:{
tableName:"knex_migrations"
},
pool: {
min: 0,
max: 7
}
});
knex.select("*").from("users").then(function(rows){
console.log(rows);
});
It works with no problems.
Thank you!

Categories

Resources