Jan Trtík avatar Jan Trtík committed 82aeff7

implemented Collection.ensureIndex

Comments (0)

Files changed (2)

fan/Collection.fan

   }
   
   **
+  **  See `DB.indexExists` for details.
+  **
+  Bool indexExists(Str indexName)
+  {
+     return db.indexExists(this.name, indexName)
+  }
+  
+  **
+  **  Ensures that an index exists in this collection, if it does not it creates it.
+  **
+  Str ensureIndex([Str:Int][] fields, Bool unique := false, Bool dropDups := false)
+  {
+    namestr := indexName(fields)
+    if(indexExists(namestr))
+    {
+       return namestr
+    }
+       return createIndex(fields,unique, dropDups)
+  }
+
+  **
   **  Create a new index in this collection.
   **
-  Str createIndex([Str:Int][] fields, Bool unique := false)
+  Str createIndex([Str:Int][] fields, Bool unique := false, Bool dropDups := false)
   {
     key := [:] { ordered = true }
     fields.each |map| { key.addAll(map) }
     selector := ["name"    : namestr,
                   "ns"     : fullName,
                   "key"    : key,
-                  "unique" : unique]
-                  // todo - dropDups
+                  "unique" : unique,
+                  "dropDups" : dropDups]
+
     Collection(db, "system.indexes").insertDocs([selector], true) // add this in safe mode?
     return namestr
   }
-  
+
   **
   ** Creates the index name used for the given fields.
   ** This is the same name that is returned from `Collection.createIndex`
     }
     return info
   }
+
+  **
+  ** Returns true if index exists in collection
+  **
+  Bool indexExists(Str coll, Str idxName)
+  {
+     idx := collection("system.indexes").findOne(["ns": "${this.name}.${coll}", "name": "$idxName"])
+     return idx != null
+  }
   
   Void dropIndex(Str coll, Str idx)
   {
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.