-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
187 lines (156 loc) · 4.56 KB
/
Copy pathmain.go
File metadata and controls
187 lines (156 loc) · 4.56 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
// Package main demonstrates database connection examples.
package main
import (
"context"
"fmt"
"time"
"github.com/yigithankarabulut/wirekit"
"github.com/yigithankarabulut/wirekit/mongox"
"go.uber.org/zap"
)
// User represents a user model.
type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"size:100"`
Email string `gorm:"uniqueIndex"`
}
// PostgresGORM demonstrates PostgreSQL with GORM.
func PostgresGORM() {
fmt.Println("\n--- PostgreSQL with GORM ---")
db, err := wirekit.Postgres().GORM().
WithDSN("host=localhost user=postgres password=secret dbname=myapp port=5432 sslmode=disable").
WithMaxIdleConns(10).
WithMaxOpenConns(100).
WithConnMaxLifetime(time.Hour).
Connect()
if err != nil {
wirekit.Error("failed to connect to postgres", zap.Error(err))
return
}
wirekit.Info("connected to postgres with GORM")
// Auto-migrate tables
if err := db.AutoMigrate(&User{}); err != nil {
wirekit.Error("failed to auto-migrate tables", zap.Error(err))
}
// Create a user
user := User{Name: "John Doe", Email: "john@example.com"}
if err := db.Create(&user).Error; err != nil {
wirekit.Error("failed to create user", zap.Error(err))
}
// Query
var users []User
db.Find(&users)
fmt.Printf("Found %d users\n", len(users))
}
// PostgresPGX demonstrates PostgreSQL with pgx.
func PostgresPGX(ctx context.Context) {
fmt.Println("\n--- PostgreSQL with PGX ---")
pool, err := wirekit.Postgres().PGX().
WithDSN("postgres://user:password@localhost:5432/mydb").
WithMaxConns(25).
WithMinConns(5).
Connect(ctx)
if err != nil {
wirekit.Error("failed to connect with pgx", zap.Error(err))
return
}
defer pool.Close()
wirekit.Info("connected to postgres with pgx")
// Query example
row := pool.QueryRow(ctx, "SELECT id, name FROM users WHERE id = $1", 1)
var id int
var name string
if err := row.Scan(&id, &name); err != nil {
wirekit.Debug("query failed", zap.Error(err))
}
}
// PostgresSQL demonstrates PostgreSQL with database/sql.
func PostgresSQL() {
fmt.Println("\n--- PostgreSQL with database/sql ---")
sqlDB, err := wirekit.Postgres().SQL().
WithDSN("postgres://user:password@localhost:5432/mydb?sslmode=disable").
WithMaxIdleConns(10).
WithMaxOpenConns(100).
Connect()
if err != nil {
wirekit.Error("failed to connect with database/sql", zap.Error(err))
return
}
defer func() {
if err := sqlDB.Close(); err != nil {
wirekit.Error("failed to close database/sql", zap.Error(err))
}
}()
wirekit.Info("connected to postgres with database/sql")
rows, err := sqlDB.Query("SELECT * FROM users LIMIT 10")
if err == nil {
defer func() {
if err := rows.Close(); err != nil {
wirekit.Error("failed to close rows", zap.Error(err))
}
}()
}
}
// MongoDBConnection demonstrates MongoDB connection.
func MongoDBConnection(ctx context.Context) {
fmt.Println("\n--- MongoDB ---")
client, mongoDB, err := wirekit.Mongo().
WithURI("mongodb://localhost:27017").
WithDatabase("myapp").
WithTimeout(10 * time.Second).
WithMaxPoolSize(100).
WithMinPoolSize(10).
ConnectWithDB(ctx)
if err != nil {
wirekit.Error("failed to connect to MongoDB", zap.Error(err))
return
}
defer func() {
if err := client.Disconnect(ctx); err != nil {
wirekit.Error("failed to disconnect from MongoDB", zap.Error(err))
}
}()
wirekit.Info("connected to MongoDB")
// Get collection
collection := mongoDB.Collection("users")
fmt.Printf("Collection: %s\n", collection.Name())
}
// MongoDBHelpers demonstrates MongoDB helper functions.
func MongoDBHelpers() {
fmt.Println("\n--- MongoDB Helpers ---")
// ObjectID utilities
objectID := wirekit.MongoX.NewObjectID()
fmt.Println("New ObjectID:", objectID.Hex())
hexString := "507f1f77bcf86cd799439011"
parsedID := wirekit.MongoX.ToObjectID(hexString)
fmt.Println("Parsed ObjectID:", parsedID.Hex())
isValid := wirekit.MongoX.IsValidObjectID(hexString)
fmt.Println("Is Valid ObjectID:", isValid)
// Filter builder
filter := mongox.Filter().
Eq("status", "active").
Gte("age", 18).
In("role", []string{"admin", "user"}).
Regex("email", ".*@example.com", "i").
Build()
fmt.Printf("Filter: %+v\n", filter)
// Update builder
update := mongox.Update().
Set("name", "John Doe").
Set("updated_at", time.Now()).
Inc("login_count", 1).
Unset("temp_field").
Push("tags", "new-tag").
Build()
fmt.Printf("Update: %+v\n", update)
}
func main() {
ctx := context.Background()
wirekit.Log(wirekit.Zap).WithLevel("info").Init()
PostgresGORM()
PostgresPGX(ctx)
PostgresSQL()
MongoDBConnection(ctx)
MongoDBHelpers()
wirekit.Info("database example completed")
}