Skip to content

Commit f6812c8

Browse files
chore: wip
1 parent 23696c4 commit f6812c8

File tree

10 files changed

+192
-22
lines changed

10 files changed

+192
-22
lines changed

storage/framework/core/database/src/custom/errors.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@ import { database } from '@stacksjs/config'
33
import { path } from '@stacksjs/path'
44
import { hasTableBeenMigrated } from '../drivers'
55

6-
const driver = database.default || ''
76

87
export async function createErrorsTable(): Promise<void> {
9-
if (['sqlite', 'mysql'].includes(driver)) {
8+
if (['sqlite', 'mysql'].includes(getDriver())) {
109
const hasBeenMigrated = await hasTableBeenMigrated('errors')
1110

1211
if (hasBeenMigrated)
@@ -38,3 +37,7 @@ export async function createErrorsTable(): Promise<void> {
3837
log.success('Created errors table')
3938
}
4039
}
40+
41+
function getDriver(): string {
42+
return database.default || ''
43+
}

storage/framework/core/database/src/custom/jobs.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,9 @@ import { err, handleError, ok } from '@stacksjs/error-handling'
66
import { path } from '@stacksjs/path'
77
import { hasMigrationBeenCreated } from '../drivers'
88

9-
const driver = database.default || ''
10-
119
export async function createJobsMigration(): Promise<Result<MigrationResult[] | string, Error>> {
1210
try {
13-
if (['sqlite', 'mysql'].includes(driver)) {
11+
if (['sqlite', 'mysql'].includes(getDriver())) {
1412
const hasBeenMigrated = await hasMigrationBeenCreated('jobs')
1513

1614
if (!hasBeenMigrated) {
@@ -48,3 +46,7 @@ export async function createJobsMigration(): Promise<Result<MigrationResult[] |
4846
return err(handleError('Error creating migration', error))
4947
}
5048
}
49+
50+
function getDriver(): string {
51+
return database.default || ''
52+
}

storage/framework/core/database/src/migrations.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ import { FileMigrationProvider, Migrator } from 'kysely'
99
import { generateMysqlMigration, generatePostgresMigration, generateSqliteMigration, resetMysqlDatabase, resetPostgresDatabase, resetSqliteDatabase } from './drivers'
1010
import { db } from './utils'
1111

12-
const driver = database.default || ''
12+
13+
function getDriver(): string {
14+
return database.default || ''
15+
}
1316

1417
export function migrator(): Migrator {
1518
return new Migrator({
@@ -70,11 +73,11 @@ export interface MigrationOptions {
7073
}
7174

7275
export async function resetDatabase(): Promise<Ok<string, never>> {
73-
if (driver === 'sqlite')
76+
if (getDriver() === 'sqlite')
7477
return await resetSqliteDatabase()
75-
if (driver === 'mysql')
78+
if (getDriver() === 'mysql')
7679
return await resetMysqlDatabase()
77-
if (driver === 'postgres')
80+
if (getDriver() === 'postgres')
7881
return await resetPostgresDatabase()
7982

8083
throw new Error('Unsupported database driver in resetDatabase')
@@ -101,13 +104,13 @@ export async function generateMigrations(): Promise<Ok<string, never> | Err<stri
101104
}
102105

103106
export async function generateMigration(modelPath: string): Promise<void> {
104-
if (driver === 'sqlite')
107+
if (getDriver() === 'sqlite')
105108
await generateSqliteMigration(modelPath)
106109

107-
if (driver === 'mysql')
110+
if (getDriver() === 'mysql')
108111
await generateMysqlMigration(modelPath)
109112

110-
if (driver === 'postgres')
113+
if (getDriver() === 'postgres')
111114
await generatePostgresMigration(modelPath)
112115
}
113116

storage/framework/core/database/src/utils.ts

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,53 @@
11
import type { Database } from '@stacksjs/orm'
22
import type { RawBuilder } from 'kysely'
3-
import { app, database } from '@stacksjs/config'
43
import { log } from '@stacksjs/logging'
54
import { projectPath } from '@stacksjs/path'
65
import { Kysely, MysqlDialect, PostgresDialect, sql } from 'kysely'
76
import { BunWorkerDialect } from 'kysely-bun-worker'
87
import { createPool } from 'mysql2'
98
import { Pool } from 'pg'
109

10+
// Get config values safely
11+
function getEnv(): string {
12+
try {
13+
// Use dynamic import to avoid initialization issues
14+
const { app } = require('@stacksjs/config')
15+
return app?.env || 'local'
16+
} catch (error) {
17+
return 'local'
18+
}
19+
}
20+
21+
function getDriver(): string {
22+
try {
23+
// Use dynamic import to avoid initialization issues
24+
const { database } = require('@stacksjs/config')
25+
return database?.default || 'sqlite'
26+
} catch (error) {
27+
return 'sqlite'
28+
}
29+
}
30+
31+
// Helper to safely get database config
32+
function getDatabaseConfig() {
33+
try {
34+
const { database } = require('@stacksjs/config')
35+
return database
36+
} catch (error) {
37+
return { connections: {} }
38+
}
39+
}
40+
1141
export function getDialect(): MysqlDialect | PostgresDialect | BunWorkerDialect {
12-
const appEnv = app.env || 'local'
13-
const driver = database.default || 'sqlite'
42+
const appEnv = getEnv()
43+
const driver = getDriver()
44+
const database = getDatabaseConfig()
1445

1546
log.debug(`Using database driver: ${driver}`)
1647

1748
if (driver === 'sqlite') {
1849
const defaultName = appEnv !== 'testing' ? 'database/stacks.sqlite' : 'database/stacks_testing.sqlite'
19-
const sqliteDbName = database.connections?.sqlite.database ?? defaultName
50+
const sqliteDbName = database.connections?.sqlite?.database ?? defaultName
2051
const dbPath = projectPath(sqliteDbName)
2152

2253
return new BunWorkerDialect({
@@ -59,3 +90,4 @@ export const now: RawBuilder<any> = sql`now()`
5990
export const db: Kysely<Database> = new Kysely<Database>({
6091
dialect: getDialect(),
6192
})
93+

storage/framework/core/error-handling/src/handler.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { appendFile, mkdir } from 'node:fs/promises'
33
import { dirname } from 'node:path'
44
import process from 'node:process'
55
import { italic, stripAnsi } from '@stacksjs/cli'
6-
import { config } from '@stacksjs/config'
76
import * as path from '@stacksjs/path'
87
import { fs } from '@stacksjs/storage'
98
import { ExitCode } from '@stacksjs/types'
@@ -105,7 +104,17 @@ interface WriteOptions {
105104
export async function writeToLogFile(message: string, options?: WriteOptions): Promise<void> {
106105
const timestamp = new Date().toISOString()
107106
const formattedMessage = `[${timestamp}] ${message}\n`
108-
const logFile = options?.logFile ?? config.logging.logsPath ?? 'storage/logs/stacks.log'
107+
108+
// Get config using dynamic import
109+
let logFile: string;
110+
try {
111+
const { config } = require('@stacksjs/config')
112+
logFile = options?.logFile ?? config?.logging?.logsPath ?? 'storage/logs/stacks.log'
113+
} catch (error) {
114+
// Fallback if config can't be loaded
115+
logFile = options?.logFile ?? 'storage/logs/stacks.log'
116+
}
117+
109118
const dirPath = dirname(logFile)
110119

111120
if (!fs.existsSync(dirPath)) {

storage/framework/core/orm/src/base.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export class BaseOrm<T, C, J> {
8989

9090
await this.loadRelations(model)
9191

92-
cache.getOrSet(`${this.tableName}:${id}`, JSON.stringify(model))
92+
// cache.getOrSet(`${this.tableName}:${id}`, JSON.stringify(model))
9393

9494
return model
9595
}
@@ -188,7 +188,7 @@ export class BaseOrm<T, C, J> {
188188
this.mapCustomGetters(model)
189189
await this.loadRelations(model)
190190

191-
cache.getOrSet(`${this.tableName}:${id}`, JSON.stringify(model))
191+
// cache.getOrSet(`${this.tableName}:${id}`, JSON.stringify(model))
192192

193193
return model
194194
}
@@ -795,7 +795,7 @@ export class BaseOrm<T, C, J> {
795795
return (this as any).hasSaved && this.isDirty(column)
796796
}
797797

798-
getOriginal(column?: keyof T): Partial<T> {
798+
getOriginal<K extends keyof T>(column?: K): K extends keyof T ? T[K] : Partial<T> {
799799
if (!('originalAttributes' in this)) {
800800
throw new Error('Child class must define originalAttributes property')
801801
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import type { Model } from '@stacksjs/types'
2+
import { schema } from '@stacksjs/validation'
3+
4+
export default {
5+
name: 'ProductUnit',
6+
table: 'product_units',
7+
primaryKey: 'id',
8+
autoIncrement: false, // Using UUID instead of auto-increment
9+
10+
traits: {
11+
useUuid: true,
12+
useTimestamps: true,
13+
useSearch: {
14+
displayable: ['id', 'name', 'abbreviation', 'type', 'description', 'is_default'],
15+
searchable: ['name', 'abbreviation', 'type', 'description'],
16+
sortable: ['name', 'type', 'created_at', 'updated_at'],
17+
filterable: ['type', 'is_default'],
18+
},
19+
20+
useSeeder: {
21+
count: 10,
22+
},
23+
24+
useApi: {
25+
uri: 'product-units',
26+
routes: ['index', 'store', 'show'],
27+
},
28+
29+
observe: true,
30+
},
31+
32+
belongsTo: ['Product'],
33+
34+
attributes: {
35+
name: {
36+
required: true,
37+
order: 1,
38+
fillable: true,
39+
validation: {
40+
rule: schema.string().maxLength(100),
41+
message: {
42+
maxLength: 'Name must have a maximum of 100 characters',
43+
},
44+
},
45+
factory: (faker) => {
46+
const units = ['Piece', 'Kilogram', 'Gram', 'Liter', 'Milliliter', 'Meter', 'Centimeter', 'Box', 'Pack', 'Pair']
47+
return faker.helpers.arrayElement(units)
48+
},
49+
},
50+
51+
abbreviation: {
52+
required: true,
53+
order: 2,
54+
fillable: true,
55+
validation: {
56+
rule: schema.string().maxLength(10),
57+
message: {
58+
maxLength: 'Abbreviation must have a maximum of 10 characters',
59+
},
60+
},
61+
factory: (faker) => {
62+
const abbrs = ['pc', 'kg', 'g', 'L', 'mL', 'm', 'cm', 'box', 'pk', 'pr']
63+
return faker.helpers.arrayElement(abbrs)
64+
},
65+
},
66+
67+
type: {
68+
required: true,
69+
order: 3,
70+
fillable: true,
71+
validation: {
72+
rule: schema.string(),
73+
message: {
74+
string: 'Type must be a string',
75+
},
76+
},
77+
factory: (faker) => {
78+
const types = ['Weight', 'Volume', 'Length', 'Quantity', 'Size']
79+
return faker.helpers.arrayElement(types)
80+
},
81+
},
82+
83+
description: {
84+
required: false,
85+
order: 4,
86+
fillable: true,
87+
validation: {
88+
rule: schema.string().maxLength(255),
89+
message: {
90+
maxLength: 'Description must have a maximum of 255 characters',
91+
},
92+
},
93+
factory: faker => faker.lorem.sentence(),
94+
},
95+
96+
is_default: {
97+
required: false,
98+
order: 5,
99+
fillable: true,
100+
validation: {
101+
rule: schema.boolean(),
102+
message: {
103+
boolean: 'Default status must be a boolean',
104+
},
105+
},
106+
factory: faker => faker.datatype.boolean(0.2), // 20% chance of being default
107+
},
108+
},
109+
110+
dashboard: {
111+
highlight: true,
112+
},
113+
} satisfies Model

storage/framework/models/User.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ export default {
112112
},
113113

114114
set: {
115-
password: (attributes: Attributes) => Bun.password.hash(attributes.password),
115+
password: (attributes: Attributes) => Bun.password.hash(String(attributes.password)),
116116
},
117117
dashboard: {
118118
highlight: true,

storage/framework/orm/src/models/User.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,7 @@ export class UserModel extends BaseOrm<UserModel, UsersTable, UserJsonResponse>
583583

584584
const model = await this.find(Number(result.numInsertedOrUpdatedRows)) as UserModel
585585

586+
console.log(model)
586587
if (model)
587588
dispatch('user:created', model)
588589

@@ -658,6 +659,7 @@ export class UserModel extends BaseOrm<UserModel, UsersTable, UserJsonResponse>
658659
.where('id', '=', this.id)
659660
.executeTakeFirst()
660661

662+
console.log('id', this.id)
661663
if (this.id) {
662664
const model = await this.find(this.id)
663665

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[2025-03-18T11:53:55.632Z] DEBUG: Using database driver: sqlite
2+
[2025-03-18T11:54:16.814Z] DEBUG: Using database driver: sqlite
3+
[2025-03-18T11:55:28.988Z] DEBUG: Using database driver: sqlite
4+
[2025-03-18T11:55:51.179Z] DEBUG: Using database driver: sqlite
5+
[2025-03-18T11:57:34.180Z] DEBUG: Using database driver: sqlite
6+
[2025-03-18T11:58:09.639Z] DEBUG: Using database driver: sqlite

0 commit comments

Comments
 (0)