StorageProvider

Struct StorageProvider 

Source
pub struct StorageProvider;
Expand description

Провайдер хранилищ - централизованное место для создания всех типов хранилищ

Ответственности:

  • Создание конкретных экземпляров хранилищ
  • Логирование процесса создания
  • Конфигурация параметров по умолчанию

Implementations§

Source§

impl StorageProvider

Source

pub fn memory() -> Box<dyn Storage>

Создает новое хранилище в памяти (dynamic dispatch)

Examples found in repository?
examples/factory_patterns.rs (line 50)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}
Source

pub fn lmdb( db_path: &str, mode: StorageMode, max_read_counter_reopen: Option<u64>, ) -> Box<dyn Storage>

Создает новое LMDB хранилище (dynamic dispatch)

Examples found in repository?
examples/factory_patterns.rs (line 53)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}
Source

pub fn remote(addr: &str) -> Box<dyn Storage>

Создает новое удаленное хранилище (dynamic dispatch)

Examples found in repository?
examples/factory_patterns.rs (line 56)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}
Source

pub fn vstorage_memory() -> VStorage

Создает VStorage с памятью

Examples found in repository?
examples/factory_patterns.rs (line 60)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}
Source

pub fn vstorage_lmdb( db_path: &str, mode: StorageMode, max_read_counter_reopen: Option<u64>, ) -> VStorage

Создает VStorage с LMDB

Source

pub fn vstorage_remote(addr: &str) -> VStorage

Создает VStorage с удаленным хранилищем

Source

pub fn memory_generic() -> VMemoryStorage

Создает generic хранилище в памяти

Examples found in repository?
examples/factory_patterns.rs (line 153)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}
Source

pub fn lmdb_generic( db_path: &str, mode: StorageMode, max_read_counter_reopen: Option<u64>, ) -> VLMDBStorage

Создает generic LMDB хранилище

Examples found in repository?
examples/factory_patterns.rs (line 156)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}
Source

pub fn remote_generic(addr: &str) -> VRemoteStorage

Создает generic удаленное хранилище

