Skip to content

Allow passing a NpgsqlDataSource to the constructor of the generated queries class #458

Open

Description

@greg-blackcurrent

I'm using sqlc-gen-csharp with Npgsql. It's working well. Cheers for making this!

One change I made for my codebase, is adding a constructor to pass in a NpgsqlDataSource to the generated queries classes.

I need this so that I can register custom types against the data source. See NpgsqlDataSourceBuilder.MapComposite.

Another reason is so I can share a single connection pool across multiple files.

I'm currently using a fork with this change. I'd be happy to discuss, and clean it up for a PR, if this is something you'd like to support.

greg-blackcurrent@fc4920b

Here is an example of the generated source.

    public QueriesSql(NpgsqlDataSource dataSource) : this()
    {
        _dataSource = new Lazy<NpgsqlDataSource>(() => dataSource);
        _ownsDataSource = false;
    }

    private readonly Lazy<NpgsqlDataSource>? _dataSource;
    private readonly bool _ownsDataSource;

    public void Dispose()
    {
        GC.SuppressFinalize(this);
        if (_ownsDataSource && _dataSource?.IsValueCreated == true)
            _dataSource.Value.Dispose();
    }

Activity

  1. doron050 commented on Oct 22, 2026

    @doron050
    Collaborator

    Thanks, glad it's useful! Yes, I'd like to support this.
    It's needed for MapComposite/plugins and for sharing one pool. Your approach looks right, especially not disposing a data source the caller passed in. A PR would be welcome. A few things:

    1. Keep the existing connection-string and transaction constructors working as they do now.
    2. Please make sure it compiles for both net8.0 and netstandard2.0 (nullable handling differs).
    3. Add or update a test that builds the class from an NpgsqlDataSource and checks that Dispose() leaves it usable.
    4. Regenerate the examples (make sqlc-generate-process).

    MySQL has the same data-source pattern. Feel free to include it, or I'll open a follow-up. 🎉

  2. greg-blackcurrent commented on Oct 22, 2026

    @greg-blackcurrent
    Author

    Great!

    I'll see if I can squeeze this (and #459 #460) into my next sprint.

  3. doron050 commented on Oct 24, 2026

    @doron050
    Collaborator

    @greg-blackcurrent Great! make sure to pull from main, I did some long awaited changes :)
    nothing there should stop you form what you are doing, I'll wait for your PR for the next release 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions