AdvancedProduction-Ready

Database Connectivity

BanglaCode provides production-grade database connectors for PostgreSQL, MySQL, MongoDB, and Redis with built-in connection pooling, async/await support, and SQL injection protection.

Supported Databases

BanglaCode supports four popular databases with both synchronous and asynchronous APIs:

  • PostgreSQL - Advanced relational database with ACID compliance
  • MySQL - Popular relational database for web applications
  • MongoDB - NoSQL document database for flexible schemas
  • Redis - In-memory data store for caching and real-time apps

Connection Pooling (50-100x Faster)

Connection pooling is crucial for performance. Creating a new database connection for every query is extremely slow (~10-50ms per connection). With connection pooling, you reuse existing connections, making queries 50-100x faster (~0.1-1ms per query).

Connection Pool Example

database_pool.bangbanglacode
1// Create connection pool (reuses connections for maximum performance)
2dhoro pool = db_pool_banao("postgres", {
3 "host": "localhost",
4 "port": 5432,
5 "database": "myapp",
6 "user": "admin",
7 "password": "secret"
8}, 10); // Max 10 connections
9
10// Get connection from pool (very fast, ~0.1ms)
11dhoro conn = db_pool_nao(pool);
12
13// Execute query
14dhoro users = db_query(conn, "SELECT * FROM users WHERE age > 25");
15
16// Iterate results
17ghuriye (dhoro i = 0; i < dorghyo(users["rows"]); i = i + 1) {
18 dhoro user = users["rows"][i];
19 dekho("User:", user["name"], "Age:", user["age"]);
20}
21
22// Return connection to pool (important! Connection is reused)
23db_pool_ferot(pool, conn);
24
25// Close pool when done
26db_pool_bondho(pool);

PostgreSQL

PostgreSQL is a powerful, open-source relational database with advanced features like ACID transactions, foreign keys, and complex queries.

Basic PostgreSQL Connection

postgres_basic.bangbanglacode
1// Connect to PostgreSQL
2dhoro conn = db_jukto("postgres", {
3 "host": "localhost",
4 "port": 5432,
5 "database": "myapp",
6 "user": "postgres",
7 "password": "password"
8});
9
10// Execute SELECT query
11dhoro result = db_query(conn, "SELECT * FROM users");
12
13dekho("Total users:", dorghyo(result["rows"]));
14
15// Iterate through results
16ghuriye (dhoro i = 0; i < dorghyo(result["rows"]); i = i + 1) {
17 dhoro user = result["rows"][i];
18 dekho("User ID:", user["id"], "Name:", user["name"]);
19}
20
21// Close connection
22db_bandho(conn);

Prepared Statements (SQL Injection Safe)

Always use prepared statements (db_proshno) to prevent SQL injection attacks. Never concatenate user input directly into SQL queries!

postgres_prepared.bangbanglacode
1// BAD - Vulnerable to SQL injection!
2// dhoro query = "SELECT * FROM users WHERE name = '" + userName + "'";
3
4// GOOD - SQL injection safe!
5dhoro result = db_proshno(conn, "SELECT * FROM users WHERE name = $1", ["Rahim"]);
6
7// Insert with parameters
8dhoro insertResult = db_proshno(conn,
9 "INSERT INTO users (name, email, age) VALUES ($1, $2, $3)",
10 ["Rahim Ahmed", "rahim@example.com", 30]
11);
12
13dekho("Rows affected:", insertResult["rows_affected"]);
14dekho("Last insert ID:", insertResult["last_insert_id"]);

Transactions

Transactions ensure that multiple database operations either all succeed or all fail together, maintaining data integrity.

postgres_transaction.bangbanglacode
1// Begin transaction
2dhoro tx = db_transaction_shuru_postgres(conn);
3
4chesta {
5 // Transfer money between accounts (atomic operation)
6 db_exec_postgres(conn, "UPDATE accounts SET balance = balance - 100 WHERE id = 1");
7 db_exec_postgres(conn, "UPDATE accounts SET balance = balance + 100 WHERE id = 2");
8
9 // Commit if all operations succeed
10 db_commit_postgres(tx);
11 dekho("Transaction completed successfully!");
12
13} dhoro_bhul (error) {
14 // Rollback if any operation fails
15 db_rollback_postgres(tx);
16 dekho("Transaction failed and rolled back:", error);
17}

PostgreSQL Functions

FunctionParametersDescription
db_jukto_postgresconfigConnect to PostgreSQL database
db_query_postgresconn, sqlExecute SELECT query
db_exec_postgresconn, sqlExecute INSERT/UPDATE/DELETE
db_proshno_postgresconn, sql, paramsPrepared statement (SQL injection safe)
db_transaction_shuru_postgresconnBegin transaction
db_commit_postgrestxCommit transaction
db_rollback_postgrestxRollback transaction

MySQL

MySQL is a popular relational database used by millions of websites and applications.

