or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-manipulation.mddatabase-management.mdindex.mdquerying-filtering.mdutility-functions.md

database-management.mddocs/

0

# Database Management

1

2

Core functionality for creating and managing TaffyDB database instances, including data insertion, merging, configuration, and persistence.

3

4

## Capabilities

5

6

### TAFFY Constructor

7

8

Creates a new TaffyDB database instance from an array of objects or JSON string.

9

10

```javascript { .api }

11

/**

12

* Creates a new TaffyDB database instance

13

* @param data - Initial data as array of objects or JSON string (optional)

14

* @returns TaffyDatabase instance

15

*/

16

function TAFFY(data?: object[] | string): TaffyDatabase;

17

```

18

19

**Usage Examples:**

20

21

```javascript

22

const TAFFY = require('taffydb').taffy;

23

24

// Create empty database

25

const emptyDB = TAFFY();

26

27

// Create database with initial data

28

const products = TAFFY([

29

{ id: 1, name: "Laptop", price: 999.99 },

30

{ id: 2, name: "Mouse", price: 29.99 }

31

]);

32

33

// Create database from JSON string

34

const jsonData = '[{"name":"Alice","age":30},{"name":"Bob","age":25}]';

35

const users = TAFFY(jsonData);

36

```

37

38

### Data Insertion

39

40

Add new records to the database with automatic ID assignment and template merging.

41

42

```javascript { .api }

43

/**

44

* Insert new records into the database

45

* @param records - Single object, array of objects, or JSON string

46

* @returns QueryResult containing inserted records

47

*/

48

insert(records: object | object[] | string): QueryResult;

49

```

50

51

**Usage Examples:**

52

53

```javascript

54

// Insert single record

55

const result = db.insert({ name: "Charlie", age: 35 });

56

57

// Insert multiple records

58

db.insert([

59

{ name: "David", age: 40 },

60

{ name: "Eve", age: 28 }

61

]);

62

63

// Insert from JSON string

64

db.insert('{"name":"Frank","age":45}');

65

66

// Insert with array format (first row as headers)

67

db.insert([

68

["name", "age", "city"],

69

["Grace", 32, "New York"],

70

["Henry", 27, "Boston"]

71

]);

72

```

73

74

### Data Merging

75

76

Insert or update records based on a key field, enabling upsert functionality.

77

78

```javascript { .api }

79

/**

80

* Insert or update records based on key field matching

81

* @param records - Array of objects to merge

82

* @param key - Field name to match on (default: 'id')

83

* @param runEvent - Whether to trigger event callbacks (default: false)

84

* @returns QueryResult containing affected records

85

*/

86

merge(records: object[], key?: string, runEvent?: boolean): QueryResult;

87

```

88

89

**Usage Examples:**

90

91

```javascript

92

// Merge based on 'id' field (default)

93

db.merge([

94

{ id: 1, name: "Updated Product", price: 899.99 }, // Update existing

95

{ id: 3, name: "New Product", price: 199.99 } // Insert new

96

]);

97

98

// Merge based on custom key field

99

db.merge([

100

{ email: "alice@example.com", name: "Alice Smith", active: true },

101

{ email: "bob@example.com", name: "Bob Jones", active: false }

102

], "email");

103

104

// Merge with event callbacks enabled

105

db.merge(newRecords, "id", true);

106

```

107

108

### Database Sorting

109

110

Change the default sort order of records in the database, affecting subsequent operations.

111

112

```javascript { .api }

113

/**

114

* Sort the database records and update internal indexes

115

* @param orderString - Sort specification (e.g., "name desc, age")

116

* @returns Boolean indicating success

117

*/

118

sort(orderString: string): boolean;

119

```

120

121

**Usage Examples:**

122

123

```javascript

124

// Sort by single field ascending

125

db.sort("name");

126

127

// Sort by single field descending

128

db.sort("price desc");

129

130

// Sort by multiple fields

131

db.sort("category, price desc");

132

133

// Logical sort (natural ordering for mixed strings/numbers)

134

db.sort("name logical");

135

136

// After sorting, queries return records in new order

137

const sortedResults = db().get(); // Returns records in sorted order

138

```

139

140

### Database Configuration

141

142

Get or set database configuration options including event callbacks and behavior settings.

143

144

```javascript { .api }

145

/**

146

* Get or set database settings

147

* @param options - Configuration object (optional)

148

* @returns Current settings object

149

*/

150

settings(options?: DatabaseSettings): DatabaseSettings;

151

152

interface DatabaseSettings {

153

template?: object; // Default template for new records

154

onInsert?: (record: object) => void; // Insert event callback

155

onUpdate?: (newRecord: object, oldRecord: object, changes: object) => void;

156

onRemove?: (record: object) => void; // Remove event callback

157

onDBChange?: () => void; // General change callback

158

storageName?: string; // localStorage key name

159

forcePropertyCase?: 'lower' | 'upper' | null; // Force property name case

160

cacheSize?: number; // Query result cache size (default: 100)

161

name?: string; // Database name

162

}

163

```

164

165

**Usage Examples:**

166

167

```javascript

168

// Get current settings

169

const currentSettings = db.settings();

170

171

// Set template for new records

172

db.settings({

173

template: { active: true, created: new Date() }

174

});

175

176

// Set event callbacks

177

db.settings({

178

onInsert: function(record) {

179

console.log('Inserted:', record);

180

},

181

onUpdate: function(newRecord, oldRecord, changes) {

182

console.log('Updated:', changes);

183

},

184

onRemove: function(record) {

185

console.log('Removed:', record);

186

}

187

});

188

189

// Configure property case handling

190

db.settings({

191

forcePropertyCase: 'lower' // All property names converted to lowercase

192

});

193

194

// Set cache size for query optimization

195

db.settings({

196

cacheSize: 500 // Cache up to 500 query results

197

});

198

```

199

200

### Local Storage Persistence

201

202

Enable automatic persistence to browser localStorage with automatic saving on database changes.

203

204

```javascript { .api }

205

/**

206

* Enable localStorage persistence for the database

207

* @param storageName - Key name for localStorage (optional)

208

* @returns TaffyDatabase instance for chaining

209

*/

210

store(storageName?: string): TaffyDatabase;

211

```

212

213

**Usage Examples:**

214

215

```javascript

216

// Enable localStorage with automatic key generation

217

db.store("myAppData");

218

219

// Database will automatically:

220

// - Load existing data from localStorage on initialization

221

// - Save changes to localStorage after modifications

222

223

// Data is stored in localStorage as:

224

// localStorage.getItem("taffy_myAppData")

225

226

// Check if data was loaded from storage

227

const db2 = TAFFY().store("existingData");

228

// Returns true if data was loaded from localStorage

229

```

230

231

### Database Identification

232

233

Every TaffyDB instance has a `TAFFY` property for identification.

234

235

```javascript { .api }

236

/**

237

* Database identification property

238

*/

239

TAFFY: boolean; // Always true for TaffyDB instances

240

```

241

242

**Usage Examples:**

243

244

```javascript

245

// Check if object is a TaffyDB instance

246

function isTaffyDB(obj) {

247

return obj && obj.TAFFY === true;

248

}

249

250

// Conditional logic based on database type

251

if (myDB.TAFFY) {

252

// Handle TaffyDB instance

253

const results = myDB({ active: true });

254

} else {

255

// Handle regular array

256

const results = myDB.filter(item => item.active);

257

}

258

```