how to use multiple database connections in sails.js? - database

I'm new in sails and I want to know that how can I use multiple database connections and use all of them in my app? now I'm using MySQL but I want to add mongo to add some data to it

Yes, you can do this with sails.
If you are using a version < v1
First thing to do is add a connection to each db in the connections.js file located in the config folder and ensure they both have a different name.
For example
someDBServer1: {
adapter: 'sails-mongo'
...
},
someDbServer2: {
adapter: 'sails-mysql',
...
},
Then in each Model, you can set the respective connection. If for example you have your User data stored in one database and your images stored in another.
You can set the connection in the User model like this:
module.exports = {
connection : 'someDBServer1',
attributes: {...
And in the Images model using the other connection:
module.exports = {
connection : 'someMongodbServer2',
attributes: {...
For sails version >= v1
The setup is very similar.
Databases are stored in datastores. Datastores are defined in the Sails config config/datastores.js.
Then as above rather than setting the connection in the specific Model, you set the datastore.
For more info on this see Sails ORM Documentation or Sails v1 ORM Documentation.

You can add all of your adapters in your config/datastores.js, if you want all of your models use a single adapter, then you just need to change the default model settings in config/models.js, if you want to override settings for a particular model, then you need to change the model's definition file.
you can find more informations in the docs here Model settings.

Related

How to set up a database connection from environment in Rocket?

I have following working database connection setup for my Rocket app:
main.rs:
#[database("my_db")]
pub struct DbConn(diesel::PgConnection);
Rocket.toml:
[global.databases]
my_db = { url = "postgres://user:pass#localhost/my_db" }
I would like to set username, password and a database name from the environment. Expected it to be something like ROCKET_MY_DB=postgres://user:pass#localhost/my_db, but it didn't work. Was unable find relevant database example for Rocket.
After a lot of experiments (as there is no specific instructions for the database and I expected something that looked more like a standard approach: ENV_PARAM=conn_string, i.e. in Diesel) I finally figured out that I need to place a complex object into the environment.
The solution is this ugly string:
ROCKET_DATABASES={my_db={url="postgres://user:pass#localhost/my_db"}}
I would like to set username, password and a database name from the environment. Didn't find relevant example for Rocket.
Front page of the doc
Rocket and Rocket libraries are configured via the Rocket.toml file and/or ROCKET_{PARAM} environment variables. For more information on how to configure Rocket, see the configuration section of the guide as well as the config module documentation.
Example just follow link:
All configuration parameters, including extras, can be overridden through environment variables. To override the configuration parameter {param}, use an environment variable named ROCKET_{PARAM}. For instance, to override the "port" configuration parameter, you can run your application with:
ROCKET_PORT=3721 ./your_application
🔧 Configured for development.
=> ...
=> port: 3721 ```

Best way to define Client to be used with localhost vs domain

so I got my Identity Server project up and running, and am setting up my project to publish. Now, when I define my client in the config for IS4, I suppose I will have to set my redirect urls to my publish domain, something like this:
new Client{
...
RedirectUris = { "localhost:5002/signin-oidc", "myclient.com/signin-oidc" }
...
}
Is including the localhost and domain the right way to do this?
I am thinking it would be ok since an attacker would have to have my client secret in order to login. Or is it better to set up two separate clients (eg. 'client' and 'client_local'), and request the appropriate client at startup?
There are two ways:
1) Use Configuration File: You can store the clients in a JSON file and load them during startup. Use different JSON files for different environments.
Example. clients.Development.json for Development and clients.Production.json in Production environment; However, The clients will be In Memory Clients and any changes in clients configuration will require a reboot of your application.
2) Use Persistent Storage: Use a database server to store configuration and operational data. A local database for development and a database for production use.
See this docs, The example uses Entity Framework for persistent storage but you're bound to Entity Framework or any ORM. You can opt to write your own Data Access Layer for IdentityServer. This will allow you to change client configurations without restarting your application as the data will be retrieved from a database.

Azure MobileServices Live/UAT/Dev environments

I have an azure mobile service that will go live at some point. So I need to create UAT and dev versions which would point to the UAT and dev databases. What I am struggling with is how to create these.
The namespace in my live, UAT and Dev databases need to be the same but if I create a new mobile service called myAppName_UAT, it's going to want to use MyAppName_UAT as the namespace and so will not find any of the tables.
Has anyone overcome this problem? Once the product goes live I'll need to be able to test the mobile apps against the Dev db without affecting live which surely must be a common scenario?
Any advice would be very gratefully received.
Edit: What I'm specifically after is how to manage the multiple environments within the Azure Portal. I can deploy all the other components of my UAT environment but I'm stuck on the mobile service.
I am not asking for a way for my applications to switch config files or to migrate data between databases. Does anyone have any experience of running azure applications with multiple components where they ran multiple mobile services?
Do you use a Version Control? For me, you just need to create branches to separate the 'UAT' and 'dev' versions.
About the databases:
You can use web.config transformations to switch the connection string between your databases.
http://msdn.microsoft.com/en-us/library/dd465326.aspx
How do I use Web.Config transform on my connection strings?
=================================================================================
Update:
Ok, now I understood what you want.
Create your two versions of mobile services:
1-Log in Windows Azure Management Portal (http://manage.windowsazure.com)
2-Create your test mobile services (if you already have then, skip this step):
2.1- New -> Compute -> Mobile Services
2.2- Url - MyMobileServicesTest
2.3- Database -> Create a new (test db).
3-Create your production mobile services (if you already have then, skip this step):
2.1- New -> Compute -> Mobile Services
2.2- Url - MyMobileServicesProduction
2.3- Database -> Create a new (production db).
Right now, you have two different versions.
Using Windows Azure SDK:
//public static MobileServiceClient MobileService = new MobileServiceClient(
// "AppUrl",
// "AppKey"
//);
Pay attention: AppUrl will be "MyMobileServicesTest.azure-mobile.net/" or "MyMobileServicesProduction.azure-mobile.net/". The app key, each environment will have it's own. You can store this settings in a config file and switch according to what you are doing.
More information:
http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-dotnet/
Multiple mobile services can share the same database. You only need to specify the same schema name in web.config in each mobile service:
<appSettings>
<add key="MS_MobileServiceName" value="MyAppName" />
</appSettings>
Updated:
The setting above only works in localhost, but not after publishing to live.
Need to do the following trick in order to make it work. Just hard code the schema name into function OnModelCreating. This way the database schema name will not depend on the mobile service name any more:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
string schema = "MyAppName"; // ServiceSettingsDictionary.GetSchemaName();
if (!string.IsNullOrEmpty(schema))
{
modelBuilder.HasDefaultSchema(schema);
}
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}

How to change Play 2 Framework DB configuration at runtime?

We are using Play 2.1.1 and its built-in JPA integration (JPA.em()
etc).
How can we dynamically change the db.pass property? Play.application().configuration() seems
to be immutable as of Play 2.1. (or we're at least not aware of the mutators)
If we are able to change db.pass, how can we reload the DB configuration so that JPA.em() returns an EntityManager using the new password?
What we are trying to avoid is having to recreate the EntityManager using
EntityManagerFactory. We want to continue to let Play manage that in
the JPA helper class.
Background
The system has a default DB configuration for running locally. When deployed to a server, the DB password is dynamically set on the running application using the following script:
#!/bin/bash
stty -echo
read -p "Password: " PASS
stty echo
curl -k https://127.0.0.1:8443/someUrl/pwd --data "password=$PASS"
The application receives this data and then recreates the Hibernate
SessionFactory. Our new Play app will be required to do something
similar.
The key is to use the ConfigFactory to create a new Config entry. This new Config contains an entry for password with the value coming from your http call to your password service.
A new Configuration is created using the new Config, which in turn falls back to the original Config from the original Configuration.
Basically the new password entry supersedes the original.
It sound long winded when you say it, but the code is pretty readable.
public class Global extends GlobalSettings {
// inject http client to make call for password
#Override
public Configuration onLoadConfig(Configuration configuration, File file, ClassLoader classLoader) {
final Config config = ConfigFactory.parseString(String.format("db.default.user=%s", callPasswordService()));
return new Configuration(config.withFallback(configuration.getWrappedConfiguration().underlying()));
}
}
To answer my own question, at first we solved the problem of updating the immutable configuration at runtime by overriding Configuration.onLoadConfig with the following:
If configuration indicates that production.level is PROD
Read the password from stdin
Create a new configuration by converting the old one to a map and building a new one with ConfigFactory.parseMap, with the new parameter as well
Return super.onLoadConfig
However, this still didn't address that the problem of reloading the DB configuration. In the end, my colleague created a Play! plugin which essentially a copy of some JPA classes with the added capability of being reloaded with a Map of configuration properties.
Update
The "hook" is the additional static method which the plugin adds to the JPA class (e.g. reloadWithProperties). This method creates a new data source which is then rebound in JNDI.

Possible to refresh Django connections on the fly?

Is it possible to add a new database connection to Django on the fly?
I have an application that uses multiple databases (django 1.2.1), and while running, it's allowed to create new databases. I'd need to use this new database right away (django.db.connections[db_alias]). Is it possible without server restart? Using module reload here and there?
Thank you for your time.
It is possible... but not recommended...
You can access the current connection handler...
Use something like this:
from django.db import connections
if not alias in connections.databases:
connections.databases[alias] = connections.databases['default'] # Copy 'default'
connections.databases[alias]['NAME'] = alias
Make sure you do not attempt to add a new alias to the databases dictionary while there is ANY database activity on the current thread.
An issue you need to overcome, is that this code will need to be placed somewhere were it will always be touched by the current thread before trying to access the database. I use middleware to achieve this.

Resources