or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cursors.mddatabase-management.mdindex.mdjson-collections.mdjx9-scripting.mdkey-value.mdtransactions.mdutilities.md

jx9-scripting.mddocs/

0

# Jx9 Scripting

1

2

Embedded Jx9 scripting engine for complex database operations and JSON manipulation with variable management. Jx9 is a JavaScript-like scripting language designed for database operations and JSON document processing.

3

4

## Capabilities

5

6

### Virtual Machine Management

7

8

Create and manage Jx9 virtual machines for script execution.

9

10

```python { .api }

11

def vm(self, code):

12

"""Create an UnQLite Jx9 virtual machine.

13

Returns VM object."""

14

...

15

16

class VM:

17

def __init__(self, unqlite, code):

18

"""Initialize VM with database connection and script code."""

19

...

20

21

def __enter__(self):

22

"""Enter context manager. Compiles script."""

23

...

24

25

def __exit__(self, exc_type, exc_val, exc_tb):

26

"""Exit context manager. Closes VM."""

27

...

28

```

29

30

**Usage Example:**

31

32

```python

33

db = unqlite.UnQLite(':mem:')

34

35

# Simple Jx9 script

36

script = """

37

$key = 'hello';

38

$value = 'world';

39

db_store($key, $value);

40

$result = db_fetch($key);

41

"""

42

43

# Create and use VM

44

vm = db.vm(script)

45

46

# Use as context manager for automatic cleanup

47

with db.vm(script) as vm:

48

vm.execute()

49

result = vm.get_value('result')

50

print(f"Script result: {result}") # "world"

51

```

52

53

### Script Compilation and Execution

54

55

Compile and execute Jx9 scripts with error handling.

56

57

```python { .api }

58

def compile(self):

59

"""Compile the Jx9 script."""

60

...

61

62

def execute(self):

63

"""Execute the compiled Jx9 script."""

64

...

65

66

def reset(self):

67

"""Reset VM state for re-execution."""

68

...

69

70

def close(self):

71

"""Close and release the virtual machine."""

72

...

73

```

74

75

**Usage Example:**

76

77

```python

78

db = unqlite.UnQLite(':mem:')

79

80

script = """

81

// Jx9 script to process data

82

$users = [

83

{'name': 'Alice', 'age': 30},

84

{'name': 'Bob', 'age': 25},

85

{'name': 'Charlie', 'age': 35}

86

];

87

88

$adult_count = 0;

89

foreach($users as $user) {

90

if ($user.age >= 18) {

91

$adult_count++;

92

db_store('user:' + $user.name, $user);

93

}

94

}

95

96

$result = $adult_count;

97

"""

98

99

vm = db.vm(script)

100

101

try:

102

# Manual VM management

103

vm.compile()

104

vm.execute()

105

106

adults = vm.get_value('result')

107

print(f"Adults processed: {adults}")

108

109

# Re-execute with reset

110

vm.reset()

111

vm.execute()

112

113

finally:

114

vm.close()

115

```

116

117

### Variable Management

118

119

Pass data between Python and Jx9 scripts using variables.

120

121

```python { .api }

122

def set_value(self, name, value):

123

"""Set the value of a variable in the Jx9 script."""

124

...

125

126

def get_value(self, name):

127

"""Retrieve the value of a variable after script execution."""

128

...

129

130

def set_values(self, dict data):

131

"""Set multiple variables from dictionary."""

132

...

133

134

def __setitem__(self, name, value):

135

"""Set variable using vm[name] = value syntax."""

136

...

137

138

def __getitem__(self, name):

139

"""Get variable using vm[name] syntax."""

140

...

141

```

142

143

**Usage Example:**

144

145

```python

146

db = unqlite.UnQLite(':mem:')

147

148

script = """

149

// Process input data from Python

150

$total = 0;

151

foreach($numbers as $num) {

152

$total += $num;

153

}

154

155

$average = $total / count($numbers);

156

$summary = {

157

'total': $total,

158

'count': count($numbers),

159

'average': $average

160

};

161

"""

162

163

with db.vm(script) as vm:

164

# Pass data to script

165

vm.set_value('numbers', [10, 20, 30, 40, 50])

166

167

# Alternative syntax

168

vm['multiplier'] = 2

169

170

# Set multiple values

171

vm.set_values({

172

'threshold': 25,

173

'category': 'test_data'

174

})

175

176

vm.execute()

177

178

# Retrieve results

179

summary = vm.get_value('summary')

180

print(f"Summary: {summary}")

181

182

# Alternative syntax

183

total = vm['total']

184

print(f"Total: {total}")

185

```

