Skip to main content

Crate coredata

Crate coredata 

Source
Expand description

§coredata

Safe Rust bindings for Apple’s Core Data framework on macOS.

Status: v0.3.0 adds a Tier-1 async_api module (gated behind the async feature) wrapping CoreData completion-handler and expensive-sync APIs as executor-agnostic Rust Futures.

§Async API

Enable the async feature to access the async_api module:

[dependencies]
coredata = { version = "0.3", features = ["async"] }

The async API is executor-agnostic — it works with Tokio, async-std, smol, pollster, or any other std::future::Future-compatible runtime.

use coredata::async_api::{AsyncPersistentContainer, AsyncManagedObjectContext};
use coredata::{NSPersistentContainer, NSManagedObjectModel};

async fn load_and_save(container: &NSPersistentContainer) -> Result<(), Box<dyn std::error::Error>> {
    // Async store loading
    AsyncPersistentContainer(container).load_persistent_stores().await?;

    // Async save on a background context
    let ctx = container.new_background_context()?;
    AsyncManagedObjectContext(&ctx).perform_save().await?;
    Ok(())
}

§Available async types

TypeApple API
AsyncPersistentContainerNSPersistentContainer.loadPersistentStores(completionHandler:)
AsyncPersistentCloudKitContainerNSPersistentCloudKitContainer.initializeCloudKitSchema(options:)
AsyncManagedObjectContextNSManagedObjectContext.perform { save() }
AsyncHistoryNSPersistentHistoryChangeRequest execute
AsyncBatchOperationNSBatchInsertRequest / NSBatchUpdateRequest

Note: performAndWait-style sync APIs and multi-fire observer patterns (e.g. NSFetchedResultsController delegate, CloudKit event notifications) are not covered here — those belong to a Tier-2 Stream wrapper.

§Quick start

use coredata::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let model = NSManagedObjectModel::new()?;
    let person = NSEntityDescription::named("Person")?;
    person.set_managed_object_class_name("NSManagedObject")?;

    let name = NSAttributeDescription::new("name", AttributeType::String)?;
    let age = NSAttributeDescription::new("age", AttributeType::Integer32)?;
    person.add_attribute(&name)?;
    person.add_attribute(&age)?;
    model.add_entity(&person)?;

    let container = NSPersistentContainer::new("Example", &model)?;
    let description = NSPersistentStoreDescription::new()?;
    description.set_store_type(store_types::IN_MEMORY)?;
    description.set_should_add_asynchronously(false);
    container.set_persistent_store_descriptions(&[&description])?;
    container.load_persistent_stores()?;

    let context = container.view_context()?;
    let person_object = NSManagedObject::new(&person, None)?;
    context.insert(&person_object)?;
    person_object.set_value("name", "doom-fish")?;
    person_object.set_value("age", 7_i32)?;
    context.save()?;
    Ok(())
}

§Highlights

  • persistent-store descriptions, option keys, CloudKit mirroring options, CloudKit event requests, and synchronous store loading
  • richer NSPersistentStoreCoordinator administration and NSPersistentStore inspection
  • NSManagedObjectContext concurrency helpers, parent/merge metadata, merge-policy round-tripping, and history-request execution
  • NSManagedObject state inspection plus NSManagedObjectID wrappers
  • entity, attribute, and relationship metadata including versioning, user info, uniqueness constraints, ordering, and validation rules
  • fetch-request result types, persistent-store request/result wrappers, fetched-results controllers/section info, prefetch configuration, batch sizing, and predicate substitution/evaluation
  • persistent-history request/result/transaction/change wrappers plus named Core Data notifications, metadata keys, option keys, and error constants
  • advanced model metadata wrappers including fetched/expression/derived/composite properties and fetch-index descriptions
  • SQLite-backed batch insert/update/delete requests and results
  • inferred mapping models, staged-migration support types, and custom-store node helpers for migration/extensibility workflows
  • validation rule metadata and object-validation entry points

