Skip to content

Commit

Permalink
add insertMany deleteMany
Browse files Browse the repository at this point in the history
  • Loading branch information
manyuanrong committed Mar 4, 2020
1 parent 715ca63 commit ff72aa4
Show file tree
Hide file tree
Showing 12 changed files with 152 additions and 65 deletions.
24 changes: 9 additions & 15 deletions src/command/delete.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::*;
use bson::Bson;
use serde_json::Value;

#[derive(Deserialize, Debug)]
Expand All @@ -19,24 +18,19 @@ pub fn delete(command: Command) -> CoreOp {
let db_name = args.db_name;
let collection_name = args.collection_name;
let delete_one = args.delete_one;
let query = args.query;
let query = util::json_to_document(args.query).expect("query canot be null");
let database = client.database(&db_name);
let collection = database.collection(&collection_name);

let query_doc: Bson = query.into();
if let Bson::Document(query_doc) = query_doc {
let delete_result = if delete_one {
collection.delete_one(query_doc, None).unwrap()
} else {
collection.delete_many(query_doc, None).unwrap()
};
Ok(util::async_result(
&command.args,
delete_result.deleted_count,
))
let delete_result = if delete_one {
collection.delete_one(query, None).unwrap()
} else {
Err(())
}
collection.delete_many(query, None).unwrap()
};
Ok(util::async_result(
&command.args,
delete_result.deleted_count,
))
};
CoreOp::Async(fut.boxed())
}
15 changes: 4 additions & 11 deletions src/command/find_one.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::*;
use bson::Bson;
use serde_json::Value;
use util::maybe_json_to_document;

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct FindOnetArgs {
db_name: String,
collection_name: String,
filter: Value,
filter: Option<Value>,
}

pub fn find_one(command: Command) -> CoreOp {
Expand All @@ -17,17 +17,10 @@ pub fn find_one(command: Command) -> CoreOp {
let args: FindOnetArgs = serde_json::from_slice(data.unwrap().as_ref()).unwrap();
let db_name = args.db_name;
let collection_name = args.collection_name;
let filter = args.filter;
let filter = maybe_json_to_document(args.filter);
let database = client.database(&db_name);
let collection = database.collection(&collection_name);

let filter_doc: Bson = filter.into();
let filter_doc = match filter_doc {
Bson::Document(doc) => Some(doc),
_ => None,
};

let doc = collection.find_one(filter_doc, None).unwrap();
let doc = collection.find_one(filter, None).unwrap();
Ok(util::async_result(&command.args, doc))
};
CoreOp::Async(fut.boxed())
Expand Down
60 changes: 60 additions & 0 deletions src/command/insert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use crate::*;
use bson::Document;
use serde_json::Value;

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct InsertManyArgs {
db_name: String,
collection_name: String,
docs: Vec<Value>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct InsertOneArgs {
db_name: String,
collection_name: String,
doc: Value,
}

pub fn insert_one(command: Command) -> CoreOp {
let fut = async move {
let client = command.get_client();
let data = command.data;
let args: InsertOneArgs = serde_json::from_slice(data.unwrap().as_ref()).unwrap();
let db_name = args.db_name;
let collection_name = args.collection_name;
let doc = util::json_to_document(args.doc).expect("doc canot be null");
let database = client.database(&db_name);
let collection = database.collection(&collection_name);

let insert_result = collection.insert_one(doc, None).unwrap();
Ok(util::async_result(&command.args, insert_result.inserted_id))
};
CoreOp::Async(fut.boxed())
}

pub fn insert_many(command: Command) -> CoreOp {
let fut = async move {
let client = command.get_client();
let data = command.data;
let args: InsertManyArgs = serde_json::from_slice(data.unwrap().as_ref()).unwrap();
let db_name = args.db_name;
let collection_name = args.collection_name;
let docs: Vec<Document> = util::jsons_to_documents(args.docs);

let database = client.database(&db_name);
let collection = database.collection(&collection_name);

let insert_result = collection.insert_many(docs, None).unwrap();
let ids: Vec<bson::Bson> = insert_result
.inserted_ids
.iter()
.map(|(_, id)| id.to_owned())
.collect();

Ok(util::async_result(&command.args, ids))
};
CoreOp::Async(fut.boxed())
}
33 changes: 0 additions & 33 deletions src/command/insert_one.rs

This file was deleted.

2 changes: 1 addition & 1 deletion src/command/list_collection_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub fn list_collection_names(command: Command) -> CoreOp {
let db_name: Vec<u8> = data.unwrap().as_ref().to_vec();
let db_name = String::from_utf8(db_name).unwrap();
let database = client.database(&db_name);
let collection_names = database.list_collection_names(None);
let collection_names = database.list_collection_names(None::<bson::Document>);

Ok(util::async_result(&command.args, collection_names.unwrap()))
};
Expand Down
4 changes: 3 additions & 1 deletion src/command/list_database_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use crate::*;

pub fn list_database_names(command: Command) -> CoreOp {
let fut = async move {
let names = command.get_client().list_database_names(None);
let names = command
.get_client()
.list_database_names(None::<bson::Document>);
let data = names.unwrap();
Ok(util::async_result(&command.args, data))
};
Expand Down
4 changes: 2 additions & 2 deletions src/command/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
mod connect;
mod delete;
mod find_one;
mod insert_one;
mod insert;
mod list_collection_names;
mod list_database_names;

pub use connect::{connect_with_options, connect_with_uri};
pub use delete::delete;
pub use find_one::find_one;
pub use insert_one::insert_one;
pub use insert::{insert_many, insert_one};
pub use list_collection_names::list_collection_names;
pub use list_database_names::list_database_names;
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub enum CommandType {
ListDatabases,
FindOne,
ListCollectionNames,
InsertMany,
InsertOne,
Delete,
}
Expand Down Expand Up @@ -94,6 +95,7 @@ fn op_command(data: &[u8], zero_copy: Option<ZeroCopyBuf>) -> CoreOp {
CommandType::ListCollectionNames => command::list_collection_names,
CommandType::FindOne => command::find_one,
CommandType::InsertOne => command::insert_one,
CommandType::InsertMany => command::insert_many,
CommandType::Delete => command::delete,
};

Expand Down
25 changes: 25 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::*;
use bson::{Bson, Document};
use serde_json::Value;

pub fn async_result<T>(args: &CommandArgs, data: T) -> Buf
where
Expand All @@ -12,3 +14,26 @@ where
let data = serde_json::to_vec(&json).unwrap();
Buf::from(data)
}

pub fn maybe_json_to_document(maybe_json: Option<Value>) -> Option<Document> {
if let Some(val) = maybe_json {
json_to_document(val)
} else {
None
}
}

pub fn json_to_document(json: Value) -> Option<Document> {
let bson: Bson = json.into();
match bson {
Bson::Document(doc) => Some(doc),
_ => None,
}
}

pub fn jsons_to_documents(jsons: Vec<Value>) -> Vec<Document> {
jsons
.iter()
.filter_map(|json| json_to_document(json.to_owned()))
.collect()
}
28 changes: 27 additions & 1 deletion test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,27 @@ test(async function testInsertOne() {
});
});

