How I connect gorm with postgres? - database

I need your help, because my app can´t connect with postgresql (docker),
this is the error:
2022/12/13 11:04:29 C:/Users/Jose Gomez/Desktop/GoPrj/go-gorm-postgresql/db/connection.go:15
[error] failed to initialize database, got error failed to connect to host=localhost user=jose database=gorm: failed SASL auth (FATAL: la autentificaci�n password fall� para el usuario �jose� (SQLSTATE 28P01))
2022/12/13 11:04:29 failed to connect to host=localhost user=jose database=gorm: failed SASL auth
(FATAL: la autentificaci�n password fall� para el usuario �jose� (SQLSTATE 28P01))
exit status 1
and my dbconnection is:
package db
import (
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var DNS = "host=localhost user=jose password=mysecretpassword dbname=gorm port=5432"
var DB *gorm.DB
func DBConnection() {
var error error
DB, error = gorm.Open(postgres.Open(DNS), &gorm.Config{})
if error != nil {
log.Fatal(error)
} else {
log.Println("DB Conectada!!!")
}
}
I need connect this dbconnection

Related

Reactjs AWS RDS retrieve

I am unable to connect and retrieve my data from AWS RDS. I've used SQL Server Management Studio(SSMS) to do the manipulation of the data. I've stored my credentials in .env file. Below are my code:
.env
REACT_APP_API_KEY = 'my-secret-api-key'
RDS_HOSTNAME= 1001
RDS_USERNAME= Admi
RDS_PASSWORD = Password
RDS_PORT = 1041
dbConfig.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.RDS_HOSTNAME,
user : process.env.RDS_USERNAME,
password : process.env.RDS_PASSWORD,
port : process.env.RDS_PORT
});
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();

Lagom Framework Topic Websocket Timeout connection closed with error

I have created a lagom Topic in my service.
def addingsTopic(): Topic[ProcessDefinitionAdded]
the descriptor:
override def descriptor: Descriptor = {
import Service._
named(ProductionService.TOPIC_NAME).withCalls(
pathCall(pathProcessDef(":id"), getProcessDefinition _)
).withTopics(
topic("processdef", addingsTopic _ )
.addProperty(
KafkaProperties.partitionKeyStrategy,
PartitionKeyStrategy[ProcessDefinitionAdded](_.entityId.toString)
),
topic("productionserviceorder", ordersTopic _)
.addProperty(
KafkaProperties.partitionKeyStrategy,
PartitionKeyStrategy[OrderAddedTopic](_.entityId.toString)
)
).withAutoAcl(true)
}
Until here all is clear. Now I have a play webpage. I have in my controller a Websocket.
val k = productionService.addingsTopic().subscribe.atMostOnceSource.mapAsync(1){e ⇒
productionService.getProcessDefinition(e.entityId).invoke().map{e ⇒
Json.toJson(e)(ProcessDefinitionResponse.format)
}
}.toMat(BroadcastHub.sink(256) )(Keep.right).run().recover{
case e ⇒ println(e)
Json.toJson("error "+e)
}
val f = Flow.fromSinkAndSource(Sink.ignore,k.concat(Source.maybe))
def fetchProcessDefinition() = WebSocket.accept[String,JsValue] { req ⇒
f
}
My javascript website use this to connect:
<script>
try{
console.log("START");
var socket = new WebSocket("ws://localhost:9000/processdef/stream");
socket.onopen = function(s){
console.log("OPEN");
console.log(s);
};
socket.onerror = function(error){
console.log("ERROR: ");
console.log(error);
};
socket.onmessage = function(msg){
console.log("Message:");
console.log(JSON.stringify(msg.data));
};
socket.onclose = function(closeevent){
console.log("CLOSE:");
console.log(closeevent);
};
socket.send("")
}catch (e) {
console.error(e);
}
</script>
I load the page on localhost after sbt runAll. It takes a time then the websockets connects (sometimes a few minutes and sometimes a few seconds). After ~ 90 seconds the console prints that the connection is closed out.
On IDE I get this error:
2018-10-18T10:54:16.655Z [error] akka.actor.ActorSystemImpl [sourceThread=application-akka.actor.default-dispatcher-213, akkaSource=akka.actor.ActorSystemImpl(application), sourceActorSystem=application, akkaTimestamp=10:54:16.654UTC] - Websocket handler failed with The connection closed with error: The connection was reset by peer
akka.stream.StreamTcpException: The connection closed with error: The connection was reset by peer
2018-10-18T10:54:16.674Z [error] akka.actor.ActorSystemImpl [sourceThread=application-akka.actor.default-dispatcher-231, akkaSource=akka.actor.ActorSystemImpl(application), sourceActorSystem=application, akkaTimestamp=10:54:16.674UTC] - Websocket handler failed with The connection closed with error: The connection was reset by peer
akka.stream.StreamTcpException: The connection closed with error: The connection was reset by peer
That is very stressful. Do I have any mistakes in my code?
Thanks for any help.