§Coverage, examples, and tests

  • COVERAGE_AUDIT.md records the 100% non-exempt public-symbol audit, and COVERAGE.md tracks family-level depth/deferred rows.
  • examples/01_in_memory_smoke.rs plus examples/02_* through examples/15_* cover every logical area.
  • tests/*_tests.rs provides smoke coverage for each logical area.

Run the full verification suite with:

cargo clippy --all-targets -- -D warnings
cargo test
for ex in examples/*.rs; do cargo run --example "$(basename "$ex" .rs)"; done

§Notes

  • CloudKit mirroring and event-request wrappers are available, but live iCloud sync callbacks remain environment-dependent.
  • Persistent-history request construction and wrappers are covered; end-to-end history replay is documented in COVERAGE.md as a deferred deeper runtime workflow.
  • Core Data still enforces queue confinement rules; use NSManagedObjectContext::perform or perform_and_wait when moving work onto a context-owned queue.

§License

Licensed under either Apache-2.0 or MIT at your option.

Re-exports§

pub use batch_operation::BatchDeleteRequestResultType;
pub use batch_operation::BatchInsertRequestResultType;
pub use batch_operation::BatchUpdateRequestResultType;
pub use batch_operation::NSBatchDeleteRequest;
pub use batch_operation::NSBatchDeleteResult;
pub use batch_operation::NSBatchInsertRequest;
pub use batch_operation::NSBatchInsertResult;
pub use batch_operation::NSBatchUpdateRequest;
pub use batch_operation::NSBatchUpdateResult;
pub use cloudkit_mirroring::event_notification_names;
pub use cloudkit_mirroring::event_user_info_keys;
pub use cloudkit_mirroring::CloudKitDatabaseScope;
pub use cloudkit_mirroring::CloudKitSchemaInitializationOptions;
pub use cloudkit_mirroring::NSPersistentCloudKitContainer;
pub use cloudkit_mirroring::NSPersistentCloudKitContainerEvent;
pub use cloudkit_mirroring::NSPersistentCloudKitContainerEventRequest;
pub use cloudkit_mirroring::NSPersistentCloudKitContainerEventResult;
pub use cloudkit_mirroring::NSPersistentCloudKitContainerEventResultType;
pub use cloudkit_mirroring::NSPersistentCloudKitContainerEventType;
pub use cloudkit_mirroring::NSPersistentCloudKitContainerOptions;
pub use constants::context_notification_names;
pub use constants::context_user_info_keys;
pub use constants::coredata_version_number;
pub use constants::error_domains;
pub use constants::error_user_info_keys;
pub use constants::persistent_store_metadata_keys;
pub use constants::persistent_store_notification_names;
pub use constants::persistent_store_option_keys;
pub use constants::persistent_store_user_info_keys;
pub use context::NSManagedObject;
pub use context::NSManagedObjectContext;
pub use context::NSManagedObjectContextConcurrencyType;
pub use custom_store::NSAtomicStore;
pub use custom_store::NSAtomicStoreCacheNode;
pub use custom_store::NSIncrementalStore;
pub use custom_store::NSIncrementalStoreNode;
pub use error::CoreDataError;
pub use error::COREDATA_BRIDGE_ERROR_DOMAIN;
pub use fetch_request::FetchRequestResultType;
pub use fetched_results_controller::FetchedResultsIndexPath;
pub use fetched_results_controller::NSFetchedResultsChangeType;
pub use fetched_results_controller::NSFetchedResultsController;
pub use fetched_results_controller::NSFetchedResultsControllerDelegate;
pub use fetched_results_controller::NSFetchedResultsSectionInfo;
pub use history::NSPersistentHistoryChange;
pub use history::NSPersistentHistoryChangeRequest;
pub use history::NSPersistentHistoryResult;
pub use history::NSPersistentHistoryToken;
pub use history::NSPersistentHistoryTransaction;
pub use history::PersistentHistoryChangeType;
pub use history::PersistentHistoryResultType;
pub use managed_object::NSManagedObjectID;
pub use managed_object::NSSnapshotEventType;
pub use merge_policy::MergePolicyType;
pub use merge_policy::NSConstraintConflict;
pub use merge_policy::NSMergeConflict;
pub use merge_policy::NSMergePolicy;
pub use migration::migration_expression_keys;
pub use migration::NSMappingModel;
pub use migration::NSMigrationManager;
pub use migration_support::NSCustomMigrationStage;
pub use migration_support::NSEntityMapping;
pub use migration_support::NSEntityMappingType;
pub use migration_support::NSEntityMigrationPolicy;
pub use migration_support::NSLightweightMigrationStage;
pub use migration_support::NSManagedObjectModelReference;
pub use migration_support::NSMigrationStage;
pub use migration_support::NSPropertyMapping;
pub use migration_support::NSStagedMigrationManager;
pub use model::NSManagedObjectModel;
pub use model_metadata::NSCompositeAttributeDescription;
pub use model_metadata::NSDerivedAttributeDescription;
pub use model_metadata::NSExpressionDescription;
pub use model_metadata::NSFetchIndexDescription;
pub use model_metadata::NSFetchIndexElementDescription;
pub use model_metadata::NSFetchIndexElementType;
pub use model_metadata::NSFetchedPropertyDescription;
pub use model_metadata::NSPropertyDescription;
pub use persistent_container::option_keys;
pub use persistent_container::NSPersistentStoreDescription;
pub use persistent_store_coordinator::NSPersistentStore;
pub use persistent_store_request::NSAsynchronousFetchRequest;
pub use persistent_store_request::NSAsynchronousFetchResult;
pub use persistent_store_request::NSFetchRequestExpression;
pub use persistent_store_request::NSFetchRequestResult;
pub use persistent_store_request::NSPersistentStoreAsynchronousResult;
pub use persistent_store_request::NSPersistentStoreRequest;
pub use persistent_store_request::NSPersistentStoreRequestType;
pub use persistent_store_request::NSPersistentStoreResult;
pub use persistent_store_request::NSSaveChangesRequest;
pub use query::NSFetchRequest;
pub use query::NSPredicate;
pub use query::SortDescriptor;
pub use query_generation::NSQueryGenerationToken;
pub use schema::AttributeType;
pub use schema::DeleteRule;
pub use schema::NSAttributeDescription;
pub use schema::NSEntityDescription;
pub use schema::NSRelationshipDescription;
pub use spotlight::NSCoreDataCoreSpotlightDelegate;
pub use store::store_types;
pub use store::NSPersistentContainer;
pub use store::NSPersistentStoreCoordinator;
pub use store::PersistentStoreOptions;
pub use validation::validation_error_codes;
pub use validation::ValidationRule;
pub use value::Value;

Modules§

async_apiasync
Async wrappers for Core Data completion-handler APIs. Async API for CoreData
batch_operation
Core Data batch-operation wrappers mirroring NSBatchDeleteRequest, NSBatchInsertRequest, and NSBatchUpdateRequest.
cloudkit_mirroring
Core Data CloudKit mirroring wrappers.
constants
Named Core Data constants and notification keys.
context
Core Data managed object and context wrappers.
custom_store
Core Data custom store wrappers.
entity_description
Extensions for NSEntityDescription.
error
Error types for Core Data bridge failures.
fetch_request
Fetch-request result-type helpers for Core Data.
fetched_results_controller
Fetched results controller wrappers.
ffi
Raw Core Data bridge symbols.
history
Persistent history tracking wrappers.
managed_object
Managed-object identifier and snapshot wrappers.
managed_object_context
Additional NSManagedObjectContext APIs.
merge_policy
Merge policy and conflict wrappers.
migration
Mapping-model and migration-manager wrappers.
migration_support
Staged migration support wrappers.
model
Managed object model wrappers.
model_metadata
Property and fetch-index metadata wrappers.
ns_predicate
Predicate helpers mirroring NSPredicate.
persistent_container
Persistent store description extensions and option keys.
persistent_store_coordinator
Persistent store wrappers and coordinator extensions.
persistent_store_request
Persistent store request and result wrappers.
prelude
Common imports.
query
Fetch-request, predicate, and sort-descriptor wrappers.
query_generation
Query-generation token wrappers.
relationship_description
Extensions for NSRelationshipDescription.
schema
Schema wrappers for entities, attributes, and relationships.
spotlight
Core Spotlight integration wrappers for Core Data.
store
Persistent container and coordinator wrappers.
validation
Validation rule and error-code helpers.
value
Value conversions used with Core Data attribute payloads.