Check if the instance is a managed entity instance belonging to the
current persistence context.
502141
boolean contains(Object entity)
    {
        Node node = getPersistenceCache().getMainCache().getNodeFromCache(entity, getMetadata(entity.getClass()), this);
        return node != null && node.isInState(ManagedState.class);
    }
677933
public boolean hasChanged(Object entity) {
        DocumentInfo documentInfo = documentsByEntity.get(entity);

        if (documentInfo == null) {
            return false;
        }

        ObjectNode document = entityToJson.convertEntityToJson(entity, documentInfo);
        return entityChanged(document, documentInfo, null);
    }
485753
private ISMgr findInstanceStateManager(Object instance) {
		Class<?> clazz = typeDescriptor.getReloadableType().getClazz();
		try {
			Field fieldAccessorField = clazz.getField(Constants.fInstanceFieldsName);
			if (fieldAccessorField == null) {
				throw new IllegalStateException("Cant find field accessor for type " + clazz.getName());
			}
			ISMgr stateManager = (ISMgr) fieldAccessorField.get(instance);
			if (stateManager == null) {
				// Looks to not have been initialized yet, this can happen if a non standard ctor was used.
				// We could push this step into the generated ctors...
				ISMgr instanceStateManager = new ISMgr(instance, typeDescriptor.getReloadableType());
				fieldAccessorField.set(instance, instanceStateManager);
				stateManager = (ISMgr) fieldAccessorField.get(instance);
				// For some reason it didn't stick!
				if (stateManager == null) {
					throw new IllegalStateException("The class '" + clazz.getName()
							+ "' has a null instance state manager object, instance is " + instance);
				}
			}
			return stateManager;
		}
		catch (Exception e) {
			throw new IllegalStateException("Unexpectedly unable to find instance state manager on class "
					+ clazz.getName(), e);
		}
	}
762705
private Map<String, EntityMetadata> getEntityMetadataCol(ApplicationMetadata appMetadata, String persistenceUnit)
    {
        Metamodel metaModel = appMetadata.getMetamodel(persistenceUnit);
        Map<String, EntityMetadata> entityMetadataMap = ((MetamodelImpl) metaModel).getEntityMetadataMap();
        return entityMetadataMap;
    }
597131
protected boolean isUnidirectionalOneToMany(PersistentProperty property) {
        return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) && !((Association)property).isBidirectional());
    }
373636
def is_current?
      ::Sequel.extension(:migration)
      ::Sequel::Migrator.is_current?(database, migration_directory)
    rescue => e
      raise ConnectionFailed, e
    end
1038037
def _validate_entity_cls(self, entity_cls):
        """"""
        # Import here to avoid cyclic dependency
        from protean.core.entity import Entity

        if not issubclass(entity_cls, Entity):
            raise AssertionError(
                f'Entity {entity_cls.__name__} must be subclass of `Entity`')

        if entity_cls.meta_.abstract is True:
            raise NotSupportedError(
                f'{entity_cls.__name__} class has been marked abstract'
                f' and cannot be instantiated')
560682
private function areColumnsExist(\common_persistence_sql_SchemaManager $schemaManager)
    {
        $columnNames = [
            RdsDeliveryExecutionService::COLUMN_ID,
            RdsDeliveryExecutionService::COLUMN_USER_ID,
            RdsDeliveryExecutionService::COLUMN_DELIVERY_ID,
            RdsDeliveryExecutionService::COLUMN_LABEL,
            RdsDeliveryExecutionService::COLUMN_STATUS,
            RdsDeliveryExecutionService::COLUMN_STARTED_AT,
            RdsDeliveryExecutionService::COLUMN_FINISHED_AT,
        ];

        $tableColumns = array_map(function(Column $column) {
            return $column->getName();
        }, $schemaManager->getColumnNames(RdsDeliveryExecutionService::TABLE_NAME));

        return array_reduce($columnNames, function($areColumnsExist, $column) use ($tableColumns) {
            $areColumnsExist = $areColumnsExist && in_array($column, $tableColumns);

            return $areColumnsExist;
        }, true);
    }
829506
@GetMapping(value = "/{entityTypeId}/exist", produces = APPLICATION_JSON_VALUE)
  public boolean entityExists(@PathVariable("entityTypeId") String entityTypeId) {
    return dataService.hasRepository(entityTypeId);
  }
