Skip to content

Commit

Permalink
chore: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbbreuer committed May 18, 2024
1 parent 13fb396 commit 32913cf
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 17 deletions.
12 changes: 9 additions & 3 deletions storage/framework/core/actions/src/migrate/fresh.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import process from 'node:process'
import { resetDatabase } from '@stacksjs/database'
import { generateMigrations, resetDatabase, runDatabaseMigration } from '@stacksjs/database'
import { log } from '@stacksjs/logging'

// this is run and checks whether new created or update migrations need to be generated
// first, reset the database, if it exists
const result = await resetDatabase()

if (result?.isErr()) {
console.error(result.error)
log.error('[stacks] generateMigrations failed', result.error)
log.error('generateMigrations failed', result.error)
process.exit(1)
}

// then,generate the migrations
await generateMigrations()

// finally, migrate the database
await runDatabaseMigration()

process.exit(0)
2 changes: 1 addition & 1 deletion storage/framework/core/database/src/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export async function resetDatabase() {

if (driver === 'postgres') return resetPostgresDatabase()

return resetSqliteDatabase()
throw new Error('Unsupported database driver in resetDatabase')
}

export async function generateMigrations() {
Expand Down
23 changes: 10 additions & 13 deletions storage/framework/core/database/src/seeder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { italic, log } from '@stacksjs/cli'
import { db } from '@stacksjs/database'
import { path } from '@stacksjs/path'
import { fs, glob } from '@stacksjs/storage'
import { isString } from '@stacksjs/validation'
import { snakeCase } from '@stacksjs/strings'
import type { Model, RelationConfig } from '@stacksjs/types'
import { isString } from '@stacksjs/validation'
import { generateMigrations, resetDatabase, runDatabaseMigration } from './migrations'

async function seedModel(name: string, model?: Model) {
Expand All @@ -18,15 +18,17 @@ async function seedModel(name: string, model?: Model) {
const tableName = model.table ?? snakeCase(model.name ?? name.replace('.ts', ''))
const seedCount =
typeof model.traits?.useSeeder === 'object' && model.traits?.useSeeder?.count ? model.traits.useSeeder.count : 10
log.info(`Seeding ${seedCount} records into ${italic(tableName)}`)
const records = []

log.info(`Seeding ${seedCount} records into ${italic(tableName)}`)

const records = []
const otherRelations = await fetchOtherModelRelations(model)

log.debug(otherRelations)

for (let i = 0; i < seedCount; i++) {
const record: any = {}

for (const fieldName in model.attributes) {
const field = model.attributes[fieldName]
// Use the factory function if available, otherwise leave the field undefined
Expand All @@ -49,27 +51,23 @@ async function seedModel(name: string, model?: Model) {
}

async function seedModelRelation(modelName: string): Promise<BigInt | number> {

const modelInstance = (await import(path.userModelsPath(modelName))).default

if (! modelInstance) return 1

const record: any = {}

const table = modelInstance.table

for (const fieldName in modelInstance.attributes) {

const field = modelInstance.attributes[fieldName]

// Use the factory function if available, otherwise leave the field undefined
record[fieldName] = field?.factory ? field.factory() : undefined
}

const data = await db.insertInto(table)
.values(record)
.executeTakeFirstOrThrow()

return data.insertId || 1
}

Expand Down Expand Up @@ -110,14 +108,11 @@ export async function getRelations(model: Model): Promise<RelationConfig[]> {
}

export async function fetchOtherModelRelations(model: Model): Promise<RelationConfig[]> {

const modelFiles = glob.sync(path.userModelsPath('*.ts'))

const modelRelations = []

for (let i = 0; i < modelFiles.length; i++) {
const modelFileElement = modelFiles[i] as string

const modelFile = await import(modelFileElement)

if (model.name === modelFile.default.name) continue
Expand All @@ -142,14 +137,16 @@ function hasRelations(obj: any, key: string): boolean {
export async function seed() {
// TODO: need to check other databases too
const dbPath = path.userDatabasePath('stacks.sqlite')

if (!fs.existsSync(dbPath)) {
log.warn('No database found, configuring it...')
// first, ensure the database is reset
await resetDatabase()

// generate the migrations
// then, generate the migrations
await generateMigrations()

// migrate the database
// finally, migrate the database
await runDatabaseMigration()
} else {
log.debug('Database configured...')
Expand Down

0 comments on commit 32913cf

Please sign in to comment.