1
- import { describe , expect , it } from 'vitest'
1
+ import { beforeEach , describe , expect , it , vi } from 'vitest'
2
2
import type { Table } from '../../schema/index.js'
3
3
import {
4
4
aCheckConstraint ,
@@ -11,10 +11,21 @@ import {
11
11
aUniqueConstraint ,
12
12
anIndex ,
13
13
} from '../../schema/index.js'
14
+ import * as GenerateRandomIdentifier from './generateRandomIdentifier.js'
14
15
import { UnsupportedTokenError , processor } from './index.js'
15
16
16
17
import { createParserTestCases } from '../__tests__/index.js'
17
18
19
+ beforeEach ( ( ) => {
20
+ vi . spyOn ( GenerateRandomIdentifier , 'generateRandomIdentifier' )
21
+ . mockImplementationOnce ( ( length ) => `[identifier(${ length } )_#1]` )
22
+ . mockImplementation ( ( ) => {
23
+ throw Error (
24
+ '"generateRandomIdentifier" is called more times than expected. Please add additional "mockImplementationOnce" calls if need' ,
25
+ )
26
+ } )
27
+ } )
28
+
18
29
describe ( processor , ( ) => {
19
30
const userTable = ( override ?: Partial < Table > ) =>
20
31
aSchema ( {
@@ -302,6 +313,38 @@ describe(processor, () => {
302
313
} )
303
314
} )
304
315
316
+ it ( 'foreign key (without explicit constraint name and column options)' , async ( ) => {
317
+ const { value } = await processor ( /* Ruby */ `
318
+ create_table "posts" do |t|
319
+ t.bigint "user_id"
320
+ end
321
+
322
+ add_foreign_key "posts", "users"
323
+ ` )
324
+
325
+ expect ( value . relationships ) . toEqual ( {
326
+ users_id_to_posts_user_id : aRelationship ( {
327
+ name : 'users_id_to_posts_user_id' ,
328
+ foreignTableName : 'posts' ,
329
+ foreignColumnName : 'user_id' ,
330
+ primaryTableName : 'users' ,
331
+ primaryColumnName : 'id' ,
332
+ } ) ,
333
+ } )
334
+ expect ( value . tables [ 'posts' ] ?. constraints ) . toEqual ( {
335
+ PRIMARY_id : aPrimaryKeyConstraint ( {
336
+ name : 'PRIMARY_id' ,
337
+ columnName : 'id' ,
338
+ } ) ,
339
+ 'fk_rails_[identifier(10)_#1]' : aForeignKeyConstraint ( {
340
+ name : 'fk_rails_[identifier(10)_#1]' ,
341
+ columnName : 'user_id' ,
342
+ targetTableName : 'users' ,
343
+ targetColumnName : 'id' ,
344
+ } ) ,
345
+ } )
346
+ } )
347
+
305
348
describe ( 'foreign key cardinality' , ( ) => {
306
349
it ( 'foreign key (one-to-many)' , async ( ) => {
307
350
const keyName = 'fk_posts_user_id'
0 commit comments