mysql_example.bangbanglacode
1// Connect to MySQL
2dhoro conn = db_jukto("mysql", {
3 "host": "localhost",
4 "port": 3306,
5 "database": "webapp",
6 "user": "root",
7 "password": "password"
8});
9
10// Complete CRUD operations
11// CREATE - Insert new user
12db_proshno(conn, "INSERT INTO users (name, email) VALUES (?, ?)",
13 ["Karim", "karim@example.com"]);
14
15// READ - Query users
16dhoro users = db_query(conn, "SELECT * FROM users");
17ghuriye (dhoro i = 0; i < dorghyo(users["rows"]); i = i + 1) {
18 dekho("User:", users["rows"][i]["name"]);
19}
20
21// UPDATE - Update user email
22db_proshno(conn, "UPDATE users SET email = ? WHERE name = ?",
23 ["new@example.com", "Karim"]);
24
25// DELETE - Delete user
26db_proshno(conn, "DELETE FROM users WHERE name = ?", ["Karim"]);
27
28db_bandho(conn);

MongoDB

MongoDB is a NoSQL document database that stores data in flexible JSON-like documents. Perfect for applications with evolving schemas or hierarchical data.

Find Documents

mongodb_find.bangbanglacode
1// Connect to MongoDB
2dhoro conn = db_jukto("mongodb", {
3 "host": "localhost",
4 "port": 27017,
5 "database": "mydb"
6});
7
8// Find documents matching filter
9dhoro users = db_khojo_mongodb(conn, "users", {
10 "age": {"$gt": 25}, // Age greater than 25
11 "city": "Dhaka" // City is Dhaka
12});
13
14dekho("Found", dorghyo(users["rows"]), "users");
15
16// Display results
17ghuriye (dhoro i = 0; i < dorghyo(users["rows"]); i = i + 1) {
18 dhoro user = users["rows"][i];
19 dekho("Name:", user["name"], "Age:", user["age"], "City:", user["city"]);
20}

Insert Documents

mongodb_insert.bangbanglacode
1// Insert single document
2db_dhokao_mongodb(conn, "users", {
3 "name": "Rahim Ahmed",
4 "age": 30,
5 "city": "Dhaka",
6 "profession": "Engineer",
7 "skills": ["Python", "Go", "BanglaCode"]
8});
9
10dekho("User inserted!");

Update and Delete

mongodb_update.bangbanglacode
1// Update documents
2dhoro updateResult = db_update_mongodb(conn, "users",
3 {"city": "Dhaka"}, // Filter
4 {"$set": {"country": "Bangladesh"}} // Update
5);
6
7dekho("Updated", updateResult["rows_affected"], "documents");
8
9// Delete documents
10dhoro deleteResult = db_mujhe_mongodb(conn, "users", {
11 "age": {"$lt": 18} // Delete users under 18
12});
13
14dekho("Deleted", deleteResult["rows_affected"], "documents");

MongoDB Functions

FunctionParametersDescription
db_jukto_mongodbconfigConnect to MongoDB
db_khojo_mongodbconn, collection, filterFind documents
db_dhokao_mongodbconn, collection, docInsert document
db_update_mongodbconn, collection, filter, updateUpdate documents
db_mujhe_mongodbconn, collection, filterDelete documents

Redis

Redis is an in-memory data store used for caching, session management, real-time analytics, and message queues. Extremely fast (sub-millisecond response times).

Key-Value Operations

redis_kv.bangbanglacode
1// Connect to Redis
2dhoro conn = db_jukto("redis", {
3 "host": "localhost",
4 "port": 6379
5});
6
7// Set key-value
8db_set_redis(conn, "user:1", "Rahim Ahmed");
9
10// Set with TTL (time to live - expires after 1 hour)
11db_set_redis(conn, "session:abc123", "user_data", 3600);
12
13// Get value
14dhoro user = db_get_redis(conn, "user:1");
15dekho("User:", user);
16
17// Delete key
18db_del_redis(conn, "user:1");
19
20// Set expiration on existing key
21db_expire_redis(conn, "session:abc123", 1800); // 30 minutes

List Operations (Queue)

redis_list.bangbanglacode
1// Redis lists work as queues (FIFO) or stacks (LIFO)
2
3// Add tasks to queue
4db_rpush_redis(conn, "tasks:queue", "Process order #123");
5db_rpush_redis(conn, "tasks:queue", "Send email to user");
6db_rpush_redis(conn, "tasks:queue", "Generate report");
7
8// Process tasks from queue
9dhoro task1 = db_lpop_redis(conn, "tasks:queue");
10dekho("Processing:", task1); // Output: Process order #123
11
12dhoro task2 = db_lpop_redis(conn, "tasks:queue");
13dekho("Processing:", task2); // Output: Send email to user

Hash Operations

