Connection pools support an event interface that allows hooks to execute upon first connect, upon each new connection, and upon checkout and checkin of connections. See PoolEvents for details.
데이터베이스 커넥션은 클라이언트 소프트웨어가 데이터베이스를 읽을 수 있도록 데이터베이스와 연결하는 것을 말한다. 데이터베이스는 여러 클라이언트가 사용하므로 다수의 연결이 발생하고, 그 연결들을 모아둔 곳이 바로 연결 풀이다. SQLAlchemy에서 연결 풀은 이벤트 인터페이스를 제공한다. 이벤트 인터페이스란 첫 연결, 새로운 연결, 연결 체크인, 연결 체크아웃이 발생할 때, 데이터베이스 기본 동작(hooks: 생성/조회/수정/삭제의 이전/이후에 발생하는 함수)이 일어나도록 한다.
The connection pool has the ability to refresh individual connections as well as its entire set of connections, setting the previously pooled connections as “invalid”. A common use case is allow the connection pool to gracefully recover when the database server has been restarted, and all previously established connections are no longer functional. There are two approaches to this.
연결 풀은 이전 풀에 들어간 연결들을 “유효하지않음(Invalid)”로 설정하면서, 전체 연결 및 각각의 연결을 업데이트(refresh)할 수 있다. 일반적인 예를 들자면, 연결 풀은 이전에 수립된(established) 연결들이 제 기능을 못하고 데이터베이스 서버가 재시작될 때, 연결 풀을 부드럽게 복구한다. 2가지 방법이 있다.
연결끊김 처리 – 비관적인 접근법
The pessimistic approach refers to emitting a test statement on the SQL connection at the start of each connection pool checkout, to test that the database connection is still viable. The implementation is dialect-specific, and makes use of either a DBAPI-specific ping method, or by using a simple SQL statement like “SELECT 1”, in order to test the connection for liveness.
The approach adds a small bit of overhead to the connection checkout process, however is otherwise the most simple and reliable approach to completely eliminating database errors due to stale pooled connections. The calling application does not need to be concerned about organizing operations to be able to recover from stale connections checked out from the pool.
Pessimistic testing of connections upon checkout is achievable by using the Pool.pre_ping argument, available from create_engine() via the create_engine.pool_pre_ping argument:
비관적인 접근법은 데이터베이스 연결이 여전히 실행 가능한지 확인(test)하기 위해, 각 연결 풀의 체크아웃이 시작될 때, SQL 연결에 테스트 문(test statement)을 보낸다. SELECT 1과 같은 SQL문을 사용하거나, 특정한 DBAPI가 제공하는 ping을 이용해 연결이 살아 있는지 테스트하는 방식으로 구현된다. (시스템마다 구현 방식은 다르다; dialect-specific)
이 접근법은 연결 체크아웃 과정에서 약간의 오버헤드 비트를 추가하는 문제점은 있지만, 풀에 들어온 지 오래된 연결 때문에 발생하는 데이터베이스 에러를 완전히 제거하기 위한 가장 단순하고 안정적인(reliable) 접근법이다. 호출하는 앱은 풀에서 오래되고 체크아웃된 연결들을 되살리기(recover) 위해 (별도의) 명령어를 쓰지 않아도 된다. (not need to be concerned)
비관적인 방법으로 체크아웃 연결을 테스팅하는 하는 것은 create_engine()에서 사용가능한 “Pool.pre_ping” 매개변수를 활용한다.
engine = create_engine("mysql+pymysql://user:pw@host/db", pool_pre_ping=True)
.
The “pre ping” feature operates on a per-dialect basis either by invoking a DBAPI-specific “ping” method, or if not available will emit SQL equivalent to “SELECT 1”, catching any errors and detecting the error as a “disconnect” situation. If the ping / error check determines that the connection is not usable, the connection will be immediately recycled, and all other pooled connections older than the current time are invalidated, so that the next time they are checked out, they will also be recycled before use.
"pre ping" 기능은 특정 DBAPI에서 제공하는 "ping"를 사용하거나, ("ping"을 사용할 수 없다면) "SECLECT 1"과 동일한 SQL문을 보내는 방식을 처리되며, 각 시스템에 따라 방식은 다르다. 이 방식은 아무 에러나 캐치한 후 "연결 끊김" 상황의 에러를 걸러낸다(detecting). ping 또는 에러 체크를 통해 연결 가능여부가 확정되면, 해당 연결은 즉시 재사용(recycle)되고, 그보다 오래도록 풀에 있던 모든 연결들은 유효하지 않는 것으로 처리(invalidate)된다. (유효하지 않는 것으로 처리된) 그 연결들도 나중에 재사용될 것이기 때문이다.
"onnection pool은 연결이 요청 될 때마다 생성되는 것이 아니라 재사용됨을 의미한다. 쉽게 말해, 우리의 어플리케이션은 Flask api이고, MySQL db에 요청을 할 때 새 MySQL db 연결을 생성하고, 작업하고, 연결을 닫게 되는데, 모든 요청에 대해 연결을 생성하고, 연결을 닫는 과정을 반복되게 된다.이 연결을 생성하고, 닫는 과정을 줄이기 위해 connection pool에 반납을 하게 되는 것이다. (캐싱 Caching)" https://velog.io/@n0wkim/sqlalchemy-connection-pool
If the database is still not available when “pre ping” runs, then the initial connect will fail and the error for failure to connect will be propagated normally. In the uncommon situation that the database is available for connections, but is not able to respond to a “ping”, the “pre_ping” will try up to three times before giving up, propagating the database error last received.
"pre ping"이 실행되었으나 데이터베이스가 아직 이용가능한 상태가 아니라면, 초기 연결은 실패로 처리되고, 실패에 대한 에러는 보통 전파(propagate)된다. "ping"에는 응답하지 않지만 데이터베이스는 사용할 수 있는 드문 상황에서, "pre_ping"은 3번 시도되며, 마지막으로 받은 데이터베이스 에러는 전파된다.