libsql-orm 0.2.5

A powerful, async-first ORM for Turso Database with first-class support for Cloudflare Workers and WebAssembly environments. Features include automatic boolean conversion, upsert operations, built-in logging, migrations, and comprehensive query building.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
# libsql-orm MCP Server Documentation

## Overview

`libsql-orm` is a powerful, async-first ORM for Turso Database (libsql) with first-class support for Cloudflare Workers and WebAssembly environments. This MCP (Model Context Protocol) server provides tools and resources for interacting with Turso databases using a type-safe, Rust-based ORM.

**Version**: 0.2.4
**License**: MIT
**Repository**: https://github.com/ayonsaha2011/libsql-orm

## Key Features

- 🚀 **Cloudflare Workers Ready** - Built specifically for edge computing environments
- 🔄 **Async/Await Support** - Fully async API with excellent performance
- 🎯 **Type-Safe** - Leverages Rust's type system for compile-time safety
- 📊 **Rich Query Builder** - Fluent API for complex queries
- 🔍 **Advanced Filtering** - Search, pagination, sorting, and aggregations
- 🎨 **Derive Macros** - Automatic model generation with `#[derive(Model)]`
- 📦 **Bulk Operations** - Efficient batch inserts, updates, and deletes
- 🌐 **WASM Compatible** - Optimized for WebAssembly targets
- 🔄 **Upsert Operations** - Smart create_or_update and upsert methods
- 📝 **Built-in Logging** - Comprehensive logging for debugging

## MCP Resources

### Resource Types

The MCP server exposes the following resource types that can be queried and manipulated:

#### 1. **Database Connection Resource**
- **Type**: `database://connection`
- **Description**: Manages connections to Turso databases
- **Operations**:
  - `new_connect(url, token)` - Create new database connection
  - `query(sql, params)` - Execute SQL queries
  - `execute(sql, params)` - Execute SQL statements

#### 2. **Model Resources**
- **Type**: `model://{table_name}`
- **Description**: Represents database tables as Rust structs with ORM capabilities
- **Operations**:
  - CRUD operations (Create, Read, Update, Delete)
  - Bulk operations
  - Search and filtering
  - Pagination

#### 3. **Query Resources**
- **Type**: `query://builder`
- **Description**: Fluent query builder for complex SQL queries
- **Operations**:
  - SELECT with column selection
  - JOIN operations (INNER, LEFT, RIGHT, FULL)
  - WHERE clauses with filters
  - GROUP BY and HAVING
  - ORDER BY with sorting
  - LIMIT and OFFSET

#### 4. **Migration Resources**
- **Type**: `migration://{migration_id}`
- **Description**: Database schema migrations
- **Operations**:
  - Create migrations
  - Execute migrations
  - Rollback migrations
  - Track migration history

---

## MCP Tools

### Database Tools

#### `database_connect`
Connect to a Turso database.

**Parameters**:
- `url` (string, required): Database URL (e.g., "turso://your-db.turso.io")
- `token` (string, required): Authentication token

**Returns**: Database connection object

**Example**:
```json
{
  "tool": "database_connect",
  "arguments": {
    "url": "turso://my-db.turso.io",
    "token": "your-auth-token"
  }
}
```

#### `database_query`
Execute a SQL query.

**Parameters**:
- `sql` (string, required): SQL query string
- `params` (array, optional): Query parameters

**Returns**: Query results as rows

**Example**:
```json
{
  "tool": "database_query",
  "arguments": {
    "sql": "SELECT * FROM users WHERE age > ?",
    "params": [18]
  }
}
```

---

### Model CRUD Tools

#### `model_create`
Create a new record in the database.

**Parameters**:
- `model` (string, required): Model name
- `data` (object, required): Record data

**Returns**: Created record with ID

**Example**:
```json
{
  "tool": "model_create",
  "arguments": {
    "model": "User",
    "data": {
      "name": "John Doe",
      "email": "john@example.com",
      "is_active": true
    }
  }
}
```

#### `model_find_by_id`
Find a record by primary key.