186

187

## Jx9 Language Features

188

189

### Data Types

190

191

Jx9 supports JavaScript-like data types with automatic conversion:

192

193

```python

194

db = unqlite.UnQLite(':mem:')

195

196

script = """

197

// Strings

198

$text = 'Hello, World!';

199

200

// Numbers

201

$integer = 42;

202

$float = 3.14159;

203

204

// Booleans

205

$flag = true;

206

$disabled = false;

207

208

// Arrays

209

$list = [1, 2, 3, 'mixed', true];

210

211

// Objects (associative arrays)

212

$person = {

213

'name': 'Alice',

214

'age': 30,

215

'active': true

216

};

217

218

// Null

219

$empty = null;

220

"""

221

222

with db.vm(script) as vm:

223

vm.execute()

224

225

# Python automatically converts types

226

person = vm['person']

227

print(f"Person: {person}") # Python dict

228

229

list_data = vm['list']

230

print(f"List: {list_data}") # Python list

231

```

232

233

### Database Operations

234

235

Jx9 provides built-in functions for database manipulation:

236

237

```python

238

db = unqlite.UnQLite(':mem:')

239

240

script = """

241

// Key-value operations

242

db_store('user:1', {'name': 'Alice', 'role': 'admin'});

243

db_store('user:2', {'name': 'Bob', 'role': 'user'});

244

245

// Fetch data

246

$alice = db_fetch('user:1');

247

$exists = db_exists('user:1');

248

249

// Delete data

250

db_delete('user:2');

251

252

// Check existence after delete

253

$bob_exists = db_exists('user:2');

254

255

$results = {

256

'alice': $alice,

257

'alice_exists': $exists,

258

'bob_exists': $bob_exists

259

};

260

"""

261

262

with db.vm(script) as vm:

263

vm.execute()

264

results = vm['results']

265

print(f"Results: {results}")

266

```

267

268

### JSON Document Operations

269

270

Jx9 excels at JSON document manipulation:

271

272

```python

273

db = unqlite.UnQLite(':mem:')

274

275

script = """

276

// Create collection

277

if (!db_exists('products')) {

278

db_create('products');

279

}

280

281

// Store documents

282

$products = [

283

{'name': 'Laptop', 'price': 999.99, 'category': 'electronics'},

284

{'name': 'Book', 'price': 19.99, 'category': 'education'},

285

{'name': 'Coffee', 'price': 4.99, 'category': 'food'}

286

];

287

288

foreach($products as $product) {

289

db_store('products', $product);

290

}

291

292

// Query documents

293

$all_products = db_fetch_all('products');

294

$product_count = db_total_records('products');

295

296

$summary = {

297

'total_products': $product_count,

298

'products': $all_products

299

};

300

"""

301

302

with db.vm(script) as vm:

303

vm.execute()

304

summary = vm['summary']

305

print(f"Product summary: {summary}")

306

```

307

308

### Control Flow

309

310

Jx9 supports standard control flow constructs:

311

312

```python

313

db = unqlite.UnQLite(':mem:')

314

315

script = """

316

$data = [10, 25, 5, 30, 15];

317

$processed = [];

318

$stats = {'min': null, 'max': null, 'sum': 0};

319

320

// Foreach loop

321

foreach($data as $value) {

322

$stats.sum += $value;

323

324

// Conditional processing

325

if ($stats.min == null || $value < $stats.min) {

326

$stats.min = $value;

327

}

328

329

if ($stats.max == null || $value > $stats.max) {

330

$stats.max = $value;

331

}

332

333

// Transform data

334

if ($value > 20) {

335

$processed[] = $value * 2;

336

} else {

337

$processed[] = $value;

338

}

339

}

340

341

$stats.average = $stats.sum / count($data);

342

$results = {'stats': $stats, 'processed': $processed};

343

"""

344

345

with db.vm(script) as vm:

346

vm.execute()

347

results = vm['results']

348

print(f"Processing results: {results}")

349

```

