How to initialize a Sequalize object with already defined connections config - sails.js

I have the connections and models config files setup + the models. Similar to this example, and now I need to use a sequelize object reference in my controller, f.e. to make raw queries sequelize.query() or the Sequelize functions (sequelize.fn(...)), but how can I initialize it? All I could find in the docs was how to setup the DB connection completely anew, and I don't need that, because I already have the connection set up and working.
If I require('sequelize') in my controller, then I need to initialize an object, with anew DB parameters (host, username, pswd, etc.). I need just to use a Sequelize object reference of the existing connection, which was setup in the config files. Is that possible?

You can create a 'connection' module which exports the sequelize object and then require that module where you need it
dbConnection.js
...
module.exports = new Sequelize(dbname, null, null, sequelizeOptions)
anyfile.js
var db = require(pathToDbConnection.js)
db.query(...)

Related

AWS CDK - How to use "placeholder" token with Low Level cfn constructs

I am using CDK (in typescript) to define an AWS Timestream DB and a table inside it.
I want to allow AWS to set the name of the database (and avoid hardcoding it). The problem is how to reference that database name in the table construct.
CDK users' will know that the actual database name is not defined until it is created in AWS (which is after the CDK code that defines the table is executed). For this purpose, CDK created the idea of a placeholder Token (my emphasis).
I know that in the higher level CDK constructs, the placeholder Token is already defined. This doesn't seem to be the case for low level cfn constructs.
Here is some sample code to explain:
This code uses the higher level dynamo construct and lambda and works:
const table = new dynamodb.Table(this, id);
const lambda = new lambda.Function(this, id);
lambda.addEnvironment("TABLE_NAME", table.tableName)
console.log(`table Token is: ${table.tableName}`); // prints *like* "${Token[TOKEN.540]}"
This is the code I am writing for AWS Timestream and no token is generated:
const db = new ts.CfnDatabase(this, id);
console.log(`database name is is: ${db.databaseName}`); // prints null
const table = new ts.CfnTable(this, id, {
databaseName: db.databaseName,
});// this will break as databaseName is null
My questions:
Why: why doesn't the lower level construct generate the Token.
How: I think I can create a token and assign it to db.databaseName but I have no clue how to populate that Token with data when the cdk deploy is run.
Any help on sample code to generate the Token and populate it would be greatly appreciated.
You are probably looking for ref instead of databaseName:
const db = new ts.CfnDatabase(this, id);
console.log(`database name is is: ${db.ref}`); // prints null
const table = new ts.CfnTable(this, id, {
databaseName: db.ref,
});
This corresponds 1:1 to the AWS::Timestream::Database CloudFormation resource. As the docs describe, the Ref return value represents the database name.
Background: properties exposed in "CFN resources" (also known as L1 resources), include both the resource properties (as they are configured when the object is initialized) and resource attributes, which is what you are after.

Postgres PGSimpleDataSource changing database name

This is what I am trying, I want to connect to a default admin database, create a new database and immediately switch to it.
Below is my pseudo-code:
// Create a new datasource
dataSource = PGSimpleDataSource()
dataSource.setURL("jdbc:postgresql://mydbserver:5432/admin")
dataSource.setUser("test")
dataSource.setPassword("testing")
// get connection to admin db and create a new database named 'mynewdb'
connection = dataSource.getConnection()
cs = connection.createStatement()
cs.executeUpdate("create database mynewdb")
cs.close()
connection.close()
// switch to the newly created database using the **same datasource**
dataSource.setDatabaseName(mynewdb)
connection_to_new_db = dataSource.getConnection()
ps = connection_to_new_db.preparedStatement()
....start doing transactions on the newly created database...
....start doing transactions on the newly created database...
Above code seems to work fine.
Questions:
is it legal to change the database name on the fly on an existing datasource? Are there any repercussions?
is this the right way to accomplish what I am trying or is there a better way?

can we create two model or controller for same collection in sails js

I am new to sails js. I am using mongodb database. I have users collection. I have created api using sails generate api users it creates Users.js and UsersController.js files. I want to know that can we create another controller or model for the same collection?
I have created User_dummy.js and User_dummyController.js using same command given above. And copied the content of the file Users.js into User_dummy.js and UsersController.js file into User_dummyController.js. But it doesn't work.
Its giving me following error :
Trying to associate a collection attribute to a model that doesn't have a Foreign Key.
I want to make two copies of both model and controller for users collection. Is there any solution or is there any way to create two controller or model.
You should be able to use the tableName model setting (see documentation) to have a shared collection for two or more models.
Users.js/User_dummy.js:
module.exports = {
tableName: 'users',
attributes: {
}
};

Check if database with specified name exists or not