**Parameters**:
- `model` (string, required): Model name
- `id` (integer, required): Primary key value

**Returns**: Record or null

**Example**:
```json
{
  "tool": "model_find_by_id",
  "arguments": {
    "model": "User",
    "id": 123
  }
}
```

#### `model_find_all`
Find all records.

**Parameters**:
- `model` (string, required): Model name

**Returns**: Array of records

**Example**:
```json
{
  "tool": "model_find_all",
  "arguments": {
    "model": "User"
  }
}
```

#### `model_find_where`
Find records matching filter criteria.

**Parameters**:
- `model` (string, required): Model name
- `filter` (object, required): Filter operator

**Returns**: Array of matching records

**Example**:
```json
{
  "tool": "model_find_where",
  "arguments": {
    "model": "User",
    "filter": {
      "type": "Single",
      "filter": {
        "column": "is_active",
        "operator": "Eq",
        "value": true
      }
    }
  }
}
```

#### `model_update`
Update an existing record.

**Parameters**:
- `model` (string, required): Model name
- `id` (integer, required): Primary key value
- `data` (object, required): Updated fields

**Returns**: Updated record

**Example**:
```json
{
  "tool": "model_update",
  "arguments": {
    "model": "User",
    "id": 123,
    "data": {
      "name": "Jane Doe",
      "email": "jane@example.com"
    }
  }
}
```

#### `model_delete`
Delete a record by ID.

**Parameters**:
- `model` (string, required): Model name
- `id` (integer, required): Primary key value

**Returns**: Success boolean

**Example**:
```json
{
  "tool": "model_delete",
  "arguments": {
    "model": "User",
    "id": 123
  }
}
```

---

### Upsert Tools

#### `model_create_or_update`
Create or update based on primary key existence.

**Parameters**:
- `model` (string, required): Model name
- `data` (object, required): Record data (must include ID for update)

**Returns**: Created or updated record

**Example**:
```json
{
  "tool": "model_create_or_update",
  "arguments": {
    "model": "User",
    "data": {
      "id": 123,
      "name": "Updated Name",
      "email": "updated@example.com"
    }
  }
}
```

#### `model_upsert`
Upsert based on unique constraint columns.

**Parameters**:
- `model` (string, required): Model name
- `unique_columns` (array, required): Column names to check for uniqueness
- `data` (object, required): Record data

**Returns**: Created or updated record

**Example**:
```json
{
  "tool": "model_upsert",
  "arguments": {
    "model": "User",
    "unique_columns": ["email"],
    "data": {
      "name": "John Doe",
      "email": "john@example.com"
    }
  }
}
```

---

### Bulk Operation Tools

#### `model_bulk_create`
Create multiple records in a transaction.

**Parameters**:
- `model` (string, required): Model name
- `records` (array, required): Array of record data

**Returns**: Array of created records

**Example**:
```json
{
  "tool": "model_bulk_create",
  "arguments": {
    "model": "User",
    "records": [
      {"name": "User 1", "email": "user1@example.com"},
      {"name": "User 2", "email": "user2@example.com"},
      {"name": "User 3", "email": "user3@example.com"}
    ]
  }
}
```

#### `model_bulk_update`
Update multiple records in a transaction.

**Parameters**:
- `model` (string, required): Model name
- `records` (array, required): Array of records with IDs

**Returns**: Array of updated records

**Example**:
```json
{
  "tool": "model_bulk_update",
  "arguments": {
    "model": "User",
    "records": [
      {"id": 1, "is_active": false},
      {"id": 2, "is_active": false},
      {"id": 3, "is_active": false}
    ]
  }
}
```

#### `model_bulk_delete`
Delete multiple records by IDs.

**Parameters**:
- `model` (string, required): Model name
- `ids` (array, required): Array of primary key values

**Returns**: Number of deleted records

**Example**:
```json
{
  "tool": "model_bulk_delete",
  "arguments": {
    "model": "User",
    "ids": [1, 2, 3, 4, 5]
  }
}
```

---

### Pagination Tools

