22
33import json
44import psycopg2
5+ from psycopg2 .extensions import AsIs
56
67from cache .cache import Cache
78from cache .cache_error import CacheError
@@ -38,6 +39,10 @@ class PostgresCache(Cache):
3839 ```
3940 """
4041
42+ CREATE_SCHEMA = """
43+ CREATE SCHEMA IF NOT EXISTS %s;
44+ """
45+
4146 CREATE_CACHE_TABLE = """
4247 CREATE TABLE IF NOT EXISTS cache (
4348 user_id text NOT NULL,
@@ -133,6 +138,9 @@ def connect(self) -> None:
133138 # even if PostgreSQL is not alive
134139 self .connection = None
135140 config = self .postgres_config
141+ namespace = "public"
142+ if config .namespace is not None :
143+ namespace = config .namespace
136144 try :
137145 self .connection = psycopg2 .connect (
138146 host = config .host ,
@@ -143,8 +151,9 @@ def connect(self) -> None:
143151 sslmode = config .ssl_mode ,
144152 sslrootcert = config .ca_cert_path ,
145153 gssencmode = config .gss_encmode ,
154+ options = f"-c search_path={ namespace } " ,
146155 )
147- self .initialize_cache ()
156+ self .initialize_cache (namespace )
148157 except Exception as e :
149158 if self .connection is not None :
150159 self .connection .close ()
@@ -166,7 +175,7 @@ def connected(self) -> bool:
166175 logger .error ("Disconnected from storage: %s" , e )
167176 return False
168177
169- def initialize_cache (self ) -> None :
178+ def initialize_cache (self , namespace : str ) -> None :
170179 """Initialize cache - clean it up etc."""
171180 if self .connection is None :
172181 logger .error ("Cache is disconnected" )
@@ -177,6 +186,10 @@ def initialize_cache(self) -> None:
177186 # and it should not interfere with other statements
178187 cursor = self .connection .cursor ()
179188
189+ logger .info ("Initializing schema" )
190+ if namespace != "public" :
191+ cursor .execute (PostgresCache .CREATE_SCHEMA , (AsIs (namespace ),))
192+
180193 logger .info ("Initializing table for cache" )
181194 cursor .execute (PostgresCache .CREATE_CACHE_TABLE )
182195
0 commit comments