패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.8.2

postgresql2

그레그의 PostgreSQL 드라이버 (xxgreg/postgresql)의 파생 버전으로, 문자열과 @@ 연산자를 존중하는 보존된 치환을 사용합니다. 또한 풀 구현을 적극적으로 최적화했습니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
840
좋아요
44
Pub 점수
120

패키지 설치

flutter pub add postgresql2

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

postgresql2는 원래 PostgreSQL 드라이버의 유지보수된 포크로, 성능과 호환성을 최적화했습니다. 문자열 치환을 보존하고 @@ 연산자와 같은 고급 SQL 기능을 지원합니다. 이 패키지는 연결 풀링 효율을 향상시키고 다양한 플랫폼에서 신뢰할 수 있는 데이터베이스 상호작용을 보장합니다. Flutter 앱에서 강력하고 고성능의 PostgreSQL 연결이 필요한 개발자를 위해 설계되었으며, 전신보다 더 높은 안정성과 반응성을 제공합니다.

사용 사례

  • 실시간 데이터 동기화
  • 고-traffice 백엔드 서비스
  • 다중 플랫폼 데이터베이스 접근
  • JSONB를 사용한 복잡한 쿼리 실행
  • 확장 가능한 모바일 애플리케이션

주요 기능

  • 최적화된 연결 풀
  • @@ 연산자 및 문자열 치환 지원
  • 크로스 플랫폼 호환성
  • 원래 드라이버 대비 성능 향상
  • 신뢰할 수 있는 거래 처리

적합한 대상

  • PostgreSQL이 필요한 Flutter 앱
  • xxgreg/postgresql에서 마이그레이션하는 개발자
  • 중요한 데이터베이스 작업 부하를 가진 애플리케이션
  • 성능과 안정성을 우선시하는 팀

고려 사항

  • PostgreSQL 서버 설정이 필요합니다
  • 복잡한 쿼리에 대해 추가 구성이 필요할 수 있습니다
  • PostgreSQL 이외의 데이터베이스에는 적합하지 않습니다
  • 주류 패키지에 비해 문서가 제한적
  • 경험이 풍부한 백엔드 개발자와 함께 사용하는 것이 가장 좋습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

PostgreSQL database driver for Dart

A fork of Greg's PostgreSQL driver.

Differences

  • Array type with single dimension supported

  • The @@ operators supported.

  • DefaultTypeConverter.encodeValueDefault() assume all unknown types as JSON.

  • Pool.connect() throws an exception immediately if failed to connect to database.

  • More options to control the pool, such as limitTimeout and limitConnections

Basic usage

Obtaining a connection
var uri = 'postgres://username:password@localhost:5432/database';
connect(uri).then((conn) {
	// ...
});
SSL connections

Set the sslmode to require by appending this to the connection uri. This driver only supports sslmode=require, if sslmode is ommitted the driver will always connect without using SSL.

var uri = 'postgres://username:password@localhost:5432/database?sslmode=require';
connect(uri).then((conn) {
	// ...
});
Querying
conn.query('select color from crayons').toList().then((rows) {
	for (var row in rows) {
		print(row.color); // Refer to columns by name,
		print(row[0]);    // Or by column index.
	}
});
Executing
conn.execute("update crayons set color = 'pink'").then((rowsAffected) {
	print(rowsAffected);
});
Query Parameters

Query parameters can be provided using a map. Strings will be escaped to prevent SQL injection vulnerabilities.

conn.query('select color from crayons where id = @id', {'id': 5})
  .toList()
	.then((result) { print(result); });

conn.execute('insert into crayons values (@id, @color)',
             {'id': 1, 'color': 'pink'})
	.then((_) { print('done.'); });
Closing the connection

You must remember to call Connection.close() when you're done. This won't be done automatically for you.

Conversion of Postgresql datatypes.

Below is the mapping from Postgresql types to Dart types. All types which do not have an explicit mapping will be returned as a String in Postgresql's standard text format. This means that it is still possible to handle all types, as you can parse the string yourself.

     Postgresql type                 Dart type
	boolean                         bool
	int2, int4, int8                int
	float4, float8                  double
	numeric                         String
	timestamp, timestamptz, date    Datetime
	json, jsonb                     Map/List
	All other types                 String
