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
use std::error::Error;
use std::sync::Arc;

use bson::{self, Bson};
use auth::Authenticator;
use client::Client;
use coll::Collection;
use coll::options::FindOptions;
use command_type::CommandType;
use common::{ReadPreference, merge_options, WriteConcern};
use cursor::{Cursor, DEFAULT_BATCH_SIZE};
use semver::Version;
use error::Result;
use error::Error::{CursorNotFoundError, OperationError, ResponseError};

use self::options::{CreateCollectionOptions, CreateUserOptions, UserInfoOptions};

pub mod options;
pub mod roles;

#[derive(Clone)]
pub struct Database {
    pub inner: Arc<DatabaseInner>
}

pub struct DatabaseInner {
    /// The database name.
    pub name: String,
    /// A reference to the client that spawned this database.
    pub client: Client,
    /// Indicates how a server should be selected for read operations.
    pub read_preference: ReadPreference,
    /// Describes the guarantees provided by MongoDB when reporting the success of a write
    /// operation.
    pub write_concern: WriteConcern,
}

fn is_send<T: Send>() {}
fn is_sync<T: Sync>() {}

impl Database {
    pub fn open(
        client: Client,
        name: &str,
        read_preference: Option<ReadPreference>,
        write_concern: Option<WriteConcern>
    ) -> Database {
        is_send::<Client>();
        is_sync::<Client>();

        let rp = read_preference.unwrap_or_else(|| client.inner.read_preference.clone());
        let wc = write_concern.unwrap_or_else(|| client.inner.write_concern.clone());

        Database {
            inner: Arc::new(DatabaseInner {
                name: name.to_string(),
                client: client,
                read_preference: rp,
                write_concern: wc,
            })
        }
    }

    pub fn auth(&self, user: &str, password: &str) -> Result<()> {
        let authenticator = Authenticator::new(self.clone());
        authenticator.auth(user, password)
    }

    pub fn collection(&self, coll_name: &str) -> Collection {
        Collection::new(
            self.clone(),
            coll_name,
            false,
            Some(self.inner.read_preference.clone()),
            Some(self.inner.write_concern.clone())
        )
    }

    pub fn collection_with_prefs(
        &self,
        coll_name: &str,
        create: bool,
        read_preference: Option<ReadPreference>,
        write_concern: Option<WriteConcern>
    ) -> Collection {
        Collection::new(
            self.clone(),
            coll_name,
            create,
            read_preference,
            write_concern
        )
    }

    pub fn get_req_id(&self) -> i32 {
        self.inner.client.get_req_id()
    }

    pub fn command_cursor(
        &self,
        spec: bson::Document,
        cmd_type: CommandType,
        read_pref: ReadPreference
    ) -> Result<Cursor> {
        Cursor::command_cursor(
            self.inner.client.clone(),
            &self.inner.name,
            spec,
            cmd_type,
            read_pref
        )
    }

    pub fn command(
        &self,
        spec: bson::Document,
        cmd_type: CommandType,
        read_preference: Option<ReadPreference>
    ) -> Result<bson::Document> {

        let coll = self.collection("$cmd");
        let mut options = FindOptions::new();
        options.batch_size = Some(1);
        options.read_preference = read_preference;
        let res = coll.find_one_with_command_type(Some(spec.clone()), Some(options), cmd_type)?;
        res.ok_or_else(|| {
            OperationError(format!("Failed to execute command with spec {:?}.", spec))
        })
    }

    pub fn list_collections(&self, filter: Option<bson::Document>) -> Result<Cursor> {
        self.list_collections_with_batch_size(filter, DEFAULT_BATCH_SIZE)
    }

    pub fn list_collections_with_batch_size(
        &self,
        filter: Option<bson::Document>,
        batch_size: i32
    ) -> Result<Cursor> {

        let mut spec = bson::Document::new();
        let mut cursor = bson::Document::new();

        cursor.insert("batchSize", Bson::Int32(batch_size));
        spec.insert("listCollections", Bson::Int32(1));
        spec.insert("cursor", Bson::Document(cursor));
        if filter.is_some() {
            spec.insert("filter", Bson::Document(filter.unwrap()));
        }

        self.command_cursor(
            spec,
            CommandType::ListCollections,
            self.inner.read_preference.clone()
        )
    }

    pub fn collection_names(&self, filter: Option<bson::Document>) -> Result<Vec<String>> {
        let mut cursor = self.list_collections(filter)?;
        let mut results = vec![];
        loop {
            match cursor.next() {
                Some(Ok(doc)) => {
                    if let Some(&Bson::String(ref name)) = doc.get("name") {
                        results.push(name.to_string());
                    }
                }
                Some(Err(err)) => return Err(err),
                None => return Ok(results),
            }
        }
    }

