A database connection lets an application send SQL to a database. In an ACH-processing workflow, the parser uses one to save each file line before parsing it, then to store fields extracted from file headers. Start by testing the connection itself: obtain it, create a cursor, and close both before adding inserts. This separates connection problems from parsing problems. section 5.2.1 section 5.3.2
If the connection fails, check where the code is running:
- Code running in an IDE on the Docker host uses localhost rather than the Docker service name postgres. section 5.2.1
- Expose PostgreSQL port 5432 in docker-compose.yml so the host can reach the container. section 5.2.1
Once the connection works, use it to insert each unaltered line into ach_files with its filename and sequence number. A with block manages the connection and cursor rather than relying on every path through the code to close them manually. Tests can open their own connection to count stored rows. Because repeated test runs otherwise leave rows behind, a pytest fixture truncates the table after the test. section 5.2.1
Pass the connection to the file-header routine
After parsing a file-header line into fields, pass the existing connection to the header routine and use it to insert those fields into ach_file_headers. Passing the connection as a parameter, rather than storing it on the parser, makes the routine easier to unit test. It is a practical choice for this workflow, not the only possible design. section 5.3.2
Listing 5.6 Updated parse function
def parse(self, filename) -> [List, List]:
with open(filename, "r") as file, self.get_db() as conn: #1
lines = file.readlines()
sequence_number = 0 #2
for line in lines:
sequence_number += 1 #3
line = line.replace("\n", "")
with conn.cursor() as cursor: #4
cursor.execute(f"INSERT INTO ach_files #4
➥ (file_name, unparsed_record, sequence_number) #4
➥ VALUES (%s, %s, %s)", (filename, line, sequence_number)) #4
conn.commit() #4
The updated parse function shows the connection and cursor in context managers alongside the insert of each file line. section 5.2.1