#### `model_find_paginated`
Find records with offset-based pagination.

**Parameters**:
- `model` (string, required): Model name
- `page` (integer, required): Page number (1-based)
- `per_page` (integer, required): Items per page

**Returns**: Paginated result with data and metadata

**Example**:
```json
{
  "tool": "model_find_paginated",
  "arguments": {
    "model": "User",
    "page": 1,
    "per_page": 10
  }
}
```

**Response**:
```json
{
  "data": [...],
  "pagination": {
    "page": 1,
    "per_page": 10,
    "total": 100,
    "total_pages": 10
  }
}
```

#### `model_find_where_paginated`
Find filtered records with pagination.

**Parameters**:
- `model` (string, required): Model name
- `filter` (object, required): Filter operator
- `page` (integer, required): Page number
- `per_page` (integer, required): Items per page

**Returns**: Paginated result

**Example**:
```json
{
  "tool": "model_find_where_paginated",
  "arguments": {
    "model": "User",
    "filter": {
      "type": "Single",
      "filter": {"column": "is_active", "operator": "Eq", "value": true}
    },
    "page": 1,
    "per_page": 20
  }
}
```

---

### Search Tools

#### `model_search`
Search records across multiple columns.

**Parameters**:
- `model` (string, required): Model name
- `query` (string, required): Search query
- `columns` (array, required): Columns to search in
- `case_sensitive` (boolean, optional): Case sensitivity flag
- `exact_match` (boolean, optional): Exact match flag
- `page` (integer, optional): Page number
- `per_page` (integer, optional): Items per page

**Returns**: Paginated search results

**Example**:
```json
{
  "tool": "model_search",
  "arguments": {
    "model": "User",
    "query": "john",
    "columns": ["name", "email"],
    "case_sensitive": false,
    "exact_match": false,
    "page": 1,
    "per_page": 10
  }
}
```

---

### Aggregation Tools

#### `model_count`
Count all records.

**Parameters**:
- `model` (string, required): Model name

**Returns**: Total count

**Example**:
```json
{
  "tool": "model_count",
  "arguments": {
    "model": "User"
  }
}
```

#### `model_count_where`
Count records matching filter.

**Parameters**:
- `model` (string, required): Model name
- `filter` (object, required): Filter operator

**Returns**: Filtered count

**Example**:
```json
{
  "tool": "model_count_where",
  "arguments": {
    "model": "User",
    "filter": {
      "type": "Single",
      "filter": {"column": "is_active", "operator": "Eq", "value": true}
    }
  }
}
```

#### `model_aggregate`
Perform aggregate operations.

**Parameters**:
- `model` (string, required): Model name
- `function` (string, required): Aggregate function (Count, Sum, Avg, Min, Max)
- `column` (string, required): Column name
- `filter` (object, optional): Filter operator

**Returns**: Aggregate value

**Example**:
```json
{
  "tool": "model_aggregate",
  "arguments": {
    "model": "Order",
    "function": "Sum",
    "column": "total_amount",
    "filter": {
      "type": "Single",
      "filter": {"column": "status", "operator": "Eq", "value": "completed"}
    }
  }
}
```

---

### Query Builder Tools

#### `query_build`
Build and execute a custom query.

**Parameters**:
- `table` (string, required): Table name
- `select` (array, optional): Column names
- `joins` (array, optional): Join clauses
- `where` (object, optional): Filter operator
- `group_by` (array, optional): Group by columns
- `having` (object, optional): Having clause
- `order_by` (array, optional): Sort specifications
- `limit` (integer, optional): Result limit
- `offset` (integer, optional): Result offset
- `distinct` (boolean, optional): Distinct flag

**Returns**: Query results

**Example**:
```json
{
  "tool": "query_build",
  "arguments": {
    "table": "orders",
    "select": ["orders.id", "users.name", "orders.total"],
    "joins": [
      {
        "type": "Inner",
        "table": "users",
        "condition": "users.id = orders.user_id"
      }
    ],
    "where": {
      "type": "Single",
      "filter": {"column": "orders.status", "operator": "Eq", "value": "completed"}
    },
    "order_by": [
      {"column": "orders.created_at", "order": "Desc"}
    ],
    "limit": 10
  }
}
```

