/*
Example:

(owner:ENTITY:table {id: {0}})
774237
protected static void appendEntityNode(String alias, EntityKeyMetadata entityKeyMetadata, StringBuilder queryBuilder) {
		appendEntityNode( alias, entityKeyMetadata, queryBuilder, 0 );
	}
239572
private static String initRemoveEntityQuery(EntityKeyMetadata entityKeyMetadata) {
		StringBuilder queryBuilder = new StringBuilder( "MATCH " );
		appendEntityNode( "n", entityKeyMetadata, queryBuilder );
		queryBuilder.append( " OPTIONAL MATCH (n)-[r]->(e:EMBEDDED), path=(e)-[*0..]->(:EMBEDDED) " );
		queryBuilder.append( " DELETE r " );
		queryBuilder.append( " FOREACH (er IN relationships(path) | DELETE er) " );
		queryBuilder.append( " FOREACH (en IN nodes(path) | DELETE en) " );
		queryBuilder.append( " WITH n " );
		queryBuilder.append( " OPTIONAL MATCH (n)-[r]-() " );
		queryBuilder.append( " DELETE r,n " );
		return queryBuilder.toString();
	}
322302
private void buildEntityFromCursor(Object entity, HashMap obj, EntityType entityType)
    {
        Iterator<Attribute> iter = entityType.getAttributes().iterator();
        while (iter.hasNext())
        {
            Attribute attribute = iter.next();
            Field field = (Field) attribute.getJavaMember();
            if (field.isAnnotationPresent(Id.class))
            {
                PropertyAccessorHelper.set(entity, field, obj.get(ID));
            }
            else
            {
                PropertyAccessorHelper.set(entity, field, obj.get(((AbstractAttribute) attribute).getJPAColumnName()));
            }

        }
    }
855288
def build_ownership_map(table, key_from_row, value_from_row):
    
    return _build_ownership_map_from_rows(
        sa.select(table.c).execute().fetchall(),
        key_from_row,
        value_from_row,
    )
534945
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
        Object columnValue, Class entityClazz) {
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        return getColumnsById(schemaName, tableName, columnName,
            ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), columnValue,
            metadata.getIdAttribute().getBindableJavaType()).toArray();
    }
848572
public function primaryWhere(Entity $entity, $data, $table)
    {
        $primaryKeys = $entity->getRepository()->getCache()->getTablePrimaryKeys($table);

        if (strpos($table, '_i18n')) {
            $primaryKeys = ['id', 'language_id'];
        } elseif (strpos($table, '_p17n')) {
            $primaryKeys = ['id', 'user_group_id'];
        }

        foreach ($primaryKeys as $primaryKey) {
            $this->where('`' . $primaryKey . '`', $data[$primaryKey]);
        }
    }
650584
function getByIdQuery(modelInstance) {
    const modelClass = modelInstance.getClass();
    const { idAttribute, modelName } = modelClass;

    return {
        table: modelName,
        clauses: [
            {
                type: FILTER,
                payload: {
                    [idAttribute]: modelInstance.getId(),
                },
            },
        ],
    };
}
728241
private Entity fixEntity(Entity entity){
		if(null == entity){
			entity = Entity.create(tableName);
		}else if(StrUtil.isBlank(entity.getTableName())){
			entity.setTableName(tableName);
		}
		return entity;
	}
1237699
function _old_MetaForeignKeys($table, $owner=false, $upper=false)
	{
		$sql = 'SELECT t.tgargs as args
		FROM
		pg_trigger t,pg_class c,pg_proc p
		WHERE
		t.tgenabled AND
		t.tgrelid = c.oid AND
		t.tgfoid = p.oid AND
		p.proname = \'RI_FKey_check_ins\' AND
		c.relname = \''.strtolower($table).'\'
		ORDER BY
			t.tgrelid';

		$rs = $this->Execute($sql);

		if (!$rs || $rs->EOF) return false;

		$arr = $rs->GetArray();
		$a = array();
		foreach($arr as $v) {
			$data = explode(chr(0), $v['args']);
			$size = count($data)-1; //-1 because the last node is empty
			for($i = 4; $i < $size; $i++) {
				if ($upper)
					$a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]);
				else
					$a[$data[2]][] = $data[$i].'='.$data[++$i];
			}
		}
		return $a;
	}
375764
private boolean ownerCanReadTable(String ownerId, String table) {
        return _internalAuthorizer.hasPermissionById(ownerId, getReadPermission(table));
    }
1261303
function Query(state, entity) {
        /**
         * Primary key ids to filter records by. It is used for filtering records
         * direct key lookup when a user is trying to fetch records by its
         * primary key.
         *
         * It should not be used if there is a logic which prevents index usage, for
         * example, an "or" condition which already requires a full scan of records.
         */
        this.idFilter = null;
        /**
         * Whether to use `idFilter` key lookup. True if there is a logic which
         * prevents index usage, for example, an "or" condition which already
         * requires full scan.
         */
        this.cancelIdFilter = false;
        /**
         * Primary key ids to filter joined records. It is used for filtering
         * records direct key lookup. It should not be cancelled, because it
         * is free from the effects of normal where methods.
         */
        this.joinedIdFilter = null;
        /**
         * The where constraints for the query.
         */
        this.wheres = [];
        /**
         * The has constraints for the query.
         */
        this.have = [];
        /**
         * The orders of the query result.
         */
        this.orders = [];
        /**
         * Number of results to skip.
         */
        this.offsetNumber = 0;
        /**
         * Maximum number of records to return.
         *
         * We use polyfill of `Number.MAX_SAFE_INTEGER` for IE11 here.
         */
        this.limitNumber = Math.pow(2, 53) - 1;
        /**
         * The relationships that should be eager loaded with the result.
         */
        this.load = {};
        this.rootState = state;
        this.state = state[entity];
        this.entity = entity;
        this.model = this.getModel(entity);
        this.module = this.getModule(entity);
        this.hook = new Hook(this);
    }