Examples found in repository?
examples/factory_patterns.rs (line 159)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("=== v-storage Factory Patterns Demonstration ===\n");
14
15    // === 1. Builder Pattern ===
16    println!("🏗️  1. Builder Pattern - step-by-step creation");
17    println!("   • Flexible and readable way to configure storage");
18    
19    // Create memory storage through builder
20    let memory_storage = StorageBuilder::new()
21        .memory()
22        .build()?;
23    println!("   • Created memory storage through builder");
24    
25    // Create LMDB storage through builder
26    let lmdb_storage = StorageBuilder::new()
27        .lmdb("/tmp/example_lmdb", StorageMode::ReadWrite, Some(1000))
28        .build();
29    
30    match lmdb_storage {
31        Ok(_) => println!("   • Created LMDB storage through builder"),
32        Err(e) => println!("   • LMDB unavailable: {}", e),
33    }
34    
35    // Create remote storage through builder
36    let remote_storage = StorageBuilder::new()
37        .remote("127.0.0.1:8080")
38        .build();
39    
40    match remote_storage {
41        Ok(_) => println!("   • Created remote storage through builder"),
42        Err(e) => println!("   • Remote unavailable: {}", e),
43    }
44
45    // === 2. Provider Pattern ===
46    println!("\n🏭 2. Provider Pattern - ready factory methods");
47    println!("   • Quick creation of standard configurations");
48    
49    // Direct creation of storages through Provider
50    let _provider_memory = StorageProvider::memory();
51    println!("   • StorageProvider::memory() - created");
52    
53    let _provider_lmdb = StorageProvider::lmdb("/tmp/provider_lmdb", StorageMode::ReadOnly, None);
54    println!("   • StorageProvider::lmdb() - created");
55    
56    let _provider_remote = StorageProvider::remote("127.0.0.1:8080");
57    println!("   • StorageProvider::remote() - created");
58    
59    // Create VStorage through Provider
60    let mut vstorage_memory = StorageProvider::vstorage_memory();
61    println!("   • StorageProvider::vstorage_memory() - created VStorage");
62    
63    // Demonstrate functionality with semantic Individual
64    let provider_individual = r#"{
65        "@": "provider:test",
66        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
67        "rdfs:label": [{"type": "String", "data": "Provider Test User"}],
68        "foaf:name": [{"type": "String", "data": "Test"}],
69        "veda:createdBy": [{"type": "Uri", "data": "provider:factory"}],
70        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T17:00:00Z"}]
71    }"#;
72    
73    let _ = vstorage_memory.put_value(StorageId::Individuals, "provider:test", provider_individual);
74    if let StorageResult::Ok(value) = vstorage_memory.get_value(StorageId::Individuals, "provider:test") {
75        println!("     Test: stored Individual ({} bytes) through Provider", value.len());
76    }
77
78    // === 3. Config Pattern ===
79    println!("\n⚙️  3. Config Pattern - creation from configuration");
80    println!("   • Creating storages from configuration structures");
81    
82    // Create from different configurations
83    let configs = vec![
84        ("Memory", StorageConfig::Memory),
85        ("LMDB", StorageConfig::Lmdb { 
86            path: "/tmp/config_lmdb".to_string(), 
87            mode: StorageMode::ReadWrite, 
88            max_read_counter_reopen: Some(500) 
89        }),
90        ("Remote", StorageConfig::Remote { 
91            address: "127.0.0.1:8080".to_string() 
92        }),
93    ];
94    
95    for (name, config) in configs {
96        match VStorage::from_config(config) {
97            Ok(mut storage) => {
98                println!("   • {} configuration: created successfully", name);
99                
100                // Test the created storage with semantic Individual
101                let test_key = format!("config:{}:key", name.to_lowercase());
102                let test_value = format!(r#"{{
103                    "@": "{}",
104                    "rdf:type": [{{"type": "Uri", "data": "veda:ConfigTest"}}],
105                    "rdfs:label": [{{"type": "String", "data": "Config Test for {}"}}],
106                    "veda:configType": [{{"type": "String", "data": "{}"}}],
107                    "dcterms:created": [{{"type": "Datetime", "data": "2024-01-15T17:30:00Z"}}]
108                }}"#, test_key, name, name);
109                
110                let _ = storage.put_value(StorageId::Individuals, &test_key, &test_value);
111                if let StorageResult::Ok(retrieved) = storage.get_value(StorageId::Individuals, &test_key) {
112                    println!("     Test: {} Individual ({} bytes)", name, retrieved.len());
113                }
114            },
115            Err(e) => println!("   • {} configuration: error - {}", name, e),
116        }
117    }
118
119    // === 4. Generic Builders ===
120    println!("\n🔧 4. Generic Builders - compile-time optimization");
121    println!("   • Typed builders without runtime overhead");
122    
123    // Generic memory builder
124    let generic_memory = StorageBuilder::new()
125        .memory()
126        .build_memory_generic()?;
127    println!("   • build_memory_generic() - created VMemoryStorage");
128    
129    // Generic LMDB builder
130    let generic_lmdb = StorageBuilder::new()
131        .lmdb("/tmp/generic_lmdb", StorageMode::ReadWrite, None)
132        .build_lmdb_generic();
133    
134    match generic_lmdb {
135        Ok(_storage) => println!("   • build_lmdb_generic() - created VLMDBStorage"),
136        Err(e) => println!("   • build_lmdb_generic() - error: {}", e),
137    }
138    
139    // Generic remote builder
140    let generic_remote = StorageBuilder::new()
141        .remote("127.0.0.1:8080")
142        .build_remote_generic();
143    
144    match generic_remote {
145        Ok(_storage) => println!("   • build_remote_generic() - created VRemoteStorage"),
146        Err(e) => println!("   • build_remote_generic() - error: {}", e),
147    }
148
149    // === 5. Provider Generic Methods ===
150    println!("\n🎯 5. Provider Generic Methods - static types");
151    println!("   • Direct creation of typed storages");
152    
153    let mut provider_generic_memory = StorageProvider::memory_generic();
154    println!("   • StorageProvider::memory_generic() - VMemoryStorage");
155    
156    let provider_generic_lmdb = StorageProvider::lmdb_generic("/tmp/generic_provider", StorageMode::ReadOnly, None);
157    println!("   • StorageProvider::lmdb_generic() - VLMDBStorage");
158    
159    let provider_generic_remote = StorageProvider::remote_generic("127.0.0.1:8080");
160    println!("   • StorageProvider::remote_generic() - VRemoteStorage");
161    
162    // Demonstrate work with typed storage using semantic Individual
163    let generic_individual = r#"{
164        "@": "generic:test",
165        "rdf:type": [{"type": "Uri", "data": "foaf:Person"}],
166        "rdfs:label": [{"type": "String", "data": "Generic Test User"}],
167        "foaf:name": [{"type": "String", "data": "Generic"}],
168        "veda:storageType": [{"type": "String", "data": "memory_generic"}],
169        "dcterms:created": [{"type": "Datetime", "data": "2024-01-15T18:00:00Z"}]
170    }"#;
171    
172    let _ = provider_generic_memory.put_value(StorageId::Individuals, "generic:test", generic_individual);
173    if let StorageResult::Ok(value) = provider_generic_memory.get_value(StorageId::Individuals, "generic:test") {
174        println!("     Generic test: Individual ({} bytes)", value.len());
175    }
176
177    // === 6. Approach comparison ===
178    println!("\n📊 6. Storage creation approach comparison");
179    
180    println!("   Builder Pattern:");
181    println!("     ✅ Readable and flexible API");
182    println!("     ✅ Validation at build() stage");
183    println!("     ✅ Can create both dynamic and generic types");
184    println!("     ❌ More code for simple cases");
185    
186    println!("   Provider Pattern:");
187    println!("     ✅ Concise code for standard cases");
188    println!("     ✅ Ready optimal configurations");
189    println!("     ❌ Less flexible for customization");
190    
191    println!("   Config Pattern:");
192    println!("     ✅ Excellent for loading from files/ENV");
193    println!("     ✅ Unified interface for all types");
194    println!("     ❌ Only dynamic dispatch");
195    
196    println!("   Generic Methods:");
197    println!("     ✅ Static dispatch");
198    println!("     ✅ Compile-time typing");
199    println!("     ❌ Less flexible at runtime");
200
201    // === 7. Usage recommendations ===
202    println!("\n💡 7. Pattern selection recommendations");
203    
204    println!("   Use Builder when:");
205    println!("     • Parameter customization is needed");
206    println!("     • Complex creation logic");
207    println!("     • Code readability is needed");
208    
209    println!("   Use Provider when:");
210    println!("     • Need to quickly create standard storage");
211    println!("     • Default parameters are suitable");
212    println!("     • Minimal boilerplate code");
213    
214    println!("   Use Config when:");
215    println!("     • Configuration is loaded from external sources");
216    println!("     • Storage type is determined at runtime");
217    println!("     • Uniform handling of different types is needed");
218    
219    println!("   Use Generic methods when:");
220    println!("     • Static dispatch is preferred");
221    println!("     • Storage type is known at compile time");
222    println!("     • Access to type-specific methods is needed");
223
224    println!("\n✨ Factory patterns demonstration completed!");
225    Ok(())
226}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.