350

351

### Error Handling

352

353

Handle errors in Jx9 scripts with proper exception management:

354

355

```python

356

db = unqlite.UnQLite(':mem:')

357

358

# Script with potential errors

359

script = """

360

try {

361

$data = db_fetch('nonexistent_key');

362

$success = true;

363

} catch($error) {

364

$success = false;

365

$error_msg = 'Key not found';

366

}

367

368

$result = {'success': $success, 'error': $error_msg};

369

"""

370

371

try:

372

with db.vm(script) as vm:

373

vm.execute()

374

result = vm['result']

375

print(f"Script result: {result}")

376

377

except unqlite.UnQLiteError as e:

378

print(f"VM execution failed: {e}")

379

```

380

381

## Advanced Usage

382

383

### Complex Data Processing

384

385

Use Jx9 for complex data transformations and business logic:

386

387

```python

388

db = unqlite.UnQLite('analytics.db')

389

390

# Complex analytics script

391

script = """

392

// Load user activity data

393

$users = db_fetch_all('users');

394

$activities = db_fetch_all('activities');

395

396

$analytics = {};

397

398

foreach($users as $user) {

399

$user_id = $user.__id;

400

$user_activities = [];

401

402

// Filter activities for this user

403

foreach($activities as $activity) {

404

if ($activity.user_id == $user_id) {

405

$user_activities[] = $activity;

406

}

407

}

408

409

// Calculate metrics

410

$total_time = 0;

411

$activity_types = {};

412

413

foreach($user_activities as $activity) {

414

$total_time += $activity.duration;

415

416

if (!isset($activity_types[$activity.type])) {

417

$activity_types[$activity.type] = 0;

418

}

419

$activity_types[$activity.type]++;

420

}

421

422

$analytics[$user.name] = {

423

'total_activities': count($user_activities),

424

'total_time': $total_time,

425

'activity_breakdown': $activity_types,

426

'average_duration': $total_time / count($user_activities)

427

};

428

}

429

430

// Store analytics results

431

db_store('analytics_summary', $analytics);

432

"""

433

434

with db.vm(script) as vm:

435

vm.execute()

436

print("Analytics processing completed")

437

```

438

439

### Custom Functions

440

441

While not directly exposed in the Python API, Jx9 scripts can define custom functions:

442

443

```python

444

db = unqlite.UnQLite(':mem:')

445

446

script = """

447

// Define custom function

448

function calculate_tax($amount, $rate) {

449

return $amount * ($rate / 100);

450

}

451

452

function format_currency($amount) {

453

return '$' + round($amount, 2);

454

}

455

456

// Use custom functions

457

$orders = [

458

{'item': 'Laptop', 'price': 999.99},

459

{'item': 'Mouse', 'price': 29.99},

460

{'item': 'Keyboard', 'price': 79.99}

461

];

462

463

$tax_rate = 8.5;

464

$processed_orders = [];

465

466

foreach($orders as $order) {

467

$tax = calculate_tax($order.price, $tax_rate);

468

$total = $order.price + $tax;

469

470

$processed_orders[] = {

471

'item': $order.item,

472

'price': format_currency($order.price),

473

'tax': format_currency($tax),

474

'total': format_currency($total)

475

};

476

}

477

478

$results = $processed_orders;

479

"""

480

481

with db.vm(script) as vm:

482

vm.execute()

483

results = vm['results']

484

for order in results:

485

print(f"Order: {order}")

486

```

487

488

## Performance Considerations

489

490

- **Compile once, execute multiple times**: Reuse compiled VMs for better performance

491

- **Minimize Python-Jx9 data transfer**: Process data within scripts when possible

492

- **Use appropriate data structures**: Jx9 arrays and objects are efficient for bulk operations

493

- **Handle errors gracefully**: VM compilation and execution can be resource-intensive

494

495

```python

496

# Efficient: Reuse compiled VM

497

db = unqlite.UnQLite(':mem:')

498

script = "$result = $input * 2;"

499

500

vm = db.vm(script)

501

vm.compile()

502

503

for i in range(100):

504

vm.set_value('input', i)

505

vm.execute()

506

result = vm.get_value('result')

507

vm.reset() # Reset for next execution

508

509

vm.close()

510

```