redis_hash.bangbanglacode
1// Store user profile as hash (like a map/object)
2db_hset_redis(conn, "user:1:profile", "name", "Rahim Ahmed");
3db_hset_redis(conn, "user:1:profile", "age", "30");
4db_hset_redis(conn, "user:1:profile", "city", "Dhaka");
5
6// Get single field
7dhoro name = db_hget_redis(conn, "user:1:profile", "name");
8dekho("Name:", name);
9
10// Get all fields
11dhoro profile = db_hgetall_redis(conn, "user:1:profile");
12dekho("Full profile:", profile);

Redis Functions

FunctionParametersDescription
db_jukto_redisconfigConnect to Redis
db_set_redisconn, key, value, ttl?Set key-value (optional TTL in seconds)
db_get_redisconn, keyGet value by key
db_del_redisconn, keyDelete key
db_expire_redisconn, key, secondsSet expiration time
db_lpush_redisconn, key, valuePush to list (left/front)
db_rpush_redisconn, key, valuePush to list (right/back)
db_lpop_redisconn, keyPop from list (left/front)
db_rpop_redisconn, keyPop from list (right/back)
db_hset_redisconn, key, field, valueSet hash field
db_hget_redisconn, key, fieldGet hash field
db_hgetall_redisconn, keyGet all hash fields

Universal Database Functions

These functions work with all supported databases (PostgreSQL, MySQL, MongoDB, Redis). The db_jukto function automatically routes to the correct database driver.

FunctionParametersDescription
db_juktotype, configConnect to database (type: "postgres", "mysql", "mongodb", "redis")
db_jukto_asynctype, configConnect to database (async, returns promise)
db_bandhoconnClose connection
db_bandho_asyncconnClose connection (async)
db_queryconn, sqlExecute SELECT query (SQL databases only)
db_query_asyncconn, sqlExecute SELECT query async
db_execconn, sqlExecute INSERT/UPDATE/DELETE (SQL databases only)
db_exec_asyncconn, sqlExecute INSERT/UPDATE/DELETE async
db_proshnoconn, sql, paramsPrepared statement (SQL injection safe)
db_proshno_asyncconn, sql, paramsPrepared statement async

Connection Pool Functions

FunctionParametersDescription
db_pool_banaotype, config, maxConnsCreate connection pool
db_pool_naopoolGet connection from pool
db_pool_ferotpool, connReturn connection to pool (important!)
db_pool_bondhopoolClose connection pool
db_pool_tothyopoolGet pool statistics

Async Database Queries

Use proyash and opekha for async database operations. This is essential for non-blocking I/O and high-performance applications.

async_database.bangbanglacode
1// Async database function
2proyash kaj fetchUsers() {
3 // Connect async
4 dhoro conn = opekha db_jukto_async("postgres", {
5 "host": "localhost",
6 "database": "myapp"
7 });
8
9 // Query async
10 dhoro users = opekha db_query_async(conn, "SELECT * FROM users");
11
12 // Close async
13 opekha db_bandho_async(conn);
14
15 ferao users;
16}
17
18// Call async function
19dhoro result = opekha fetchUsers();
20dekho("Fetched", dorghyo(result["rows"]), "users");
21
22// Multiple concurrent queries
23proyash kaj fetchMultiple() {
24 dhoro conn = opekha db_jukto_async("postgres", {...});
25
26 // Run multiple queries concurrently
27 dhoro users = opekha db_query_async(conn, "SELECT * FROM users");
28 dhoro posts = opekha db_query_async(conn, "SELECT * FROM posts");
29
30 opekha db_bandho_async(conn);
31
32 ferao {"users": users, "posts": posts};
33}

Function Name Meanings

FunctionBengaliMeaning
juktoযুক্তconnect/join
bandhoবন্ধclose
proshnoপ্রশ্নquestion/query
banaoবানাওcreate/make
naoনাওtake/get
ferotফেরতreturn
tothyoতথ্যinformation/data
khojoখোঁজোsearch/find
dhokaoঢোকাওinsert/put
mujheমুছেdelete/erase

Best Practices

  • Always use connection pooling for production applications (50-100x faster)
  • Always use prepared statements (db_proshno) to prevent SQL injection
  • Always close connections or return them to the pool when done
  • Use transactions for operations that must succeed or fail together
  • Use async/await for non-blocking database operations
  • Choose the right database for your needs:
    • PostgreSQL/MySQL - Structured data, complex queries, ACID compliance
    • MongoDB - Flexible schemas, hierarchical data, rapid iteration
    • Redis - Caching, sessions, real-time data, message queues

Performance Tips

  • Connection pooling reduces connection overhead by 50-100x (from ~10ms to ~0.1ms)
  • Use db_proshno for repeated queries (2-5x faster than concatenated SQL)
  • Index frequently queried columns in SQL databases
  • Use Redis for frequently accessed data (sub-millisecond response times)
  • Batch operations when possible to reduce round trips

Next Steps

Learn more about related topics: