@@ -5,6 +5,8 @@ const crypto = require('crypto')
55const { Writable, Readable } = require ( 'stream' )
66const sessionVariableMap = require ( './session.json' )
77
8+ const LOG = cds . log ( 'sql|db' )
9+
810class PostgresService extends SQLService {
911 init ( ) {
1012 if ( ! this . options . independentDeploy ) {
@@ -18,10 +20,12 @@ class PostgresService extends SQLService {
1820 }
1921
2022 get factory ( ) {
23+ const service = this
24+ const maxRetries = 3
2125 return {
2226 options : this . options . pool || { } ,
23- create : async ( ) => {
24- const { credentials : cr = { } , client : clientOptions = { } } = this . options
27+ create : async function create ( tenant , attempt = 1 ) {
28+ const { credentials : cr = { } , client : clientOptions = { } } = service . options
2529 const credentials = {
2630 // Cloud Foundry provides the user in the field username the pg npm module expects user
2731 user : cr . username || cr . user ,
@@ -42,11 +46,17 @@ class PostgresService extends SQLService {
4246 ca : cr . sslrootcert ,
4347 } ) ,
4448 }
45- const dbc = new Client ( { ...credentials , ...clientOptions } )
46- await dbc . connect ( )
47- dbc . open = true
48- dbc . on ( 'end' , ( ) => { dbc . open = false } )
49- return dbc
49+ try {
50+ const dbc = new Client ( { ...credentials , ...clientOptions } )
51+ await dbc . connect ( )
52+ dbc . open = true
53+ dbc . on ( 'end' , ( ) => { dbc . open = false } )
54+ return dbc
55+ } catch ( err ) {
56+ if ( attempt >= maxRetries ) throw err
57+ LOG . debug ( 'connection attempt' , attempt , 'of' , maxRetries , 'failed - retrying' )
58+ return create ( tenant , attempt + 1 )
59+ }
5060 } ,
5161 destroy : dbc => dbc . end ( ) ,
5262 validate : dbc => dbc . open ,
0 commit comments