nanodb-orm 0.0.1 → 0.0.2

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 (3) hide show
  1. package/README.md +150 -4
  2. package/llm.txt +268 -0
  3. package/package.json +3 -2
package/README.md CHANGED
@@ -20,16 +20,108 @@ npm install nanodb-orm
20
20
 
21
21
  ## Quick Start
22
22
 
23
+ ### 1. Define Your Models with Drizzle
24
+
25
+ Create your Drizzle table definitions (e.g., `models/users.ts`):
26
+
27
+ ```typescript
28
+ // models/users.ts
29
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
30
+
31
+ export const usersTable = sqliteTable('users', {
32
+ id: integer('id').primaryKey({ autoIncrement: true }),
33
+ name: text('name').notNull(),
34
+ age: integer('age').notNull(),
35
+ email: text('email').unique().notNull(),
36
+ });
37
+
38
+ export type InsertUser = typeof usersTable.$inferInsert;
39
+ export type SelectUser = typeof usersTable.$inferSelect;
40
+ ```
41
+
42
+ ```typescript
43
+ // models/posts.ts
44
+ import { sql } from 'drizzle-orm';
45
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
46
+ import { usersTable } from './users';
47
+
48
+ export const postsTable = sqliteTable('posts', {
49
+ id: integer('id').primaryKey({ autoIncrement: true }),
50
+ title: text('title').notNull(),
51
+ content: text('content').notNull(),
52
+ userId: integer('user_id')
53
+ .notNull()
54
+ .references(() => usersTable.id, { onDelete: 'cascade' }),
55
+ createdAt: text('created_at')
56
+ .default(sql`(datetime('now'))`)
57
+ .notNull(),
58
+ updatedAt: text('updated_at').$onUpdate(() => new Date().toISOString()),
59
+ });
60
+
61
+ export type InsertPost = typeof postsTable.$inferInsert;
62
+ export type SelectPost = typeof postsTable.$inferSelect;
63
+ ```
64
+
65
+ ```typescript
66
+ // models/categories.ts
67
+ import { sql } from 'drizzle-orm';
68
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
69
+
70
+ export const categoriesTable = sqliteTable('categories', {
71
+ id: integer('id').primaryKey({ autoIncrement: true }),
72
+ name: text('name').notNull(),
73
+ description: text('description'),
74
+ color: text('color').notNull().default('#000000'),
75
+ isActive: integer('is_active').notNull().default(1),
76
+ createdAt: text('created_at')
77
+ .default(sql`(datetime('now'))`)
78
+ .notNull(),
79
+ });
80
+
81
+ export type InsertCategory = typeof categoriesTable.$inferInsert;
82
+ export type SelectCategory = typeof categoriesTable.$inferSelect;
83
+ ```
84
+
85
+ ```typescript
86
+ // models/index.ts
87
+ export * from './users';
88
+ export * from './posts';
89
+ export * from './categories';
90
+
91
+ // Import tables for aggregation
92
+ import { usersTable } from './users';
93
+ import { postsTable } from './posts';
94
+ import { categoriesTable } from './categories';
95
+
96
+ // Export aggregated tables for nanodb-orm
97
+ export const tables = {
98
+ users: usersTable,
99
+ posts: postsTable,
100
+ categories: categoriesTable,
101
+ } as const;
102
+ ```
103
+
104
+ ### 2. Initialize and Setup Database
105
+
23
106
  ```typescript
24
107
  import { initializeDatabase, DatabaseSync } from 'nanodb-orm';
25
- import { tables } from './models'; // Your Drizzle table definitions
108
+ import { tables } from './models';
26
109
 
27
- // Initialize the database package
110
+ // Initialize the database package with your Drizzle tables
28
111
  initializeDatabase({
29
112
  tables,
30
113
  seedData: {
31
114
  users: [
32
- { name: 'John Doe', age: 30, email: 'john@example.com' }
115
+ { name: 'John Doe', age: 30, email: 'john@example.com' },
116
+ { name: 'Jane Smith', age: 25, email: 'jane@example.com' }
117
+ ],
118
+ posts: [
119
+ { title: 'Welcome Post', content: 'This is my first post!', userId: 1 },
120
+ { title: 'Getting Started', content: 'Here are some tips...', userId: 2 }
121
+ ],
122
+ categories: [
123
+ { name: 'Technology', description: 'Tech-related posts', color: '#3B82F6' },
124
+ { name: 'Lifestyle', description: 'Life and personal posts', color: '#10B981' }
33
125
  ]
34
126
  }
35
127
  });
@@ -38,6 +130,51 @@ initializeDatabase({
38
130
  await DatabaseSync.setup();
39
131
  ```
