Pyorient : Querying a vertex in OrientDB - orientdb

this works
data = client.query("SELECT FROM Person WHERE id = '1000'")
print(data)
but this doesn't
results = graph.query(Person, name='Prakash')
print(results)
this throws an error saying
TypeError: query() got an unexpected keyword argument 'name'

Creating a graph db called "pydb", empty, (i use graphic interface with orientdb 2.2.28 in Windows 10) and then, using this code (runned in eclipse), you have the list of animal vertexs:
The result:
The guide is here: https://github.com/orientechnologies/pyorient

Related

Slick codegen not giving any output

I am trying to use the current version of slick and slick-codegen (3.2.0) with a sqlite database. When I try listing the table, I get the names properly. However, when I try to generate classes corresponding to the tables, I do not get any output.
This works:
object TableCodeGenerator extends App
{
val db = Database.forURL("jdbc:sqlite:/home/samik/db/mydb.db", driver = "org.sqlite.JDBC")
val tables = Await.result(db.run(MTable.getTables), 1 second).toList
tables.foreach(println)
}
I get the output below:
MTable(MQName(models),TABLE,null,None,None,None)
MTable(MQName(users),TABLE,null,None,None,None)
However, the following code, run directly in the same way, doesn't work:
object TableCodeGenerator extends App
{
val db = Database.forURL("jdbc:sqlite:/home/samik/db/mydb.db", driver = "org.sqlite.JDBC")
val dbio = SQLiteProfile.createModel(Some(MTable.getTables))
val model = db.run(dbio)
val codegenFuture: Future[SourceCodeGenerator] = model.map(model => new SourceCodeGenerator(model))
codegenFuture.onSuccess
{
case codegen => codegen.writeToFile(
"org.sqlite.JDBC",
"/tmp",
"my.package.dao",
"Tables",
"Tables.scala")
}
}
Meaning, the code runs successfully, but I do not see any output file. Is there anything I am missing?
The above was happening because the underlying code was silently throwing an exception. The reason for this exception was that I was using a "feature" of sqlite where if you don't mention the datatype in schema, sqlite assumes it to be text type. However that creates a problem for the slick code.
More details here. The immediate solution was to fix the schema, but I think this has now been fixed in slick as well.

Realm how to write subquery

I am study about Realm db, this db is nice as compare with core data but I am stuck on one place as follows:
I have two RLMObject in that I created relationship and I want to run join query (sub query) on that, but I can't do that.
first object (table) in Ralm
class Dog : RLMObject
{
dynamic var name = ""
dynamic var age = 0
// create variable of Owner object
dynamic var owner = RLMArray(objectClassName: "Owner")
override class func primaryKey() -> String!{
return "name"
}
}
second object (table) in Ralm
class Owner : RLMObject{
dynamic var myName = ""
}
so I want to fetch only those Dog names which belong with owner name 'ram'
I tried following sub query
var dog = Dog.allObjects().objectsWithPredicate(NSPredicate(format:"SUBQUERY(Owner, $owner, $owner.myName = 'ram')", argumentArray: nil))
but app is crashing with following error
RealTest[1701:17960] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SUBQUERY(owner, $owner, $owner.myName = 'ram')"'
also I search it on net I found that realm.objects but it gave me error about not found.
Thanks in advance!
Your predicate should look like this:
let predicate = NSPredicate(format:"SUBQUERY(Owner, $owner, $owner.myName = 'ram') .#count > 0", argumentArray: nil)
The idea here is to make sure you add .# count > 0 at the end, as the predicate needs to return true or false for it to work.
This can be achieved using a query like:
Dog.allObjects().objectsWhere("ANY owner.myName = 'ram'")
SUBQUERY is only necessary if you have multiple constraints on the target of the relationship that must all be fulfilled by a single row, or if you wish to express a constraint other than ANY / ALL / NONE on the number of rows that match.
That said, as of Realm Objective-C and Swift 0.98.0 SUBQUERY is now supported.
While Realm supports filtering objects via NSPredicate, at this time of writing, Realm's implementation of NSPredicate yet support every single type of keyword that the native Apple frameworks do, including SUBQUERY. Realm provides an NSPredicate cheat sheet on its website, outlining which types of queries it presently supports.
That being said, if you already have an Owner object at this point, you can actually use another Realm method on the Owner object ([RLMObject linkingObjectsOfClass:forProperty:]) to find out which Dog objects are referencing it.
Finally, that realm.objects error is because that syntax is from the native Swift version of Realm, and the code you're using here is the Objective-C version of Realm, bridged over to Swift.
Let me know if you need any more clarification!