unable to connect to ms sql window authetication using node js

Here is my node js code
app.get('/', function (req, res) {
var config = {
server: 'localhost\\SQLEXPRESS2008',
database: 'TestingDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userform', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
});
Please suggest me to connect sql and getting this error after running this in command prompt
Server is running.. on Port 8020
{ Error: Failed to connect to localhost:undefined in 15000ms
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.connectTimeout (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:795:12)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
code: 'ETIMEOUT',
originalError:
{ ConnectionError: Failed to connect to localhost:undefined in 15000ms
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Connection.connectTimeout (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:795:28)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
message: 'Failed to connect to localhost:undefined in 15000ms',
code: 'ETIMEOUT' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:118:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
undefined
This might help :
Start the "SQL SERVER BROWSER" Service in Windows services (I've configured it to start automatically)
allow SQL Server Express to accept remote connections over TCP/IP for port 1433 : http://support.webecs.com/kb/a868/how-do-i-configure-sql-server-express-to-allow-remote-tcp-ip-connections-on-port-1433.aspx
Finally restart 'SQL Server' and 'SQL Browser Agent' services
Installing mssql package I had a similiar problem and I got fixed addiyng an instance and database name to my config.
I thought it was better create an user on db.
After I need to handling the errors, addiyng try catch to my function that will connect in db and closing the connection if the function get an error.
All database connections are in a different file, so I export the modules to use in my application and if I need to use in other application just add a reference to that
let QueryDB = {
Query_SelectAll: 'SELECT [COLUMN] \
, [COLUMN] \
, [COLUMN] \
FROM [DATABASE].[dbo].[TABLE_NAME]',
Query_Delete: 'DELETE FROM [DATABASE].[dbo].[TABLE_NAME] WHERE COLUMN = '
};
I put all queries in an object to simplify the use for me.
let ConnectionString = {
user: 'YOUR_DBUSER',
password: '****',
server: '0.0.000.00',
options: {
instance: 'YOURINSTANCE',
database: 'DATABASE_NAME'
}
};
In the server property, I put the server IP, after add the options with instance and database name.
function SQL_Server(Query, ret) {
sql.close();
sql.connect(ConnectionString).then(() => {
console.log("Connected");
return request(Query, ret);
}).catch((error) => {
console.log("Connect error");
console.error(error);
sql.close();
});
}
function request(Query, ret) {
let returning = undefined;
let request = new sql.Request();
(request.query(Query).then((recordset) => {
sql.close();
returning = recordset.recordset;
}).catch((error) => {
console.error(error);
sql.close();
})).then(() => {
if (ret != undefined)
ret(returning);
console.log("Successful object return");
});
}
Those are my connect and request functions.
module.exports.SQL_Server = SQL_Server;
module.exports.QueryDB = QueryDB;
So I export the modules to use the functions.
An example of using:
let DataBase = require("./Connection_Query");
let FuncSql = DataBase.SQL_Server;
let SQL = DataBase.QueryDB;
APP.get(ProjectName + '/Home', (req, resp) => {
FuncSql(SQL.Query_SelectAll, (rec) => {
resp.render("Home", { YourObjects: rec });
});
});
Think that you use this answer to guide you.
you have to write the database instance in config.options.instanceName
var config = {
server: 'localhost\\SQLEXPRESS2008',
database: 'TestingDB'
};
instead:
const config = {
user: '...',
password: '...',
server: 'localhost',
database: 'TestingDB',
options: {
encrypt: false, // Use this if you're on Windows Azure
instanceName: 'SQLEXPRESS2008'
}
};

I am trying to connect to postgres database instance in aws but I can't

I have the following code.
var express = require('express');
var app = express();
var path = require('path');
var pg = require('pg');
var conString = "postgres://user:password#endpoint:5432/StudentRecords";
//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 20 (also configurable)
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
else{
console.log("asdfaf")
}
});
client.connect();
It shows cannot connect to postgres. But when I try connecting from the terminal using
psql --host=endpoint --port=5432 --username xxxxx --password --dbname=StudentRecords
I can connect. Why is the code not working? Error I am getting is:
could not connect to postgres [Error: Connection terminated]

Connection to table denied in SQL Server 2012

I am trying to manipulate a table in SQL Server with node. I've succeeded to connect to the database but when I do a query request I get this error :
SELECT permission was denied on the object Customer
I've tried this command but it didn't work :
USE NodeDB;
GRANT SELECT ON OBJECT::Customer TO test;
GO
This is the code I've written in node :
/*--------------------Connection--------------------------------*/
var sql = require('mssql');
var config = {
user: 'test',
password: '11111',
server: 'ICEFOX-PC\\SQLSQL',
database: 'NodeDB'
}
sql.connect(config, function(err) {
if (err){
throw err ;
} else{
console.log('connected');
}
/*--------------------Connection--------------------------------*/
var request = new sql.Request([config]);
request.query('select * from Customer', function(err, recordset) {
if (err) {
throw err ;
} else {
console.dir(recordset);
});

Resources