40
132
 
133
+ ### 3. Working with Drizzle Tables
134
+
135
+ nanodb-orm works seamlessly with Drizzle ORM table definitions. Here are the key Drizzle column types and methods:
136
+
137
+ #### Drizzle Column Types
138
+ - `integer()` - Integer numbers
139
+ - `text()` - Text strings
140
+ - `real()` - Floating point numbers
141
+ - `blob()` - Binary data
142
+
143
+ #### Drizzle Column Methods
144
+ - `.primaryKey({ autoIncrement: true })` - Primary key with auto-increment
145
+ - `.notNull()` - NOT NULL constraint
146
+ - `.unique()` - UNIQUE constraint
147
+ - `.default(value)` - Default value
148
+ - `.references(table.column)` - Foreign key reference
149
+
150
+ #### Example Drizzle Column Definitions
151
+ ```typescript
152
+ // Primary key with auto-increment
153
+ id: integer('id').primaryKey({ autoIncrement: true })
154
+
155
+ // Required text field
156
+ name: text('name').notNull()
157
+
158
+ // Optional text field with default
159
+ color: text('color').notNull().default('#000000')
160
+
161
+ // Unique email field
162
+ email: text('email').unique().notNull()
163
+
164
+ // Boolean field (stored as integer)
165
+ isActive: integer('is_active').notNull().default(1)
166
+
167
+ // Timestamp field with SQL function
168
+ createdAt: text('created_at')
169
+ .default(sql`(datetime('now'))`)
170
+ .notNull()
171
+
172
+ // Foreign key reference
173
+ userId: integer('user_id')
174
+ .notNull()
175
+ .references(() => usersTable.id, { onDelete: 'cascade' })
176
+ ```
177
+
41
178
  ## API Reference
42
179
 
43
180
  ### `initializeDatabase(schemaData: SchemaData)`
@@ -279,7 +416,16 @@ MIT © Damilola Alao
279
416
 
280
417
  ## Changelog
281
418
 
282
- ### 1.0.0
419
+ ### 0.0.2
420
+ - **Enhanced Documentation**: Added comprehensive Drizzle ORM integration examples
421
+ - **Real Model Examples**: Updated documentation with actual Drizzle table definitions
422
+ - **Schema Validation Fix**: Fixed table existence validation logic for proper health checks
423
+ - **LLM Documentation**: Added detailed `llm.txt` file for AI/LLM integration
424
+ - **Column Types Guide**: Added complete Drizzle column types and methods documentation
425
+ - **Foreign Key Support**: Documented foreign key relationships and cascade deletes
426
+ - **Type Safety**: Enhanced TypeScript integration examples with Drizzle's type inference
427
+
428
+ ### 0.0.1
283
429
  - Initial release
284
430
  - Auto-migration system
285
431
  - Schema introspection
