xdl-database 0.1.1

Database connectivity module for XDL - supports PostgreSQL, MySQL, DuckDB, SQLite, ODBC, Redis, and more
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
# XDL Database Connectivity Module

Unified database connectivity for XDL supporting multiple database systems including PostgreSQL, MySQL, DuckDB, ODBC, Redis, and Kafka.

## Features

- **Multiple Database Support**
  - ✅ PostgreSQL (fully implemented)
  - ✅ MySQL (fully implemented - native async driver with connection pooling)
  - ✅ DuckDB (fully implemented)
  - ✅ Redis (fully implemented)
  - ✅ ODBC (fully implemented - supports SQL Server, Oracle, MySQL, PostgreSQL, etc.)
  - ✅ Apache Kafka (fully implemented - producer/consumer/admin operations)

- **Async/Await Support** - Built on Tokio for high-performance async operations
- **Connection Pooling** - Efficient connection management (via deadpool)
- **Type-Safe Queries** - Automatic type conversion to XDL types
- **Object-Oriented API** - Familiar IDL/GDL-style object interface

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
xdl-database = { path = "../xdl-database", features = ["postgres-support", "duckdb-support", "redis-support"] }
```

### Available Features

- `postgres-support` - PostgreSQL support
- `mysql-support` - MySQL support
- `duckdb-support` - DuckDB support
- `odbc-support` - ODBC support
- `redis-support` - Redis support
- `kafka-support` - Apache Kafka support
- `all` - Enable all databases

## Usage from XDL

### Basic Example

```xdl
; Create a database object
objdb = OBJ_NEW('XDLdbDatabase')

; Connect to PostgreSQL
conn_str = 'postgresql://user:password@localhost:5432/dbname'
objdb->Connect, CONNECTION=conn_str

; Execute a query
recordset = objdb->ExecuteSQL('SELECT * FROM my_table')

; Get the data
data = recordset->GetData()
PRINT, data

; Get row count
n_rows = recordset->RowCount()
PRINT, 'Number of rows:', n_rows

; Get column names
columns = recordset->ColumnNames()
PRINT, 'Columns:', columns

; Cleanup
recordset->Destroy()
objdb->Disconnect()
OBJ_DESTROY, objdb
```

### MySQL Example

```xdl
; Create database object
objdb = OBJ_NEW('XDLdbDatabase')

; Connect to MySQL
objdb->Connect, CONNECTION='mysql://root:password@localhost:3306/testdb'

; Create a table
objdb->ExecuteCommand, 'CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), salary DECIMAL(10,2))'

; Insert data
objdb->ExecuteCommand, "INSERT INTO employees (name, salary) VALUES ('Alice', 95000.00)"
objdb->ExecuteCommand, "INSERT INTO employees (name, salary) VALUES ('Bob', 75000.00)"

; Query data
recordset = objdb->ExecuteSQL('SELECT * FROM employees ORDER BY salary DESC')
data = recordset->GetData()
PRINT, data

; Cleanup
recordset->Destroy()
objdb->Disconnect()
OBJ_DESTROY, objdb
```

### DuckDB Example

```xdl
; Create database object
objdb = OBJ_NEW('XDLdbDatabase')

; Connect to DuckDB file
objdb->Connect, CONNECTION='my_data.duckdb'

; Create a table
objdb->ExecuteCommand, 'CREATE TABLE users (id INTEGER, name VARCHAR)'

; Insert data
objdb->ExecuteCommand, "INSERT INTO users VALUES (1, 'Alice'), (2, 'Bob')"

; Query data
recordset = objdb->ExecuteSQL('SELECT * FROM users WHERE id > 0')
data = recordset->GetData()
PRINT, data

; Cleanup
recordset->Destroy()
objdb->Disconnect()
OBJ_DESTROY, objdb
```

### Redis Example

```xdl
; Create database object
objdb = OBJ_NEW('XDLdbDatabase')

; Connect to Redis
objdb->Connect, CONNECTION='redis://localhost:6379'

; Set a value
objdb->ExecuteCommand, 'SET mykey myvalue'

; Delete a key
rows_affected = objdb->ExecuteCommand('DEL mykey')
PRINT, 'Rows affected:', rows_affected

; Cleanup
objdb->Disconnect()
OBJ_DESTROY, objdb
```

### ODBC Example (SQL Server)

```xdl
; Create database object
objdb = OBJ_NEW('XDLdbDatabase')

; Connect to SQL Server via ODBC
conn_str = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=mydb;UID=user;PWD=pass'
objdb->Connect, CONNECTION=conn_str

; Create table
objdb->ExecuteCommand, 'CREATE TABLE Products (ID INT, Name NVARCHAR(100), Price DECIMAL(10,2))'

; Insert data
objdb->ExecuteCommand, "INSERT INTO Products VALUES (1, 'Laptop', 1299.99)"

; Query data
recordset = objdb->ExecuteSQL('SELECT * FROM Products')
data = recordset->GetData()
PRINT, data

