efcore.pg icon indicating copy to clipboard operation
efcore.pg copied to clipboard

Large Object Support

Open day01 opened this issue 9 years ago • 9 comments

Hi,
Are you planning Large Object Support (https://www.postgresql.org/docs/current/static/largeobjects.html)?

Regards, P.

day01 avatar Jul 07 '17 19:07 day01

Yes, Npgsql includes an API for large object support. However, this has nothing to do with the Entity Framework Core provider (which is this repo).

Am closing but post back if you have further questions or run into issues.

roji avatar Jul 08 '17 01:07 roji

I couldn't find it... but :) thanks. is it possible to make stream object in entity and however make mapping for it?

I would like to create entity which will contains stream object (large object in psql). That kind of basic functionality will be a great feature.

day01 avatar Jul 08 '17 06:07 day01

Make sure you understand the difference between PostgreSQL's large object support (which is a very specific thing) and general streaming of large columns, which is not "large object" support. For example, you can have very big bytea or text columns in a table, and access them via ADO.NET streaming APIs (GetStream(), GetTextReader()).

However, none of the above works with Entity Framework, which is about mapping CLR classes to database rows, without any specific streaming support.

roji avatar Jul 08 '17 08:07 roji

The difference between a large object in psql vs getstream in adonet is mainly in stream source. e.g. in psql LO it is directly from db in adonet we have to download bytea/text representant and then make a stream from downloaded source. Of course, i can be mistaken :)

So my proposition is about made stream object in clr mapping as LO. I don't know how to do it yet .

But basically, it looks possible. How do you think about it? Of course, I declare any help with it if you will be interested.

day01 avatar Jul 08 '17 08:07 day01

With ADO.NET bytea/text, you can efficiently stream values directly from the database with the methods I mentioned above - this allows you to efficiently retrieve large bytea/text data. You can do something very similar with LO by getting an NpgsqlLargeObjectStream from an NpgsqlLargeObjectManager, and efficiently stream data to/from the database.

I'm still not understanding exactly what it is you're requesting - are you looking for Entity Framework Core mapping of PostgreSQL Large Objects somehow? I don't think that would fit the idea of an O/RM (or of EF Core specifically). Please note that there's nothing stopping you from dropping down to ADO.NET and using Npgsql's LO support in an EF Core application. Can you please provide a bit more detail on what you're proposing?

roji avatar Jul 08 '17 08:07 roji

Ok, my bad. I thought, it is a necessary to download row representant (or field) and then make a stream from value.

My requesting was about

are you looking for Entity Framework Core mapping of PostgreSQL Large Objects somehow

But i understand it doesn't fit orm's idea.

Thank you for the explanation.

day01 avatar Jul 08 '17 09:07 day01

Hi,

I have a bytea storing 80MB Files. Now I would like to stream that coulum somehow to the web browser via e.g. asp core:

var output = _context. ... .GetStream(); return File(output, MediaTypeNames.Application.Pdf);

This would allow to stream the 80MB to the browser, instead of loading it first to the asp core server and then to the browser.

Ideas????

Thanks

dietrichha avatar May 31 '18 15:05 dietrichha

As written above, you can easily do this with ADO.NET by calling DbDataReader.GetStream(). However, as an O/RM EF Core doesn't expose this in any way, it simply reads values from the database and stores them in a class property. You can still use EF Core and drop down to ADO.NET specifically for streaming the 80MB operation. Just get the DbConnection from your DbContext and use that to query your value with SQL, calling GetStream() on the resulting reader.

roji avatar May 31 '18 18:05 roji

Thanks.

Based on this ideas https://stackoverflow.com/questions/4396863/how-to-make-streams-from-blobs-available-in-plain-old-c-sharp-objects-when-using and https://docs.microsoft.com/de-de/dotnet/framework/data/adonet/sqlclient-streaming-support

I adopted this class... It wraps the database connection into a Stream so you can use it to stream it the browser/client.

/// <summary>
/// There must be a SqlConnection that works inside the SqlCommand. Remember to dispose of the object after usage.
/// </summary>
public class SqlBlobReader : Stream
{
    private readonly DbConnection _dbConnection;
    private DbCommand _dbCommand;
    private Stream _stream;
    private DbDataReader _dbDataReader;
    private bool disposed = false;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="command">The supplied <para>sqlCommand</para> must only have one field in select statement, or else the stream won't work. Select just one row, all others will be ignored.</param>
    public SqlBlobReader(DbConnection dbConnection, String query)
    {
        _dbConnection = dbConnection;
        ConnectAsync(query).GetAwaiter().GetResult();
    }


    private async Task ConnectAsync(String query)
    {
        await _dbConnection.OpenAsync();
        _dbCommand = _dbConnection.CreateCommand();

        _dbCommand.CommandText = query;
        _dbDataReader = await _dbCommand.ExecuteReaderAsync(CommandBehavior.SequentialAccess);
        if (await _dbDataReader.ReadAsync())
        {
            if (!await _dbDataReader.IsDBNullAsync(0))
            {
                _stream = _dbDataReader.GetStream(0);
            }
            else
            {
                throw new Exception("SQL BLOL NOT FOUND FOR QUERY: " + query);
            }
        }
        else
        {
            throw new Exception("SQL BLOL NOT FOUND FOR QUERY: " + query);
        }
    }

    /// <summary>
    /// Not supported
    /// </summary>
    public override long Seek(long offset, SeekOrigin origin)
    {
        return _stream.Seek(offset, origin);
        throw new NotSupportedException();
    }

    /// <summary>
    /// Not supported
    /// </summary>
    public override void SetLength(long value)
    {
        _stream.SetLength(value);
        return;
        throw new NotSupportedException();
    }

    public override int Read(byte[] buffer, int index, int count)
    {
        return _stream.Read(buffer, index, count);
    }



    public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
    {
        return _stream.ReadAsync(buffer, offset, count, cancellationToken);
    }

    public new Task<int> ReadAsync(byte[] buffer, int offset, int count)
    {
        return _stream.ReadAsync(buffer, offset, count);
    }



    /// <summary>
    /// Not supported
    /// </summary>
    public override void Write(byte[] buffer, int offset, int count)
    {
        throw new NotSupportedException();
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override int ReadTimeout
    {
        get => _stream.ReadTimeout;
        set => _stream.ReadTimeout = value;
    }

    public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback,
        object state)
    {
        return _stream.BeginRead(buffer, offset, count, callback, state);
    }


    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override long Length
    {
        get { return _stream.Length; }
    }

    public override long Position
    {
        get { throw new NotSupportedException(); }
        set { throw new NotSupportedException(); }
    }

    protected override void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                _stream?.Dispose();
                _dbDataReader?.Dispose();
                _dbCommand?.Dispose();
                _dbConnection?.Dispose();
                disposed = true;
            }
        }
        base.Dispose(disposing);
    }

    public override void Flush()
    {
        throw new NotSupportedException();
    }
}

dietrichha avatar Jun 15 '18 21:06 dietrichha