# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

query1 = """query all($a: string)
        {
           all(func: eq(%s, $a)) 
            {
               uid
            }   
        }"""
print(query1%("name"))

# +
import datetime

d=datetime.datetime(1980, 1, 1, 23, 0, 0, 0).isoformat()
print(d)
datetime.datetime.fromtimestamp(1548508162215/1000)

# +
from sagas.ofbiz.entities import OfEntity as e, oc
from sagas.ofbiz.entity_gen import get_dgraph_type
import json

def to_isoformat(datetime_val):
    dt=datetime.datetime.fromtimestamp(datetime_val/1000)
    return dt.isoformat()

def filter_json_val(model, json_val):
    result={}
    for k,v in json_val.items():
        if v is not None:
            if is_dt_field(model, k):
                result[k]=to_isoformat(v)
            else:
                result[k]=v
    return result

def is_dt_field(model, fld_name):
    fld=model.getField(fld_name)
    vt=get_dgraph_type(fld.getType())
    return vt=='datetime'        

val=e().refProduct('GZ-2002')
print(val['createdTxStamp'])
jval=json.loads(e('json').refProduct('GZ-2002'))
print(jval['createdTxStamp'])
print(datetime.datetime.fromtimestamp(jval['createdTxStamp']/1000))

print(to_isoformat(jval['createdTxStamp']))
model=oc.delegator.getModelEntity('Product')
print(filter_json_val(model, jval))
# -

import sagas.ofbiz.entities as ee
ent=ee.entity('Product')
val=ent.record('GZ-2002')
print(ent.to_json(val,True))

schema = """
    mo_name: string @index(exact) .
    mo_relation: uid @reverse .
    mo_total: int .
    mo_last_modified: datetime .
    mo_table: string .
    mo_service: string .
    mo_form_uri: string .
    mo_field: uid .
    mo_type: string .
    mo_mode: string .
    mo_primary: bool .
    mo_primary_keys: [string] @index(term) .    
    """
# print(schema)



from sagas.ofbiz.entities import OfEntity as e, MetaEntity, oc, format
ent_name="Person"
ent=MetaEntity(ent_name)
flds=[str(fld.getName()) for fld in ent.model.getFieldsIterator()]
print(flds)

prikeys=['*' if fld.getIsPk() else ' '  for fld in ent.model.getFieldsIterator()]
print(prikeys)
print(ent.primary)

# +
from sagas.ofbiz.entities import OfEntity as e, MetaEntity, oc, format
from sagas.ofbiz.entity_gen import get_dgraph_type
ent_name="Person"
ent=MetaEntity(ent_name)
flds=[]
for fld in ent.model.getFieldsIterator():
    # print(fld.getName(), fld.getType(), fld.getIsPk(), fld.getIsAutoCreatedInternal())
    if not fld.getIsAutoCreatedInternal():
        flds.append({'name':fld.getName(), 
                     'type':fld.getType(), 
                     'schema_type': get_dgraph_type(fld.getType()),
                     'primary':fld.getIsPk()})

print(flds[:3])
ent_desc={'name':ent_name, 'primary_keys':ent.primary, 'field':flds}
# -

types=['id', 'currency-precise']
for t in types:
    print(get_dgraph_type(t))

# +
from sagas.ofbiz.entities import OfEntity as e, MetaEntity, oc, format
import sagas.ofbiz.entities as es
from sagas.ofbiz.entity_gen import get_dgraph_type

# ents=[str(v) for v in es.all_entities()]
ents=es.all_entities(False)
print(ents[:5])
servs=es.oc.all_service_names()
print(servs[:5])


# +
def deduce_type(a,b):
    src=set([a,b])
    result='string'
    if src==set(['string','int']):
        result='string'
    elif src==set(['int','float']):
        result='float'
    elif src==set(['string','datetime']):
        result='datetime'
    else:
        raise ValueError('cannot reduce: %s-%s', a,b)
    return result

print(deduce_type('string','int'))


# +
def collect_internal_fields(ent_name, fld_mapping):
    ent=MetaEntity(ent_name)
    for fld in ent.model.getFieldsIterator():
        # print(fld.getName(), fld.getType(), fld.getIsPk(), fld.getIsAutoCreatedInternal())
        if fld.getIsAutoCreatedInternal():            
            fld_name=str(fld.getName())
            fld_type=get_dgraph_type(fld.getType())
            fld_mapping[fld_name]=fld_type

def to_schema(var_map):
    all_types=[]
    for k,v in var_map.items():
        all_types.append("%s: %s ."%(k,v))
    schema='\n'.join(all_types)
    return schema

fld_map={}
collect_internal_fields('Person', fld_map)
print(fld_map)
print(to_schema(fld_map))


# +
def collect_fields(ent_name, fld_mapping, skip_fields, messages):
    ent=MetaEntity(ent_name)
    for fld in ent.model.getFieldsIterator():
        # print(fld.getName(), fld.getType(), fld.getIsPk(), fld.getIsAutoCreatedInternal())
        if not fld.getIsAutoCreatedInternal():            
            fld_name=str(fld.getName())
            fld_type=get_dgraph_type(fld.getType())
            if fld_name in fld_mapping:
                if fld_type!=fld_mapping[fld_name]:
                    messages.append("%s's field %s has different field type: %s-%s"%
                         (ent_name, fld_name, fld_type, fld_mapping[fld_name])
                        )
                    skip_fields.append((ent_name, fld_name, fld_type))
                    dtype=deduce_type(fld_type, fld_mapping[fld_name])
                    fld_mapping[fld_name]=dtype
                else:
                    pass
            else:
                fld_mapping[fld_name]=fld_type


fld_mapping={}
skip_fields=[]
messages=[]
for ent in ents:
    collect_fields(ent, fld_mapping, skip_fields, messages)
print('deduce fields', len(skip_fields))
print('total fields', len(fld_mapping))
for sf in skip_fields[:5]:
    print(sf)
for m in messages:
    if 'datetime' in m:
        print(m)    

# +
import pickle
import redis

r = redis.StrictRedis('localhost')
p_mydict = pickle.dumps(fld_mapping)
r.set('entitySchema',p_mydict)
# -

read_dict = r.get('entitySchema')
entity_schema = pickle.loads(read_dict)

print(len(entity_schema))
limit=0
# mo_table: string .
for k,v in entity_schema.items():
    print("%s: %s ."%(k,v))
    limit=limit+1
    if limit>=5:
        break

all_types=[]
for k,v in entity_schema.items():
    all_types.append("%s: %s ."%(k,v))
print(all_types[:5])
schema='\n'.join(all_types)

import sagas.graph.graph_manager as g
gm=g.GraphManager()
gm.reset_schema(schema)

from sagas.ofbiz.entities import oc,finder,OfEntity

StarcoderdataJupyterScriptsDedupFiltered