// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package nosql.orientdb.doc;

import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.executor.OResultSet;

public class Test3 {
    private static void dump(ODatabaseSession db, String criteria) {
        System.out.println("dumping " + criteria);
        OResultSet rs = db.query("SELECT FROM Order " + criteria);
        while(rs.hasNext()) {
        	ODocument d = (ODocument)rs.next().getRecord().get();
            System.out.println(d.toJSON());
        }
    }
    public static void main(String[] args) {
        // open
    	OrientDB client = new OrientDB("remote:localhost", null);
    	ODatabaseSession db = client.open("test3", "admin", "hemmeligt");
db.query("SELECT FROM Order").forEachRemaining(o -> { o.getRecord().get().delete(); }); 
        // setup
        String s1 = "{ \"id\": 1, \"customer\": \"A A\", \"items\": [ { \"no\": 1, \"name\": \"A good Java book\", \"price\": \"19.95\" } ] }";
        System.out.println(s1);
        ODocument d1 = new ODocument("Order");
        d1.fromJSON(s1);
        db.save(d1);
        String s2 = "{ \"id\": 2, \"customer\": \"B B\", \"items\": [ { \"no\": 1, \"name\": \"ASUS MB\", \"price\": \"249.00\" }, " +
                                                                    "{ \"no\": 1, \"name\": \"i5 CPU\", \"price\": \"299.00\", \"note\": \"handle with care\" }, " +
                                                                    "{ \"no\": 1, \"name\": \"4 GB kit\", \"price\": \"249.00\", \"quantity\": 4} ] }";
        System.out.println(s2);
        ODocument d2 = new ODocument("Order");
        d2.fromJSON(s2);
        db.save(d2);
        // query
        dump(db, ""); // all
        dump(db, "WHERE id = 2"); // where id=2
        dump(db, "WHERE customer = 'A A'"); // where customer='A A'
        dump(db, "WHERE customer LIKE 'A%'"); // where customer like 'A%'
        dump(db, "WHERE items CONTAINS(name = 'i5 CPU')"); // where items.name='i5 CPU'
        dump(db, "WHERE items CONTAINS(name LIKE '%Java%')"); // where items.name like '%Java%'
        dump(db, "WHERE id IN [1,2]"); // where id in (1,2)
        dump(db, "WHERE items CONTAINS(note IS NOT NULL)"); // where exists items.note
        // close
        db.close();
        client.close();
    }
}
