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
Related
If I have a collections of docs in which I provide the ids (i.e. not the Firestore auto ids), how can I be certain to create a new doc rather than referencing an existing one?
For instance if I have a collection foo with a document id bar, I can reference it as (given db is the injected AngularFirestore service) this.db.doc('foo/bar').
Then later I want to create another foo doc, I can check if it already exists with something like
checkExits(id: string): Observable<boolean> {
const docRef = this.db.doc(`foo/${id}`);
return docRef.snapshotChanges().map(change => change.payload.exists);
}
However in the time that I check that it exists, to creating the doc, isn't it possible that it gets created? Such that when I try to create the new doc, it is instead referencing an existing one and overwriting it? i.e. this.db.doc('foo/bar').set({})
How can I create new docs specifying the id, while avoiding referencing existing docs (and throwing an error if it exists).
You'll want to use a transaction for that. Within the transaction you first call get() on the location, to ensure nothing exists yet. Then you write to the same location, to create the document.
I am new to Breeze.js, but really enjoy it so far. I ran into an issue with updating a database with Breeze.js, when selecting only portion of columns of a model.
When I ran this statement:
$scope.emFac.entityQuery.from('Company');
the company entity matches my EF entity, retrieves all columns, creates entityAspect, and all is working fine when updating database:
However, when I retrieve only portion of corresponding Model's columns, Breeze.js returns anonymous object with specified properties (retrieving data works, but not updating does not), without the entityAspect, which is being used for tracking changes.
Here is the code with select statement:
$scope.emFac.entityQuery.from('Company').select('companyId, displayName');
Is there a way to retrieve only some columns of EF Model columns, and still track changes with Breeze.js, needed for database updates?
As you've discovered, Breeze treats the incoming data as plain objects instead of entities when you use select.
Your choices are:
On the server, Create a CustomerLite or similar object, and have a server endpoint that returns those without the need for select; OR
On the client, get the results from the query and create entities from each object, with status Unchanged
Example of #2:
var entities = [];
em.executeQuery(customerProjectionQuery).then(queryResult => {
queryResult.results.forEach(obj => {
// obj contains values to initialize entity
var entity = em.createEntity(Customer.prototype.entityType, obj, EntityState.Unchanged);
entities.push(entity);
});
})
Either way, you will need to ensure that your saveChanges endpoint on the server can handle saving the truncated Customer objects without wiping out the other fields.
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: {
}
};
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(...)
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. :)