<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def read_metadata_from_uri(self, uri, metadata_format):
 """Try to get metadata from the DB entry associated with a URI. This is used for layers that are non local layer (e.g. postgresql connection) and so we need to retrieve the metadata from the sqlite metadata db. A hash will be constructed from the supplied uri and a lookup made in a local SQLITE database for the metadata. If there is an existing record it will be returned, if not and error will be thrown. .. seealso:: write_metadata_for_uri, delete_metadata_for_uri :param uri: A layer uri. e.g. ```dbname=\'osm\' host=localhost port=5432 user=\'foo\' password=\'bar\' sslmode=disable key=\'id\' srid=4326``` :type uri: str :param metadata_format: The format of the metadata to retrieve. Valid types are: 'json', 'xml' :type metadata_format: str :returns: A string containing the retrieved metadata :raises: metadataNotFoundError if the metadata is not found. """


        allowed_formats = ['json', 'xml']
        if metadata_format not in allowed_formats:
            message = 'Metadata format %s is not valid. Valid types: %s' % (
                metadata_format, allowed_formats)
            raise RuntimeError('%s' % message)

        hash_value = self.hash_for_datasource(uri)
        try:
            self.open_connection()
        except OperationalError:
            raise
        try:
            cursor = self.get_cursor()
            # now see if we have any data for our hash
            sql = (
                'select %s from metadata where hash = \'%s\';' % (
                    metadata_format, hash_value))
            cursor.execute(sql)
            data = cursor.fetchone()
            if data is None:
                raise HashNotFoundError('No hash found for %s' % hash_value)
            data = data[0]  # first field

            # get the ISO out of the DB
            metadata = str(data)
            return metadata

        except sqlite.Error as e:
            LOGGER.debug("Error %s:" % e.args[0])
        except Exception as e:
            LOGGER.debug("Error %s:" % e.args[0])
            raise
        finally:
            self.close_connection()