1062533
private static String initMatchOwnerEntityNode(EntityKeyMetadata ownerEntityKeyMetadata) {
		StringBuilder queryBuilder = new StringBuilder();
		appendMatchOwnerEntityNode( queryBuilder, ownerEntityKeyMetadata );
		return queryBuilder.toString();
	}
375626
private void setEntityIdValue(final Object entity, final BigDecimal id, final MappingColumn column) {
		Class<?> rawType = column.getJavaType().getRawType();
		if (int.class.equals(rawType) || Integer.class.equals(rawType)) {
			column.setValue(entity, id.intValue());
		} else if (long.class.equals(rawType) || Long.class.equals(rawType)) {
			column.setValue(entity, id.longValue());
		} else if (BigInteger.class.equals(rawType)) {
			column.setValue(entity, id.toBigInteger());
		} else if (BigDecimal.class.equals(rawType)) {
			column.setValue(entity, id);
		} else if (String.class.equals(rawType)) {
			column.setValue(entity, id.toPlainString());
		} else {
			throw new UroborosqlRuntimeException(
					"Column is not correct as ID type. column=" + column.getCamelName() + ", type=" + rawType);
		}
	}
869059
function createIndexes() {
            // create listed indexes if they don't already exist.
            return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) {
                var entity = CRUD.EntityManager.entities[entityName];
                if (('indexes' in entity)) {
                    return Promise.all(entity.indexes.map(function(index) {
                        var indexName = index.replace(/\W/g, '') + '_idx';
                        if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) {
                            return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) {
                                CRUD.log("index created: ", entity.table, index, indexName);
                                if (!(entity.table in indexes)) {
                                    indexes[entity.table] = [];
                                }
                                indexes[entity.table].push(indexName);
                                return;
                            });
                        }
                        return;
                    }));
                }
            }));
        }
787032
function MetaPrimaryKeys($table, $owner = false)
	{
		$sql = "SELECT c.column_name " .
			   "FROM syscolumn c, systable t " .
			   "WHERE t.table_name='$table' AND c.table_id=t.table_id " .
			   "AND t.table_type='BASE' " .
			   "AND c.pkey = 'Y' " .
			   "ORDER BY c.column_id";

		$a = $this->GetCol($sql);
		if ($a && sizeof($a)>0) return $a;
		return false;
	}
149732
function createEntity(html, id) {
    let $ = parser.load(html)

    let table = $('tr.past')

    let states = utils.tableParser(table, {
        date: {
            idx: 3,
            mandatory: true
        },
        hours: {
            idx: 5,
            mandatory: true
        },
        state: {
            idx: 7,
            mandatory: true
        },
        area: {
            idx: 9,
            mandatory: false
        }
    }).map(line => {
        let d = line.date + ' ' + line.hours
        return {
            date: moment.tz(d, "DD/MM/YYYY HH:mm", zone).format(),
            state: line.state,
            area: line.area
        }
    })

    return new EntityInfo({
        id: id,
        states: states
    })
}
253102
function resolveEntityOrId(entityOrId, entities, schema) {
  const key = schema.key;

  let entity = entityOrId;
  let id = entityOrId;

  if (isObject(entityOrId)) {
    const mutableEntity = isImmutable(entity) ? entity.toJS() : entity;
    id = schema.getId(mutableEntity) || getIn(entity, ['id']);
  } else {
    entity = getIn(entities, [key, id]);
  }

  return { entity, id };
}