Skip to content

Commit 83e49d0

Browse files
author
Léo Guillaume
committed
fix: migrations
1 parent 1c030a7 commit 83e49d0

File tree

2 files changed

+22
-16
lines changed

2 files changed

+22
-16
lines changed

api/database/migrations/1690232642901_move_searches_locations_to_user_locations.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,30 @@ import Database from '@ioc:Adonis/Lucid/Database'
33

44
export default class MoveSearchesLocationsToUserLocations extends BaseSchema {
55
public async up() {
6+
const searchUsers = await Database.from('search_users')
7+
8+
searchUsers.map(async (searchUser) => {
9+
const search = await Database.from('searches')
10+
.where('id', searchUser.search_id)
11+
.whereNotNull('location_id')
12+
.first()
13+
14+
await Database.table('user_locations').insert({
15+
user_id: searchUser.user_id,
16+
location_id: search.location_id,
17+
name: `Location ${search.location_id}`,
18+
})
19+
})
20+
621
const searches = await Database.from('searches').whereNotNull('location_id')
722

8-
for (let search of searches) {
23+
searches.map(async (search) => {
924
await Database.table('user_locations').insert({
10-
user_id: search.user_id,
25+
user_id: search.creator_id,
1126
location_id: search.location_id,
1227
name: `Location ${search.location_id}`,
1328
})
14-
}
29+
})
1530
}
1631

1732
public async down() {}

api/database/migrations/1690232737281_remove_location_id_from_searches.ts

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,10 @@ export default class RemoveLocationIdFromSearches extends BaseSchema {
55
protected tableName = 'searches'
66

77
public async up() {
8-
const result = await Database.rawQuery(`
9-
SELECT COUNT(*) as count
10-
FROM information_schema.table_constraints
11-
WHERE constraint_schema = 'your_database_name'
12-
AND table_name = 'searches'
13-
AND constraint_name = 'searches_location_id_foreign'
14-
`)
15-
16-
const count = result[0].count
17-
18-
if (count > 0) {
8+
const hasColumn = await this.schema.hasColumn(this.tableName, 'location_id')
9+
if (hasColumn) {
10+
await Database.rawQuery('ALTER TABLE searches DROP FOREIGN KEY searches_location_id_foreign')
1911
await this.schema.table(this.tableName, (table) => {
20-
table.dropForeign(['location_id'])
2112
table.dropColumn('location_id')
2213
})
2314
}
@@ -34,8 +25,8 @@ export default class RemoveLocationIdFromSearches extends BaseSchema {
3425
.references('id')
3526
.inTable('locations')
3627
.onDelete('CASCADE')
37-
table.foreign('location_id')
3828
})
29+
await Database.rawQuery('ALTER TABLE searches ADD CONSTRAINT searches_location_id_foreign FOREIGN KEY (location_id) REFERENCES locations(id) ON DELETE CASCADE')
3930
}
4031
}
4132
}

0 commit comments

Comments
 (0)