Skip to content

Commit 503c27c

Browse files
chore: wip
1 parent 02c2c88 commit 503c27c

File tree

13 files changed

+174
-126
lines changed

13 files changed

+174
-126
lines changed

storage/framework/core/actions/src/orm/generate-model.ts

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,29 @@ async function getPivotTables(
425425
return []
426426
}
427427

428+
export async function fetchOtherModelRelations(model: Model): Promise<RelationConfig[]> {
429+
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
430+
const modelRelations = []
431+
432+
for (let i = 0; i < modelFiles.length; i++) {
433+
const modelFileElement = modelFiles[i] as string
434+
const modelFile = await import(modelFileElement)
435+
436+
if (model.name === modelFile.default.name) continue
437+
438+
const relations = await getRelations(modelFile.default)
439+
440+
if (! relations.length) continue
441+
442+
const relation = relations.find(relation => relation.model === model.name)
443+
444+
if (relation)
445+
modelRelations.push(relation)
446+
}
447+
448+
return modelRelations
449+
}
450+
428451
async function generateModelString(
429452
tableName: string,
430453
model: Model,
@@ -459,9 +482,9 @@ async function generateModelString(
459482
if (relationType === 'throughType') {
460483
const relationName = relation.relationName || formattedModelName + modelRelation
461484
const throughRelation = relation.throughModel
462-
// const throughRelationModel =
463-
const formattedThroughRelation = relation.throughModel.name.toLowerCase()
464-
const throughTableRelation = throughRelation.table
485+
486+
const formattedThroughRelation = relation.throughModel.toLowerCase()
487+
const throughTableRelation = throughRelation
465488
const foreignKeyThroughRelation = relation.throughForeignKey || `${formattedThroughRelation}_id`
466489

467490
relationMethods += `
@@ -563,6 +586,10 @@ async function generateModelString(
563586

564587
for (const attribute of attributes) fieldString += ` ${attribute.field}: ${attribute.fieldArray?.entity}\n `
565588

589+
const otherModelRelations = await fetchOtherModelRelations(model)
590+
591+
for (const otherModelRelation of otherModelRelations) fieldString += ` ${otherModelRelation.foreignKey}: number`
592+
566593
return `import type { ColumnType, Generated, Insertable, Selectable, Updateable } from 'kysely'
567594
import type { Result } from '@stacksjs/error-handling'
568595
import { err, handleError, ok } from '@stacksjs/error-handling'
@@ -1023,12 +1050,20 @@ async function generateModelString(
10231050
.executeTakeFirst()
10241051
}
10251052
1026-
export async function last() {
1027-
return await db.selectFrom('${tableName}')
1028-
.selectAll()
1029-
.orderBy('id', 'desc')
1030-
.executeTakeFirst()
1031-
}
1053+
export async function recent(limit: number) {
1054+
return await db.selectFrom('${tableName}')
1055+
.selectAll()
1056+
.limit(limit)
1057+
.execute()
1058+
}
1059+
1060+
export async function last(limit: number) {
1061+
return await db.selectFrom('${tableName}')
1062+
.selectAll()
1063+
.orderBy('id', 'desc')
1064+
.limit(limit)
1065+
.execute()
1066+
}
10321067
10331068
export async function update(id: number, ${formattedModelName}Update: ${modelName}Update) {
10341069
return await db.updateTable('${tableName}')
@@ -1134,6 +1169,7 @@ async function generateModelString(
11341169
Model,
11351170
first,
11361171
last,
1172+
recent,
11371173
where,
11381174
whereIn,
11391175
model: ${modelName}Model

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { log } from '@stacksjs/cli'
22
import { db } from '@stacksjs/database'
33
import { path } from '@stacksjs/path'
4-
import { fs } from '@stacksjs/storage'
4+
import { fs, glob } from '@stacksjs/storage'
55
import { plural, snakeCase } from '@stacksjs/strings'
66
import type { Attributes, Model, RelationConfig, VineType } from '@stacksjs/types'
77
import { isString } from '@stacksjs/validation'
@@ -155,7 +155,9 @@ export async function getRelations(model: Model): Promise<RelationConfig[]> {
155155
return relationships
156156
}
157157

158-
export async function fetchOtherModelRelations(model: Model, modelFiles: string[]): Promise<RelationConfig[]> {
158+
export async function fetchOtherModelRelations(model: Model): Promise<RelationConfig[]> {
159+
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
160+
159161
const modelRelations = []
160162

161163
for (let i = 0; i < modelFiles.length; i++) {

storage/framework/core/database/src/drivers/mysql.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,8 @@ async function createTableMigration(modelPath: string) {
118118

119119
await createPivotTableMigration(model)
120120

121-
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
122-
const otherModelRelations = await fetchOtherModelRelations(model, modelFiles)
121+
const otherModelRelations = await fetchOtherModelRelations(model)
122+
123123
const fields = model.attributes
124124
const useTimestamps = model?.traits?.useTimestamps ?? model?.traits?.timestampable ?? true
125125
const useSoftDeletes = model?.traits?.useSoftDeletes ?? model?.traits?.softDeletable ?? false

storage/framework/core/database/src/drivers/postgres.ts

Lines changed: 5 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ import { ok } from '@stacksjs/error-handling'
44
import { modelTableName } from '@stacksjs/orm'
55
import { path } from '@stacksjs/path'
66
import { fs, glob } from '@stacksjs/storage'
7-
import type { Attribute, Attributes } from '@stacksjs/types'
8-
import { checkPivotMigration, fetchOtherModelRelations, getLastMigrationFields, hasTableBeenMigrated, mapFieldTypeToColumnType } from '.'
7+
import type { Attribute, Attributes, Model } from '@stacksjs/types'
8+
import { checkPivotMigration, fetchOtherModelRelations, getLastMigrationFields, getPivotTables, hasTableBeenMigrated, mapFieldTypeToColumnType } from '.'
99

1010
export async function resetPostgresDatabase() {
1111
const tables = await fetchMysqlTables()
@@ -120,8 +120,7 @@ async function createTableMigration(modelPath: string) {
120120

121121
await createPivotTableMigration(model)
122122

123-
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
124-
const otherModelRelations = await fetchOtherModelRelations(model, modelFiles)
123+
const otherModelRelations = await fetchOtherModelRelations(model)
125124
const fields = model.attributes
126125
const useTimestamps = model.traits?.useTimestamps ?? model.traits?.timestampable ?? true
127126
const useSoftDeletes = model.traits?.useSoftDeletes ?? model.traits?.softDeletable ?? false
@@ -192,15 +191,15 @@ async function createPivotTableMigration(model: any) {
192191
migrationContent += `import { sql } from '@stacksjs/database'\n\n`
193192
migrationContent += `export async function up(db: Database<any>) {\n`
194193
migrationContent += ` await db.schema\n`
195-
migrationContent += ` .createTable('${pivotTable}')\n`
194+
migrationContent += ` .createTable('${pivotTable.table}')\n`
196195
migrationContent += ` .addColumn('id', 'serial', (col) => col.primaryKey())\n`
197196
migrationContent += ` .addColumn('user_id', 'integer')\n`
198197
migrationContent += ` .addColumn('subscriber_id', 'integer')\n`
199198
migrationContent += ` .execute()\n`
200199
migrationContent += ` }\n`
201200

202201
const timestamp = new Date().getTime().toString()
203-
const migrationFileName = `${timestamp}-create-${pivotTable}-table.ts`
202+
const migrationFileName = `${timestamp}-create-${pivotTable.table}-table.ts`
204203
const migrationFilePath = path.userMigrationsPath(migrationFileName)
205204

206205
// Assuming fs.writeFileSync is available or use an equivalent method
@@ -210,31 +209,6 @@ async function createPivotTableMigration(model: any) {
210209
}
211210
}
212211

213-
async function getPivotTables(
214-
model: any,
215-
): Promise<{ table: string; firstForeignKey: string; secondForeignKey: string }[]> {
216-
const pivotTable = []
217-
218-
if ('belongsToMany' in model.default) {
219-
for (const belongsToManyRelation of model.default.belongsToMany) {
220-
const modelRelationPath = path.userModelsPath(`${belongsToManyRelation.model}.ts`)
221-
const modelRelation = await import(modelRelationPath)
222-
223-
const formattedModelName = model.default.name.toLowerCase()
224-
225-
pivotTable.push({
226-
table: belongsToManyRelation?.pivotTable || `${formattedModelName}_${modelRelation.default.table}`,
227-
firstForeignKey: belongsToManyRelation.firstForeignKey,
228-
secondForeignKey: belongsToManyRelation.secondForeignKey,
229-
})
230-
}
231-
232-
return pivotTable
233-
}
234-
235-
return []
236-
}
237-
238212
export async function createAlterTableMigration(modelPath: string) {
239213
console.log('createAlterTableMigration')
240214

storage/framework/core/database/src/drivers/sqlite.ts

Lines changed: 3 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { modelTableName } from '@stacksjs/orm'
55
import { path } from '@stacksjs/path'
66
import { fs, glob } from '@stacksjs/storage'
77
import type { Attribute, Attributes, Model } from '@stacksjs/types'
8-
import { checkPivotMigration, fetchOtherModelRelations, getLastMigrationFields, hasTableBeenMigrated, mapFieldTypeToColumnType } from '.'
8+
import { checkPivotMigration, fetchOtherModelRelations, getLastMigrationFields, hasTableBeenMigrated, mapFieldTypeToColumnType, getPivotTables } from '.'
99

1010
export async function resetSqliteDatabase() {
1111
const dbPath = path.userDatabasePath('stacks.sqlite')
@@ -108,41 +108,14 @@ export async function generateSqliteMigration(modelPath: string) {
108108
else await createTableMigration(modelPath)
109109
}
110110

111-
async function getPivotTables(
112-
model: Model,
113-
): Promise<{ table: string; firstForeignKey: string | undefined; secondForeignKey: string | undefined }[]> {
114-
const pivotTable = []
115-
116-
if (model.belongsToMany && model.name) {
117-
if ('belongsToMany' in model) {
118-
for (const belongsToManyRelation of model.belongsToMany) {
119-
const modelRelationPath = path.userModelsPath(`${belongsToManyRelation.model}.ts`)
120-
const modelRelation = (await import(modelRelationPath)).default
121-
const formattedModelName = model.name.toLowerCase()
122-
123-
pivotTable.push({
124-
table: belongsToManyRelation?.pivotTable || `${formattedModelName}_${modelRelation.table}`,
125-
firstForeignKey: belongsToManyRelation.firstForeignKey,
126-
secondForeignKey: belongsToManyRelation.secondForeignKey,
127-
})
128-
}
129-
130-
return pivotTable
131-
}
132-
}
133-
134-
return []
135-
}
136-
137111
async function createTableMigration(modelPath: string): Promise<void> {
138112
log.debug('createTableMigration modelPath:', modelPath)
139113

140114
const model = (await import(modelPath)).default as Model
141115
const tableName = await modelTableName(model)
142116

143117
await createPivotTableMigration(model)
144-
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
145-
const otherModelRelations = await fetchOtherModelRelations(model, modelFiles)
118+
const otherModelRelations = await fetchOtherModelRelations(model)
146119
const fields = model.attributes
147120
const useTimestamps = model?.traits?.useTimestamps ?? model?.traits?.timestampable ?? true
148121
const useSoftDeletes = model?.traits?.useSoftDeletes ?? model?.traits?.softDeletable ?? false
@@ -221,7 +194,7 @@ async function createPivotTableMigration(model: Model) {
221194
migrationContent += ` }\n`
222195

223196
const timestamp = new Date().getTime().toString()
224-
const migrationFileName = `${timestamp}-create-${pivotTable}-table.ts`
197+
const migrationFileName = `${timestamp}-create-${pivotTable.table}-table.ts`
225198
const migrationFilePath = path.userMigrationsPath(migrationFileName)
226199

227200
// Assuming fs.writeFileSync is available or use an equivalent method

storage/framework/core/orm/src/generated/types.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import type { PostsTable } from '../../../../orm/src/models/Post'
88
import type { Generated } from 'kysely'
99

1010
export interface TeamAccessTokensTable {
11-
id: Generated<number>
12-
team_id: number
13-
accesstoken_id: number
14-
}
11+
id: Generated<number>
12+
team_id: number
13+
accesstoken_id: number
14+
}
1515
export interface Database {
1616
projects: ProjectsTable
1717
access_tokens: AccessTokensTable

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

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
1515
token: string
1616
plainTextToken: string
1717
abilities: enum
18-
18+
team_id: number
1919
created_at: ColumnType<Date, string | undefined, never>
2020
updated_at: ColumnType<Date, string | undefined, never>
2121
deleted_at: ColumnType<Date, string | undefined, never>
@@ -480,12 +480,20 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
480480
.executeTakeFirst()
481481
}
482482

483-
export async function last() {
484-
return await db.selectFrom('access_tokens')
485-
.selectAll()
486-
.orderBy('id', 'desc')
487-
.executeTakeFirst()
488-
}
483+
export async function recent(limit: number) {
484+
return await db.selectFrom('access_tokens')
485+
.selectAll()
486+
.limit(limit)
487+
.execute()
488+
}
489+
490+
export async function last(limit: number) {
491+
return await db.selectFrom('access_tokens')
492+
.selectAll()
493+
.orderBy('id', 'desc')
494+
.limit(limit)
495+
.execute()
496+
}
489497

490498
export async function update(id: number, accesstokenUpdate: AccessTokenUpdate) {
491499
return await db.updateTable('access_tokens')
@@ -591,6 +599,7 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
591599
Model,
592600
first,
593601
last,
602+
recent,
594603
where,
595604
whereIn,
596605
model: AccessTokenModel

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

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
1818
executionTime: number
1919
deployScript: string
2020
terminalOutput: string
21-
21+
user_id: number
2222
created_at: ColumnType<Date, string | undefined, never>
2323
updated_at: ColumnType<Date, string | undefined, never>
2424
deleted_at: ColumnType<Date, string | undefined, never>
@@ -483,12 +483,20 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
483483
.executeTakeFirst()
484484
}
485485

486-
export async function last() {
487-
return await db.selectFrom('deployments')
488-
.selectAll()
489-
.orderBy('id', 'desc')
490-
.executeTakeFirst()
491-
}
486+
export async function recent(limit: number) {
487+
return await db.selectFrom('deployments')
488+
.selectAll()
489+
.limit(limit)
490+
.execute()
491+
}
492+
493+
export async function last(limit: number) {
494+
return await db.selectFrom('deployments')
495+
.selectAll()
496+
.orderBy('id', 'desc')
497+
.limit(limit)
498+
.execute()
499+
}
492500

493501
export async function update(id: number, deploymentUpdate: DeploymentUpdate) {
494502
return await db.updateTable('deployments')
@@ -594,6 +602,7 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
594602
Model,
595603
first,
596604
last,
605+
recent,
597606
where,
598607
whereIn,
599608
model: DeploymentModel

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

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
1313
id: Generated<number>
1414
title: string
1515
body: string
16-
16+
user_id: number
1717
created_at: ColumnType<Date, string | undefined, never>
1818
updated_at: ColumnType<Date, string | undefined, never>
1919
deleted_at: ColumnType<Date, string | undefined, never>
@@ -478,12 +478,20 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
478478
.executeTakeFirst()
479479
}
480480

481-
export async function last() {
482-
return await db.selectFrom('posts')
483-
.selectAll()
484-
.orderBy('id', 'desc')
485-
.executeTakeFirst()
486-
}
481+
export async function recent(limit: number) {
482+
return await db.selectFrom('posts')
483+
.selectAll()
484+
.limit(limit)
485+
.execute()
486+
}
487+
488+
export async function last(limit: number) {
489+
return await db.selectFrom('posts')
490+
.selectAll()
491+
.orderBy('id', 'desc')
492+
.limit(limit)
493+
.execute()
494+
}
487495

488496
export async function update(id: number, postUpdate: PostUpdate) {
489497
return await db.updateTable('posts')
@@ -589,6 +597,7 @@ import type { ColumnType, Generated, Insertable, Selectable, Updateable } from '
589597
Model,
590598
first,
591599
last,
600+
recent,
592601
where,
593602
whereIn,
594603
model: PostModel

0 commit comments

Comments
 (0)