AttributeError: 'Bottle' object has no attribute 'template'

Example One
Consider the following:
import bottle
import pymongo
application = bottle.Bottle()
#application.route('/')
def index():
cursor = [ mongodb query here ]
return application.template('page1',{'dbresult':cursor['content']})
Assume that the MongoDB query is correct, and the application is calling the content value of cursor correctly and passing it to the template which is formatted correctly.
The errors I am getting in the logs are to do with being able to use the template() method eg:
AttributeError: 'Bottle' object has no attribute 'template'
Example Two
If I change the corresponding assignment and call to:
application = bottle
application.template
The error is:
TypeError: 'module' object is not callable
Example Three
If I change the corresponding assignment and call to:
application = bottle
#application.route('/')
#application.view('page1.tpl')
return {'dbresult':cursor['content']}
The error is:
TypeError: 'module' object is not callable
Question
What is the correct call to the template() method to use to get Example One working?
To get "Example One" working:
return bottle.template('page1',{'dbresult':cursor['content']})
template() is in the bottle module; just reference it as bottle.template(...).
bottle.template() isn't a method of the bottle.Bottle() application object. It's a function in the bottle module.

Yii RBAC make Users update profile by himself

I'm trying to do this with mongodbauthmanager. I'm follow step by step in Usage section but finally i'm getting PHP warning: Illegal offset type. I had posted this question at Yii Extension before clone to SO:
Please tell me what is wrong?
1// Config
'authManager'=>array(
'class' =>'CMongoDbAuthManager',
'showErrors' => true,
),
2// Create auth items in db
$auth = new CMongoDbAuthManager();
$bizRule = 'return Yii::app()->user->id==$params["User"]->_id;';
$auth->createTask('updateSelf', 'update own information', $bizRule);
//I had tried with $auth->createOperation() but they has the same error
$role = $auth->createRole('user');
$role->addChild('updateSelf');
$auth->save();
and here is result in db
result in db http://i.minus.com/iIpXoBlDxaEfo.png
**3// Checking access in controller ** - UPDATE CODE AND ERROR
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$params = array('User'=>$model);
if (!Yii::app()->user->checkAccess('updateSelf', Yii::app()->user->id,$params) )
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
//another statement ...
}
4// Getting error:
Fatal error : Cannot use object of type MongoId as array in F:\Data\03. Lab\www\yii\framework\web\auth\CAuthManager.php(150) : eval()'d code on line 1
RESOLVED PROBLEM
Base-on the answer of #Willem Renzema, I resolve my problem. Now, I update here and hope it useful for someone have this error.
0// First, config authManager with defaultRoles
'authManager'=>array(
'class'=>'CMongoDbAuthManager',
'showErrors' => true,
'defaultRoles'=> array('user'),//important, this line help we don't need assign role for every user manually
),
1// Fix save id in UserIdentity class
class UserIdentity extends CUserIdentity
{
private $_id;
//...
public function authenticate()
{
//...
$this->_id = (string)$user->_id;//force $this save _id by string, not MongoId object
//...
}
//...
}
2// Fix $bizrule in authe items
($bizrule will run by eval() in checkAccess)
//use _id as string, not MongoId object
$bizRule = 'return Yii::app()->user->id==(string)$params["User"]->_id;';
3// And user checkAccess to authorization
public function actionUpdate($id){
/**
* #var User $model
*/
$model=$this->loadModel($id);
$params = array('User'=>$model);
if (!Yii::app()->user->checkAccess('updateSelf', $params) )
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
//...
}
4// Done, now we can use checkAccess :D
First off, your original use of checkAccess was correct. Using Yii::app()->user->checkAccess() you are using the following definition:
http://www.yiiframework.com/doc/api/1.1/CWebUser#checkAccess-detail
Now, CWebUser's implementation of checkAccess calls CPHPAuthManager's implementation, which is where you encountered your problem with an illegal offset type.
http://www.yiiframework.com/doc/api/1.1/CPhpAuthManager#checkAccess-detail
An Illegal offset type means you are attempting to access an array element by specifying its key (also known as: offset) with a value that doesn't work as a key. This could be another array, an object, null, or possibly something else.
Your stack trace posted on the extensions page reveals that the following line gives the problem:
if(isset($this->_assignments[$userId][$itemName]))
So we have two possibilities for the illegal offset: $userId and $itemName.
Since $itemName is clearly a string, the problem must be with $userId.
(As a side note, the fact that your stack trace revealed surrounding code of this error also revealed that, at least for CPHPAuthManager, you are using a version of Yii that is prior to 1.1.11. Observe that lines 73 and 74 of https://github.com/yiisoft/yii/blob/1.1.11/framework/web/auth/CPhpAuthManager.php do not exist in your file's code.)
At this point I would have guessed that the problem is that the specified user is not logged in, and so Yii::app()->user->id is returning null. However, the new error you encountered when placing Yii::app()->user->id as the 2nd parameter of checkAccess reveals something else.
Since the 2nd parameter is in fact what should be the $params array that appears in your bizRule. Based on the error message, this means that Yii::app()->user->id is returning a mondoId type object.
I was unfamiliar with this type of object, so looked it up:
http://php.net/manual/en/class.mongoid.php
Long story short, you need to force Yii::app()->user->id to return the string value equivalent of this mondoId object. This likely set in your UserIdentity class in the components folder. To force it to be a string, simply place (string) to force a type conversion.
Example:
$this->_id = (string)$User->_id;
Your exact code will vary, based on what is in your UserIdentity class.
Then, restore your checkAccess to the signature you had before, and it should eliminate the Illegal offset error you encountered originally.
Note however that I have not used this extension, and while performing the following actions should fix this issue, it may cause new issues if the extension relies on the fact that Yii::app()->user->id is a mondoId object, and not a string.

MongoDB C# - update using custom strongly-typed objects not allowed?

I am trying to perform an update using strongly-typed objects. For example,
public void setAppointmentPrefs(string UserName, IEnumerable<AppointmentInfo> info)
{
var query = new QueryDocument {{ "ProviderId", UserName}};
var update = Update.Set("Prefs",prefs); // prefs.toList() gives same error
// providerprefs initialized in constructor
providerprefs.Update(query, update);
}
I receive a compiler error saying:Error 14 The best overloaded method match for 'MongoDB.Driver.Builders.Update.Set(string, MongoDB.Bson.BsonValue)' has some invalid arguments
Obviously the Mongo driver will not let me update based on my own object (whether as IEnumerable or prefs.toList()), which seems a contrast from the way it permits me to insert or query with custom objects. Surely I am missing something obvious that would permit me to avoid deserializing, weakly typing then creating a generic BsonDocument!! TIA.
You can do an Update based on your own types! Have you tried using the typed Query and Update builders?
Try something like this:
var query = Query<AppointmentInfo>.EQ(i => i.ProviderId, userName);
var update = Update<AppointmentInfo>.Set(i => i.Prefs, info.Prefs);
Not sure I got the types and everything write from your partial code, but that should give you the general idea.
Let me know if you have any further questions.
I know this has been answered but I for one don't fully understand Roberts answer.
All I did is call the "ToBsonDocument()" method for it to except the object as a parameter
So:
customObject.ToBsonDocument()
If you have an array of objects inside a document:
var query = Query.EQ("_id", ObjectId.Parse(id.ToString()));
var update = Update.Push("ArrayOfObjects", customObject.ToBsonDocument());
collection.Update(query, update);