22from schemas .plant_schema import PlantSchema
33import psycopg2
44from psycopg2 import DatabaseError , IntegrityError
5+ from pathlib import Path
6+ import os
7+ from fastapi .responses import FileResponse
8+
9+
510
611class PlantDAL :
712 def __init__ (self ):
@@ -16,9 +21,9 @@ def create_plant(self, plant: PlantSchema):
1621
1722 # Execute the query to insert the plant data
1823 self .cursor .execute ("""
19- INSERT INTO plant (PlantID, PlantName, ScientificName, Threshold)
20- VALUES (%s, %s, %s, %s) RETURNING PlantID;
21- """ , (plant .PlantID , plant .PlantName , plant .ScientificName , plant .Threshold ))
24+ INSERT INTO plant (PlantID, PlantName, ScientificName, Threshold, ImageFileName )
25+ VALUES (%s, %s, %s, %s, %s ) RETURNING PlantID;
26+ """ , (plant .PlantID , plant .PlantName , plant .ScientificName , plant .Threshold , plant . ImageFilename ))
2227
2328 # Commit the transaction
2429 self .conn .commit ()
@@ -32,7 +37,8 @@ def create_plant(self, plant: PlantSchema):
3237 "PlantID" : plant_id ,
3338 "PlantName" : plant .PlantName ,
3439 "ScientificName" : plant .ScientificName ,
35- "Threshhold" : plant .Threshhold
40+ "Threshhold" : plant .Threshhold ,
41+ "ImageFilename" : plant .ImageFilename
3642 }
3743
3844 except IntegrityError as e :
@@ -81,7 +87,7 @@ def create_plant(self, plant: PlantSchema):
8187 def get_plants (self ):
8288 try :
8389
84- self .cursor .execute ( "SELECT PlantID, PlantName, ScientificName, Threshold FROM plant;" )
90+ self .cursor .execute ( "SELECT PlantID, PlantName, ScientificName, Threshold FROM plant;" ) # + ImageFilename maybe?
8591
8692 plants = self .cursor .fetchall ()
8793
@@ -98,6 +104,7 @@ def get_plants(self):
98104 "PlantName" : plant [1 ],
99105 "ScientificName" : plant [2 ],
100106 "Threshhold" : plant [3 ]
107+ #"ImageFilename" plant[4]
101108 }
102109 for plant in plants
103110 ]
@@ -127,6 +134,72 @@ def get_plants(self):
127134 "error" : error_message
128135 }
129136
137+ finally :
138+ # Ensure that the connection is released
139+ release_connection (self .conn )
140+
141+
142+ def update_plant_image (self , plant_id : int , new_image_filename : str , file_content : bytes ):
143+ try :
144+ # Query for the current image filename
145+ self .cursor .execute ("SELECT ImageFilename FROM plant WHERE PlantID = %s;" , (plant_id ,))
146+ result = self .cursor .fetchone ()
147+ if not result :
148+ return {"status" : "error" , "error" : "Plant not found" }
149+
150+ current_image_filename = result [0 ]
151+
152+ # Define the image directory
153+ IMAGE_DIR = Path ("/path/to/your/image/directory" )
154+
155+ # Delete the old image file if it exists
156+ if current_image_filename :
157+ old_image_path = IMAGE_DIR / current_image_filename
158+ if old_image_path .exists ():
159+ os .remove (old_image_path )
160+
161+ # Save the new image file
162+ new_image_path = IMAGE_DIR / new_image_filename
163+ with open (new_image_path , "wb" ) as buffer :
164+ buffer .write (file_content )
165+
166+ # Update the image filename in the database
167+ self .cursor .execute ("""
168+ UPDATE plant
169+ SET ImageFilename = %s
170+ WHERE PlantID = %s;
171+ """ , (new_image_filename , plant_id ))
172+
173+ # Commit the transaction
174+ self .conn .commit ()
175+
176+ # Return the updated image
177+ return FileResponse (
178+ path = str (new_image_path ),
179+ filename = new_image_filename
180+ )
181+
182+
183+ except (psycopg2 .Error , DatabaseError ) as db_error :
184+ # Handle database errors
185+ self .conn .rollback () # Rollback transaction on error
186+ error_message = f"Database error: { db_error } "
187+ print (f"Database error: { db_error } " )
188+ return {
189+ "status" : "error" ,
190+ "error" : error_message
191+ }
192+
193+ except Exception as e :
194+ # Catch any other unexpected errors
195+ self .conn .rollback () # Rollback transaction on error
196+ error_message = f"Unexpected error: { e } "
197+ print (f"Unexpected error: { e } " )
198+ return {
199+ "status" : "error" ,
200+ "error" : error_message
201+ }
202+
130203 finally :
131204 # Ensure that the connection is released
132205 release_connection (self .conn )
0 commit comments