react-native-cozo
v0.2.0
Published
CozoDB React Native plugin with Cypher-to-Datalog translation
Downloads
214
Maintainers
Readme
react-native-cozo
A React Native plugin for CozoDB - an embedded relational-graph-vector database with Datalog.
Features:
- Full CozoDB functionality via native TurboModules (JSI)
- Cypher-to-Datalog query translation
- React hooks for queries and mutations
- Multiple storage backends (Memory, SQLite, RocksDB)
- TypeScript support
- React Native New Architecture (0.76+) support
- Expo support with config plugins (development builds)
Installation
npm install react-native-cozo
# or
yarn add react-native-cozoiOS
cd ios && pod installAndroid
No additional setup required.
Expo
For Expo projects, see EXPO.md for detailed instructions. Quick start:
npx expo install react-native-cozoAdd to app.json:
{
"expo": {
"plugins": ["react-native-cozo"]
}
}Then create a development build:
npx expo prebuild
npx expo run:ios # or npx expo run:androidUsage
Basic Setup
import { CozoProvider, useQuery, useMutation } from 'react-native-cozo';
function App() {
return (
<CozoProvider
options={{ engine: 'sqlite', path: 'mydb.db' }}
onReady={(db) => console.log('Database ready')}
>
<MyApp />
</CozoProvider>
);
}Queries with Hooks
import { useQuery, useCypher } from 'react-native-cozo';
function PersonList() {
// Datalog query
const { data, loading, error, refetch } = useQuery(`
?[name, age] := *Person[id, name, age], age > 21
`);
// Or use Cypher syntax
const cypherResult = useCypher(`
MATCH (p:Person) WHERE p.age > 21 RETURN p.name, p.age
`);
if (loading) return <Text>Loading...</Text>;
if (error) return <Text>Error: {error.message}</Text>;
return (
<FlatList
data={data}
renderItem={({ item }) => <Text>{item[0]}: {item[1]}</Text>}
/>
);
}Mutations
import { useMutation } from 'react-native-cozo';
function AddPerson() {
const { mutate, loading } = useMutation(`
?[id, name, age] <- [[$id, $name, $age]]
:put Person { id, name, age }
`);
const handleAdd = () => {
mutate({ id: '123', name: 'Alice', age: 30 });
};
return (
<Button onPress={handleAdd} disabled={loading}>
Add Person
</Button>
);
}Direct Database Access
import { useCozo, useCozoDatabase } from 'react-native-cozo';
function MyComponent() {
const { db, isReady, run, cypher } = useCozo();
// Or get the database instance directly
const database = useCozoDatabase();
const query = async () => {
// Run Datalog
const result = await run('?[x] <- [[1], [2], [3]]');
// Run Cypher (auto-translated)
const cypherResult = await cypher('MATCH (n:Person) RETURN n.name');
// Create a relation
await db.createRelation('users', { id: 'String', name: 'String' });
// Insert data
await db.insert('users', [
{ id: '1', name: 'Alice' },
{ id: '2', name: 'Bob' },
]);
};
}API Reference
CozoProvider
The context provider for database access.
<CozoProvider
options={{
engine: 'sqlite', // 'mem' | 'sqlite' | 'rocksdb'
path: 'database.db',
options: {}
}}
onReady={(db) => {}}
onError={(error) => {}}
>
{children}
</CozoProvider>useQuery / useCypher
Hooks for executing queries with automatic state management.
const {
data, // Query result rows
headers, // Column headers
loading, // Loading state
error, // Error if any
took, // Query execution time
refetch, // Function to re-execute query
} = useQuery(query, params, options);Options:
skip- Skip query executionpollInterval- Auto-refresh interval in mscacheKey- Custom cache keyonSuccess/onError- Callbacks
useMutation / useCypherMutation
Hooks for executing mutations.
const {
data, // Result data
loading, // Loading state
error, // Error if any
mutate, // Execute function
reset, // Reset state
} = useMutation(query, options);CozoDatabase
The main database class.
import { CozoDatabase, StorageEngine } from 'react-native-cozo';
const db = new CozoDatabase({
engine: StorageEngine.SQLite,
path: 'mydb.db',
});
await db.open();
// Run queries
const result = await db.run('?[x] <- [[1, 2, 3]]');
// Execute Cypher
const cypherResult = await db.cypher('MATCH (n) RETURN n');
// Translate Cypher to Datalog
const datalog = db.translateCypher('MATCH (n:Person) RETURN n.name');
// Schema operations
await db.createRelation('users', { id: 'String', name: 'String' }, ['id']);
const relations = await db.relations();
const schema = await db.schema('users');
await db.dropRelation('users');
// Data operations
await db.insert('users', { id: '1', name: 'Alice' });
await db.delete('users', { id: '1' });
// Import/Export
const data = await db.exportRelations(['users']);
await db.importRelations(data);
// Backup/Restore
await db.backup('/path/to/backup');
await db.restore('/path/to/backup');
// Transactions
await db.transaction([
'?[id, name] <- [["1", "Alice"]]',
':put users { id, name }',
]);
// Graph operations
const nodeId = await db.createNode('Person', { name: 'Alice' });
await db.createRelationship('KNOWS', nodeId1, nodeId2, { since: 2020 });
await db.close();Cypher Support
The library includes a Cypher-to-Datalog translator. For complete documentation, see CYPHER.md.
Quick Examples
import { translateCypher, useCozo } from 'react-native-cozo';
// Basic query
const datalog = translateCypher('MATCH (n:Person) RETURN n.name');
// Output: ?[name] := *Person{name}
// With conditions
translateCypher("MATCH (e:Employee) WHERE e.department = 'Engineering' RETURN e.name");
// Output: ?[name] := *Employee{department, name}, department == "Engineering"
// Aggregations
translateCypher('MATCH (e:Employee) RETURN e.department, count(*)');
// Output: ?[department, count(id)] := *Employee{department, id}Supported Features
| Category | Features |
|----------|----------|
| Patterns | Nodes, relationships, labels, properties, variable-length paths |
| Clauses | MATCH, WHERE, RETURN, CREATE, DELETE, SET, MERGE |
| Operators | =, <>, <, >, AND, OR, NOT, IN, IS NULL |
| String | CONTAINS, STARTS WITH, ENDS WITH, toUpper, toLower |
| Aggregations | count, sum, avg, min, max, collect, stdev |
| Modifiers | ORDER BY, LIMIT, SKIP, DISTINCT |
| Math | abs, ceil, floor, round, sqrt, log, trig functions |
See CYPHER.md for the complete translation reference, examples, and limitations.
Storage Engines
StorageEngine.Memory- In-memory (default)StorageEngine.SQLite- SQLite-backed persistent storageStorageEngine.RocksDB- RocksDB-backed persistent storage
Contributing
See CONTRIBUTING.md for development setup, testing instructions, and contribution guidelines.
Error Handling
All database operations may throw CozoError:
import { CozoError, CozoErrorCode } from 'react-native-cozo';
try {
await db.run('invalid query');
} catch (error) {
if (error instanceof CozoError) {
console.log(error.code); // Error code
console.log(error.message); // Error message
console.log(error.display); // User-friendly message
}
}License
MPL-2.0
