How to connect to MS SQL in Rails - sql-server

I am attempting to migrate legacy data from a MS SQL database into my Rails Application. I have added configuration in freetds which is connecting properly. In my Gemfile, I have added the tiny_tds and activerecord-sqlserver-adapter, respectively.
I have created a file to house the classes from the legacy database to translate to ActiveRecord:
class LegacyUser < ActiveRecord::Base
establish_connection :legacy
set_table_name 'users'
end
.
.
.
database.yml
legacy:
adapter: sqlserver
mode: odbc
dsn: legacy_db_name
host: db_host_name
database: legacy_db_name
port: 1433
username: username
password: password
Then I have rake tasks to convert the data:
legacy.rake
desc 'migrate users'
task :users => :environment do
require 'lib/tasks/legacy_classes'
LegacyUser.each do |user|
begin
new_user = User.new
new_user.attributes = {
:firstname => user.firstname,
:lastname => user.lastname,
:email => user.email,
:created_at => Time.now,
:updated_at => Time.now
}
new_user.save!
puts "User #{user.id} successfully migrated"
rescue
puts "Error migrating #{user.id}"
end
end
At this point I am just trying to get the rake task to 'connect' to the legacy database.
When I try 'rake users', I get:
rake aborted!
database configuration does not specify adapter
It looks to me like I have clearly specified the adapter. What is the proper way to configure this?
Also as a side question, in my 'classes' file for legacy database tables, should all of those tables mirror the 'new' Rails database schema? Ideally I want to be able to simply connect to various tables in the legacy database and fit them into the new database schema where needed. The associations in the old do not match the new, nor do the naming conventions.
Any help is appreciated. Thanks.
Update
Still experiencing this error. Sadly, the only threads I could find that have had the same error were odd spacing issues in the database.yml file. So I actually took the time to go through and make sure all of the spacing matched my other configurations. Given that it is a vague error I am not really even sure what to check past the instructions for setting up activerecord-sqlserver-adapter.

Got an answer to this here: https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/issues/250
'You can try connecting to your DB like so, this works for us on that branch on Rails 4:'
class LegacyTable < ActiveRecord::Base
establish_connection({
:adapter => "sqlserver",
:host => "host",
:username => "user",
:password => "pass",
:database => "dbname"
})
This solved my issue. Hope it helps someone in the future.

Related

ActiveRecord (w/o Rails): How to configure a connection to an azure database

Note - I have never stood up a ruby app like this from the ground up and I am also very unfamiliar with Azure.
I am trying to connect to an existing DB on hosted on Azure via ActiveRecord. I am using ActiveRecord independently of Rails so any convention magic will be unavailable to me. I am currently unable to connect to the database and am unsure if my code configuration is incorrect, if I haven't configured azure correctly, or perhaps my account doesn't have the correct permissions. With my lack of experience I am just unable to determine which is which.
I am currently getting the Login Failed for user '<username>' error from tiny-tds. I've quadruple checked my username and pass and confirmed it is the same credentials I am using to log into the DB from Azure Data Studio. I have also created an app registration from which I got our client id and secret. I'm pretty sure that using the same url for host and resource is not correct but I'm not sure what resource is tbh. With all that said here is my code snippet.
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlserver',
tenant_id: '<tenant_id>',
client_id: '<client_id>',
client_secret: '<client_secret>',
resource: '<servername>.database.windows.net',
active_directory_domain: '<domain> (got this from the primary domain field on the overview screen in azure portal',
host: '<servername>.database.windows.net',
username: '<username>',
password: '<pass>',
database: '<db name>'
)
class IndividualProfiles < ActiveRecord::Base
self.table_name = 'individual_profiles'
end
def run
puts 'Start'
puts IndividualProfiles.first
puts 'End'
end
run
For reference:
activerecord (4.2.11.3)
activerecord-sqlserver-adapter (4.2.18)
tiny_tds (2.1.5)
freetds (v1.3.16)
Not sure exactly what your issue is here (as I do not use all those additional options) however I did notice you are not passing the azure option (which could be the cause of your failure).
There is a configuration in the activerecord-sqlserver-adapter gem specifically for Azure. This is passed through to TinyTDS and without this configuration the connection will not work.
According to the TinyTDS README
TinyTDS is fully tested with the Azure platform. You must set the azure: true connection option when connecting. This is needed to specify the default database name in the login packet since Azure has no notion of USE [database]. FreeTDS must be compiled with OpenSSL too.
My working configurations look akin to:
connection_options = {
adapter: 'sqlserver',
encoding: 'utf8',
pool: 5,
host: '[server].database.windows.net',
database: [DATABASE_NAME],
port: 1433,
azure: true,
timeout: YOUR_TIMEOUT_VALUE,
username: ENV['SQL_USERNAME'],
password: ENV['SQL_PASSWORD']
}
If this does not work please add the following to your post:
Your ActiveRecord version
Your tiny_tds version
Your FreeTDS Version
For Example I have the following working right now: (among other configurations)
ActiveRecord (6.0.4)
tiny_tds (2.1.5)
FreeTDS (v1.00.27 - TDS version 7.3)

Cakephp 4 MySQL on hosted environment