327990
private void instanceAlreadyLoaded(
		final Tuple resultset,
		final int i,
			//TODO create an interface for this usage
		final OgmEntityPersister persister,
		final org.hibernate.engine.spi.EntityKey key,
		final Object object,
		final LockMode lockMode,
		final SharedSessionContractImplementor session)
	throws HibernateException {
		if ( !persister.isInstance( object ) ) {
			throw new WrongClassException(
					"loaded object was of wrong class " + object.getClass(),
					key.getIdentifier(),
					persister.getEntityName()
				);
		}

		if ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested

			final boolean isVersionCheckNeeded = persister.isVersioned() &&
					session.getPersistenceContext().getEntry( object )
							.getLockMode().lessThan( lockMode );
			// we don't need to worry about existing version being uninitialized
			// because this block isn't called by a re-entrant load (re-entrant
			// loads _always_ have lock mode NONE)
			if ( isVersionCheckNeeded ) {
				//we only check the version when _upgrading_ lock modes
				Object oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();
				persister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );
				//we need to upgrade the lock mode to the mode requested
				session.getPersistenceContext().getEntry( object )
						.setLockMode( lockMode );
			}
		}
	}
1344395
def persistent_object_context_changed(self):
        
        super().persistent_object_context_changed()

        def source_registered(source):
            self.__source = source

        def source_unregistered(source=None):
            pass

        def reference_registered(property_name, reference):
            self.__referenced_objects[property_name] = reference

        def reference_unregistered(property_name, reference=None):
            pass

        if self.persistent_object_context:
            self.persistent_object_context.subscribe(self.source_uuid, source_registered, source_unregistered)

            for property_name, value in self.__properties.items():
                if isinstance(value, dict) and value.get("type") in {"data_item", "display_item", "data_source", "graphic", "structure"} and "uuid" in value:
                    self.persistent_object_context.subscribe(uuid.UUID(value["uuid"]), functools.partial(reference_registered, property_name), functools.partial(reference_unregistered, property_name))
        else:
            source_unregistered()

            for property_name, value in self.__properties.items():
                if isinstance(value, dict) and value.get("type") in {"data_item", "display_item", "data_source", "graphic", "structure"} and "uuid" in value:
                    reference_unregistered(property_name)
278087
def is_instance_running(self, instance_id):
        
        items = self.list_instances(filter=('name eq "%s"' % instance_id))
        for item in items:
            if item['status'] == 'RUNNING':
                return True
        return False
992163
private boolean isMethodAlreadyDefined(M2MEntity entity, final String methodName) {

		final One<Boolean> found = new One<Boolean>(false);
		SqlBuilderHelper.forEachMethods(entity.daoElement, new MethodFoundListener() {

			@Override
			public void onMethod(ExecutableElement executableMethod) {
				if (executableMethod.getSimpleName().toString().equals(methodName)) {
					found.value0 = true;
				}

			}
		});

		return found.value0;
	}
481495
public boolean isTransient(DbEntity dbEntity) {
    CachedDbEntity cachedDbEntity = getCachedEntity(dbEntity);
    if(cachedDbEntity == null) {
      return false;
    } else {
      return cachedDbEntity.getEntityState() == TRANSIENT;
    }
  }
1322920
public static function checkNeeded(): void
    {
        set_time_limit(0);
        ignore_user_abort(true);
        ini_set('memory_limit', '1G');

        $services_collection = new ServiceEntityRepository;
        $services_collection
            ->setWhereRunning(0)
            ->setWhereAutoStart(1);

        /** @var ServiceEntity $service_entity */
        foreach ($services_collection->getAsArrayOfObjects() as $service_entity) {
            if (NOW - $service_entity->getLastTs() >= $service_entity->getPeriod()) {
                self::run($service_entity->getId());
            }
        }
    }
1081997
def assert_instance_deleted(self, model_class, **kwargs):
        
        return _InstanceContext(
            self.assert_instance_exists,
            self.assert_instance_does_not_exist,
            model_class,
            **kwargs
        )
1040784
private void checkAllEnvelopes(PersistenceBroker broker)
    {
        Iterator iter = ((List) mvOrderOfIds.clone()).iterator();
        while(iter.hasNext())
        {
            ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());
            // only non transient objects should be performed
            if(!mod.getModificationState().isTransient())
            {
                mod.markReferenceElements(broker);
            }
        }
    }