---

### Filter Tools

#### Filter Operators

**Single Filter**:
```json
{
  "type": "Single",
  "filter": {
    "column": "age",
    "operator": "Gt",
    "value": 18
  }
}
```

**AND Combination**:
```json
{
  "type": "And",
  "filters": [
    {
      "type": "Single",
      "filter": {"column": "is_active", "operator": "Eq", "value": true}
    },
    {
      "type": "Single",
      "filter": {"column": "age", "operator": "Ge", "value": 18}
    }
  ]
}
```

**OR Combination**:
```json
{
  "type": "Or",
  "filters": [
    {
      "type": "Single",
      "filter": {"column": "role", "operator": "Eq", "value": "admin"}
    },
    {
      "type": "Single",
      "filter": {"column": "role", "operator": "Eq", "value": "moderator"}
    }
  ]
}
```

**NOT Filter**:
```json
{
  "type": "Not",
  "filter": {
    "type": "Single",
    "filter": {"column": "status", "operator": "Eq", "value": "deleted"}
  }
}
```

#### Supported Operators

- `Eq` - Equal to
- `Ne` - Not equal to
- `Lt` - Less than
- `Le` - Less than or equal
- `Gt` - Greater than
- `Ge` - Greater than or equal
- `Like` - Pattern matching
- `NotLike` - Negative pattern matching
- `In` - In list
- `NotIn` - Not in list
- `IsNull` - Is NULL
- `IsNotNull` - Is NOT NULL
- `Between` - Between range
- `NotBetween` - Not between range

---

### Migration Tools

#### `migration_create`
Create a new migration.

**Parameters**:
- `name` (string, required): Migration name
- `sql` (string, required): Migration SQL

**Returns**: Migration object

**Example**:
```json
{
  "tool": "migration_create",
  "arguments": {
    "name": "create_users_table",
    "sql": "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
  }
}
```

#### `migration_execute`
Execute a migration.

**Parameters**:
- `migration_id` (string, required): Migration ID

**Returns**: Success status

**Example**:
```json
{
  "tool": "migration_execute",
  "arguments": {
    "migration_id": "550e8400-e29b-41d4-a716-446655440000"
  }
}
```

#### `migration_rollback`
Rollback a migration.

**Parameters**:
- `migration_id` (string, required): Migration ID

**Returns**: Success status

**Example**:
```json
{
  "tool": "migration_rollback",
  "arguments": {
    "migration_id": "550e8400-e29b-41d4-a716-446655440000"
  }
}
```

#### `migration_list_pending`
List pending migrations.

**Returns**: Array of pending migrations

**Example**:
```json
{
  "tool": "migration_list_pending",
  "arguments": {}
}
```

#### `migration_list_executed`
List executed migrations.

**Returns**: Array of executed migrations

**Example**:
```json
{
  "tool": "migration_list_executed",
  "arguments": {}
}
```

#### `migration_generate_from_model`
Generate migration from model definition.

**Parameters**:
- `model` (string, required): Model name

**Returns**: Generated migration

**Example**:
```json
{
  "tool": "migration_generate_from_model",
  "arguments": {
    "model": "User"
  }
}
```

---

### Migration Template Tools

#### `migration_template_create_table`
Create table migration template.

**Parameters**:
- `table_name` (string, required): Table name
- `columns` (array, required): Column definitions

**Returns**: Migration object

**Example**:
```json
{
  "tool": "migration_template_create_table",
  "arguments": {
    "table_name": "posts",
    "columns": [
      {"name": "id", "definition": "INTEGER PRIMARY KEY AUTOINCREMENT"},
      {"name": "title", "definition": "TEXT NOT NULL"},
      {"name": "content", "definition": "TEXT"},
      {"name": "created_at", "definition": "TEXT NOT NULL"}
    ]
  }
}
```

#### `migration_template_add_column`
Add column migration template.

