LibPq constructor

LibPq(
  1. String info, {
  2. DynamicLibrary? dynamicLibrary,
  3. String? dllPath,
  4. Encoding? encoding,
})

Implementation

LibPq(String info,
    {DynamicLibrary? dynamicLibrary, String? dllPath, Encoding? encoding})
    : encoding = encoding ?? Utf8Codec(allowMalformed: true) {
  final winPath = r'libpq.dll';
  final linuxPath = r'libpq.so';
  var path = winPath;
  if (Platform.isWindows) {
    path = winPath;
  } else if (Platform.isLinux) {
    path = linuxPath;
  } else {
    throw Exception('Platform not implemented');
  }
  if (dllPath != null) {
    path = dllPath;
  }

  final dl = dynamicLibrary ?? DynamicLibrary.open(path);
  pq = LibpqBindings(dl);
  connInfo = info.toNativeUtf8().cast();
  conn = pq.PQconnectdb(connInfo);

  if (pq.PQstatus(conn) != ConnStatusType.CONNECTION_OK) {
    throw LibPqException(
        pq.PQerrorMessage(conn).asDartString(encoding: encoding));
  }

  int v = pq.PQserverVersion(conn);
  int major = v ~/ 10000;
  v -= major * 10000;
  int minor = v ~/ 100;
  v -= minor * 100;

  _version = "${major}.${minor}.${v}";
  _protocol = pq.PQprotocolVersion(conn);
}