parse-rs 0.2.0

A modern and asynchronous Rust SDK for interacting with Parse Server backends
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use parse_rs::schema::{ClassLevelPermissionsSchema, FieldSchema, FieldType, IndexFieldType};
use parse_rs::ParseError;
use serde_json::json;
use std::collections::HashMap;

mod query_test_utils;
use query_test_utils::shared::setup_client_with_master_key;

// Helper function to generate a unique class name for testing to avoid collisions
fn unique_class_name(base: &str) -> String {
    use rand::distributions::Alphanumeric;
    use rand::{thread_rng, Rng};
    let suffix: String = thread_rng()
        .sample_iter(&Alphanumeric)
        .take(8)
        .map(char::from)
        .collect();
    format!("{}_{}", base, suffix)
}

#[tokio::test]
async fn test_create_get_and_delete_class_schema() {
    let client = setup_client_with_master_key();
    let class_name = unique_class_name("TestSchemaLifecycle");

    // 1. Create a new class schema
    let mut fields_to_create = HashMap::new();
    fields_to_create.insert(
        "textField".to_string(),
        FieldSchema {
            field_type: FieldType::String,
            target_class: None,
            required: Some(false),
            default_value: Some(json!("default text")),
        },
    );
    fields_to_create.insert(
        "numberField".to_string(),
        FieldSchema {
            field_type: FieldType::Number,
            target_class: None,
            required: Some(true),
            default_value: None,
        },
    );

    let clp = ClassLevelPermissionsSchema {
        find: Some([("*".to_string(), true)].iter().cloned().collect()),
        get: Some([("*".to_string(), true)].iter().cloned().collect()),
        create: Some([("*".to_string(), true)].iter().cloned().collect()),
        update: Some([("*".to_string(), true)].iter().cloned().collect()),
        delete: Some([("*".to_string(), true)].iter().cloned().collect()),
        add_field: Some([("*".to_string(), true)].iter().cloned().collect()),
        ..Default::default()
    };

    let schema_to_create_payload = json!({
        "className": class_name,
        "fields": fields_to_create,
        "classLevelPermissions": clp
    });

    let created_schema = client
        .create_class_schema(&class_name, &schema_to_create_payload)
        .await
        .expect("Failed to create class schema");

    assert_eq!(created_schema.class_name, class_name);
    assert_eq!(created_schema.fields.len(), fields_to_create.len() + 4); // +3 for default ACL, objectId, createdAt, updatedAt (actually +4, server adds them)
    assert!(created_schema.fields.contains_key("textField"));
    assert!(created_schema.fields.contains_key("numberField"));
    assert!(created_schema.fields.contains_key("ACL"));
    assert!(created_schema.fields.contains_key("objectId"));
    assert!(created_schema.fields.contains_key("createdAt"));
    assert!(created_schema.fields.contains_key("updatedAt"));

    if let Some(retrieved_clp) = &created_schema.class_level_permissions {
        assert_eq!(retrieved_clp.find, clp.find);
    } else {
        panic!("CLP not found in created schema response");
    }

    // 2. Verify by fetching the specific schema
    let fetched_schema = client
        .get_class_schema(&class_name)
        .await
        .expect("Failed to fetch created class schema");

    assert_eq!(fetched_schema.class_name, class_name);
    assert_eq!(fetched_schema.fields.len(), created_schema.fields.len());
    assert_eq!(
        fetched_schema.class_level_permissions,
        created_schema.class_level_permissions
    );

    // 3. Verify it appears in all schemas list
    let all_schemas_response = client
        .get_all_schemas()
        .await
        .expect("Failed to get all schemas");

    // Debug print for indexes
    for schema in &all_schemas_response.results {
        if let Some(indexes) = &schema.indexes {
            for (index_name, index_fields) in indexes {
                for (field_name, value) in index_fields {
                    match value {
                        IndexFieldType::Text(text_val) => {
                            println!(
                                "DEBUG: Schema '{}', Index '{}', Field '{}': Text index value: {:?}",
                                schema.class_name, index_name, field_name, text_val
                            );
                        }
                        IndexFieldType::Other(other_val) => {
                            println!(
                                "DEBUG: Schema '{}', Index '{}', Field '{}': Other index value: {:?}",
                                schema.class_name, index_name, field_name, other_val
                            );
                        }
                        IndexFieldType::SortOrder(_) => {
                            // This is expected, do nothing.
                        }
                    }
                }
            }
        }
    }

    assert!(
        all_schemas_response
            .results
            .iter()
            .any(|s| s.class_name == class_name),
        "Created schema not found in all schemas list"
    );

    // 4. Delete the class schema
    client
        .delete_class_schema(&class_name, true)
        .await
        .expect("Failed to delete class schema");

    // 5. Verify deletion by trying to fetch it again (should fail)
    match client.get_class_schema(&class_name).await {
        Err(ParseError::OtherParseError { code, message }) => {
            assert_eq!(code, 103);
            assert!(
                message.to_lowercase().contains("does not exist")
                    || message.to_lowercase().contains("class not found")
            );
        }
        Ok(_) => panic!("Fetching schema after deletion should have failed but succeeded."),
        Err(e) => panic!(
            "Fetching schema after deletion failed with an unexpected error: {}",
            e
        ),
    }

    // Also check it's not in all_schemas list anymore
    let all_schemas_after_delete = client
        .get_all_schemas()
        .await
        .expect("Failed to get all schemas after delete");
    assert!(
        !all_schemas_after_delete
            .results
            .iter()
            .any(|s| s.class_name == class_name),
        "Deleted schema still found in all schemas list"
    );
}

