nanodb-orm 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +506 -333
  2. package/dist/cli.d.ts +96 -0
  3. package/dist/cli.d.ts.map +1 -0
  4. package/dist/cli.js +348 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/constants/index.d.ts +7 -54
  7. package/dist/constants/index.d.ts.map +1 -1
  8. package/dist/constants/index.js +9 -61
  9. package/dist/constants/index.js.map +1 -1
  10. package/dist/core/config.d.ts +3 -13
  11. package/dist/core/config.d.ts.map +1 -1
  12. package/dist/core/config.js +5 -27
  13. package/dist/core/config.js.map +1 -1
  14. package/dist/core/connection.d.ts +16 -31
  15. package/dist/core/connection.d.ts.map +1 -1
  16. package/dist/core/connection.js +42 -78
  17. package/dist/core/connection.js.map +1 -1
  18. package/dist/core/index.d.ts +2 -3
  19. package/dist/core/index.d.ts.map +1 -1
  20. package/dist/core/index.js +3 -18
  21. package/dist/core/index.js.map +1 -1
  22. package/dist/index.d.ts +235 -12
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +252 -35
  25. package/dist/index.js.map +1 -1
  26. package/dist/init.d.ts +127 -18
  27. package/dist/init.d.ts.map +1 -1
  28. package/dist/init.js +280 -47
  29. package/dist/init.js.map +1 -1
  30. package/dist/jest.setup.d.ts +4 -0
  31. package/dist/jest.setup.d.ts.map +1 -0
  32. package/dist/jest.setup.js +40 -0
  33. package/dist/jest.setup.js.map +1 -0
  34. package/dist/types/errors.d.ts +30 -12
  35. package/dist/types/errors.d.ts.map +1 -1
  36. package/dist/types/errors.js +98 -23
  37. package/dist/types/errors.js.map +1 -1
  38. package/dist/types/index.d.ts +268 -4
  39. package/dist/types/index.d.ts.map +1 -1
  40. package/dist/types/index.js +5 -4
  41. package/dist/types/index.js.map +1 -1
  42. package/dist/utils/error-handler.d.ts +6 -31
  43. package/dist/utils/error-handler.d.ts.map +1 -1
  44. package/dist/utils/error-handler.js +24 -81
  45. package/dist/utils/error-handler.js.map +1 -1
  46. package/dist/utils/index.d.ts +1 -3
  47. package/dist/utils/index.d.ts.map +1 -1
  48. package/dist/utils/index.js +4 -6
  49. package/dist/utils/index.js.map +1 -1
  50. package/dist/utils/logger.d.ts +6 -25
  51. package/dist/utils/logger.d.ts.map +1 -1
  52. package/dist/utils/logger.js +20 -38
  53. package/dist/utils/logger.js.map +1 -1
  54. package/dist/utils/migrations.d.ts +16 -90
  55. package/dist/utils/migrations.d.ts.map +1 -1
  56. package/dist/utils/migrations.js +220 -422
  57. package/dist/utils/migrations.js.map +1 -1
  58. package/dist/utils/schema-introspection.d.ts +30 -169
  59. package/dist/utils/schema-introspection.d.ts.map +1 -1
  60. package/dist/utils/schema-introspection.js +125 -462
  61. package/dist/utils/schema-introspection.js.map +1 -1
  62. package/dist/utils/seeds.d.ts +15 -48
  63. package/dist/utils/seeds.d.ts.map +1 -1
  64. package/dist/utils/seeds.js +108 -186
  65. package/dist/utils/seeds.js.map +1 -1
  66. package/dist/utils/sync.d.ts +16 -41
  67. package/dist/utils/sync.d.ts.map +1 -1
  68. package/dist/utils/sync.js +78 -172
  69. package/dist/utils/sync.js.map +1 -1
  70. package/dist/utils/transactions.d.ts +61 -44
  71. package/dist/utils/transactions.d.ts.map +1 -1
  72. package/dist/utils/transactions.js +103 -137
  73. package/dist/utils/transactions.js.map +1 -1
  74. package/package.json +29 -10
  75. package/dist/example.d.ts +0 -67
  76. package/dist/example.d.ts.map +0 -1
  77. package/dist/example.js +0 -86
  78. package/dist/example.js.map +0 -1
  79. package/dist/types/database.d.ts +0 -74
  80. package/dist/types/database.d.ts.map +0 -1
  81. package/dist/types/database.js +0 -6
  82. package/dist/types/database.js.map +0 -1
  83. package/dist/types/types.d.ts +0 -30
  84. package/dist/types/types.d.ts.map +0 -1
  85. package/dist/types/types.js +0 -6
  86. package/dist/types/types.js.map +0 -1
  87. package/llm.txt +0 -336
