tomyeh / postgresql

Dart Postgresql database library.
https://quire.io
BSD 2-Clause "Simplified" License
15 stars 7 forks source link

All connections from pool closing on random occasions #15

Closed Raigiku closed 3 years ago

Raigiku commented 3 years ago

I have a flutter app that connects directly to a postgresql database, most of the time there's no problem with the connection, but in some rare occasions I get this error: image

The methods I use to interact with the database have this similar structure

Connection connection = await postgreSQLPool.connect();
try {
    List<Row> rows = await connection.query('select * from x').toList();
    return rows
        .map((e) => X(id: e[0]))
        .toList();
} catch (e) {
    throw e;
} finally {
    connection.close();
}

I can execute a single method 10+ times and it always works, I even tried putting the app on the background and locking the phone for 10 minutes, and when I open the app again and execute a db method, it works. But there still are some random occasions where this error appears. The PgPool is being initialized in the main method:

void main() async {
  await postgreSQLPool.start();
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserModel()),
        ChangeNotifierProvider(create: (_) => MainMenuModel()),
      ],
      child: App(),
    ),
  );
}

And postgreSQLPool is a global variable defined in a file like this:

final Pool postgreSQLPool = new Pool(
  'url',
  minConnections: 2,
  maxConnections: 2,
);

I even tried setting the timeout params for the Pool object to 1 minute thinking that maybe in those rare occasions the cause was a connection timeout, but after 2 minutes I still can connect to the database with no problems:

final Pool postgreSQLPool = new Pool(
  'url',
  minConnections: 2,
  maxConnections: 2,
  idleTimeout: Duration(minutes: 1),
  stopTimeout: Duration(minutes: 1),
  startTimeout: Duration(minutes: 1),
  establishTimeout: Duration(minutes: 1),
  connectionTimeout: Duration(minutes: 1),
  maxLifetime: Duration(minutes: 1),
);
tomyeh commented 3 years ago

You have to wait for rows...toList() to complete.