-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
6196 lines (5242 loc) · 280 KB
/
coverage.html
File metadata and controls
6196 lines (5242 loc) · 280 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>basic-crud: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/aptlogica/go-postgres-rest/examples/basic-crud/main.go (0.0%)</option>
<option value="file1">github.com/aptlogica/go-postgres-rest/pkg/config/config.go (100.0%)</option>
<option value="file2">github.com/aptlogica/go-postgres-rest/pkg/database/dbFactory.go (100.0%)</option>
<option value="file3">github.com/aptlogica/go-postgres-rest/pkg/database/factory.go (100.0%)</option>
<option value="file4">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/bulk_repo.go (100.0%)</option>
<option value="file5">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/connector.go (85.7%)</option>
<option value="file6">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/core_repo.go (100.0%)</option>
<option value="file7">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/database_repo.go (100.0%)</option>
<option value="file8">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/ddl_repo.go (90.0%)</option>
<option value="file9">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/dml_repo.go (100.0%)</option>
<option value="file10">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/dsn_builder.go (86.7%)</option>
<option value="file11">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/migration_repo.go (100.0%)</option>
<option value="file12">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/performance_repo.go (100.0%)</option>
<option value="file13">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/postgres.go (81.8%)</option>
<option value="file14">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/relationship_repo.go (100.0%)</option>
<option value="file15">github.com/aptlogica/go-postgres-rest/pkg/database/postgres/repo.go (91.7%)</option>
<option value="file16">github.com/aptlogica/go-postgres-rest/pkg/database/repoFactory.go (100.0%)</option>
<option value="file17">github.com/aptlogica/go-postgres-rest/pkg/database/repository_factory.go (100.0%)</option>
<option value="file18">github.com/aptlogica/go-postgres-rest/pkg/pkg.go (91.7%)</option>
<option value="file19">github.com/aptlogica/go-postgres-rest/pkg/services/bulk_service.go (100.0%)</option>
<option value="file20">github.com/aptlogica/go-postgres-rest/pkg/services/migration_service.go (86.1%)</option>
<option value="file21">github.com/aptlogica/go-postgres-rest/pkg/services/performance_service.go (95.3%)</option>
<option value="file22">github.com/aptlogica/go-postgres-rest/pkg/services/relationship_service.go (84.6%)</option>
<option value="file23">github.com/aptlogica/go-postgres-rest/pkg/services/table_service.go (96.2%)</option>
<option value="file24">github.com/aptlogica/go-postgres-rest/pkg/utils/file_utility.go (90.0%)</option>
<option value="file25">github.com/aptlogica/go-postgres-rest/pkg/utils/helpers.go (98.7%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">no coverage</span>
<span class="cov1">low coverage</span>
<span class="cov2">*</span>
<span class="cov3">*</span>
<span class="cov4">*</span>
<span class="cov5">*</span>
<span class="cov6">*</span>
<span class="cov7">*</span>
<span class="cov8">*</span>
<span class="cov9">*</span>
<span class="cov10">high coverage</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/aptlogica/go-postgres-rest/pkg/config"
"github.com/aptlogica/go-postgres-rest/pkg/database/interfaces"
"github.com/aptlogica/go-postgres-rest/pkg/database/postgres"
)
// Constants for HTTP headers and error messages
const (
contentTypeHeader = "Content-Type"
contentTypeJSON = "application/json"
dbErrorMessage = "Database error: %v"
userNotFoundMsg = "User not found"
)
// User represents our sample data model
type User struct {
ID int `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Email string `json:"email" db:"email"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
var db interfaces.DB
func main() <span class="cov0" title="0">{
fmt.Println("=== Go PostgreSQL REST - Basic CRUD Example ===")
// Database configuration
cfg := config.DatabaseConfig{
Host: getEnv("DB_HOST", "localhost"),
Port: config.ParseInt(getEnv("DB_PORT", "5432"), 5432),
Username: getEnv("DB_USER", "postgres"),
Password: getEnv("DB_PASSWORD", "password"),
DatabaseName: getEnv("DB_NAME", "sereni_examples"),
SSLMode: "disable",
MaxOpenConns: 25,
MaxIdleConns: 5,
ConnMaxLifetime: time.Hour,
}
// Initialize database connection
var err error
db, err = postgres.Connect(&cfg)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to connect to database: %v", err)
}</span>
<span class="cov0" title="0">defer db.Close()
fmt.Printf("✅ Connected to PostgreSQL: %s@%s:%d/%s\n",
cfg.Username, cfg.Host, cfg.Port, cfg.DatabaseName)
// Create tables if they don't exist
if err := createTables(); err != nil </span><span class="cov0" title="0">{
log.Fatalf("Failed to create tables: %v", err)
}</span>
// Setup HTTP routes
<span class="cov0" title="0">http.HandleFunc("/health", healthHandler)
http.HandleFunc("/api/users", usersHandler)
http.HandleFunc("/api/users/", userHandler)
port := getEnv("API_PORT", "8080")
fmt.Printf("\n🚀 Server starting on port %s\n", port)
fmt.Println("\nAvailable endpoints:")
fmt.Println(" GET /health - Health check")
fmt.Println(" GET /api/users - Get all users")
fmt.Println(" POST /api/users - Create new user")
fmt.Println(" GET /api/users/{id} - Get user by ID")
fmt.Println(" PUT /api/users/{id} - Update user by ID")
fmt.Println(" DELETE /api/users/{id} - Delete user by ID")
fmt.Println("\nExample requests:")
fmt.Printf(` curl http://localhost:%s/health`+"\n", port)
fmt.Printf(` curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}' http://localhost:%s/api/users`+"\n", port)
fmt.Printf(` curl http://localhost:%s/api/users`+"\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))</span>
}
func createTables() error <span class="cov0" title="0">{
query := `
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Create trigger to update updated_at automatically
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ language 'plpgsql';
DROP TRIGGER IF EXISTS update_users_updated_at ON users;
CREATE TRIGGER update_users_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
`
_, err := db.Exec(query)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create tables: %v", err)
}</span>
<span class="cov0" title="0">fmt.Println("✅ Database tables created/verified")
return nil</span>
}
// Health check endpoint
func healthHandler(w http.ResponseWriter, r *http.Request) <span class="cov0" title="0">{
health := map[string]interface{}{
"status": "healthy",
"timestamp": time.Now().Unix(),
"database": "connected",
"version": "1.0.0",
}
w.Header().Set(contentTypeHeader, contentTypeJSON)
json.NewEncoder(w).Encode(health)
}</span>
// Handle /api/users (GET, POST)
func usersHandler(w http.ResponseWriter, r *http.Request) <span class="cov0" title="0">{
switch r.Method </span>{
case http.MethodGet:<span class="cov0" title="0">
getAllUsers(w, r)</span>
case http.MethodPost:<span class="cov0" title="0">
createUser(w, r)</span>
default:<span class="cov0" title="0">
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)</span>
}
}
// Handle /api/users/{id} (GET, PUT, DELETE)
func userHandler(w http.ResponseWriter, r *http.Request) <span class="cov0" title="0">{
// Extract ID from URL path
path := strings.TrimPrefix(r.URL.Path, "/api/users/")
if path == "" </span><span class="cov0" title="0">{
http.Error(w, "User ID required", http.StatusBadRequest)
return
}</span>
<span class="cov0" title="0">id, err := strconv.Atoi(path)
if err != nil </span><span class="cov0" title="0">{
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}</span>
<span class="cov0" title="0">switch r.Method </span>{
case http.MethodGet:<span class="cov0" title="0">
getUserByID(w, r, id)</span>
case http.MethodPut:<span class="cov0" title="0">
updateUser(w, r, id)</span>
case http.MethodDelete:<span class="cov0" title="0">
deleteUser(w, r, id)</span>
default:<span class="cov0" title="0">
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)</span>
}
}
// Get all users
func getAllUsers(w http.ResponseWriter, r *http.Request) <span class="cov0" title="0">{
query := `SELECT id, name, email, created_at, updated_at FROM users ORDER BY created_at DESC`
rows, err := db.Query(query)
if err != nil </span><span class="cov0" title="0">{
http.Error(w, fmt.Sprintf(dbErrorMessage, err), http.StatusInternalServerError)
return
}</span>
<span class="cov0" title="0">defer rows.Close()
var users []User
for rows.Next() </span><span class="cov0" title="0">{
var user User
err := rows.Scan(&user.ID, &user.Name, &user.Email, &user.CreatedAt, &user.UpdatedAt)
if err != nil </span><span class="cov0" title="0">{
http.Error(w, fmt.Sprintf("Scan error: %v", err), http.StatusInternalServerError)
return
}</span>
<span class="cov0" title="0">users = append(users, user)</span>
}
<span class="cov0" title="0">if users == nil </span><span class="cov0" title="0">{
users = []User{} // Return empty array instead of null
}</span>
<span class="cov0" title="0">w.Header().Set(contentTypeHeader, contentTypeJSON)
json.NewEncoder(w).Encode(map[string]interface{}{
"data": users,
"count": len(users),
})</span>
}
// Create new user
func createUser(w http.ResponseWriter, r *http.Request) <span class="cov0" title="0">{
var user User
if err := json.NewDecoder(r.Body).Decode(&user); err != nil </span><span class="cov0" title="0">{
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}</span>
// Validate required fields
<span class="cov0" title="0">if user.Name == "" || user.Email == "" </span><span class="cov0" title="0">{
http.Error(w, "Name and email are required", http.StatusBadRequest)
return
}</span>
<span class="cov0" title="0">query := `
INSERT INTO users (name, email)
VALUES ($1, $2)
RETURNING id, name, email, created_at, updated_at
`
err := db.QueryRow(query, user.Name, user.Email).Scan(
&user.ID, &user.Name, &user.Email, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil </span><span class="cov0" title="0">{
if strings.Contains(err.Error(), "unique constraint") </span><span class="cov0" title="0">{
http.Error(w, "Email already exists", http.StatusConflict)
}</span> else<span class="cov0" title="0"> {
http.Error(w, fmt.Sprintf(dbErrorMessage, err), http.StatusInternalServerError)
}</span>
<span class="cov0" title="0">return</span>
}
<span class="cov0" title="0">w.Header().Set(contentTypeHeader, contentTypeJSON)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)</span>
}
// Get user by ID
func getUserByID(w http.ResponseWriter, r *http.Request, id int) <span class="cov0" title="0">{
var user User
query := `SELECT id, name, email, created_at, updated_at FROM users WHERE id = $1`
err := db.QueryRow(query, id).Scan(
&user.ID, &user.Name, &user.Email, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil </span><span class="cov0" title="0">{
if err.Error() == "sql: no rows in result set" </span><span class="cov0" title="0">{
http.Error(w, userNotFoundMsg, http.StatusNotFound)
}</span> else<span class="cov0" title="0"> {
http.Error(w, fmt.Sprintf(dbErrorMessage, err), http.StatusInternalServerError)
}</span>
<span class="cov0" title="0">return</span>
}
<span class="cov0" title="0">w.Header().Set(contentTypeHeader, contentTypeJSON)
json.NewEncoder(w).Encode(user)</span>
}
// Update user by ID
func updateUser(w http.ResponseWriter, r *http.Request, id int) <span class="cov0" title="0">{
var updateData User
if err := json.NewDecoder(r.Body).Decode(&updateData); err != nil </span><span class="cov0" title="0">{
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}</span>
// Check if user exists
<span class="cov0" title="0">var exists bool
err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)", id).Scan(&exists)
if err != nil </span><span class="cov0" title="0">{
http.Error(w, "Database error", http.StatusInternalServerError)
return
}</span>
<span class="cov0" title="0">if !exists </span><span class="cov0" title="0">{
http.Error(w, userNotFoundMsg, http.StatusNotFound)
return
}</span>
<span class="cov0" title="0">query := `
UPDATE users
SET name = $2, email = $3, updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING id, name, email, created_at, updated_at
`
var user User
err = db.QueryRow(query, id, updateData.Name, updateData.Email).Scan(
&user.ID, &user.Name, &user.Email, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil </span><span class="cov0" title="0">{
if strings.Contains(err.Error(), "unique constraint") </span><span class="cov0" title="0">{
http.Error(w, "Email already exists", http.StatusConflict)
}</span> else<span class="cov0" title="0"> {
http.Error(w, fmt.Sprintf(dbErrorMessage, err), http.StatusInternalServerError)
}</span>
<span class="cov0" title="0">return</span>
}
<span class="cov0" title="0">w.Header().Set(contentTypeHeader, contentTypeJSON)
json.NewEncoder(w).Encode(user)</span>
}
// Delete user by ID
func deleteUser(w http.ResponseWriter, r *http.Request, id int) <span class="cov0" title="0">{
result, err := db.Exec("DELETE FROM users WHERE id = $1", id)
if err != nil </span><span class="cov0" title="0">{
http.Error(w, fmt.Sprintf(dbErrorMessage, err), http.StatusInternalServerError)
return
}</span>
<span class="cov0" title="0">rowsAffected, _ := result.RowsAffected()
if rowsAffected == 0 </span><span class="cov0" title="0">{
http.Error(w, userNotFoundMsg, http.StatusNotFound)
return
}</span>
<span class="cov0" title="0">w.Header().Set(contentTypeHeader, contentTypeJSON)
json.NewEncoder(w).Encode(map[string]interface{}{
"message": "User deleted successfully",
"id": id,
})</span>
}
// Helper function to get environment variables with default values
func getEnv(key, defaultValue string) string <span class="cov0" title="0">{
if value := os.Getenv(key); value != "" </span><span class="cov0" title="0">{
return value
}</span>
<span class="cov0" title="0">return defaultValue</span>
}
</pre>
<pre class="file" id="file1" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package config
import (
"os"
"strconv"
"time"
"github.com/joho/godotenv"
)
type Config struct {
Database DatabaseConfig
}
type DatabaseConfig struct {
// ─── Connection ─────────────────────────
Host string
Port int
Username string
Password string
DatabaseName string
URL string // optional full database URL
// ─── SQL (GORM) Specific ─────────────────
Driver string // postgres | mysql | sqlite
SSLMode string // disable | require
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
}
// ─── Helpers ──────────────────────────────
func ParseInt(value string, defaultValue int) int <span class="cov10" title="6">{
if value == "" </span><span class="cov1" title="1">{
return defaultValue
}</span>
<span class="cov9" title="5">v, err := strconv.Atoi(value)
if err != nil </span><span class="cov1" title="1">{
return defaultValue
}</span>
<span class="cov7" title="4">return v</span>
}
func ParseDuration(value string, defaultValue time.Duration) time.Duration <span class="cov7" title="4">{
if value == "" </span><span class="cov1" title="1">{
return defaultValue
}</span>
<span class="cov6" title="3">d, err := time.ParseDuration(value)
if err != nil </span><span class="cov1" title="1">{
return defaultValue
}</span>
<span class="cov4" title="2">return d</span>
}
// ─── Loader ───────────────────────────────
func Load() (*Config, error) <span class="cov1" title="1">{
// Load .env if present (optional but recommended)
_ = godotenv.Load()
cfg := &Config{
Database: DatabaseConfig{
Host: os.Getenv("DATABASE_HOST"),
Port: ParseInt(os.Getenv("DATABASE_PORT"), 5432),
Username: os.Getenv("DATABASE_USER"),
Password: os.Getenv("DATABASE_PASSWORD"),
DatabaseName: os.Getenv("DATABASE_NAME"),
URL: os.Getenv("DATABASE_URL"),
Driver: "postgres",
SSLMode: os.Getenv("DATABASE_SSL_MODE"),
MaxOpenConns: ParseInt(os.Getenv("DATABASE_MAX_OPEN_CONNS"), 25),
MaxIdleConns: ParseInt(os.Getenv("DATABASE_MAX_IDLE_CONNS"), 5),
ConnMaxLifetime: ParseDuration(os.Getenv("DATABASE_CONN_MAX_LIFETIME"), time.Hour),
},
}
return cfg, nil
}</span>
</pre>
<pre class="file" id="file2" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package database
import (
"github.com/aptlogica/go-postgres-rest/pkg/config"
"github.com/aptlogica/go-postgres-rest/pkg/database/interfaces"
)
// ============================================================================
// DEPRECATED: Use DatabaseConnectorFactory instead
// This is kept for backwards compatibility
// ============================================================================
type Database struct {
Factory *DatabaseConnectorFactory
}
func NewDB() *Database <span class="cov1" title="1">{
// Create factory with default connectors
factory := NewDatabaseConnectorFactory()
factory.RegisterConnector("postgres", NewPostgresConnectionFactory(nil, nil))
return &Database{Factory: factory}
}</span>
// Connect creates a database connection using the configured factory.
// Kept for backwards compatibility; prefer DatabaseConnectorFactory directly.
func (db *Database) Connect(dbType string, cfg *config.DatabaseConfig) (interfaces.DB, error) <span class="cov10" title="5">{
if db.Factory == nil </span><span class="cov1" title="1">{
factory := NewDatabaseConnectorFactory()
factory.RegisterConnector("postgres", NewPostgresConnectionFactory(nil, nil))
db.Factory = factory
}</span>
<span class="cov10" title="5">return db.Factory.CreateConnection(dbType, cfg)</span>
}
</pre>
<pre class="file" id="file3" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package database
import (
"fmt"
"github.com/aptlogica/go-postgres-rest/pkg/config"
"github.com/aptlogica/go-postgres-rest/pkg/database/interfaces"
"github.com/aptlogica/go-postgres-rest/pkg/database/postgres"
)
// ConnectionFactory defines the interface for creating database connections
type ConnectionFactory interface {
CreateConnection(cfg *config.DatabaseConfig) (interfaces.DB, error)
}
// DatabaseConnectorFactory manages multiple database connector implementations
// using a registry pattern for extensibility
type DatabaseConnectorFactory struct {
ConnectorMap map[string]ConnectionFactory
}
// NewDatabaseConnectorFactory creates a new database connector factory
func NewDatabaseConnectorFactory() *DatabaseConnectorFactory <span class="cov8" title="6">{
return &DatabaseConnectorFactory{
ConnectorMap: make(map[string]ConnectionFactory),
}
}</span>
// RegisterConnector registers a connection factory for a specific database type
// This allows extending the factory with new database types without modifying factory code
func (dcf *DatabaseConnectorFactory) RegisterConnector(dbType string, connector ConnectionFactory) <span class="cov8" title="6">{
dcf.ConnectorMap[dbType] = connector
}</span>
// CreateConnection creates a database connection using the registered connector for the specified type
func (dcf *DatabaseConnectorFactory) CreateConnection(dbType string, cfg *config.DatabaseConfig) (interfaces.DB, error) <span class="cov10" title="8">{
connector, exists := dcf.ConnectorMap[dbType]
if !exists </span><span class="cov4" title="2">{
return nil, fmt.Errorf("unsupported database type: %s", dbType)
}</span>
<span class="cov8" title="6">return connector.CreateConnection(cfg)</span>
}
// PostgresConnectionFactory implements ConnectionFactory for PostgreSQL
type PostgresConnectionFactory struct {
dsnBuilder postgres.DSNBuilder
connector postgres.Connector
}
// NewPostgresConnectionFactory creates a new PostgreSQL connection factory
// It uses dependency injection to make the factory testable
func NewPostgresConnectionFactory(dsnBuilder postgres.DSNBuilder, connector postgres.Connector) ConnectionFactory <span class="cov10" title="8">{
if dsnBuilder == nil </span><span class="cov5" title="3">{
dsnBuilder = postgres.NewPostgresDSNBuilder()
}</span>
<span class="cov10" title="8">if connector == nil </span><span class="cov5" title="3">{
connector = postgres.NewPostgresConnector()
}</span>
<span class="cov10" title="8">return &PostgresConnectionFactory{
dsnBuilder: dsnBuilder,
connector: connector,
}</span>
}
// CreateConnection creates a PostgreSQL connection by building DSN and connecting
func (pcf *PostgresConnectionFactory) CreateConnection(cfg *config.DatabaseConfig) (interfaces.DB, error) <span class="cov9" title="7">{
// Build DSN (testable step 1)
dsn, err := pcf.dsnBuilder.BuildDSN(cfg)
if err != nil </span><span class="cov4" title="2">{
return nil, fmt.Errorf("failed to build DSN: %w", err)
}</span>
// Connect (testable step 2)
<span class="cov7" title="5">return pcf.connector.Connect(dsn)</span>
}
// NewDefaultDatabaseConnectorFactory creates a factory pre-configured with standard connectors
func NewDefaultDatabaseConnectorFactory() *DatabaseConnectorFactory <span class="cov1" title="1">{
factory := NewDatabaseConnectorFactory()
factory.RegisterConnector("postgres", NewPostgresConnectionFactory(nil, nil))
return factory
}</span>
</pre>
<pre class="file" id="file4" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package postgres
// BulkRepoImpl implements BulkRepo interface
type BulkRepoImpl struct {
db *PostgresDbService
}
func NewBulkRepo(db *PostgresDbService) *BulkRepoImpl <span class="cov10" title="6">{
return &BulkRepoImpl{db: db}
}</span>
// BulkInsert inserts multiple records
func (b *BulkRepoImpl) BulkInsert(tableName string, records []map[string]interface{}) ([]map[string]interface{}, error) <span class="cov1" title="1">{
return b.db.BulkInsert(tableName, records)
}</span>
// BulkUpdate updates multiple records
func (b *BulkRepoImpl) BulkUpdate(tableName string, updates []map[string]interface{}, whereColumn string) (int64, error) <span class="cov1" title="1">{
return b.db.BulkUpdate(tableName, updates, whereColumn)
}</span>
// BulkDelete deletes multiple records
func (b *BulkRepoImpl) BulkDelete(tableName string, ids []interface{}, idColumn string) (int64, error) <span class="cov1" title="1">{
return b.db.BulkDelete(tableName, ids, idColumn)
}</span>
// Upsert performs insert or update based on conflict
func (b *BulkRepoImpl) Upsert(tableName string, data map[string]interface{}, conflictColumns, updateColumns []string) (map[string]interface{}, error) <span class="cov1" title="1">{
return b.db.Upsert(tableName, data, conflictColumns, updateColumns)
}</span>
</pre>
<pre class="file" id="file5" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package postgres
import (
"database/sql"
"fmt"
"github.com/aptlogica/go-postgres-rest/pkg/database/interfaces"
"time"
_ "github.com/lib/pq"
)
// Connector defines the interface for SQL database connections
type Connector interface {
Connect(dsn string) (interfaces.DB, error)
}
// PostgresConnectorImpl handles PostgreSQL connection creation
type PostgresConnectorImpl struct {
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
}
// NewPostgresConnector creates a new PostgreSQL connector with default settings
func NewPostgresConnector() Connector <span class="cov6" title="2">{
return &PostgresConnectorImpl{
MaxOpenConns: 25,
MaxIdleConns: 5,
ConnMaxLifetime: time.Hour,
}
}</span>
// NewPostgresConnectorWithConfig creates a new PostgreSQL connector with custom settings
func NewPostgresConnectorWithConfig(maxOpen, maxIdle int, maxLifetime time.Duration) Connector <span class="cov10" title="3">{
return &PostgresConnectorImpl{
MaxOpenConns: maxOpen,
MaxIdleConns: maxIdle,
ConnMaxLifetime: maxLifetime,
}
}</span>
// Connect establishes a PostgreSQL connection using the provided DSN
func (pc *PostgresConnectorImpl) Connect(dsn string) (interfaces.DB, error) <span class="cov10" title="3">{
if dsn == "" </span><span class="cov6" title="2">{
return nil, fmt.Errorf("DSN cannot be empty")
}</span>
<span class="cov1" title="1">db, err := sql.Open("postgres", dsn)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to open connection: %w", err)
}</span>
// Configure connection pool
<span class="cov1" title="1">db.SetMaxOpenConns(pc.MaxOpenConns)
db.SetMaxIdleConns(pc.MaxIdleConns)
db.SetConnMaxLifetime(pc.ConnMaxLifetime)
// Verify connection is actually working
if err := db.Ping(); err != nil </span><span class="cov1" title="1">{
db.Close()
return nil, fmt.Errorf("failed to ping database: %w", err)
}</span>
<span class="cov0" title="0">return db, nil</span>
}
</pre>
<pre class="file" id="file6" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package postgres
import (
"context"
"fmt"
"github.com/aptlogica/go-postgres-rest/pkg/models"
)
// CoreRepoImpl implements CoreRepo interface
type CoreRepoImpl struct {
db *PostgresDbService
}
func NewCoreRepo(db *PostgresDbService) *CoreRepoImpl <span class="cov10" title="7">{
return &CoreRepoImpl{db: db}
}</span>
// Ping checks the database connection
//
//go:noinline
func (c *CoreRepoImpl) Ping() (bool, error) <span class="cov6" title="3">{
pgDb := c.db.db
if err := pgDb.Ping(); err != nil </span><span class="cov1" title="1">{
return false, fmt.Errorf("failed to ping database: %w", err)
}</span>
<span class="cov4" title="2">return true, nil</span>
}
// ListCollections retrieves all tables from a schema
//
//go:noinline
func (c *CoreRepoImpl) ListCollections(schema string) ([]models.Table, error) <span class="cov4" title="2">{
return c.db.ListCollections(schema)
}</span>
// ExecuteQuery executes a complex query with parameters
//
//go:noinline
func (c *CoreRepoImpl) ExecuteQuery(name string, params models.QueryParams) (any, error) <span class="cov4" title="2">{
return c.db.ExecuteQuery(name, params)
}</span>
// ExecuteFunction executes a PostgreSQL function
//
//go:noinline
func (c *CoreRepoImpl) ExecuteFunction(ctx context.Context, name string, args map[string]interface{}) (any, error) <span class="cov4" title="2">{
return c.db.ExecuteFunction(ctx, name, args)
}</span>
// ExecuteRawSQL executes raw SQL statements
//
//go:noinline
func (c *CoreRepoImpl) ExecuteRawSQL(ctx context.Context, sql string) error <span class="cov4" title="2">{
_, err := c.db.db.ExecContext(ctx, sql)
if err != nil </span><span class="cov1" title="1">{
return fmt.Errorf("failed to execute raw SQL: %w", err)
}</span>
<span class="cov1" title="1">return nil</span>
}
</pre>
<pre class="file" id="file7" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package postgres
import (
"github.com/aptlogica/go-postgres-rest/pkg/database/interfaces"
)
// DatabaseRepoImpl is the composite implementation that embeds all repository interfaces
type DatabaseRepoImpl struct {
*CoreRepoImpl
*DDLRepoImpl
*DMLRepoImpl
*BulkRepoImpl
*RelationshipRepoImpl
*PerformanceRepoImpl
*MigrationRepoImpl
}
// Verify that DatabaseRepoImpl implements DatabaseRepo interface
var _ interfaces.DatabaseRepo = (*DatabaseRepoImpl)(nil)
// NewDatabaseRepo creates a new composite DatabaseRepo implementation
func NewDatabaseRepo(db *PostgresDbService) interfaces.DatabaseRepo <span class="cov10" title="3">{
return &DatabaseRepoImpl{
CoreRepoImpl: NewCoreRepo(db),
DDLRepoImpl: NewDDLRepo(db),
DMLRepoImpl: NewDMLRepo(db),
BulkRepoImpl: NewBulkRepo(db),
RelationshipRepoImpl: NewRelationshipRepo(db),
PerformanceRepoImpl: NewPerformanceRepo(db),
MigrationRepoImpl: NewMigrationRepo(db),
}
}</span>
// Convenience methods to satisfy specific interfaces if needed
//
//go:noinline
func (dr *DatabaseRepoImpl) AsCoreRepo() interfaces.CoreRepo <span class="cov6" title="2">{
return dr.CoreRepoImpl
}</span>
//go:noinline
func (dr *DatabaseRepoImpl) AsDDLRepo() interfaces.DDLRepo <span class="cov6" title="2">{
return dr.DDLRepoImpl
}</span>
//go:noinline
func (dr *DatabaseRepoImpl) AsDMLRepo() interfaces.DMLRepo <span class="cov6" title="2">{
return dr.DMLRepoImpl
}</span>
//go:noinline
func (dr *DatabaseRepoImpl) AsBulkRepo() interfaces.BulkRepo <span class="cov6" title="2">{
return dr.BulkRepoImpl
}</span>
//go:noinline
func (dr *DatabaseRepoImpl) AsRelationshipRepo() interfaces.RelationshipRepo <span class="cov6" title="2">{
return dr.RelationshipRepoImpl
}</span>
//go:noinline
func (dr *DatabaseRepoImpl) AsPerformanceRepo() interfaces.PerformanceRepo <span class="cov6" title="2">{
return dr.PerformanceRepoImpl
}</span>
//go:noinline
func (dr *DatabaseRepoImpl) AsMigrationRepo() interfaces.MigrationRepo <span class="cov6" title="2">{
return dr.MigrationRepoImpl
}</span>
</pre>
<pre class="file" id="file8" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com
// Support: support@aptlogica.com | support@serenibase.com
package postgres
import (
"fmt"
"github.com/aptlogica/go-postgres-rest/pkg/models"
)
// DDLRepoImpl implements DDLRepo interface
type DDLRepoImpl struct {
db *PostgresDbService
}
func NewDDLRepo(db *PostgresDbService) *DDLRepoImpl <span class="cov10" title="7">{
return &DDLRepoImpl{db: db}
}</span>
// CreateCollection creates a new table
//
//go:noinline
func (d *DDLRepoImpl) CreateCollection(req models.CreateTableRequest) error <span class="cov4" title="2">{
return d.db.CreateCollection(req)
}</span>
// AddField adds a new column to a table
//
//go:noinline
func (d *DDLRepoImpl) AddField(collection string, req models.AddColumnRequest) error <span class="cov4" title="2">{
return d.db.AddField(collection, req)
}</span>
// AlterCollection alters an existing table
//
//go:noinline
func (d *DDLRepoImpl) AlterCollection(collection string, req models.AlterTableRequest) error <span class="cov4" title="2">{
return d.db.AlterCollection(collection, req)
}</span>
// CheckTableExists checks if a table exists
//
//go:noinline
func (d *DDLRepoImpl) CheckTableExists(tableName string) (bool, error) <span class="cov4" title="2">{
query := `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1)`
var exists bool
err := d.db.db.QueryRow(query, tableName).Scan(&exists)
if err != nil </span><span class="cov0" title="0">{
return false, fmt.Errorf("failed to check table existence: %w", err)
}</span>
<span class="cov4" title="2">return exists, nil</span>
}
</pre>
<pre class="file" id="file9" style="display: none">// Copyright (c) 2026 Aptlogica Technologies Private Limited
// SPDX-License-Identifier: MIT
// Websites: https://www.aptlogica.com | https://www.serenibase.com