Skip to content

Commit 75e54c4

Browse files
chore: wip
1 parent 8d76ee4 commit 75e54c4

File tree

8 files changed

+59
-47
lines changed

8 files changed

+59
-47
lines changed

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './schema'
2+
export * from './drivers'
23
export * from './migrations'
34
export * from './seeder'
45
export * from './types'

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

Lines changed: 1 addition & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
import { dim, italic, log } from '@stacksjs/cli'
1+
import { log } from '@stacksjs/cli'
22
import { database } from '@stacksjs/config'
33
import { err, ok } from '@stacksjs/error-handling'
4-
import { extractAttributesFromModel } from '@stacksjs/orm'
54
import { path } from '@stacksjs/path'
65
import { fs, globSync } from '@stacksjs/storage'
7-
import type { Attribute, Attributes } from '@stacksjs/types'
86
import { $ } from 'bun'
97
import { FileMigrationProvider, Migrator } from 'kysely'
108
import { generateMysqlMigration, resetMysqlDatabase } from './drivers'
@@ -107,15 +105,6 @@ export async function generateMigration(modelPath: string) {
107105
if (driver === 'postgres') await generatePostgresMigration(modelPath)
108106
}
109107

110-
export async function getExecutedMigrations() {
111-
try {
112-
// @ts-expect-error the migrations table is not typed yet
113-
return await db.selectFrom('migrations').select('name').execute()
114-
} catch (error) {
115-
return []
116-
}
117-
}
118-
119108
export async function haveModelFieldsChangedSinceLastMigration(modelPath: string) {
120109
log.debug(`haveModelFieldsChangedSinceLastMigration for model: ${modelPath}`)
121110

@@ -154,20 +143,3 @@ export async function lastMigrationDate(): Promise<string | undefined> {
154143
return undefined
155144
}
156145
}
157-
158-
// This is a placeholder function. You need to implement the logic to
159-
// read the last migration file and extract the fields that were modified.
160-
export async function getLastMigrationFields(modelName: string): Promise<Attribute> {
161-
const oldModelPath = path.frameworkPath(`database/models/${modelName}`)
162-
const model = (await import(oldModelPath)).default as Model
163-
let fields = {} as Attributes
164-
165-
if (typeof model.attributes === 'object') fields = model.attributes
166-
else fields = JSON.parse(model.attributes) as Attributes
167-
168-
return fields
169-
}
170-
171-
export async function getCurrentMigrationFields(modelPath: string): Promise<Attribute | undefined> {
172-
return extractAttributesFromModel(modelPath)
173-
}

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,25 @@
1-
import { database } from '@stacksjs/config'
1+
import { app, database } from '@stacksjs/config'
22
import { log } from '@stacksjs/logging'
33
import type { Database } from '@stacksjs/orm'
44
import { Kysely, MysqlDialect, PostgresDialect, sql } from 'kysely'
55
import { BunWorkerDialect } from 'kysely-bun-worker'
66
import { createPool } from 'mysql2'
77
import { Pool } from 'pg'
88