As you may know that whenever we set a new database inside "sails-orientdb adapter" configurations it creates database, now on the creation time of the database of course database will be created if there is no database inside orientdb with this name, now I want to create vertices related to a class you can say those vertices are defaults of my application, whenever new database will be created those defaults will also be created, but when database already exists those defaults will also be skipped.
Now, is there any function like exists() available inside Waterline or Oriento which can check that database with the specified name inside configurations exists or not inside orientdb and return true or false?
There is not a function .exists() but Oriento has a function named .list() which will list all DBs and allows checking if a particular DB is present. To do this from Sails-OrientDB you can use the custom method .getServer() as follows:
// Assume a model named "Post"
Post.getServer()
.list()
.then(function (dbs) {
var dbExists = _.find(dbs, function(db) {
return db.name === 'myDatabaseName';
});
console.log('myDatabaseName exists:', dbExists);
});
This is the logic that Sails-OrientDB uses to determine if the DB exists before creating it: https://github.com/appscot/sails-orientdb/blob/master/lib/connection.js#L604-L608

Preceding any database access with specific command in CakePHP

I'm new to CakePHP and using version 1.3.
How can I dynamically change the 'schema' property as found in DATABASE_CONFIG prior to any database operation? What is the class where I could have the postgres-specific command "set search_path to 'schema_xyz'" executed before any database interaction?
I want to use Postgres' ability to maintain multiple distinct namespaces (aka schema in postgres parlance) within a single database to implement multi-tenancy in my application. That is, every namespace will contain the same set of tables, but evidently with different content. Here, it's important not to understand schema as meaning table metadata, but rather as the postgres-specific concept of namespace where a schema is a container for tables. The exact Postgres command isn't important. What is, is the mechanism by which it can be invoked, and steering clear of Cake's typical meaning of table description, as seen in the SchemaShell. The only place I have found where Cake exposes the concept of namespace is in the database.php file, which is then used when the DB connection is first established. See: api13.cakephp.org/view_source/dbo-postgres/#line-113 (new user link limit, sorry)
if ($this->connection) {
$this->connected = true;
$this->_execute("SET search_path TO " . $config['schema']);
I want to set that search_path before ALL DB queries, not just at connection time as is currently done.
As a proof of concept, I have tried setting $useDbConfig in my models, but according to the debug output where the SQL commands are printed, this only seems to affect a subset of all queries. I've moved this up into app_model.php with the same result. As did augmenting that with creating a db_config instance on the fly and passing to the ConnectionManager through loadDataSource. Maybe I should slap that code in all flavors of before... methods.
I have seen many posts online where people discuss using one of several DB configurations in database.php to use different databases for dev, lab and production environments. But I have a single database with multiple namespaces/schemas. Also, my number of such namespaces will be too high and dynamic to make hardcoding a new variable in database.php practical.
Thus, where is the spot in CakePHP where I could insert something to set the search_path prior to any database command? I'll deal with optimizing that later. Remember that I'm new to Cake, so try to be as specific as you can. Let me know if I can clarify this question.
Thanks in advance. Here's the partially working code snippet:
class AppModel extends Model {
function beforeFind($queryData)
{
App::import("ConnectionManager");
$cm = &ConnectionManager::getInstance();
$namespace = 'xyz_namespace'; //name of the new schema/namespace/search path
$new_db_config_name = 'new_config'; //name for the new DB config to be used in the ConnectionManager
$new_db_config = $cm->config->default; //copy the 'default' DB config into an array
$new_db_config['schema'] = $namespace; //change/add the new schema/namespace/search path
$cm->create($new_db_config_name, $new_db_config); //turn the array into a DbConfig object
$cm->loadDataSource($new_db_config_name); //load the new DbConfig into the ConnectionManager
$this->useDbConfig = $new_db_config_name; //tell the model to new use the Db Config
return $queryData;
}
}
There is a very simple way in PostgreSQL if you want to switch schema per login role:
ALTER ROLE foo SET search_path=bar, public;
ALTER ROLE baz SET search_path=bam, public;
Thus a connection initiated by that role has that search_path set automatically.
If your login names are the same as the desired schema names, there is an even simpler way, I quote the fine manual:
If one of the list items is the special value $user, then the schema
having the name returned by SESSION_USER is substituted, if there is
such a schema. (If not, $user is ignored.)
But be advised that - the fine manual again:
Role-specific variable settings take effect only at login; SET ROLE
and SET SESSION AUTHORIZATION do not process role-specific variable
settings.
If I understand your question correctly, (bear with me, I know little about Postgres but basically I think you mean, reloading the schema whenever the table perspective changes?), here's how to dynamically switch schemas in your controller:
// Model::getDataSource()->configKeyName holds whichever db config you're using
if ($this->Model->getDataSource()->configKeyName != 'default') {
// do something...
$this->loadModel("Special")
$this->Model->table = "extras";
$this->Model->schema(true);
} else {
// predictably, Model::setDataSource($configKey) changes configs
$this->Model->setDataSource("offsite"); // this could be a string variable
}
Or from the model, $this->getDataSource()->configKeyName and $this->schema(true) and so forth. Note $this->schema(true) actually reloads the model schema and registers it with cake. app_model, a component, or config/bootstrap might be an appropriate place for this. I'm not sure where Cake would have defined the search_path the first time, but it would almost certainly be a property of the dataSource object and could be redefined there just like the table name, etc. And then reload Cake's schema to register the changed path. It is necessary to ensure Cake unloads any default it may have picked up, and load the correct schema based on the currently defined table. (It sounds like this may have been the only step you were missing.)
If this does not answer your question or if I misunderstood, let me know. HTH. :)