Connecting to postgresql database - scala

I keep getting an authentication error when trying to connect to a postgresql database. Here is the specific error:
[error] c.j.b.h.AbstractConnectionHook - Failed to obtain initial connection Sleeping for 0ms and trying again. Attempts left: 0. Exception: null.Message:FATAL: password authentication failed for user
I've checked and double checked the username and password, so this is not the issue. I was able to successfully connect using psql to this very same database. Here is what my application.conf looks like
# Database configuration
# ~~~~~
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#
# db.default.driver=org.h2.Driver
# db.default.url="jdbc:h2:mem:play"
# db.default.user=sa
# db.default.password=""
#Database configuration using PostgreSQL database engine
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://website.com/database"
db.default.user="username"
db.default.password="password")
# Evolutions
# ~~~~~
# You can disable evolutions if needed
# evolutionplugin=disabled
# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/),
# by providing an application-logger.xml file in the conf directory.
# Root logger:
logger.root=ERROR
# Logger used by the framework:
logger.play=INFO
# Logger provided to your application:
logger.application=DEBUG
68,0-1 Bot
Thanks for the insight!

db.default.password="password")
the ) is a typing error?
If not, remove it and try again.

db.default.driver="org.postgresql.Driver"
db.default.url="postgres://username:password#localhost:5432/mydb"
This works fine for me, I don't event use the db.default.user and db.default.password

Related

Akka Projection configuration for a JDBC database connection

In Akka Projection’s documentation under offsetting in a relational database with JDBC, there is no information about how and where the configuration for establishing a connection to the relational database used should be included. I mean configs such as the username, password, or the url.
In the documentation under offset in a relational database with Slick, the following configuration is provided for the database connection, which is unclear whether it can be used for JDBC as well:
# add here your Slick db settings
db {
# url = "jdbc:h2:mem:test1"
# driver = org.h2.Driver
# connectionPool = disabled
# keepAliveConnection = true
}
How and where should I specify the JDBC connection parameters?
https://doc.akka.io/docs/akka-projection/current/jdbc.html#defining-a-jdbcsession
The following line in the Scala code snippet is where you can specify connection parameters:
val c = DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")

Quarkus: Datasource '<default>': FATAL: no pg_hba.conf entry for host

I wrote a Quarkus JPA/Hibernate app with PostgreSQL DB perfectly working with a JVM - run by 'quarkusDev' gradle task.
When I compile the native application with
#!/usr/bin/env bash
export QUARKUS_PROFILE=****
export PG_USERNAME=*****
export PG_PASSWORD=*****
export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
./gradlew build -Dquarkus.package.type=native
the compilation goes fine, but when I run the native image I get:
14:41:23 WARN [io.ag.pool] Datasource '<default>': FATAL: no pg_hba.conf entry for host "***.***.***.***", user "xxxxxxxxxxxxxx", database "*****", SSL on
14:41:23 WARN [or.hi.en.jd.sp.SqlExceptionHelper] SQL Error: 0, SQLState: 28000
14:41:23 ERROR [or.hi.en.jd.sp.SqlExceptionHelper] FATAL: no pg_hba.conf entry for host "***.***.***.***", user "xxxxxxxxxxxxxx", database "*****", SSL on
14:41:23 ERROR [io.qu.application] Failed to start application: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
I tried to add a pg_hba.conf file:
# TYPE DATABASE USER ADDRESS METHOD
host all all 0.0.0.0/0 md5
and put it to
/src/main/resources
and/or to the native image directory, but without luck.
Also, I configured the resources for my native image adding a 'resources-config.json' to '/src/main/resources':
{
"resources": [
{
"pattern": ".*\\.yaml$"
},
{
"pattern": ".*\\.conf$"
},
{
"pattern": ".*\\.txt$"
},
{
"pattern": ".*\\.html$"
}
]
}
I added the following line to 'application.yml'
quarkus:
native:
additional-build-args: -H:ResourceConfigurationFiles=resources-config.json
But even doing so, the pga_hba.conf is not found, and when run, the native image keeps on complaining.
The issue is with the pg_hba.conf being used by the Postgres server. You need to find it and add an entry that will match the connection parameters you are sending to the server.
It turned out that I missed to pass environment variables to the executable.
Of course - obvious after realizing what the problem was! - you not only need to pass DB Environment Variables when you compile the native image - so the tests can be run - but you also need to pass them when you launch it.
So, a script like this solves the issue:
#!/usr/bin/env bash
export PG_USERNAME=*****
export PG_PASSWORD=*****
./build/my-native-image.runner

Spring data configuration for mongodb

I am using spring data for storing and fetching records from the database. Initially the database was MySQL, but now I want to configure the same application for mongodb. Please the application resource properties for MysQL.
# ===============================
# = DATA SOURCE
# ===============================
# Connection url for the database connection
spring.datasource.url = jdbc:mysql://localhost:27017/purchase_books
# Username and password
spring.datasource.username = root
spring.datasource.password = root
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in the project
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Can anyone please tell the configuration changes in case of mongodb ?
MySQL is an RDBMS and MongoDB is an Document Database.
Hibernate supports NOSQL Database in the form OGM (Object/Grid Mapper), Documentation on OGM http://docs.jboss.org/hibernate/ogm/4.2/reference/en-US/html/
Refer the below example for Spring, Hibernate and MongoDB
https://pragmaticintegrator.wordpress.com/2011/07/14/use-spring-and-hibernate-with-mongodb/
Moreover if you are using spring and if you want to remove Hibernate you can go for Spring MongoTemplate
Refer the sample in the below url
https://spring.io/guides/gs/accessing-data-mongodb/
spring.data.mongodb.uri=mongodb://localhost:27017/<database name>
spring.datasource.username= <username>
spring.datasource.password= <password>
#OR
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=<database name>
spring.data.mongodb.username=<username>
spring.data.mongodb.password=<password>

Unable to connect to MS-SQL with ISQL