**Parameters**:
- `table_name` (string, required): Table name
- `column_name` (string, required): Column name
- `definition` (string, required): Column definition

**Returns**: Migration object

**Example**:
```json
{
  "tool": "migration_template_add_column",
  "arguments": {
    "table_name": "users",
    "column_name": "last_login",
    "definition": "TEXT"
  }
}
```

#### `migration_template_create_index`
Create index migration template.

**Parameters**:
- `index_name` (string, required): Index name
- `table_name` (string, required): Table name
- `columns` (array, required): Column names

**Returns**: Migration object

**Example**:
```json
{
  "tool": "migration_template_create_index",
  "arguments": {
    "index_name": "idx_users_email",
    "table_name": "users",
    "columns": ["email"]
  }
}
```

---

## Data Types

### Value Types

The ORM supports the following value types:

- **Null**: NULL value
- **Integer**: 64-bit signed integer
- **Real**: 64-bit floating point
- **Text**: UTF-8 string
- **Blob**: Binary data
- **Boolean**: Boolean (stored as INTEGER 0/1)

### Sort Order

- **Asc**: Ascending order
- **Desc**: Descending order

### Join Types

- **Inner**: INNER JOIN
- **Left**: LEFT JOIN
- **Right**: RIGHT JOIN
- **Full**: FULL JOIN

### Aggregate Functions

- **Count**: COUNT(column)
- **Sum**: SUM(column)
- **Avg**: AVG(column)
- **Min**: MIN(column)
- **Max**: MAX(column)

---

## Error Handling

The MCP server returns errors in the following format:

```json
{
  "error": {
    "type": "Error Type",
    "message": "Detailed error message"
  }
}
```

### Error Types

- **Connection**: Database connection errors
- **Sql**: SQL execution errors
- **Serialization**: Data serialization/deserialization errors
- **Validation**: Data validation errors
- **NotFound**: Resource not found errors
- **Pagination**: Pagination parameter errors
- **Query**: Query building errors
- **DatabaseError**: General database errors

---

## Usage Examples

### Example 1: Basic CRUD Operations

```json
// Create a user
{
  "tool": "model_create",
  "arguments": {
    "model": "User",
    "data": {
      "name": "Alice",
      "email": "alice@example.com",
      "age": 30,
      "is_active": true
    }
  }
}

// Find user by ID
{
  "tool": "model_find_by_id",
  "arguments": {
    "model": "User",
    "id": 1
  }
}

// Update user
{
  "tool": "model_update",
  "arguments": {
    "model": "User",
    "id": 1,
    "data": {
      "email": "alice.updated@example.com"
    }
  }
}

// Delete user
{
  "tool": "model_delete",
  "arguments": {
    "model": "User",
    "id": 1
  }
}
```

### Example 2: Complex Filtering

```json
// Find active users over 18
{
  "tool": "model_find_where",
  "arguments": {
    "model": "User",
    "filter": {
      "type": "And",
      "filters": [
        {
          "type": "Single",
          "filter": {"column": "is_active", "operator": "Eq", "value": true}
        },
        {
          "type": "Single",
          "filter": {"column": "age", "operator": "Gt", "value": 18}
        }
      ]
    }
  }
}
```

### Example 3: Pagination

```json
// Get page 2 with 20 items
{
  "tool": "model_find_paginated",
  "arguments": {
    "model": "User",
    "page": 2,
    "per_page": 20
  }
}
```

### Example 4: Search

```json
// Search for "john" in name and email fields
{
  "tool": "model_search",
  "arguments": {
    "model": "User",
    "query": "john",
    "columns": ["name", "email"],
    "page": 1,
    "per_page": 10
  }
}
```

### Example 5: Aggregation

```json
// Count active users
{
  "tool": "model_count_where",
  "arguments": {
    "model": "User",
    "filter": {
      "type": "Single",
      "filter": {"column": "is_active", "operator": "Eq", "value": true}
    }
  }
}

// Average age of users
{
  "tool": "model_aggregate",
  "arguments": {
    "model": "User",
    "function": "Avg",
    "column": "age"
  }
}
```

