2 Commits

Author SHA1 Message Date
336dea8147 ensure multiple index via db interface 2022-02-10 16:10:38 +01:00
f8f8cb2366 removed debug msg 2022-02-10 15:33:20 +01:00
3 changed files with 15 additions and 10 deletions

7
mgo.go
View File

@@ -2,7 +2,6 @@ package mgocrud
import (
"errors"
"fmt"
"runtime"
mgo "gopkg.in/mgo.v2"
@@ -14,7 +13,6 @@ type MgoConnection struct {
}
func NewMgoConnection(dial string) (Connection, error) {
fmt.Println("CONNECTION CREATE")
connection, err := mgo.Dial(dial)
if err != nil {
return nil, err
@@ -22,7 +20,6 @@ func NewMgoConnection(dial string) (Connection, error) {
connection.SetMode(mgo.Monotonic, true)
c := &MgoConnection{connection: connection}
runtime.SetFinalizer(c, func(c *MgoConnection) {
fmt.Println("CONNECTION CLOSE FINALIZER")
if !c.closed {
c.Close()
}
@@ -31,7 +28,6 @@ func NewMgoConnection(dial string) (Connection, error) {
}
func (c *MgoConnection) Close() {
fmt.Println("CONNECTION CLOSE MANUALLY")
if !c.closed {
c.connection.Close()
c.closed = true
@@ -45,7 +41,6 @@ type MgoSession struct {
}
func (s *MgoSession) Close() {
fmt.Println("SESSION CLOSE MANUALLY")
if !s.closed {
s.session.Close()
s.closed = true
@@ -54,10 +49,8 @@ func (s *MgoSession) Close() {
}
func (c *MgoConnection) NewSession() Session {
fmt.Println("SESSION CREATE")
s := &MgoSession{session: c.connection.Copy()}
runtime.SetFinalizer(s, func(s *MgoSession) {
fmt.Println("SESSION CLOSE FINALIZER")
if !s.closed {
s.Close()
}

View File

@@ -9,10 +9,22 @@ import (
)
// EnsureIndex ensured mongodb index reflecting model struct index tag
func (db *MgoDatabase) EnsureIndex(m ModelInterface) error {
func (db *MgoDatabase) EnsureIndex(m ModelInterface, index ...Index) error {
colName := GetCollectionName(m)
col := db.C(colName)
if len(index) > 0 {
// only ensure given index
for _, i := range index {
err := col.EnsureIndex(i)
if err != nil {
return err
}
}
return nil
}
// ensure index by struct fields
mType := reflect.TypeOf(m)
textFields := []string{}

View File

@@ -22,9 +22,9 @@ type Session interface {
type Database interface {
Session() Session
C(name string) Collection
// C(name string) Collection
Name() string
EnsureIndex(m ModelInterface) error
EnsureIndex(m ModelInterface, index ...Index) error
ValidateObject(m ModelInterface, changes bson.M) error
ReadDocument(m ModelInterface, selector bson.M) error
CreateDocument(m ModelInterface) error