test(async function testInsertMany() {
const db = getClient().database("test");
const users = db.collection("mongo_test_users");
const insertIds = await users.insertMany([
{
username: "many",
password: "pass1"
},
{
username: "many",
password: "pass1"
}
]);

assertEquals(insertIds.length, 2);
});

test(async function testFindOne() {
const db = getClient().database("test");
const users = db.collection("mongo_test_users");
const user1 = await users.findOne({});
const user1 = await users.findOne();
assert(user1 instanceof Object);
assertEquals(Object.keys(user1), ["_id", "username", "password"]);

Expand All @@ -73,6 +90,15 @@ test(async function testDeleteOne() {
assertEquals(deleteCount, 1);
});

test(async function testDeleteMany() {
const db = getClient().database("test");
const users = db.collection("mongo_test_users");
const deleteCount = await users.deleteMany({
username: "many"
});
assertEquals(deleteCount, 2);
});

await cargoBuild();
await init("master");
await runTests();
19 changes: 18 additions & 1 deletion ts/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class Collection {
private readonly collectionName: string
) {}

public async findOne(filter: Object): Promise<any> {
public async findOne(filter?: Object): Promise<any> {
const doc = await dispatchAsync(
{
command_type: CommandType.FindOne,
Expand Down Expand Up @@ -43,6 +43,23 @@ export class Collection {
return _id;
}

public async insertMany(docs: Object[]): Promise<any> {
const _ids = await dispatchAsync(
{
command_type: CommandType.InsertMany,
client_id: this.client.clientId
},
encode(
JSON.stringify({
dbName: this.dbName,
collectionName: this.collectionName,
docs
})
)
);
return _ids;
}

private async _delete(
query: Object,
deleteOne: boolean = false
Expand Down
1 change: 1 addition & 0 deletions ts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ export enum CommandType {
ListCollectionNames = "ListCollectionNames",
FindOne = "FindOne",
InsertOne = "InsertOne",
InsertMany = "InsertMany",
Delete = "Delete"
}

0 comments on commit ff72aa4

Please sign in to comment.