1+ const { GenericContainer } = require ( "testcontainers" ) ;
2+
3+ //https://www.npmjs.com/package/postgres
4+ const postgres = require ( "postgres" ) ;
5+
6+ // docker run -p 5432:5432 -e POSTGRES_PASSWORD=bar -e POSTGRES_USER=foo postgres:11
7+
8+ let dbPort = 5432 ;
9+ let exposedDbPort = 0 ;
10+ let dbURL = "postgres://localhost"
11+ let test_container = null ;
12+ let connection = null ;
13+
14+
15+
16+ module . exports = {
17+
18+ startDb : async ( ) => {
19+
20+ dbPort = process . env . DB_PORT || 5432 ;
21+
22+ if ( process . env . DOCKER_DBC && process . env . DOCKER_DBC === '0' ) {
23+ process . env . DB_PORT = dbPort
24+ console . log ( "use local Postgres on port:" + dbPort )
25+ } else {
26+ console . log ( "start db with test container" )
27+ test_container = await new GenericContainer ( "postgres:11" )
28+ . withEnv ( "POSTGRES_USER" , "foo" )
29+ . withEnv ( "POSTGRES_PASSWORD" , "bar" )
30+ . withEnv ( "POSTGRES_DB" , "db" )
31+ . withExposedPorts ( dbPort )
32+ . withTmpFs ( { "/var/lib/postgresql/data" : "rw" } )
33+ . start ( ) ;
34+ exposedDbPort = test_container . getMappedPort ( dbPort )
35+ process . env . DB_PORT = exposedDbPort
36+ dbURL = `postgres://localhost:${ exposedDbPort } `
37+
38+ console . log ( "connecting " + dbURL ) ;
39+ }
40+
41+ connection = postgres ( dbURL , {
42+ // host : '', // Postgres ip address[s] or domain name[s]
43+ // port : 5432, // Postgres server port[s]
44+ database : 'db' , // Name of database to connect to
45+ username : 'foo' , // Username of database user
46+ password : 'bar' , // Password of database user
47+ } )
48+
49+ return test_container ;
50+
51+ } ,
52+
53+ checkdb : async ( ) => {
54+ console . log ( "todo check" )
55+ } ,
56+
57+ cleanDb : ( ) => {
58+
59+ const queryAllTables = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where (TABLE_TYPE=\'TABLE\' OR TABLE_TYPE=\'BASE TABLE\')'
60+ + " AND TABLE_SCHEMA='public' " ;
61+
62+ //TODO
63+ // return new Promise(resolve => {
64+ //
65+ // querySql(queryAllTables)
66+ // .then(results => {
67+ // let truncateAll= '';
68+ // let resetSeq = '';
69+ // for (const element of results){
70+ // truncateAll += `TRUNCATE TABLE ${element.TABLE_NAME};`;
71+ // resetSeq += `ALTER TABLE ${element.TABLE_NAME} AUTO_INCREMENT=1;`;
72+ // }
73+ //
74+ // querySql(truncateAll+resetSeq).then(e=>
75+ // querySql(enableReferentialIntegrity).then(f=>resolve())
76+ // )
77+ // })
78+
79+
80+ } ,
81+
82+ stopDb : async ( ) => {
83+ if ( connection )
84+ connection . end ( ) ;
85+
86+ if ( test_container ) {
87+ await test_container . stop ( ) ;
88+ test_container = null ;
89+ }
90+ }
91+ }
0 commit comments