I have created a Cake solution locally and have uploaded this on my hosting provider's environment. It runs MySQL. I have full access to the respective database but of course not the MySQL main database. If I understand the situation correctly, there are multiple databases in the same environment used by other clients on different domains that I would never see.
The provider has disabled the ability to manage user rights in PHPMyAdmin. Through an admin panel I was able to create a user that is granted INSERT, UPDATE, SELECT and DELETE rights. However, with the specified datasource parameters in appl_local.php, I get the message below when I try to add a new user to the database through the users/add page. For security reasons I have marked the name of the user with asterisks in the code below.
Could it be that I have to more specifically explain on which database we are trying to execute this?
Is there a way to tell the system to always specify the database when asking for a table? For example "SELECT * FROM database_name.users" instead of just "SELECT * FROM users"? I ask this because in the message below it does not specify which database was accessed when this error was raised, only the command, the user, the table and the source code file and line number.
Or is there some schema that needs to be specified when working in a shared environment?
2021-01-07 10:39:00 Error: [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user '******'#'localhost' for table 'users' in /home/multigra/domains/multi-grade.nl/public_html/content/vendor/cakephp/cakephp/src/Database/Statement/MysqlStatement.php on line 39
'default' => [
'host' => 'localhost',
/*
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
'port' => '3306',
'username' => '******',
'password' => '******',
'database' => '******',
/**
* If not using the default 'public' schema with the PostgreSQL driver
* set it here.
*/
//'schema' => 'myapp',
/**
* You can use a DSN string to set the entire configuration
*/
'url' => env('DATABASE_URL', null),
],
This was an overight from my end. I had specified the location of information a little too much in order to learn about specifying databases when data is spread over different databases. Because the production environment connects to a different database, the requested table was not found at all. The error "SELECT command denied to user '******'#'localhost' for table 'users'" did not point me in that direction. I thought it was a permission issue. Instead, the table was not found in the database and that's why the SELECT statement failed.

Why i can not able to access my rails application db after establishing new connection to wordpress db manually?

I have a rails 4.2 application with postgres database which is running. I have requirement to connect with other databases (word_press_sites) on demand basis.
I have tried the below code this into rails console:
ActiveRecord::Base.establish_connection(
adapter: "mysql2",
host: ENV["HOST"],
username: ENV["USERNAME"],
password: ENV["PASSWORD"],
database: ENV["DB_NAME"]
)
above code results,
No error, connected to the word_press database_tables.
1) If am trying to access the table by calling User.all in my rails application db i can not able to access which is throwing an error.
After opening the rails console you can check
ActiveRecord::Base.connection.current_database
This will give the current db info,Then try the script you have given
ActiveRecord::Base.establish_connection(
adapter: "mysql2",
host: ENV["HOST"],
username: ENV["USERNAME"],
password: ENV["PASSWORD"],
database: ENV["DB_NAME"]
)
Now try the same command
ActiveRecord::Base.connection.current_database
This will give the newly connected ActiveRecord connection
Which means Active record is shifted into newly connected wordpress database so that you can not able to access the table in your rails application database
If you want to revert back to your rails app db you can do this
ActiveRecord::Base.remove_connection( ActiveRecord::Base)
Let me know if you need more information

laravel 4 local developing but I want to use a remote database

I have set up xampp server where I am developing a laravel app:
Every day (when I make an update to my app) I have to export and import the SQL from the database. That takes a lot of time if I have worked on 10 apps that day :(
Is there a way I can use the online database with a local test version of laravel?
I am using shared hosting and not migrations. I insert tables myself.
Online I see a tab:
access hosts: 'localhost'
I can add a host, but what name should I add and how can I get laravel to access this host?
Could it be 'subdomain.mywebsitename.nl/hostname'?
I'm too scared my app will crash if I change it :s
This i tried this after the solution i got:
I filled in a host. This is the same url i fill in my adress bar.
'host' => 'http://safetyanalyse.nl:2222/',
'host' => 'http://safetyanalyse.nl',
Both options do not work :( Do i have to put the port number somewhere else?
I also have this error:
SQLSTATE[HY000] [1130] Host 'D97A1650.cm-3-3a.dynamic.ziggo.nl' is not allowed to connect to this MySQL server
Step 2 (next i tried this).
In the error it says something about the host, i tried filling in this host.
'host' => 'D97A1650.cm-3-3a.dynamic.ziggo.nl',
Now i get the error:
SQLSTATE[HY000] [1045] Access denied for user 'safety_cert-user'#'d97a1650.cm-3-3a.dynamic.ziggo.nl' (using password: YES)
Try to use domain name as host, that should work.
Also, look for port, if specified.
All this information should be provided to you is hosting control panel. If not, I would change hosting provider.
Edit
Define your host without protocol.
In your app/config/database.phpset
'host' => 'safetyanalyse.nl',

Connecting Ruby on Rails to an External Database

I have an MSSQL external DB and I need to connect to it.
I made a new entry in the database.yml
external_database:
adapter: sqlserver
host: xxx.xxx.xxx.xxx
database: Trader
username: name
password: pw
timeout : 5000
and made a model file in app/models/database.rb
class Database < ActiveRecord::Base
establish_connection(:external_database)
self.table_name = 'dbo.Trade'
end
What models/controllers do I need to access something in my database? I have no idea even if I'm connected properly to the database.
There is this case where a guy uses PHP, but this seems to eliminate the point of Ruby.
This link just shows errors after completion in the view where you do the actual value retrieving.

Resources