geminiCoder
geminiCoder

Reputation: 2906

How to find out if a class exists on an OrientDB using PyOrient?

How is it possible to find out if a class exists; this allowing the prevention of a 'class x already exists in current database' error message?

I have seen the following Question, which gives answers in Java and SQL. I'm looking for the Python equivalent.

Upvotes: 1

Views: 611

Answers (2)

anber
anber

Reputation: 874

You can use the same query as in the Java example.

import pyorient

className = "MyClass"

database = pyorient.OrientDB("localhost", 2424)
database.db_open(
"DB_name",
"user",
"password"
)

if not database.command("SELECT FROM ( SELECT expand( classes ) FROM metadata:schema ) WHERE name = '%s'" % className):
    print("Create class %s" % className)
    database.command("CREATE CLASS %s EXTENDS V" % className)
else:
    print("Class already exist.")

Upvotes: -1

LucaS
LucaS

Reputation: 1418

I created the following example in pyorient:

MY STRUCTURE:

enter image description here

PyORIENT CODE:

import pyorient

db_name = 'Stack37277880'

print("Connecting to the server...")
client = pyorient.OrientDB("localhost",2424)
session_id = client.connect("root","root")
print("OK - sessionID: ",session_id,"\n")

if client.db_exists( db_name, pyorient.STORAGE_TYPE_PLOCAL ):
    client.db_open(db_name, "root", "root")
    dbClasses = client.command("SELECT name FROM (SELECT expand(classes) FROM metadata:schema)")
    newClass = "MyClass"
    classFound = False
    for idx, val in enumerate(dbClasses):
        if (val.name == newClass):
            classFound = True
            break
    if (classFound != True):
        client.command("CREATE CLASS " + newClass)
        print("Class " + newClass + " correctly created")
    else:
        print("Class " + newClass + " already exists into the DB")

client.db_close() 

First Run Output:

Connecting to the server...
OK - sessionID:  70 

Class MyClass correctly created

OrientDB Studio:

enter image description here

Second Run Output:

Connecting to the server...
OK - sessionID:  74 

Class MyClass already exists into the DB

Hope it helps

Upvotes: 0

Related Questions