@@ -96,19 +96,27 @@ export const apply = async ({
9696 }
9797 }
9898
99- function getRelationships (
100- object : { schema : string ; name : string } ,
101- relationships : GeneratorMetadata [ 'relationships' ]
102- ) : Pick <
99+ const relationshipsByRelation = new Map < string , GeneratorMetadata [ 'relationships' ] > ( )
100+ for ( const relationship of relationships ) {
101+ const key = `${ relationship . schema } .${ relationship . relation } `
102+ let bucket = relationshipsByRelation . get ( key )
103+ if ( ! bucket ) {
104+ bucket = [ ]
105+ relationshipsByRelation . set ( key , bucket )
106+ }
107+ bucket . push ( relationship )
108+ }
109+
110+ function getRelationships ( object : {
111+ schema : string
112+ name : string
113+ } ) : Pick <
103114 GeneratorMetadata [ 'relationships' ] [ number ] ,
104115 'foreign_key_name' | 'columns' | 'is_one_to_one' | 'referenced_relation' | 'referenced_columns'
105116 > [ ] {
106- return relationships . filter (
107- ( relationship ) =>
108- relationship . schema === object . schema &&
109- relationship . referenced_schema === object . schema &&
110- relationship . relation === object . name
111- )
117+ const candidates = relationshipsByRelation . get ( `${ object . schema } .${ object . name } ` )
118+ if ( ! candidates ) return [ ]
119+ return candidates . filter ( ( relationship ) => relationship . referenced_schema === object . schema )
112120 }
113121
114122 function generateRelationshiptTsDefinition ( relationship : TsRelationship ) : string {
@@ -124,23 +132,23 @@ export const apply = async ({
124132 if ( table . schema in introspectionBySchema ) {
125133 introspectionBySchema [ table . schema ] . tables . push ( {
126134 table,
127- relationships : getRelationships ( table , relationships ) ,
135+ relationships : getRelationships ( table ) ,
128136 } )
129137 }
130138 }
131139 for ( const table of foreignTables ) {
132140 if ( table . schema in introspectionBySchema ) {
133141 introspectionBySchema [ table . schema ] . tables . push ( {
134142 table,
135- relationships : getRelationships ( table , relationships ) ,
143+ relationships : getRelationships ( table ) ,
136144 } )
137145 }
138146 }
139147 for ( const view of views ) {
140148 if ( view . schema in introspectionBySchema ) {
141149 introspectionBySchema [ view . schema ] . views . push ( {
142150 view,
143- relationships : getRelationships ( view , relationships ) ,
151+ relationships : getRelationships ( view ) ,
144152 } )
145153 }
146154 }
@@ -151,7 +159,7 @@ export const apply = async ({
151159 ...materializedView ,
152160 is_updatable : false ,
153161 } ,
154- relationships : getRelationships ( materializedView , relationships ) ,
162+ relationships : getRelationships ( materializedView ) ,
155163 } )
156164 }
157165 }
0 commit comments