9+
const appEnv = app.env
10+
911
export function getDialect() {
1012
const driver = database.default ?? 'sqlite'
1113

1214
log.debug(`Using database driver: ${driver}`)
1315

16+
let dbName = database.connections?.mysql?.name ?? 'stacks' // Default database name
17+
18+
// Check if appEnv is testing and modify dbName accordingly
19+
if (appEnv === 'testing') {
20+
dbName += '-testing' // Append '-testing' to the database name
21+
}
22+
1423
if (driver === 'sqlite') {
1524
const path = database.connections?.sqlite.database ?? 'database/stacks.sqlite'
1625
return new BunWorkerDialect({
@@ -21,7 +30,7 @@ export function getDialect() {
2130
if (driver === 'mysql') {
2231
return new MysqlDialect({
2332
pool: createPool({
24-
database: database.connections?.mysql?.name ?? 'stacks',
33+
database: dbName, // Use modified dbName
2534
host: database.connections?.mysql?.host ?? '127.0.0.1',
2635
user: database.connections?.mysql?.username ?? 'root',
2736
password: database.connections?.mysql?.password ?? '',
@@ -31,9 +40,12 @@ export function getDialect() {
3140
}
3241

3342
if (driver === 'postgres') {
43+
const pgDbName = database.connections?.postgres?.name ?? 'stacks' // Default Postgres database name
44+
const finalPgDbName = appEnv === 'testing' ? `${pgDbName}-testing` : pgDbName // Modify if testing
45+
3446
return new PostgresDialect({
3547
pool: new Pool({
36-
database: database.connections?.postgres?.name ?? 'stacks',
48+
database: finalPgDbName, // Use modified pgDbName
3749
host: database.connections?.postgres?.host ?? '127.0.0.1',
3850
user: database.connections?.postgres?.username ?? '',
3951
password: database.connections?.postgres?.password ?? '',

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,9 @@ export async function generateKyselyTypes() {
783783
}
784784
}
785785

786+
text += `\nexport interface MigrationsTable {\n`
787+
text += `name: string\n timestamp: string \n }`
788+
786789
text += `\nexport interface Database {\n`
787790

788791
for (const modelFile of modelFiles) {
@@ -799,6 +802,8 @@ export async function generateKyselyTypes() {
799802
text += ` ${tableName}: ${formattedTableName}\n`
800803
}
801804

805+
text += `migrations: MigrationsTable`
806+
802807
text += `}`
803808

804809
const file = Bun.file(path.frameworkPath(`orm/src/types.ts`))

storage/framework/core/testing/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"devDependencies": {
4949
"@happy-dom/global-registrator": "^15.7.4",
5050
"@stacksjs/config": "workspace:*",
51+
"@stacksjs/database": "workspace:*",
5152
"@stacksjs/development": "workspace:*"
5253
}
5354
}
Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,44 @@
11
import { database } from '@stacksjs/config'
2-
import { db } from '@stacksjs/database'
2+
import { db, fetchTables, fetchTestSqliteFile, runDatabaseMigration, sql } from '@stacksjs/database'
33

44
const driver = database.default || ''
55

6-
export async function refreshDatabase() {
6+
export async function setupDatabase() {
7+
const dbName = `${database.connections?.mysql?.name ?? 'stacks'}_testing`
8+
79
if (driver === 'mysql') {
8-
await refreshMysql()
10+
await sql`CREATE DATABASE IF NOT EXISTS ${sql.raw(dbName)}`.execute(db)
11+
12+
await runDatabaseMigration()
913
}
1014

1115
if (driver === 'sqlite') {
12-
await refreshMysql()
16+
await sql`CREATE DATABASE IF NOT EXISTS ${sql.raw(dbName)}`.execute(db)
17+
18+
await runDatabaseMigration()
1319
}
1420
}
1521

16-
export async function refreshMysql() {
17-
const tables = await fetchTables()
22+
// export async function refreshDatabase() {
23+
// if (driver === 'mysql') await truncateMysql()
1824

19-
for (const table of tables) {
20-
await sql`TRUNCATE TABLE ${sql.raw(table)}`.execute(db)
21-
}
22-
}
25+
// if (driver === 'sqlite') await truncateSqlite()
26+
// }
2327

24-
export async function refreshSqlite() {
25-
const dbPath = await fetchTestSqliteFile()
28+
// export async function truncateMysql() {
29+
// const tables = await fetchTables()
2630

27-
if (fs.existsSync(dbPath)) await Bun.$`rm ${dbPath}`
28-
}
31+
// for (const table of tables) {
32+
// await sql`TRUNCATE TABLE ${sql.raw(table)}`.execute(db)
33+
// }
34+
// }
35+
36+
// export async function truncateSqlite() {
37+
// const dbPath = await fetchTestSqliteFile()
38+
39+
// if (fs.existsSync(dbPath)) await Bun.$`rm ${dbPath}`
40+
41+
// await runDatabaseMigration()
42+
// }
43+
44+
await setupDatabase()

storage/framework/core/types/src/app.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export type AppEnvType = 'local' | 'dev' | 'stage' | 'prod' | string
1+
export type AppEnvType = 'local' | 'dev' | 'stage' | 'prod' | 'testing' | string
22

33
/**
44
* **Application Options**

storage/framework/orm/src/types.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ export interface UserTeamsTable {
2424
user_id: number
2525
team_id: number
2626
}
27+
export interface MigrationsTable {
28+
name: string
29+
timestamp: string
30+
}
2731
export interface Database {
2832
projects: ProjectsTable
2933
subscriber_emails: SubscriberEmailsTable
@@ -37,4 +41,5 @@ export interface Database {
3741
user_teams: UserTeamsTable
3842
users: UsersTable
3943
posts: PostsTable
44+
migrations: MigrationsTable
4045
}

0 commit comments

Comments
 (0)