package/llm.txt ADDED
@@ -0,0 +1,268 @@
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.2
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. **TypeScript Support**: Full TypeScript definitions and type safety
24
+ 6. **Data Seeding**: Built-in seed data management
25
+ 7. **Health Checks**: Database health monitoring and validation
26
+
27
+ ## Main Exports
28
+ ```typescript
29
+ import {
30
+ initializeDatabase, // Initialize the package with schema
31
+ DatabaseSync, // Database operations and health checks
32
+ SchemaIntrospection, // Schema analysis utilities
33
+ DatabaseMigrations, // Migration management
34
+ DatabaseSeeds, // Seed data management
35
+ DatabaseConnection, // Database connection management
36
+ logger // Logging utilities
37
+ } from 'nanodb-orm';
38
+ ```
39
+
40
+ ## Basic Usage Pattern
41
+ ```typescript
42
+ // 1. Define your Drizzle tables (models/users.ts)
43
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
44
+
45
+ export const usersTable = sqliteTable('users', {
46
+ id: integer('id').primaryKey({ autoIncrement: true }),
47
+ name: text('name').notNull(),
48
+ age: integer('age').notNull(),
49
+ email: text('email').unique().notNull(),
50
+ });
51
+
52
+ // models/posts.ts
53
+ import { sql } from 'drizzle-orm';
54
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
55
+ import { usersTable } from './users';
56
+
57
+ export const postsTable = sqliteTable('posts', {
58
+ id: integer('id').primaryKey({ autoIncrement: true }),
59
+ title: text('title').notNull(),
60
+ content: text('content').notNull(),
61
+ userId: integer('user_id')
62
+ .notNull()
63
+ .references(() => usersTable.id, { onDelete: 'cascade' }),
64
+ createdAt: text('created_at')
65
+ .default(sql`(datetime('now'))`)
66
+ .notNull(),
67
+ });
68
+
69
+ // models/index.ts
70
+ import { usersTable } from './users';
71
+ import { postsTable } from './posts';
72
+
73
+ export const tables = {
74
+ users: usersTable,
75
+ posts: postsTable,
76
+ } as const;
77
+
78
+ // 2. Initialize the package
79
+ initializeDatabase({
80
+ tables,
81
+ seedData: {
82
+ users: [{ name: 'John Doe', age: 30, email: 'john@example.com' }],
83
+ posts: [{ title: 'Welcome', content: 'First post!', userId: 1 }]
84
+ }
85
+ });
86
+
87
+ // 3. Setup database
88
+ await DatabaseSync.setup();
89
+
90
+ // 4. Use the database
91
+ const health = await DatabaseSync.healthCheck();
92
+ ```
93
+
94
+ ## Schema Definition Format
95
+ nanodb-orm works with Drizzle ORM table definitions. Tables are defined using Drizzle's `sqliteTable` function:
96
+
97
+ ```typescript
98
+ import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
99
+
100
+ export const tableName = sqliteTable('table_name', {
101
+ id: integer('id').primaryKey({ autoIncrement: true }),
102
+ name: text('name').notNull(),
103
+ email: text('email').unique().notNull(),
104
+ isActive: integer('is_active').notNull().default(1),
105
+ createdAt: text('created_at').default(sql`(datetime('now'))`).notNull()
106
+ });
107
+ ```
108
+
109
+ ### Drizzle Column Types and Methods:
110
+ - **Types**: `integer()`, `text()`, `real()`, `blob()`
111
+ - **Methods**: `.primaryKey()`, `.notNull()`, `.unique()`, `.default()`, `.references()`
112
+
113
+ ## Database Configuration
114
+ The package automatically detects the environment and uses:
115
+ - **Local SQLite**: When no Turso configuration is found
116
+ - **Turso**: When TURSO_DATABASE_URL and TURSO_AUTH_TOKEN are set
117
+
118
+ ## Key Classes and Methods
119
+
120
+ ### DatabaseSync
121
+ - `setup()`: Initialize database schema and seed data
122
+ - `healthCheck()`: Check database health and schema validity
123
+ - `reset()`: Reset database (drop, recreate, seed)
124
+ - `getDatabaseInfo()`: Get comprehensive database information
125
+
126
+ ### SchemaIntrospection
127
+ - `getAllTableNames()`: Get all table names from schema
128
+ - `getTable(tableName)`: Get table definition
129
+ - `getColumnNames(tableName)`: Get column names for a table
130
+ - `getSchemaStats()`: Get schema statistics
131
+ - `validateSchema()`: Validate database schema matches definition
132
+
133
+ ### DatabaseMigrations
134
+ - `initializeSchema()`: Create tables using Drizzle
135
+ - `validateSchema()`: Validate schema integrity
136
+ - `checkTableExistence()`: Check which tables exist
137
+
138
+ ### DatabaseSeeds
139
+ - `seedDatabase()`: Seed database with sample data
140
+ - `hasData()`: Check if database has existing data
141
+
142
+ ## Error Handling
143
+ The package provides custom error classes:
144
+ - `DatabaseError`: Base database error
145
+ - `SchemaError`: Schema-related errors
146
+ - `SyncError`: Synchronization errors
147
+ - `ConnectionError`: Connection-related errors
148
+ - `ValidationError`: Validation errors
149
+
150
+ ## Logging
151
+ Built-in logging system with different levels:
152
+ - `logger.info()`: Information messages
153
+ - `logger.warn()`: Warning messages
154
+ - `logger.error()`: Error messages
155
+ - `logger.debug()`: Debug messages
156
+
157
+ ## Testing
158
+ The package includes comprehensive tests:
159
+ - Package initialization tests
160
+ - Schema introspection tests
161
+ - Database setup tests
162
+ - Health check tests
163
+
164
+ ## File Structure
165
+ ```
166
+ nanodb-orm/
167
+ ├── core/ # Core database functionality
168
+ ├── utils/ # Utility classes and functions
169
+ ├── types/ # TypeScript type definitions
170
+ ├── constants/ # Package constants
171
+ ├── dist/ # Compiled JavaScript output
172
+ ├── __tests__/ # Test files
173
+ ├── example.ts # Usage example
174
+ └── package.json # Package configuration
175
+ ```
176
+
177
+ ## Dependencies
178
+ - **@libsql/client**: Turso database client
179
+ - **drizzle-orm**: Database ORM
180
+ - **dotenv**: Environment variable management (peer dependency)
181
+
182
+ ## Development Dependencies
183
+ - **TypeScript**: Type checking and compilation
184
+ - **Jest**: Testing framework
185
+ - **@types/node**: Node.js type definitions
186
+
187
+ ## Environment Variables
188
+ - `TURSO_DATABASE_URL`: Turso database URL
189
+ - `TURSO_AUTH_TOKEN`: Turso authentication token
190
+ - `NODE_ENV`: Environment (development, production, test)
191
+ - `FORCE_LOCAL_DB`: Force local SQLite usage
192
+
193
+ ## Migration Configuration
194
+ ```typescript
195
+ const migrationConfig = {
196
+ preserveData: true, // Preserve existing data during migrations
197
+ autoMigrate: true, // Enable automatic migrations
198
+ dropTables: false // Don't drop tables by default
199
+ };
200
+ ```
201
+
202
+ ## Seed Data Format
203
+ ```typescript
204
+ const seedData = {
205
+ tableName: [
206
+ { column1: 'value1', column2: 'value2' },
207
+ { column1: 'value3', column2: 'value4' }
208
+ ]
209
+ };
210
+ ```
211
+
212
+ ## Health Check Response
213
+ ```typescript
214
+ {
215
+ healthy: boolean,
216
+ tables: string[],
217
+ tableCounts: Record<string, number>,
218
+ totalRecords: number,
219
+ schemaValid: boolean,
220
+ syncSupported: boolean,
221
+ errors: string[]
222
+ }
223
+ ```
224
+
225
+ ## Best Practices
226
+ 1. Always initialize the package before using any database operations
227
+ 2. Use TypeScript for better type safety
228
+ 3. Define clear schema structures
229
+ 4. Handle errors appropriately
230
+ 5. Use health checks in production
231
+ 6. Test with different database configurations
232
+
233
+ ## Common Use Cases
234
+ 1. **Rapid Prototyping**: Quick database setup for new projects
235
+ 2. **Microservices**: Lightweight database layer for services
236
+ 3. **Full-Stack Applications**: Backend database management
237
+ 4. **Testing**: Database utilities for test suites
238
+ 5. **Data Migration**: Schema migration and data seeding
239
+
240
+ ## Support and Documentation
241
+ - **GitHub**: https://github.com/damilolaalao/nanodb-orm
242
+ - **NPM**: https://www.npmjs.com/package/nanodb-orm
243
+ - **Issues**: https://github.com/damilolaalao/nanodb-orm/issues
244
+
245
+ ## License
246
+ MIT License - see LICENSE file for details.
247
+
248
+ ## Author
249
+ Damilola Alao
250
+
251
+ ## Version History
252
+ ### 0.0.2
253
+ - **Enhanced Documentation**: Added comprehensive Drizzle ORM integration examples
254
+ - **Real Model Examples**: Updated documentation with actual Drizzle table definitions
255
+ - **Schema Validation Fix**: Fixed table existence validation logic for proper health checks
256
+ - **LLM Documentation**: Added detailed `llm.txt` file for AI/LLM integration
257
+ - **Column Types Guide**: Added complete Drizzle column types and methods documentation
258
+ - **Foreign Key Support**: Documented foreign key relationships and cascade deletes
259
+ - **Type Safety**: Enhanced TypeScript integration examples with Drizzle's type inference
260
+
261
+ ### 0.0.1
262
+ - Initial release
263
+ - Auto-migration system
264
+ - Schema introspection
265
+ - Multi-database support (SQLite, Turso)
266
+ - TypeScript support
267
+ - Testing utilities
268
+ - Comprehensive documentation
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "nanodb-orm",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "Generic database package with Drizzle ORM, auto-migrations, and schema introspection",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
8
8
  "dist/**/*",
9
9
  "README.md",
10
- "LICENSE"
10
+ "LICENSE",
11
+ "llm.txt"
11
12
  ],
12
13
  "scripts": {
13
14
  "build": "tsc",