; Cleanup
recordset->Destroy()
objdb->Disconnect()
OBJ_DESTROY, objdb
```

### Apache Kafka Example

```xdl
; Create database object
objdb = OBJ_NEW('XDLdbDatabase')

; Connect to Kafka
objdb->Connect, CONNECTION='kafka://localhost:9092'

; Create a topic
objdb->ExecuteSQL, 'CREATE TOPIC my-topic'

; Produce messages
objdb->ExecuteSQL, 'PRODUCE TO my-topic: Hello from XDL!'
objdb->ExecuteSQL, 'PRODUCE TO my-topic: Second message'

; Consume messages
recordset = objdb->ExecuteSQL('CONSUME FROM my-topic LIMIT 10')
messages = recordset->GetData()
PRINT, messages

; List topics
topics = objdb->ExecuteSQL('LIST TOPICS')
PRINT, topics->GetData()

; Cleanup
recordset->Destroy()
topics->Destroy()
objdb->Disconnect()
OBJ_DESTROY, objdb
```

### Advanced Query Example

```xdl
; Connect to PostgreSQL
objdb = OBJ_NEW('XDLdbDatabase')
objdb->Connect, CONNECTION='postgresql://localhost/mydb'

; Execute complex query
query = 'SELECT id, name, salary FROM employees WHERE department = ''Engineering'' ORDER BY salary DESC'
recordset = objdb->ExecuteSQL(query)

; Get data as structured columns
data_struct = recordset->GetDataStructured()

; Access individual columns
ids = data_struct.id
names = data_struct.name
salaries = data_struct.salary

; Print results
FOR i = 0, N_ELEMENTS(ids) - 1 DO BEGIN
    PRINT, ids[i], names[i], salaries[i]
ENDFOR

; Cleanup
recordset->Destroy()
objdb->Disconnect()
OBJ_DESTROY, objdb
```

## Connection Strings

### PostgreSQL
```
postgresql://user:password@host:port/database
postgres://user:password@host:port/database
```

### MySQL
```
mysql://user:password@host:port/database
mysql://user:password@host/database  (port defaults to 3306)
mysql://root:pass@localhost:3306/mydb
```

Also compatible with MariaDB and other MySQL-protocol databases.

### DuckDB
```
duckdb://path/to/file.duckdb
/path/to/file.duckdb
file.db
```

### ODBC
```
DRIVER={PostgreSQL Unicode(x64)};SERVER=host;UID=user;PWD=password;DATABASE=dbname;PORT=5432
```

### Redis
```
redis://localhost:6379
redis://:password@localhost:6379/0
```

### Kafka
```
kafka://localhost:9092
kafka://broker1:9092,broker2:9092  (multiple brokers)
localhost:9092                      (simplified format)
```

**Special Kafka Query Syntax:**

Kafka uses a special query syntax since it's a streaming platform:

```xdl
; Topic Management
'LIST TOPICS'
'CREATE TOPIC topic-name'
'DELETE TOPIC topic-name'

; Producer (send messages)
'PRODUCE TO topic-name: message content'
'PRODUCE TO sensors: {"temp":25.5,"humidity":60}'