#[tokio::test]
async fn test_update_class_schema() {
    let client = setup_client_with_master_key();
    let class_name = unique_class_name("TestSchemaUpdate");

    // 1. Create an initial class schema
    let mut initial_fields = HashMap::new();
    initial_fields.insert(
        "fieldToDelete".to_string(),
        FieldSchema {
            field_type: FieldType::String,
            target_class: None,
            required: Some(false),
            default_value: None,
        },
    );
    initial_fields.insert(
        "fieldToKeep".to_string(),
        FieldSchema {
            field_type: FieldType::Number,
            target_class: None,
            required: Some(false),
            default_value: Some(json!(100)),
        },
    );

    let initial_clp = ClassLevelPermissionsSchema {
        find: Some([("*".to_string(), true)].iter().cloned().collect()),
        get: Some([("*".to_string(), true)].iter().cloned().collect()),
        create: Some([("*".to_string(), true)].iter().cloned().collect()),
        update: Some([("*".to_string(), true)].iter().cloned().collect()),
        delete: Some([("*".to_string(), true)].iter().cloned().collect()),
        add_field: Some([("*".to_string(), true)].iter().cloned().collect()),
        ..Default::default()
    };

    let initial_schema_payload = json!({
        "className": class_name,
        "fields": initial_fields,
        "classLevelPermissions": initial_clp
    });

    let created_schema = client
        .create_class_schema(&class_name, &initial_schema_payload)
        .await
        .expect("Failed to create initial schema for update test");

    // Server adds 4 default fields: objectId, createdAt, updatedAt, ACL
    assert_eq!(
        created_schema.fields.len(),
        initial_fields.len() + 4,
        "Initial field count mismatch"
    );

    // 2. Update the schema
    let mut fields_update = HashMap::new();
    // Add a new field
    fields_update.insert(
        "addedField".to_string(),
        json!({
            "type": "Boolean",
            "required": true,
            "defaultValue": false
        }),
    );
    // Delete an existing field
    fields_update.insert("fieldToDelete".to_string(), json!({ "__op": "Delete" }));

    let updated_clp_map: HashMap<String, bool> =
        [("role:Admin".to_string(), true)].iter().cloned().collect();
    let updated_clp = ClassLevelPermissionsSchema {
        find: Some(updated_clp_map.clone()),
        get: Some(updated_clp_map.clone()),
        create: Some(updated_clp_map.clone()),
        update: Some(updated_clp_map.clone()),
        delete: Some(updated_clp_map.clone()),
        add_field: Some(updated_clp_map.clone()),
        ..Default::default()
    };

    let mut indexes_to_add = HashMap::new();
    let mut index_fields = HashMap::new();
    index_fields.insert("fieldToKeep".to_string(), 1); // 1 for ascending
    indexes_to_add.insert("idx_fieldToKeep".to_string(), index_fields);

    let schema_update_payload = json!({
        "className": class_name, // Must match class_name in path
        "fields": fields_update,
        "classLevelPermissions": updated_clp,
        "indexes": indexes_to_add
    });

    let updated_schema = client
        .update_class_schema(&class_name, &schema_update_payload)
        .await
        .expect("Failed to update class schema");

    // 3. Verify the updates
    assert_eq!(updated_schema.class_name, class_name);
    // Expected fields: fieldToKeep, addedField + 4 default fields (objectId, createdAt, updatedAt, ACL)
    // fieldToDelete was removed.
    assert_eq!(
        updated_schema.fields.len(),
        1 + 1 + 4,
        "Updated field count mismatch"
    );
    assert!(updated_schema.fields.contains_key("fieldToKeep"));
    assert!(updated_schema.fields.contains_key("addedField"));
    assert!(!updated_schema.fields.contains_key("fieldToDelete"));

    assert_eq!(
        updated_schema.fields.get("addedField").unwrap().field_type,
        FieldType::Boolean
    );
    assert_eq!(
        updated_schema.fields.get("addedField").unwrap().required,
        Some(true)
    );
    assert_eq!(
        updated_schema
            .fields
            .get("addedField")
            .unwrap()
            .default_value,
        Some(json!(false))
    );

    if let Some(clp_after_update) = &updated_schema.class_level_permissions {
        assert_eq!(
            clp_after_update.find, updated_clp.find,
            "CLP 'find' mismatch after update"
        );
        assert_eq!(
            clp_after_update.get, updated_clp.get,
            "CLP 'get' mismatch after update"
        );
    } else {
        panic!("CLP not found in updated schema response");
    }

    if let Some(indexes_after_update) = &updated_schema.indexes {
        assert!(
            indexes_after_update.contains_key("idx_fieldToKeep"),
            "Index not found after update"
        );
        assert_eq!(
            indexes_after_update
                .get("idx_fieldToKeep")
                .unwrap()
                .get("fieldToKeep"),
            Some(&IndexFieldType::SortOrder(1))
        );
    } else {
        // Note: Parse Server might not return indexes if none were *explicitly* set beyond defaults like _id.
        // If indexes_to_add was empty, this branch might be hit. For this test, we expect it.
        // However, some Parse Server versions might not return the 'indexes' field at all if it's empty after operations.
        // For this test, we are adding one, so we expect it.
        panic!("Indexes not found in updated schema response, but an index was added.");
    }

    // Fetch again to ensure persistence
    let fetched_again_schema = client
        .get_class_schema(&class_name)
        .await
        .expect("Failed to fetch schema after update and verification");
    assert_eq!(
        fetched_again_schema.fields.len(),
        updated_schema.fields.len()
    );
    assert_eq!(
        fetched_again_schema.class_level_permissions,
        updated_schema.class_level_permissions
    );
    assert_eq!(fetched_again_schema.indexes, updated_schema.indexes);

    // 4. Clean up
    client
        .delete_class_schema(&class_name, true)
        .await
        .expect("Failed to delete class schema after update test");
}