@@ -1,6 +0,0 @@
1
- "use strict";
2
- /**
3
- * Database-related TypeScript interfaces and types
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../types/types.ts"],"names":[],"mappings":";AAAA;;GAEG"}
package/llm.txt DELETED
@@ -1,336 +0,0 @@
1
- # nanodb-orm - LLM Documentation
2
-
3
- ## Package Overview
4
- nanodb-orm is a generic, flexible database package built on top of Drizzle ORM. It provides auto-migrations, schema introspection, and multi-database support for SQLite and Turso databases.
5
-
6
- ## Package Information
7
- - **Name**: nanodb-orm
8
- - **Version**: 0.0.3
9
- - **License**: MIT
10
- - **Repository**: https://github.com/damilolaalao/nanodb-orm
11
- - **NPM**: https://www.npmjs.com/package/nanodb-orm
12
-
13
- ## Installation
14
- ```bash
15
- npm install nanodb-orm
16
- ```
17
-
18
- ## Core Features
19
- 1. **Generic Database Operations**: Works with any table structure defined in schema
20
- 2. **Auto-Migrations**: Automatic schema creation and migration handling
21
- 3. **Schema Introspection**: Dynamic schema analysis and validation
22
- 4. **Multi-Database Support**: SQLite (local) and Turso (cloud) databases
23
- 5. **Atomic Transactions**: Full transaction support with rollback protection
24
- 6. **TypeScript Support**: Full TypeScript definitions and type safety
25
- 7. **Data Seeding**: Built-in seed data management
26
- 8. **Health Checks**: Database health monitoring and validation
27
- 9. **Thread Safety**: Race condition fixes and concurrent access protection
28
- 10. **Security**: SQL injection protection and input validation
29
- 11. **Error Handling**: Standardized error handling and recovery
30
-
31
- ## Main Exports
32
- ```typescript
33
- import {
34
- initializeDatabase, // Initialize the package with schema
35
- DatabaseSync, // Database operations and health checks
36
- SchemaIntrospection, // Schema analysis utilities
37
- DatabaseMigrations, // Migration management
38
- DatabaseSeeds, // Seed data management
39
- DatabaseConnection, // Database connection management
40
- TransactionManager, // NEW: Transaction management
41
- ErrorHandler, // NEW: Standardized error handling
42
- logger // Logging utilities
43
- } from 'nanodb-orm';
44
- ```
45
-
46
- ## Basic Usage Pattern
47
- ```typescript
48
- // 1. Define your Drizzle tables (models/users.ts)
49
- import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
50
-
51
- export const usersTable = sqliteTable('users', {
52
- id: integer('id').primaryKey({ autoIncrement: true }),
53
- name: text('name').notNull(),
54
- age: integer('age').notNull(),
55
- email: text('email').unique().notNull(),
56
- });
57
-
58
- // models/posts.ts
59
- import { sql } from 'drizzle-orm';
60
- import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
61
- import { usersTable } from './users';
62
-
63
- export const postsTable = sqliteTable('posts', {
64
- id: integer('id').primaryKey({ autoIncrement: true }),
65
- title: text('title').notNull(),
66
- content: text('content').notNull(),
67
- userId: integer('user_id')
68
- .notNull()
69
- .references(() => usersTable.id, { onDelete: 'cascade' }),
70
- createdAt: text('created_at')
71
- .default(sql`(datetime('now'))`)
72
- .notNull(),
73
- });
74
-
75
- // models/index.ts
76
- import { usersTable } from './users';
77
- import { postsTable } from './posts';
78
-
79
- export const tables = {
80
- users: usersTable,
81
- posts: postsTable,
82
- } as const;
83
-
84
- // 2. Initialize the package
85
- initializeDatabase({
86
- tables,
87
- seedData: {
88
- users: [{ name: 'John Doe', age: 30, email: 'john@example.com' }],
89
- posts: [{ title: 'Welcome', content: 'First post!', userId: 1 }]
90
- }
91
- });
92
-
93
- // 3. Setup database
94
- await DatabaseSync.setup();
95
-
96
- // 4. Use the database
97
- const health = await DatabaseSync.healthCheck();
98
- ```
99
-
100
- ## Schema Definition Format
101
- nanodb-orm works with Drizzle ORM table definitions. Tables are defined using Drizzle's `sqliteTable` function:
102
-
103
- ```typescript
104
- import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
105
-
106
- export const tableName = sqliteTable('table_name', {
107
- id: integer('id').primaryKey({ autoIncrement: true }),
108
- name: text('name').notNull(),
109
- email: text('email').unique().notNull(),
110
- isActive: integer('is_active').notNull().default(1),
111
- createdAt: text('created_at').default(sql`(datetime('now'))`).notNull()
112
- });
113
- ```
114
-
115
- ### Drizzle Column Types and Methods:
116
- - **Types**: `integer()`, `text()`, `real()`, `blob()`
117
- - **Methods**: `.primaryKey()`, `.notNull()`, `.unique()`, `.default()`, `.references()`
118
-
119
- ## Database Configuration
120
- The package automatically detects the environment and uses:
121
- - **Local SQLite**: When no Turso configuration is found
122
- - **Turso**: When TURSO_DATABASE_URL and TURSO_AUTH_TOKEN are set
123
-
124
- ## Key Classes and Methods
125
-
126
- ### DatabaseSync
127
- - `setup()`: Initialize database schema and seed data
128
- - `healthCheck()`: Check database health and schema validity
129
- - `reset()`: Reset database (drop, recreate, seed)
130
- - `getDatabaseInfo()`: Get comprehensive database information
131
-
132
- ### SchemaIntrospection
133
- - `getAllTableNames()`: Get all table names from schema
134
- - `getTable(tableName)`: Get table definition
135
- - `getColumnNames(tableName)`: Get column names for a table
136
- - `getSchemaStats()`: Get schema statistics
137
- - `validateSchema()`: Validate database schema matches definition
138
-
139
- ### DatabaseMigrations
140
- - `initializeSchema()`: Create tables using Drizzle
141
- - `validateSchema()`: Validate schema integrity
142
- - `checkTableExistence()`: Check which tables exist
143
-
144
- ### DatabaseSeeds
145
- - `seedDatabase()`: Seed database with sample data
146
- - `hasData()`: Check if database has existing data
147
-
148
- ## NEW in v0.0.3: Transaction Support
149
-
150
- ### TransactionManager
151
- ```typescript
152
- import { TransactionManager } from 'nanodb-orm';
153
-
154
- // Atomic operations
155
- await TransactionManager.execute(async (db) => {
156
- await db.run('INSERT INTO users (name, email) VALUES (?, ?)', ['John', 'john@example.com']);
157
- await db.run('INSERT INTO posts (title, content, userId) VALUES (?, ?, ?)', ['Hello', 'World', 1]);
158
- // All operations succeed or all fail
159
- });
160
-
161
- // Batch operations
162
- await TransactionManager.executeBatch([
163
- async (db) => await db.run('INSERT INTO users ...'),
164
- async (db) => await db.run('INSERT INTO posts ...')
165
- ]);
166
-
167
- // Table recreation with transactions
168
- await TransactionManager.recreateTable('users', async (db) => {
169
- await db.run('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
170
- });
171
-
172
- // Check transaction support
173
- const supportsTransactions = await TransactionManager.supportsTransactions();
174
- const status = await TransactionManager.getTransactionStatus();
175
- ```
176
-
177
- ### Enhanced Error Handling
178
- ```typescript
179
- import { ErrorHandler, DatabaseError } from 'nanodb-orm';
180
-
181
- // Standardized error handling
182
- try {
183
- await DatabaseSync.setup();
184
- } catch (error) {
185
- if (error instanceof DatabaseError) {
186
- console.log('Operation:', error.operation);
187
- console.log('Context:', error.message);
188
- }
189
- }
190
-
191
- // Non-throwing error handling
192
- const result = ErrorHandler.handleNonThrowingError(
193
- someError,
194
- 'optional-operation',
195
- 'This operation is optional'
196
- );
197
- ```
198
-
199
- ### Thread-Safe Connections
200
- ```typescript
201
- import { DatabaseConnection } from 'nanodb-orm';
202
-
203
- // NEW: Async connection (recommended)
204
- const db = await DatabaseConnection.getInstance();
205
-
206
- // OLD: Synchronous connection (deprecated but still works)
207
- const db = DatabaseConnection.getInstanceSync();
208
- ```
209
-
210
- ## Error Handling
211
- The package provides custom error classes:
212
- - `DatabaseError`: Base database error
213
- - `SchemaError`: Schema-related errors
214
- - `SyncError`: Synchronization errors
215
- - `ConnectionError`: Connection-related errors
216
- - `ValidationError`: Validation errors
217
-
218
- ## Logging
219
- Built-in logging system with different levels:
220
- - `logger.info()`: Information messages
221
- - `logger.warn()`: Warning messages
222
- - `logger.error()`: Error messages
223
- - `logger.debug()`: Debug messages
224
-
225
- ## Testing
226
- The package includes comprehensive tests:
227
- - Package initialization tests
228
- - Schema introspection tests
229
- - Database setup tests
230
- - Health check tests
231
-
232
- ## File Structure
233
- ```
234
- nanodb-orm/
235
- ├── core/ # Core database functionality
236
- ├── utils/ # Utility classes and functions
237
- ├── types/ # TypeScript type definitions
238
- ├── constants/ # Package constants
239
- ├── dist/ # Compiled JavaScript output
240
- ├── __tests__/ # Test files
241
- ├── example.ts # Usage example
242
- └── package.json # Package configuration
243
- ```
244
-
245
- ## Dependencies
246
- - **@libsql/client**: Turso database client
247
- - **drizzle-orm**: Database ORM
248
- - **dotenv**: Environment variable management (peer dependency)
249
-
250
- ## Development Dependencies
251
- - **TypeScript**: Type checking and compilation
252
- - **Jest**: Testing framework
253
- - **@types/node**: Node.js type definitions
254
-
255
- ## Environment Variables
256
- - `TURSO_DATABASE_URL`: Turso database URL
257
- - `TURSO_AUTH_TOKEN`: Turso authentication token
258
- - `NODE_ENV`: Environment (development, production, test)
259
- - `FORCE_LOCAL_DB`: Force local SQLite usage
260
-
261
- ## Migration Configuration
262
- ```typescript
263
- const migrationConfig = {
264
- preserveData: true, // Preserve existing data during migrations
265
- autoMigrate: true, // Enable automatic migrations
266
- dropTables: false // Don't drop tables by default
267
- };
268
- ```
269
-
270
- ## Seed Data Format
271
- ```typescript
272
- const seedData = {
273
- tableName: [
274
- { column1: 'value1', column2: 'value2' },
275
- { column1: 'value3', column2: 'value4' }
276
- ]
277
- };
278
- ```
279
-
280
- ## Health Check Response
281
- ```typescript
282
- {
283
- healthy: boolean,
284
- tables: string[],
285
- tableCounts: Record<string, number>,
286
- totalRecords: number,
287
- schemaValid: boolean,
288
- syncSupported: boolean,
289
- errors: string[]
290
- }
291
- ```
292
-
293
- ## Best Practices
294
- 1. Always initialize the package before using any database operations
295
- 2. Use TypeScript for better type safety
296
- 3. Define clear schema structures
297
- 4. Handle errors appropriately
298
- 5. Use health checks in production
299
- 6. Test with different database configurations
300
-
301
- ## Common Use Cases
302
- 1. **Rapid Prototyping**: Quick database setup for new projects
303
- 2. **Microservices**: Lightweight database layer for services
304
- 3. **Full-Stack Applications**: Backend database management
305
- 4. **Testing**: Database utilities for test suites
306
- 5. **Data Migration**: Schema migration and data seeding
307
-
308
- ## Support and Documentation
309
- - **GitHub**: https://github.com/damilolaalao/nanodb-orm
310
- - **NPM**: https://www.npmjs.com/package/nanodb-orm
311
- - **Issues**: https://github.com/damilolaalao/nanodb-orm/issues
312
-
313
- ## License
314
- MIT License - see LICENSE file for details.
315
-
316
- ## Author
317
- Damilola Alao
318
-
319
- ## Version History
320
- ### 0.0.2
321
- - **Enhanced Documentation**: Added comprehensive Drizzle ORM integration examples
322
- - **Real Model Examples**: Updated documentation with actual Drizzle table definitions
323
- - **Schema Validation Fix**: Fixed table existence validation logic for proper health checks
324
- - **LLM Documentation**: Added detailed `llm.txt` file for AI/LLM integration
325
- - **Column Types Guide**: Added complete Drizzle column types and methods documentation
326
- - **Foreign Key Support**: Documented foreign key relationships and cascade deletes
327
- - **Type Safety**: Enhanced TypeScript integration examples with Drizzle's type inference
328
-
329
- ### 0.0.1
330
- - Initial release
331
- - Auto-migration system
332
- - Schema introspection
333
- - Multi-database support (SQLite, Turso)
334
- - TypeScript support
335
- - Testing utilities
336
- - Comprehensive documentation