### Example 6: Complex Query with Joins

```json
{
  "tool": "query_build",
  "arguments": {
    "table": "orders",
    "select": ["orders.*", "users.name as user_name", "products.title as product_title"],
    "joins": [
      {
        "type": "Inner",
        "table": "users",
        "condition": "users.id = orders.user_id"
      },
      {
        "type": "Inner",
        "table": "products",
        "condition": "products.id = orders.product_id"
      }
    ],
    "where": {
      "type": "And",
      "filters": [
        {
          "type": "Single",
          "filter": {"column": "orders.status", "operator": "Eq", "value": "completed"}
        },
        {
          "type": "Single",
          "filter": {"column": "orders.created_at", "operator": "Ge", "value": "2024-01-01"}
        }
      ]
    },
    "order_by": [
      {"column": "orders.created_at", "order": "Desc"}
    ],
    "limit": 50
  }
}
```

---

## Best Practices

### 1. Connection Management
- Reuse database connections when possible
- Close connections properly after use
- Use connection pooling for high-traffic applications

### 2. Query Optimization
- Use indexes for frequently queried columns
- Avoid N+1 queries by using joins
- Use pagination for large result sets
- Use specific column selection instead of SELECT *

### 3. Data Validation
- Validate data before database operations
- Use appropriate data types
- Implement constraints at the database level

### 4. Error Handling
- Always handle errors gracefully
- Log errors for debugging
- Provide meaningful error messages to users

### 5. Migrations
- Version control migration files
- Test migrations before production deployment
- Always provide rollback scripts
- Use descriptive migration names

### 6. Security
- Use parameterized queries to prevent SQL injection
- Validate and sanitize user input
- Implement proper authentication and authorization
- Use environment variables for sensitive data

---

## Cloudflare Workers Integration

For deploying with Cloudflare Workers:

### Dependencies
```toml
[dependencies]
libsql-orm = { version = "0.2.4", features = ["cloudflare"] }
worker = { version = ">=0.7.0", features = ['http', 'axum'] }
```

### Environment Variables
- `TURSO_DATABASE_URL` - Database URL
- `TURSO_AUTH_TOKEN` - Authentication token

### Sample Worker Request
```json
{
  "method": "POST",
  "path": "/api/users",
  "body": {
    "name": "John Doe",
    "email": "john@example.com"
  }
}
```

---

## Performance Considerations

### Batch Operations
Use bulk operations for multiple inserts/updates to reduce round trips:
- `model_bulk_create` for multiple inserts
- `model_bulk_update` for multiple updates
- `model_bulk_delete` for multiple deletes

### Pagination
- Use cursor-based pagination for large datasets
- Offset-based pagination is simpler but less efficient for large offsets

### Indexing
- Create indexes on frequently queried columns
- Use composite indexes for multi-column queries
- Monitor index usage and remove unused indexes

### Caching
- Cache frequently accessed data
- Invalidate cache on data updates
- Use edge caching with Cloudflare Workers

---

## Limitations

1. **WASM Environment**:
   - Limited to libsql/Turso databases
   - Some native database features may not be available

2. **Boolean Type**:
   - Stored as INTEGER (0/1) in SQLite
   - Automatic conversion provided

3. **Transaction Support**:
   - Manual transaction handling in WASM
   - Use BEGIN/COMMIT for atomic operations

4. **Last Insert ID**:
   - Not available in WASM environments
   - Placeholder value returned

---

## Additional Resources

- **Documentation**: https://docs.rs/libsql-orm
- **Repository**: https://github.com/ayonsaha2011/libsql-orm
- **Turso Database**: https://turso.tech/
- **Cloudflare Workers**: https://workers.cloudflare.com/

---

## Support

For issues, questions, or contributions:
- GitHub Issues: https://github.com/ayonsaha2011/libsql-orm/issues
- GitHub Discussions: https://github.com/ayonsaha2011/libsql-orm/discussions

---

**Last Updated**: 2025-12-29
**Documentation Version**: 1.0.0