Mapping the results of a query to an object
class Crayon {
	String color;
	int length;
}

conn.query('select color, length from crayons')
	.map((row) => new Crayon()
	                     ..color = row.color
	                     ..length = row.length)
	.toList()
	.then((List<Crayon> crayons) {
		for (var c in crayons) {
			print(c is Crayon);
			print(c.color);
			print(c.length);
		}
	});

Or for an immutable object:

class ImmutableCrayon {
	ImmutableCrayon(this.color, this.length);
	final String color;
	final int length;
}

conn.query('select color, length from crayons')
  .map((row) => new ImmutableCrayon(row.color, row.length))
     .toList()
	.then((List<ImmutableCrayon> crayons) {
		for (var c in crayons) {
			print(c is ImmutableCrayon);
			print(c.color);
			print(c.length);
		}
	});
Query queueing

Queries are queued and executed in the order in which they were queued.

So if you're not concerned about handling errors, you can write code like this:

conn.execute("create table crayons (color text, length int)");
conn.execute("insert into crayons values ('pink', 5)");
conn.query("select color from crayons").single.then((crayon) {
	print(crayon.color); // prints 'pink'
});
Query streaming

Connection.query() returns a Stream of results. You can use each row as soon as it is received, or you can wait till they all arrive by calling Stream.toList().

Connection pooling

In server applications, a connection pool can be used to avoid the overhead of obtaining a connection for each request.

import 'package:postgresql2/pool.dart';

main() {
  var uri = 'postgres://username:password@localhost:5432/database';
  var pool = new Pool(uri, minConnections: 2, maxConnections: 5);
  pool.messages.listen(print);
  pool.start().then((_) {
    print('Min connections established.');
    pool.connect().then((conn) { // Obtain connection from pool
      conn.query("select 'oi';")
        .toList()
        .then(print)
        .then((_) => conn.close()) // Return connection to pool
        .catchError((err) => print('Query error: $err'));
    });
  });
}
Example program

Add postgresql to your pubspec.yaml file, and run pub install.

name: postgresql_example
dependencies:
  postgresql2: any
import 'package:postgresql2/postgresql.dart';

void main() {
  var uri = 'postgres://testdb:password@localhost:5432/testdb';
  var sql = "select 'oi'"; 
  connect(uri).then((conn) {
    conn.query(sql).toList()
    	.then((result) {
    		print('result: $result');
    	})
    	.whenComplete(() {
    		conn.close();
    	});
  });
}

Testing

To run the unit tests you will need to create a database, and edit 'test/config.yaml' accordingly.

Creating a database for testing

Change to the postgres user and run the administration commands.

sudo su postgres
createuser --pwprompt testdb
  Enter password for new role: password
  Enter it again: password
  Shall the new role be a superuser? (y/n) n
  Shall the new role be allowed to create databases? (y/n) n
  Shall the new role be allowed to create more new roles? (y/n) n
createdb --owner testdb testdb
exit

Check that it worked by logging in.

psql -h localhost -U testdb -W

Enter "\q" to quit from the psql console.

Notes

Substitution of Array types

Like others, you can specify the array type in a substitution. For example,

insert into foo values(@name, @tags:array)

However, if the list can be empty, you have to specify the type explicitly since PostgreSQL cannot determine type of empty array. For example,

insert into foo values(@name, @tags:text_array)

It is equivalent to the following:

insert into foo values(@name, @tags:array::text[])

License

BSD

Utilities

  • Transaction management: https://github.com/rikulo/access
  • Entity management: https://github.com/rikulo/entity

Links

  • https://www.postgresql.org/docs/9.2/static/index.html
  • https://www.dartlang.org/

Who Uses

  • Quire - a simple, collaborative, multi-level task management tool.
  • Keikai - a sophisticated spreadsheet for big data
  • Ottava - a no-code SaaS platform simplifying data management, chart creation, and data analysis.

카테고리

의존성

의존성 목록 5 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.