#[tokio::test]
async fn test_delete_non_empty_class_schema_fails() {
    let client = setup_client_with_master_key();
    let class_name = unique_class_name("TestNonEmptyDelete");

    // 1. Create a class schema
    let schema_payload = json!({
        "className": class_name,
        "fields": {
            "message": { "type": "String" }
        },
        "classLevelPermissions": { // Make it fully open for easy object creation/deletion
            "find": { "*": true },
            "get": { "*": true },
            "create": { "*": true },
            "update": { "*": true },
            "delete": { "*": true },
            "addField": { "*": true }
        }
    });
    client
        .create_class_schema(&class_name, &schema_payload)
        .await
        .expect("Failed to create schema for non-empty delete test");

    // 2. Create an object in that class
    let object_payload = json!({ "message": "Hello, World!" });
    let created_object = client
        .create_object(&class_name, &object_payload)
        .await
        .expect("Failed to create object in class");
    assert!(!created_object.object_id.is_empty());

    // 3. Attempt to delete the class schema (should fail as it's not empty)
    match client.delete_class_schema(&class_name, true).await {
        Err(ParseError::OtherParseError { code, message }) => {
            assert_eq!(
                code, 255,
                "Expected error code 255 for non-empty class deletion"
            );
            assert!(message.to_lowercase().contains("not empty"));
        }
        Ok(_) => panic!("Deleting non-empty schema should have failed but succeeded."),
        Err(e) => panic!(
            "Deleting non-empty schema failed with an unexpected error: {}",
            e
        ),
    }

    // 4. Clean up: Delete the object first, then the schema
    client
        .delete_object(&class_name, &created_object.object_id)
        .await
        .expect("Failed to delete object for cleanup");

    client
        .delete_class_schema(&class_name, true)
        .await
        .expect("Failed to delete class schema for cleanup after deleting object");

    // Verify schema is actually gone
    match client.get_class_schema(&class_name).await {
        Err(ParseError::OtherParseError { code, message: _ }) => {
            assert_eq!(code, 103);
        }
        Ok(_) => panic!("Schema should not exist after cleanup but was found."),
        Err(e) => panic!(
            "Fetching schema after cleanup failed with an unexpected error: {}",
            e
        ),
    }
}