    pub fn version(&self) -> Result<Version> {
        let doc = doc! { "buildinfo": 1 };
        let out = self.command(doc, CommandType::BuildInfo, None)?;

        match out.get("version") {
            Some(&Bson::String(ref s)) => {
                match Version::parse(s) {
                    Ok(v) => Ok(v),
                    Err(e) => Err(ResponseError(e.description().to_string())),
                }
            }
            _ => Err(ResponseError("No version received from server".to_string())),
        }
    }

    pub fn create_collection(
        &self,
        name: &str,
        options: Option<CreateCollectionOptions>
    ) -> Result<()> {
        let mut doc = doc! { "create": name };

        if let Some(create_collection_options) = options {
            doc = merge_options(doc, create_collection_options);
        }

        self.command(doc, CommandType::CreateCollection, None).map(|_| ())
    }

    pub fn create_user(
        &self,
        name: &str,
        password: &str,
        options: Option<CreateUserOptions>
    ) -> Result<()> {
        let mut doc = doc! {
            "createUser": name,
            "pwd": password
        };

        match options {
            Some(user_options) => {
                doc = merge_options(doc, user_options);
            }
            None => {
                doc.insert("roles", Bson::Array(Vec::new()));
            }
        };

        self.command(doc, CommandType::CreateUser, None).map(|_| ())
    }

    pub fn drop_all_users(&self, write_concern: Option<WriteConcern>) -> Result<(i32)> {
        let mut doc = doc! { "dropAllUsersFromDatabase": 1 };

        if let Some(concern) = write_concern {
            doc.insert("writeConcern", Bson::Document(concern.to_bson()));
        }

        let response = self.command(doc, CommandType::DropAllUsers, None)?;

        match response.get("n") {
            Some(&Bson::Int32(i)) => Ok(i),
            Some(&Bson::Int64(i)) => Ok(i as i32),
            _ => Err(CursorNotFoundError),
        }
    }

    pub fn drop_collection(&self, name: &str) -> Result<()> {
        let mut spec = bson::Document::new();
        spec.insert("drop", Bson::String(name.to_string()));
        self.command(spec, CommandType::DropCollection, None)?;
        Ok(())
    }

    pub fn drop_database(&self) -> Result<()> {
        let mut spec = bson::Document::new();
        spec.insert("dropDatabase", Bson::Int32(1));
        self.command(spec, CommandType::DropDatabase, None)?;
        Ok(())
    }

    pub fn drop_user(&self, name: &str, write_concern: Option<WriteConcern>) -> Result<()> {
        let mut doc = doc! { "dropUser": name };

        if let Some(concern) = write_concern {
            doc.insert("writeConcern", (concern.to_bson()));
        }

        self.command(doc, CommandType::DropUser, None).map(|_| ())
    }

    pub fn get_all_users(&self, show_credentials: bool) -> Result<Vec<bson::Document>> {
        let doc = doc! {
            "usersInfo": 1,
            "showCredentials": show_credentials
        };

        let out = self.command(doc, CommandType::GetUsers, None)?;
        let vec = match out.get("users") {
            Some(&Bson::Array(ref vec)) => vec.clone(),
            _ => return Err(CursorNotFoundError),
        };

        let mut users = vec![];

        for bson in vec {
            match bson {
                Bson::Document(doc) => users.push(doc),
                _ => return Err(CursorNotFoundError),
            };
        }

        Ok(users)
    }

    pub fn get_user(&self, user: &str, options: Option<UserInfoOptions>) -> Result<bson::Document> {
        let mut doc = doc! {
            "usersInfo": {
                "user": user,
                "db": (self.inner.name.to_string())
            }
        };

        if let Some(user_info_options) = options {
            doc = merge_options(doc, user_info_options);
        }

        let out = match self.command(doc, CommandType::GetUser, None) {
            Ok(doc) => doc,
            Err(e) => return Err(e),
        };

        let users = match out.get("users") {
            Some(&Bson::Array(ref v)) => v.clone(),
            _ => return Err(CursorNotFoundError),
        };

        match users.first() {
            Some(&Bson::Document(ref doc)) => Ok(doc.clone()),
            _ => Err(CursorNotFoundError),
        }
    }

    pub fn get_users(
        &self,
        users: Vec<&str>,
        options: Option<UserInfoOptions>
    ) -> Result<Vec<bson::Document>> {
        let vec: Vec<_> = users.into_iter()
            .map(|user| {
                let doc = doc! {
                    "user": user,
                    "db": (self.inner.name.to_string())
                };
                Bson::Document(doc)
            })
            .collect();

        let mut doc = doc! { "usersInfo": vec };

        if let Some(user_info_options) = options {
            doc = merge_options(doc, user_info_options);
        }

        let out = self.command(doc, CommandType::GetUsers, None)?;
        let vec = match out.get("users") {
            Some(&Bson::Array(ref vec)) => vec.clone(),
            _ => return Err(CursorNotFoundError),
        };

        let mut users = vec![];

        for bson in vec {
            match bson {
                Bson::Document(doc) => users.push(doc),
                _ => return Err(CursorNotFoundError),
            };
        }

        Ok(users)
    }
}