First post on StackExchange - please go easy :)
I have setup ODBC in Centos 6 in order to perform ms-sql queries from my Asterisk installation.
My Config files are:
/etc/odbc.ini
[asterisk-connector]
Description = MS SQL connection to 'asterisk' database
Driver = /usr/lib64/libtdsodbc.so
Setup = /usr/lib64/libtdsS.so
Servername = SQL2
Port = 1433
Username = MyUsername
Password = MyPassword
TDS_Version = 7.0
/etc/odbcinst.ini
[odbc-test]
Description = TDS connection
Driver = /usr/lib64/libtdsodbc.so
Setup = /usr/lib64/libtdsS.so
UsageCount = 1
FileUsage = 1
/etc/asterisk/res_odbc.conf
[asterisk-connector]
enabled => yes
dsn => asterisk-connector
username => MyUsername
password => MyPassword
pooling => no
limit =>
pre-connect => yes
I am able to connect via ISQL when I pass in the password and username:
[root#TestVM etc]# isql -v asterisk-connector MyUsername MyPassword
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>
..but I should be able to connect without the username / password. All that returns is:
[root#TestVM etc]# isql -v asterisk-connector
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[01000][unixODBC][FreeTDS][SQL Server]Adaptive Server connection failed
[ISQL]ERROR: Could not SQLConnect
It is as if ISQL cannot read the username and password from the config files.
I need to be able to perform MS-SQL lookups from within the Asterisk dialplan, but for that to happen I must be able to call ISQL with just the data source name and can't pass in the authentication parameters.
All the guides I've read online state that I should be able to connect with just the
isql -v asterisk-connector
command, but that's not happening for me.
I've been pulling my hair out for a few days on this, so any help or pointers in the right direction would be much appreciated.
Thanks in advance.
Edit:
I have turned on logging, and may have a clue. The username and password definitely aren't being passed in. Look:
[ODBC][27557][1455205133.129690][SQLConnect.c][3614]
Entry:
Connection = 0xac3080
Server Name = [asterisk-connector][length = 18 (SQL_NTS)]
User Name = [NULL]
Authentication = [NULL]
UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE'
DIAG [01000] [FreeTDS][SQL Server]Adaptive Server connection failed
DIAG [S1000] [FreeTDS][SQL Server]Unable to connect to data source
So User Name and Authentication here are [NULL]. It's obviously not picking up the username / password in odbc.ini or res_odbc.conf, but the question is why. I'll keep investigating :)
Edit2:
The OSQL utility returns:
[root#TestVM etc]# osql -S SQL2 -U MyUsername -P MyPassword
checking shared odbc libraries linked to isql for default directories...
strings: '': No such file
trying /tmp/sqlH ... no
trying /tmp/sqlL ... no
trying /etc ... OK
checking odbc.ini files
reading /root/.odbc.ini
[SQL2] not found in /root/.odbc.ini
reading /etc/odbc.ini
[SQL2] found in /etc/odbc.ini
found this section:
looking for driver for DSN [SQL2] in /etc/odbc.ini
no driver mentioned for [SQL2] in odbc.ini
looking for driver for DSN [default] in /etc/odbc.ini
osql: error: no driver found for [SQL2] in odbc.ini
I would replace "Username" with "UID" and "Password" with "PWD" in your odbc.ini.... from FreeTDS Manual - Chapter 4 - Preparing ODBC:
The original ODBC solution to this conundrum employed the odbc.ini file. odbc.ini stored information about a server, known generically as a Data Source Name (DSN). ODBC applications connected to the server by calling the function SQLConnect(DSN, UID, PWD), where DSN is the Data Source Name entry in odbc.ini, UID is the username, and PWD the password. Any and all information about the DSN was kept in odbc.ini. And all was right with the world.
The ODBC 3.0 specification introduced a new function: SQLDriverConnect. The connection attributes are provided as a single argument, a string of concatenated name-value pairs. SQLDriverConnect subsumed the functionality of SQLConnect, in that the name-value pair string allowed the caller to pass — in addition the the original DSN, UID, and PWD — any other parameters the driver could accept. Moreover, the application can specify which driver to use. In effect, it became possible to specify the entire set of DSN properties as parameters to SQLDriverConnect, obviating the need for odbc.ini. This led to the use of the so-called DSN-less configuration, a setup with no odbc.ini.
Ok, so I solved it (pretty much). The password and username in my odbc files were being ignored. Because I was calling the DB queries from Asterisk, I was using a file called res_odbc.ini too. This contained my username and password also, and when I run the query from Asterisk, it conencts and returns the correct result.
In case it helps, here is my final working configuration.
odbc.ini
[asterisk-connector]
Description = MS SQL connection to asterisk database
driver = /usr/lib64/libtdsodbc.so
servername = SQL2
Port = 1433
User = MyUsername
Password = MyPassword
odbcinst.ini
[FreeTDS]
Description = TDS connection
Driver = /usr/lib64/libtdsodbc.so
UsageCount = 1
[ODBC]
trace = Yes
TraceFile = /tmp/sql.log
ForceTrace = Yes
freetds.conf
# $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".
# Global settings are overridden by those in a database
# server specific section
[global]
# TDS protocol version
; tds version = 4.2
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
dump file = /tmp/freetds.log
; debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
# A typical Sybase server
[egServer50]
host = symachine.domain.com
port = 5000
tds version = 5.0
# A typical Microsoft server
[SQL2]
host = 192.168.1.59
port = 1433
tds version = 8.0
res_odbc.conf
[asterisk-connector]
enabled = yes
dsn = asterisk-connector
username = MyUsername
password = MyPassword
pooling = no
limit = 1
pre-connect = yes
Remember if you are using Centos 64 bit to modify the driver path to lib64. Most of the guides online have the wrong (for 64 bit) paths.
Good luck - it's a headache :)
I contacted the Nick Gorham the developer of unixODBC about this exact issue and he confirmed that isql is not reading the username/password from the config file
Hi Nick,
I think unixODBC is a great project but I was surprised to see that it
is insecure (or at least I don’t know how to use it properly).
When I connect to the database using the isql I have to type in the
password. On a shared server this is insecure because the
$ ps –aux
Command shows the password in clear.
Is there a fix for that? Can I put the password in a file readable
only by my user?
Thank you for your help.
The answer:
Hi,
It depends on the driver. Some can read the user and password from the
odbc.ini or ~/.odbc.ini file so you can store the password there.
isql is only designed as a simple test app, there is nothing stopping
you from modifying ilsq to pull the user and password from a file of
your choice, decrypting it if needed.
I was having a slightly different issue, but my google search lead me here. When trying to connect through isql, I was getting Login failed for user '' even though I had specified a user in my odbc.ini file
[SQLSERVER_SAMPLE]
Driver=ODBC Driver 17 for SQL Server
Server=SERVER
Database=DATABASE
Trusted_Connection=no
UID=USER
PWD=PASSWORD
I tried both UID and User, but both gave the same error. After reading #Andrei Sura's solution, I figured out that the username and password were being ignored.
My solution was to run isql -v SQLSERVER_SAMPLE USER PASSWORD even though the username and password were specified in the odbc.ini file - and it connected.

Mongoid sessions not found

Trying out a Sinatra | Mongoid 3. I run into the following error, whenever I attempt to save to the database.
Mongoid::Errors::NoSessionsConfig:
Problem:
No sessions configuration provided.
Summary:
Mongoid's configuration requires that you provide details about each session that can be connected to, and requires in the sessions config at least 1 default session to exist.
Resolution:
Double check your mongoid.yml to make sure that you have a top-level sessions key with at least 1 default session configuration for it. You can regenerate a new mongoid.yml for assistance via `rails g mongoid:config`.
Example:
development:
sessions:
default:
database: mongoid_dev
hosts:
- localhost:27017
from /Users/rhodee/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/mongoid-3.0.13/lib/mongoid/sessions/factory.rb:61:in `create_session'
I've already confirmed the following:
Mongoid.yml file is loaded
The hash contains correct environment and db name
Using pry the return value from the Mongoid.load! method returns:
=> {"sessions"=>
{"default"=>
{"database"=>"bluster",
"hosts"=>["localhost:27017"],
"options"=>{"consistency"=>"strong "}}}}
If it's any help check, I've added the app.rb file and mongoid.yml file as well.
App.rb
require 'sinatra'
require 'mongoid'
require 'pry'
require 'routes'
require 'location'
configure :development do
enable :logging, :dump_errors, :run, :sessions
Mongoid.load!(File.join(File.dirname(__FILE__), "config", "mongoid.yml"))
end
Mongoid.yml
development:
sessions:
default:
database: bluster
hosts:
- localhost:27017
options:
consistency: strong 
require 'sinatra'
require 'mongoid'
require 'pry'
require 'routes'
configure :development do
enable :logging, :dump_errors, :run, :sessions
Mongoid.load!(File.join(File.dirname(__FILE__), "config", "mongoid.yml"))
end
get '/db' do
"db: " << Mongoid.default_session[:moped].database.inspect
end
I put together an example, and it is working just fine for me. Probably your problem is something else, like the config file not having read access or something else. Anyways my config file is identical as yours and this is my sinatra file, and it works fine.