; Consumer (read messages)
'CONSUME FROM topic-name LIMIT 10'
'CONSUME FROM events LIMIT 100'
```

## API Reference

### XDLdbDatabase Methods

#### Connect
```xdl
objdb->Connect, CONNECTION=connection_string
```
Connects to the database using the specified connection string.

#### Disconnect
```xdl
objdb->Disconnect
```
Disconnects from the database.

#### ExecuteSQL
```xdl
recordset = objdb->ExecuteSQL(query_string)
```
Executes a SELECT query and returns a recordset object.

#### ExecuteCommand
```xdl
rows_affected = objdb->ExecuteCommand(command_string)
```
Executes a command (INSERT, UPDATE, DELETE) and returns the number of rows affected.

#### IsConnected
```xdl
connected = objdb->IsConnected()
```
Returns 1 if connected, 0 otherwise.

#### DatabaseType
```xdl
db_type = objdb->DatabaseType()
```
Returns the type of database currently connected.

### Recordset Methods

#### GetData
```xdl
data = recordset->GetData()
```
Returns all data as a nested array.

#### GetDataStructured
```xdl
data_struct = recordset->GetDataStructured()
```
Returns data as a structure with column names as fields.

#### GetColumn
```xdl
column_data = recordset->GetColumn('column_name')
```
Returns a specific column as an array.

#### RowCount
```xdl
n_rows = recordset->RowCount()
```
Returns the number of rows in the recordset.

#### ColumnCount
```xdl
n_cols = recordset->ColumnCount()
```
Returns the number of columns in the recordset.

#### ColumnNames
```xdl
names = recordset->ColumnNames()
```
Returns an array of column names.

#### Next
```xdl
has_more = recordset->Next()
```
Moves to the next row. Returns 1 if successful, 0 if no more rows.

#### Reset
```xdl
recordset->Reset
```
Resets the cursor to the first row.

#### CurrentRow
```xdl
row_data = recordset->CurrentRow()
```
Returns the current row as a structure.

## Architecture

### Module Structure

```
xdl-database/
├── src/
│   ├── lib.rs                 # Main module, registry, XDLDatabase
│   ├── error.rs               # Error types
│   ├── connection.rs          # Connection enum wrapper
│   ├── recordset.rs           # Query results
│   └── drivers/
│       ├── mod.rs             # Driver exports
│       ├── postgres.rs        # PostgreSQL driver
│       ├── mysql.rs           # MySQL driver
│       ├── duckdb.rs          # DuckDB driver
│       ├── odbc.rs            # ODBC driver
│       ├── redis_driver.rs    # Redis driver
│       └── kafka.rs           # Kafka driver
├── Cargo.toml
└── README.md
```

### Key Components

1. **XDLDatabase** - Main database object
   - Manages connections
   - Executes queries
   - Returns recordsets

2. **DatabaseConnection** - Enum wrapper for different database types
   - Abstracts driver differences
   - Provides unified interface

3. **Recordset** - Query results container
   - Stores rows and columns
   - Provides data access methods
   - Converts to XDL types

4. **DatabaseRegistry** - Global object registry
   - Maps object IDs to database instances
   - Manages object lifecycle
   - Thread-safe with RwLock

5. **Drivers** - Individual database implementations
   - PostgreSQL (tokio-postgres with connection pooling)
   - MySQL (mysql_async with connection pooling)
   - DuckDB (duckdb crate - embedded analytics)
   - Redis (redis crate - key-value store)
   - ODBC (odbc-api - universal SQL connectivity)
   - Kafka (rdkafka - streaming platform)

## Type Conversion

Database types are automatically converted to XDL types:

| Database Type | XDL Type |
|---------------|----------|
| BOOLEAN | Long (0/1) |
| SMALLINT | Int |
| INTEGER | Long |
| BIGINT | Long64 |
| REAL/FLOAT4 | Float |
| DOUBLE/FLOAT8 | Double |
| VARCHAR/TEXT | String |
| NULL | Undefined |

## Error Handling

The module provides comprehensive error handling:

```xdl
objdb = OBJ_NEW('XDLdbDatabase')

; Try to connect
CATCH, error
IF error NE 0 THEN BEGIN
    PRINT, 'Connection failed: ', !ERROR_STATE.MSG
    RETURN
ENDIF

objdb->Connect, CONNECTION='postgresql://localhost/mydb'

; Execute query with error handling
CATCH, error
IF error NE 0 THEN BEGIN
    PRINT, 'Query failed: ', !ERROR_STATE.MSG
    objdb->Disconnect()
    RETURN
ENDIF

recordset = objdb->ExecuteSQL('SELECT * FROM users')
```

## Performance Considerations

1. **Connection Pooling** - Reuse connections for better performance
2. **Async Operations** - All I/O is asynchronous
3. **Batch Operations** - Use transactions for multiple commands
4. **Result Set Size** - Be mindful of large result sets

## Future Enhancements

### Planned Features

1. **Prepared Statements** - For secure parameterized queries (PostgreSQL, MySQL)
2. **Transaction Support** - BEGIN, COMMIT, ROLLBACK
3. **Enhanced Connection Pooling** - More pool configuration options
4. **Streaming Results** - For large datasets
5. **Additional Databases** - MongoDB, Cassandra, ClickHouse

### Example Future API

```xdl
; Prepared statement
stmt = objdb->Prepare('SELECT * FROM users WHERE id = ?')
recordset = stmt->Execute([123])

; Transaction
objdb->BeginTransaction()
objdb->ExecuteCommand('INSERT INTO users VALUES (1, ''Alice'')')
objdb->ExecuteCommand('INSERT INTO users VALUES (2, ''Bob'')')
objdb->Commit()

; Connection pool
pool = OBJ_NEW('XDLdbConnectionPool', SIZE=10)
pool->Connect, CONNECTION='postgresql://localhost/mydb'
conn1 = pool->GetConnection()
conn2 = pool->GetConnection()
```

## Testing

Run tests with:

```bash
cargo test --package xdl-database --all-features
```

## Examples

See the `examples/` directory for more usage examples:

- `postgresql_example.xdl` - PostgreSQL query example
- `mysql_example.xdl` - MySQL CRUD operations and queries
- `duckdb_analytics.xdl` - DuckDB analytics example
- `odbc_sqlserver_example.xdl` - ODBC with SQL Server
- `kafka_streaming_example.xdl` - Kafka streaming operations

## Contributing

To add support for a new database:

1. Add the driver dependency to `Cargo.toml`
2. Create a new driver module in `src/drivers/`
3. Implement the required methods:
   - `connect()`
   - `execute()`
   - `execute_command()`
   - `close()`
   - `is_connected()`
4. Add the driver to `DatabaseConnection` enum
5. Add feature flag support
6. Write tests
7. Update documentation

## License

GPL-2.0 (same as XDL)

## Support

For issues and questions:
- GitHub Issues: https://github.com/gnudatalanguage/gdl/issues
- Documentation: https://docs.gnudatalanguage.com