DBA Data[Home] [Help]

PACKAGE BODY: APPS.BSC_MO_HELPER_PKG

Source


1 Package Body BSC_MO_HELPER_PKG AS
2 /* $Header: BSCMOHPB.pls 120.39 2007/05/18 13:05:50 amitgupt ship $ */
3 g_write_count number := 0;
4 newline VARCHAR2(10):='
5 ';
6 g_newline_length number:= length(newline);
7 
8 TYPE cLookupMap IS RECORD(
9 value varchar2(2000));
10 TYPE tab_cLookupMap is table of cLookupMap index by VARCHAR2(300);
11 gLookup_Value tab_cLookupMap;
12 
13 FUNCTION validate_dimension_views return BOOLEAN IS
14  --  Bug 4937922 change to new api which returns error message correctly
15  --  Moved API from PL/SQL for loop into SQL itself for performance
16 cursor cMissingViews is
17 select distinct sysdim.short_name, sysdim.level_view_name
18   from bsc_sys_dim_levels_b sysdim,
19        bsc_kpi_dim_levels_b kpidim,
20        bsc_tmp_opt_ui_kpis  proc
21  where proc.process_id = bsc_metadata_optimizer_pkg.g_ProcessID
22    and proc.indicator=kpidim.indicator
23    and kpidim.level_table_name = sysdim.level_table_name
24    and sysdim.source = 'PMF'
25    and BIS_UTILITIES_PVT.is_rolling_period_level(sysdim.short_name) = 0
26 minus
27 select sysdim.short_name, sysdim.level_view_name
28   from user_views vws
29      , bsc_sys_dim_levels_b sysdim
30  where vws.view_name=sysdim.level_view_name;
31 
32 x_return_status varchar2(1000);
33 x_msg_count number;
34 x_msg_data varchar2(1000);
35 
36 PRAGMA AUTONOMOUS_TRANSACTION;
37 BEGIN
38   FOR i in cMissingViews LOOP
39     BSC_BIS_DIM_OBJ_PUB.Validate_Refresh_BSC_PMF_Views(i.short_name
40         ,   x_return_status
41         ,   x_msg_count
42         ,   x_msg_data
43     );
44     --This API Requires Commit
45     commit;
46     IF x_return_status<>FND_API.G_RET_STS_SUCCESS THEN
47       writeTmp('Exception in BSC_BIS_DIM_OBJ_PUB.Validate_Refresh_BSC_PMF_Views for short_name='
48                 ||i.short_name||':'||x_msg_data, FND_LOG.LEVEL_EXCEPTION, true);
49       raise BSC_METADATA_OPTIMIZER_PKG.optimizer_exception;
50     ELSE
51       writeTmp('Successfully generated BSC View '||i.level_view_name,  FND_LOG.LEVEL_EXCEPTION, true);
52     END IF;
53   END LOOP;
54   commit;
55   return true;
56 
57   EXCEPTION WHEN OTHERS THEN
58     commit;
59     TerminateWithMsg('Exception in validate_dimension_views:'||sqlerrm);
60     return false;
61 END;
62 
63 FUNCTION getSourceTable(p_table IN VARCHAR2) return VARCHAR2 IS
64 CURSOR cSource is
65 SELECT SOURCE_TABLE_NAME
66 FROM BSC_DB_TABLES_RELS
67 WHERE TABLE_NAME = p_table;
68 l_table VARCHAR2(100);
69 BEGIN
70   OPEN cSource;
71   FETCH cSource INTO l_table;
72   CLOSE cSource;
73   return l_table;
74 END;
75 
76 FUNCTION filters_exist(p_kpi_number IN NUMBER, p_dim_set_id IN NUMBER, p_column_name IN VARCHAR2, p_filter_view OUT NOCOPY VARCHAR2) return boolean
77 IS
78 l_stmt varchar2(1000) := 'select level_view_name from '||BSC_METADATA_OPTIMIZER_PKG.g_filtered_indics||' where indicator=:1 and dim_set_id=:2 and level_pk_col=:3';
79 cv CurTyp;
80 
81 BEGIN
82   OPEN cv FOR l_stmt using p_kpi_number, p_dim_set_id, p_column_name;
83   FETCH cv INTO p_filter_view;
84   CLOSE cv;
85   IF (p_filter_view IS NULL) THEN
86     return false;
87   ELSE
88     return true;
89   END IF;
90 END;
91 
92 PROCEDURE DropAppsTables IS
93 l_count NUMBER;
94 l_stmt varchar2(1000);
95 BEGIN
96   l_stmt := 'DROP TABLE ';
97   l_count := bsc_metadata_optimizer_pkg.g_dropAppsTables.first;
98   LOOP
99     EXIT WHEN bsc_metadata_optimizer_pkg.g_dropAppsTables.count=0;
100     begin
101 	execute immediate l_stmt||bsc_metadata_optimizer_pkg.g_dropAppsTables(l_count);
102 	exception when others then
103 	  null;
104 	end;
105     EXIT WHEN l_count = bsc_metadata_optimizer_pkg.g_dropAppsTables.last;
106     l_count := bsc_metadata_optimizer_pkg.g_dropAppsTables.next(l_count);
107   END LOOP;
108 END;
109 -- performance fix, query bsc_kpi_Data_tables instead of bsc_kpi_data_tables_last
110 PROCEDURE CreateKPIDataTableTmp IS
111   TableName varchar2(30);
112   l_stmt varchar2(1000);
113 
114 BEGIN
115   bsc_metadata_optimizer_pkg.logProgress('INIT', 'Starting CreateKPIDataTableTmp');
116   TableName := BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table ;
117   DropTable(TableName);
118   l_stmt := 'create table '||TableName||' TABLESPACE '|| BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName||' as ';
119   --select distinct indicator, dim_set_id, table_name from bsc_kpi_data_tables';
120   l_stmt := l_stmt || ' select distinct
121        substr(table_name, instr(table_name, ''_'',  1, 2)+1, instr(table_name, ''_'',  1, 3)-instr(table_name, ''_'',  1, 2)-1) indicator,
122        substr(table_name, instr(table_name, ''_'',  1, 3)+1, instr(table_name, ''_'',  1, 4)-instr(table_name, ''_'',  1, 3)-1) dim_set_id,
123        table_name
124        from bsc_db_tables_rels
125        where table_name like ''BSC_S%''
126        and (source_table_name like ''BSC_B%'' or source_table_name like ''BSC_T%'' )';
127 
128   do_ddl(l_stmt, ad_ddl.create_table, TableName);
129   bsc_metadata_optimizer_pkg.logProgress('INIT', 'Created '||TableName);
130   writeTmp('Created '||TableName, FND_LOG.LEVEL_STATEMENT, false);
131   l_stmt := 'create unique index '||TableName||'_u1 on '||TableName||'(indicator, dim_set_id, table_name) TABLESPACE '||BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName;
132   do_ddl(l_stmt, ad_ddl.create_index, TableName||'_U1');
133   bsc_metadata_optimizer_pkg.logProgress('INIT', 'Created '||TableName||'_U1');
134   writeTmp('Created index '||TableName||'_u1', FND_LOG.LEVEL_STATEMENT, false);
135   l_stmt := 'create index '||TableName||'_n1 on '||TableName||'(table_name) TABLESPACE '||BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName;
136   do_ddl(l_stmt, ad_ddl.create_index, TableName||'_N1');
137   writeTmp('Created index '||TableName||'_n1', FND_LOG.LEVEL_STATEMENT, false);
138   bsc_metadata_optimizer_pkg.logProgress('INIT', 'Created '||TableName||'_N1');
139   bsc_metadata_optimizer_pkg.logProgress('INIT', 'Completed CreateKPIDataTableTmp');
140 
141   exception when others then
142     writeTmp('Exception in CreateKPIDataTableTmp :'||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
143     writeTmp('Exception in CreateKPIDataTableTmp stmt= :'||l_stmt, FND_LOG.LEVEL_EXCEPTION, true);
144   	raise;
145 END;
146 
147 -- performance fix, query bsc_kpi_Data_tables_ind instead of bsc_kpi_data_tables_last
148 PROCEDURE CreateDBMeasureByDimSetTmp IS
149   TableName varchar2(30);
150   l_stmt varchar2(1000);
151   l_count NUMBER;
152   cv   CurTyp;
153   strWhereInIndics VARCHAR2(1000);
154   l_index_name varchar2(30);
155 BEGIN
156   return;
157   -- using a SQL instead now...
158 END;
159 
160 FUNCTION find_objectives_for_table_old(p_table IN VARCHAR2) return BSC_METADATA_OPTIMIZER_PKG.tab_clsKPIDimSet  IS
161 CURSOR cObjectives IS
162 select distinct indicator, dim_set_id from bsc_kpi_data_tables
163 where table_name in
164 (select table_name from bsc_db_tables_rels
165 where table_name like 'BSC_S%'
166 connect by prior table_name = source_table_name
167 start with table_name = p_table);
168 l_objective number;
169 l_dim_set number;
170 l_results BSC_METADATA_OPTIMIZER_PKG.tab_clsKPIDimSet;
171 l_KPI BSC_METADATA_OPTIMIZER_PKG.clsKPIDimSet;
172 BEGIN
173   OPEN cObjectives;
174   LOOP
175     FETCH cObjectives INTO l_objective, l_dim_set;
176     EXIT WHEN cObjectives%NOTFOUND;
177     l_KPI.kpi_number := l_objective;
178     l_KPI.dim_set_id := l_dim_set;
179     l_results(l_results.count) := l_KPI;
180   END LOOP;
181   CLOSE cObjectives;
182   return l_results;
183   exception when others then
184     writeTmp('Exception in find_objectives_for_table_old :'||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
185   	raise;
186 END;
187 
188 FUNCTION find_objectives_for_table_new(p_table IN VARCHAR2) return BSC_METADATA_OPTIMIZER_PKG.tab_clsKPIDimSet  IS
189 l_stmt VARCHAR2(1000) :=
190 'select distinct indicator, dim_set_id from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||'
191 where table_name in
192 (select table_name from bsc_db_tables_rels
193 where table_name like ''BSC_S%''
194 connect by prior table_name = source_table_name
195 start with table_name = :1)';
196 l_objective number;
197 l_results BSC_METADATA_OPTIMIZER_PKG.tab_clsKPIDimSet;
198 cv CurTyp;
199 l_KPI BSC_METADATA_OPTIMIZER_PKG.clsKPIDimSet;
200 l_dim_set number;
201 BEGIN
202   OPEN cv FOR l_stmt USING p_table;
203   LOOP
204     FETCH cv INTO l_objective, l_dim_set ;
205     EXIT WHEN cv%NOTFOUND;
206     l_KPI.kpi_number := l_objective;
207     l_KPI.dim_set_id := l_dim_set;
208     l_results(l_results.count) := l_KPI;
209   END LOOP;
210   CLOSE cv;
211   RETURN l_results;
212  exception when others then
213     writeTmp('Exception in find_objectives_for_table_new :'||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
214     writeTmp('l-stmt was :'||l_stmt||' with bind variable :1='||p_table, FND_LOG.LEVEL_EXCEPTION, true);
215   	raise;
216 
217 END;
218 
219 FUNCTION find_objectives_for_table(p_table IN VARCHAR2) return BSC_METADATA_OPTIMIZER_PKG.tab_clsKPIDimSet  IS
220 BEGIN
221   IF NOT TableExists(BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table) then
222     RETURN find_objectives_for_table_old(p_table);
223   ELSE
224     RETURN find_objectives_for_table_new(p_table);
225   END IF;
226  exception when others then
227     writeTmp('Exception in find_objectives_for_table :'||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
228   	raise;
229 
230 END;
231 
232 FUNCTION getPeriodicityForTable(p_table_name IN VARCHAR2) return NUMBER IS
233 CURSOR cPeriodicity IS
234 select periodicity_id from bsc_db_tables
235 where table_name = upper(p_table_name);
236 l_value NUMBER;
237 BEGIN
238   OPEN cPeriodicity;
239   FETCH cPeriodicity INTO l_value;
240   CLOSE cPeriodicity;
241   return l_value;
242 END;
243 
244 Function is_base_table(p_table IN VARCHAR2) RETURN Boolean IS
245 l_count NUMBER;
246 CURSOR cTableType IS
247 select count(1)
248 from bsc_db_tables tbl,
249 bsc_db_tables_rels rels
250 where
251 rels.table_name = p_table
252 and rels.source_table_name = tbl.table_name
253 and tbl.table_type = 0;
254 
255 BEGIN
256   OPEN cTableType;
257   FETCH cTableType INTO l_count;
258   CLOSE cTableType;
259   IF (l_count=0) THEN
260      return false;
261   ELSE
262      return true;
263   END IF;
264   EXCEPTION WHEN OTHERS THEN
265     bsc_mo_helper_pkg.writeTmp('Exception in is_Base_Table for '||p_table||':'||sqlerrm, FND_LOG.LEVEL_UNEXPECTED, true);
266   	raise;
267 End ;
268 
269 
270 PROCEDURE checkError(apiName IN VARCHAR2) IS
271 l_error VARCHAR2(32000) := null;
272 CURSOR cMsg IS
273 SELECT MESSAGE
274 FROM BSC_MESSAGE_LOGS
275 WHERE TYPE = 0
276 AND UPPER(SOURCE) = upper(apiName)
277 AND LAST_UPDATE_LOGIN = bsc_metadata_optimizer_pkg.g_session_id;
278 
279 BEGIN
280   OPEN cMsg;
281   FETCH cMsg INTO l_error;
282   CLOSE cMsg;
283   If l_error IS NOT NULL Then
284       --if there was an error then shows the error and exit
285       bsc_utility.do_rollback;
286       BSC_METADATA_OPTIMIZER_PKG.g_errbuf := l_error;
287       BSC_METADATA_OPTIMIZER_PKG.g_retcode := 2;
288       BSC_METADATA_OPTIMIZER_PKG.logProgress('CHECKERROR', apiName);
289       BSC_MO_HELPER_PKG.TerminateWithMsg(l_error);
290       raise BSC_METADATA_OPTIMIZER_PKG.optimizer_exception;
291   END IF;
292 
293 END;
294 
295 FUNCTION get_time RETURN VARCHAR2 IS
296 
297 BEGIN
298   return to_char(sysdate, 'mm/dd/yyyy hh24:mi:ss');
299 END;
300 
301 FUNCTION getTablespaceClauseTbl RETURN VARCHAR2 IS
302 l_stmt varchar2(1000);
303 l_return_value varchar2(1000);
304 cv   CurTyp;
305 CURSOR cTableSpace IS
306 SELECT BSC_APPS.Get_Tablespace_Clause_Tbl FROM DUAL;
307 BEGIN
308 
309 	OPEN cTableSpace;
310 	FETCH cTableSpace INTO l_return_value;
311 	CLOSE cTableSpace;
312 	RETURN l_return_value;
313 
314   	EXCEPTION WHEN others then
315       bsc_mo_helper_pkg.writeTmp('EXCEPTION in getTablespaceClauseTbl', FND_LOG.LEVEL_UNEXPECTED, true);
316   RAISE;
317 END;
318 
319 FUNCTION getTablespaceClauseIdx RETURN VARCHAR2 IS
320 l_stmt varchar2(1000);
321 l_return_value varchar2(1000);
322 
323 cv   CurTyp;
324 BEGIN
325 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
326       bsc_mo_helper_pkg.writeTmp('Inside getTablespaceClauseIdx', FND_LOG.LEVEL_PROCEDURE);
327 	END IF;
328 
329 	l_stmt := 'SELECT BSC_APPS.Get_Tablespace_Clause_Idx  FROM DUAL';
330 
331   OPEN cv FOR l_stmt;
332 	FETCH cv INTO l_return_value;
333 	CLOSE cv;
334 
335 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
336       bsc_mo_helper_pkg.writeTmp('Completed getTablespaceClauseIdx, returning '||l_return_value, FND_LOG.LEVEL_PROCEDURE);
337 	END IF;
338 
339 	RETURN l_return_value;
340 
341  	EXCEPTION WHEN others then
342       bsc_mo_helper_pkg.writeTmp('EXCEPTION in getTablespaceClauseIdx', FND_LOG.LEVEL_UNEXPECTED, true);
343 	RAISE;
344 END;
345 
346 FUNCTION getStorageClause RETURN VARCHAR2 IS
347 l_stmt varchar2(1000);
348 l_return_value varchar2(1000);
349 CURSOR cStorage IS
350 SELECT BSC_APPS.Get_Storage_Clause FROM DUAL;
351 
352 BEGIN
353 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
354       bsc_mo_helper_pkg.writeTmp('Inside getStorageClause', FND_LOG.LEVEL_PROCEDURE);
355 	END IF;
356 
357 	OPEN cStorage;
358 	FETCH cStorage INTO l_return_value;
359 	CLOSE cStorage;
360 
361 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
362       bsc_mo_helper_pkg.writeTmp('Completed getStorageClause, returning '||l_return_value, FND_LOG.LEVEL_PROCEDURE);
363 	END IF;
364 
365 	RETURN l_return_value;
366 
367   	EXCEPTION WHEN others then
368         bsc_mo_helper_pkg.writeTmp('EXCEPTION in getStorageClause', FND_LOG.LEVEL_UNEXPECTED, true);
369 	   RAISE;
370 END;
371 
372 
373 PROCEDURE addStack(pStack IN OUT NOCOPY VARCHAR2, pMsg IN VARCHAR2) IS
374 BEGIn
375   IF (length (pStack) + length(pMsg) > 30000) THEN
376       pStack := null;
377   END IF;
378   pStack := pStack || newline||pMsg;
379 END;
380 
381 FUNCTION boolean_decode (pVal IN BOOLEAN) RETURN VARCHAR2 IS
382 l_val VARCHAR2(10);
383 BEGIN
384   IF pVal THEN
385       l_val := 'Y';
386   ELSE
387       l_val := 'N';
388   END IF;
389   return l_val;
390 END;
391 
392 FUNCTION boolean_decode_num (pVal IN BOOLEAN) RETURN NUMBER IS
393 l_val VARCHAR2(10);
394 BEGIN
395   IF pVal THEN
396       return 1;
397   ELSE
398       return 0;
399   END IF;
400   return 0;
401 END;
402 
403 
404 
405 
406 PROCEDURE InitTablespaceNames IS
407   --Initialize the global variables with tablespace names
408 BEGIN
409 
410   BSC_METADATA_OPTIMIZER_PKG.gInputTableTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.input_table_tbs_type);
411   BSC_METADATA_OPTIMIZER_PKG.gInputIndexTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.input_index_tbs_type);
412   BSC_METADATA_OPTIMIZER_PKG.gBaseTableTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.base_table_tbs_type);
413   BSC_METADATA_OPTIMIZER_PKG.gBaseIndexTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.base_index_tbs_type);
414   BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.summary_table_tbs_type);
415   BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.summary_index_tbs_type);
416   BSC_METADATA_OPTIMIZER_PKG.gOtherTableTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.other_table_tbs_type);
417   BSC_METADATA_OPTIMIZER_PKG.gOtherIndexTbsName := BSC_APPS.get_tablespace_name(BSC_APPS.other_table_tbs_type);
418 End ;
419 
420 
421 PROCEDURE write_this (
422   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsConfigKpiMV,
423   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
424   pForce IN boolean default false)
425   IS
426 l_count number;
427 BEGIN
428 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
429   writeTmp('LevelComb = '||pTable.LevelComb||' , MVName = '||
430         pTable.MVName||', DataSource = '||pTable.MVName||', SqlStmt = '||pTable.SqlStmt,
431 			FND_LOG.LEVEL_STATEMENT, pForce);
432 	END IF;
433 
434 END;
435 
436 
437 PROCEDURE write_this (
438   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsConfigKpiMV,
439   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
440   pForce IN boolean default false)
441   IS
442 l_count NUMBER;
443 l_table BSC_METADATA_OPTIMIZER_PKG.clsConfigKpiMV;
444 BEGIN
445   IF (pTable.count=0) THEN
446       return;
447   END IF;
448   l_count := pTable.first;
449   LOOP
450       l_table := pTable(l_count);
451       write_this(l_table, pSeverity, pForce);
452       exit when l_count = pTable.last;
453       l_count := pTable.next(l_count);
454   END LOOP;
455 END;
456 /*
457 PROCEDURE write_this (pTable IN DBMS_SQL.VARCHAR2_TABLE, pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT, pForce IN boolean default false) IS
458 l_count NUMBER;
459 l_string VARCHAR2(4000);
460 BEGIN
461   IF (pTable.count=0) THEN
462       return;
463   END IF;
464   l_count := pTable.first;
465   l_string := l_string ||'  ';
466   LOOP
467       l_string := l_string ||pTable(l_count);
468       IF (length(l_string) > 3000) THEN
469 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
470         writeTmp(l_string, pSeverity);
471 	END IF;
472 
473         l_string := null;
474       END IF;
475       EXIT WHEN l_count = pTable.last;
476       l_count := pTable.next(l_count);
477       l_string := l_string ||', ';
478   END LOOP;
479 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
480   writeTmp(l_string, pSeverity);
481 	END IF;
482 
483 
484 END;
485 */
486 
487 PROCEDURE write_this (
488   pTable IN DBMS_SQL.VARCHAR2_TABLE,
489   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
490   pForce IN boolean default false) IS
491 l_count NUMBER;
492 l_string VARCHAR2(4000);
493 BEGIN
494   IF (pTable.count=0) THEN
495       return;
496   END IF;
497   l_count := pTable.first;
498 
499   LOOP
500 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
501         writeTmp(pTable(l_count), pSeverity, pForce);
502 	END IF;
503 
504       EXIT WHEN l_count = pTable.last;
505       l_count := pTable.next(l_count);
506   END LOOP;
507 END;
508 
509 
510 
511 PROCEDURE write_this (
512   pTable IN DBMS_SQL.NUMBER_TABLE,
513   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
514   pForce IN boolean default false)
515   IS
516 l_count NUMBER;
517 l_string VARCHAR2(3000);
518 BEGIN
519   IF (pTable.count=0) THEN
520       return;
521   END IF;
522   l_count := pTable.first;
523   LOOP
524       l_string := l_string ||pTable(l_count);
525       EXIT WHEN l_count = pTable.last;
526       l_count := pTable.next(l_count);
527       l_string := l_string ||', ';
528       IF (length(l_string) > 200) THEN
529 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
530         writeTmp(l_string, pSeverity, pForce);
531 	END IF;
532 
533         l_string := null;
534       END IF;
535   END LOOP;
536 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
537     writeTmp(l_string, pSeverity, pForce);
538 	END IF;
539 
540   EXCEPTION WHEN OTHERS THEN
541       raise;
542 END;
543 
544 PROCEDURE write_this(
545   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsParent,
546   ind IN NUMBER default null,
547   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
548   pForce IN boolean default false)
549   IS
550 BEGIN
551 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
552   writeTmp(ind||' Name = '||pTable.name||', relationColumn = '||pTable.relationColumn, pSeverity, pForce);
553 	END IF;
554 
555 END;
556 
557 PROCEDURE write_this(
558   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsParent,
559   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
560   pForce IN boolean default false)
561   IS
562 l_count NUMBER;
563 l_table BSC_METADATA_OPTIMIZER_PKG.clsParent;
564 BEGIN
565 
566   IF (pTable.count=0) THEN
567       return;
568   END IF;
569   l_count := pTable.first;
570   LOOP
571       l_table := pTable(l_count);
572       write_this(l_table, l_count, pSeverity, pForce);
573       exit when l_count = pTable.last;
574       l_count := pTable.next(l_count);
575   END LOOP;
576 END;
577 
578 PROCEDURE write_this(
579   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsMasterTable,
580   ind IN NUMBER default null,
581   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
582   pForce IN boolean default false)
583   IS
584 l_string varchar2(30000);
585 BEGIN
586   l_string := ind||' Name = '||pTable.name||', keyName = '||pTable.keyName||', userTable = ';
587   IF (pTable.userTable) THEN
588       l_string := l_string ||'true';
589   ELSE
590       l_string := l_string ||'false';
591   END IF;
592   l_string := l_string ||', EDW_FLAG='||pTable.EDW_FLAG||', inputTable='||pTable.inputTable;
593 	IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
594   writeTmp(l_string, pSeverity);
595 	END IF;
596 
597 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
598   writeTmp('Parent_name='||pTable.parent_name||', parent_rel_col='||pTable.parent_rel_col, pSeverity, pForce);
599   writeTmp('Auxillary='||pTable.auxillaryFields, pSeverity, pForce);
600 	END IF;
601 
602 END;
603 
604 PROCEDURE write_this(
605   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsMasterTable,
606   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
607   pForce IN boolean default false)
608 IS
609 l_count NUMBER;
610 l_table BSC_METADATA_OPTIMIZER_PKG.clsMasterTable;
611 BEGIN
612   IF (pTable.count=0) THEN
613       return;
614   END IF;
615   l_count := pTable.first;
616   LOOP
617       l_table := pTable(l_count);
618       write_this(l_table, l_count, pSeverity, pForce);
619       exit when l_count = pTable.last;
620       l_count := pTable.next(l_count);
621   END LOOP;
622 END;
623 
624 PROCEDURE write_this(
625   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsRelationMN,
626   ind IN NUMBER default null,
627   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
628   pForce IN boolean default false)
629   IS
630 BEGIN
631 	IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
632   writeTmp(ind||' TableA='||pTable.TableA||', keyNameA='||pTable.keyNameA, pSeverity, pForce);
633   writeTmp(', TableB='||pTable.TableB||', keyNameB='||pTable.keyNameB
634       ||', TableRel='||pTable.TableRel||', InputTable='||pTable.InputTable, pSeverity, pForce);
635 	END IF;
636 
637 END;
638 
639 PROCEDURE write_this(
640   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsRelationMN,
641   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
642   pForce IN boolean default false) IS
643 l_count NUMBER;
644 l_table BSC_METADATA_OPTIMIZER_PKG.clsRelationMN;
645 BEGIN
646   IF (pTable.count=0) THEN
647       return;
648   END IF;
649   l_count := pTable.first;
650   LOOP
651       l_table := pTable(l_count);
652       write_this(l_table, l_count, pSeverity, pForce);
653       exit when l_count = pTable.last;
654       l_count := pTable.next(l_count);
655   END LOOP;
656 END;
657 
658 PROCEDURE write_this(
659   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsIndicator,
660   ind IN NUMBER default null,
661   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
662   pForce IN boolean default false)
663   IS
664 BEGIN
665 	IF BSC_METADATA_OPTIMIZER_PKG.g_log OR pForce THEN
666   writeTmp(ind||' Code='||pTable.code||', Name='||pTable.Name||', IndicatorType='||pTable.IndicatorType||', ConfigType='||pTable.configType
667       ||', periodicity='||pTable.periodicity||', OptimizationMode='||pTable.OptimizationMode||', Action_Flag='||pTable.Action_Flag||', Share_Flag='||pTable.Share_flag
668       ||', source_Indicator='||pTable.source_Indicator||', EDW_Flag='||pTable.EDW_FLag||',impl_type='||pTable.impl_type, pSeverity, pForce);
669 	END IF;
670 
671 END;
672 
673 PROCEDURE write_this(
674   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsIndicator,
675   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
676   pForce IN boolean default false) IS
677 l_count NUMBER;
678 l_table BSC_METADATA_OPTIMIZER_PKG.clsIndicator;
679 BEGIN
680   IF (pTable.count=0) THEN
681     return;
682   END IF;
683   l_count := pTable.first;
684   LOOP
685     l_table := pTable(l_count);
686     write_this(l_table, l_count, pSeverity, pForce);
687     exit when l_count = pTable.last;
688     l_count := pTable.next(l_count);
689   END LOOP;
690 END;
691 PROCEDURE write_this(
692   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsPeriodicity,
693   ind IN NUMBER default null,
694   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
695   pForce IN boolean default false) IS
696 l_count NUMBER;
697 l_string VARCHAR2(30000);
698 BEGIN
699   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
700     writeTmp(ind||' Code='||pTable.code||', EDW_Flag='||pTable.EDW_Flag||', Yearly_Flag='||pTable.Yearly_flag
701       ||', CalendarID='||pTable.calendarID||', PeriodicityType='||pTable.PeriodicityType
702       ||'  Origin ='||pTable.PeriodicityOrigin , pSeverity, pForce);
703   END IF;
704 END;
705 
706 PROCEDURE write_this(
707   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsPeriodicity ,
708   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
709   pForce IN boolean default false)
710   IS
711 l_count NUMBER;
712 l_table BSC_METADATA_OPTIMIZER_PKG.clsPeriodicity;
713 BEGIN
714   IF (pTable.count=0) THEN
715     return;
716   END IF;
717   l_count := pTable.first;
718   LOOP
719     l_table := pTable(l_count);
720     write_this(l_table, l_count, pSeverity, pForce);
721     exit when l_count = pTable.last;
722     l_count := pTable.next(l_count);
723   END LOOP;
724 END;
725 
726 PROCEDURE write_this(
727   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsIndicPeriodicity,
728   ind IN NUMBER default null,
729   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
730   pForce IN boolean default false)
731   IS
732 l_count NUMBER;
733 l_string VARCHAR2(30000);
734 BEGIN
735   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
736     writeTmp(ind||' Code='||pTable.code||', TargetLevel='||pTable.TargetLevel, pSeverity, pForce);
737   END IF;
738 END;
739 PROCEDURE write_this(
740   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsIndicPeriodicity ,
741   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
742   pForce IN boolean default false)
743   IS
744 l_count NUMBER;
745 l_table BSC_METADATA_OPTIMIZER_PKG.clsIndicPeriodicity;
746 BEGIN
747   IF (pTable.count=0) THEN
748     return;
749   END IF;
750   l_count := pTable.first;
751   LOOP
752     l_table := pTable(l_count);
753     write_this(l_table, l_count, pSeverity, pForce);
754     exit when l_count = pTable.last;
755     l_count := pTable.next(l_count);
756   END LOOP;
757 END;
758 
759 PROCEDURE write_this(
760   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsCalendar,
761   ind IN NUMBER default null,
762   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
763   pForce IN boolean default false)
764   IS
765 l_count NUMBER;
766 l_string VARCHAR2(30000);
767 BEGIN
768   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
769     writeTmp(ind||' Code='||pTable.code||', EDW_FLAG='||pTable.EDW_FLAG||', Name='||pTable.Name
770       ||', CurrFiscalYear='||pTable.CurrFiscalYear||', RangeYrMod='||pTable.RangeYrMod
771       ||', NumOfYears='||pTable.NumOfYears||', PreviousYears='||pTable.PreviousYears, pSeverity, pForce);
772   END IF;
773 END;
774 
775 PROCEDURE write_this(
776   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsCalendar,
777   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
778   pForce IN boolean default false)
779   IS
780 l_count NUMBER;
781 l_table BSC_METADATA_OPTIMIZER_PKG.clsCalendar;
782 BEGIN
783   IF (pTable.count=0) THEN
784     return;
785   END IF;
786   l_count := pTable.first;
787   LOOP
788     l_table := pTable(l_count);
789     write_this(l_table, l_count, pSeverity, pForce);
790     exit when l_count = pTable.last;
791     l_count := pTable.next(l_count);
792   END LOOP;
793 END;
794 
795 PROCEDURE write_this(
796   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsOldBTables,
797   ind IN NUMBER default null,
798   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
799   pForce IN boolean default false)
800   IS
801 l_count NUMBER;
802 l_string VARCHAR2(30000);
803 BEGIN
804   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
805     writeTmp(ind||' Name='||pTable.name||', periodicity='||pTable.periodicity||', InputTable='||pTable.InputTable
806       ||', numFields='||pTable.numFields||', NumIndicators='||pTable.NumIndicators||
807         ', Fields='||pTable.fields||', Indicators='||pTable.Indicators, pSeverity, pForce);
808   END IF;
809 END;
810 
811 PROCEDURE write_this(
812   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsOldBTables,
813   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
814   pForce IN boolean default false)
815   IS
816 l_count NUMBER;
817 l_table BSC_METADATA_OPTIMIZER_PKG.clsOldBTables;
818 BEGIN
819   IF (pTable.count=0) THEN
820     return;
821   END IF;
822   l_count := pTable.first;
823   LOOP
824     l_table := pTable(l_count);
825     write_this(l_table, l_count, pSeverity, pForce);
826     exit when l_count = pTable.last;
827     l_count := pTable.next(l_count);
828   END LOOP;
829 END;
830 
831 PROCEDURE write_this(
832   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsMeasureLOV,
833   ind IN NUMBER default null,
834   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
835   pForce IN boolean default false)
836   IS
837 l_count NUMBER;
838 l_string VARCHAR2(30000);
839 BEGIN
840   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
841     writeTmp(ind||' field='||pTable.fieldName||', source='||pTable.source||', desc='||pTable.description||', group='||pTable.groupCode
842       ||', prj='||pTable.prjMethod||', measureType='||pTable.measureType, pSeverity, pForce);
843   END IF;
844 END;
845 
846 PROCEDURE write_this(
847   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsMeasureLOV,
848   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
849   pForce IN boolean default false)
850   IS
851 l_count NUMBER;
852 l_table BSC_METADATA_OPTIMIZER_PKG.clsMeasureLOV;
853 BEGIN
854   IF (pTable.count=0) THEN
855     return;
856   END IF;
857   l_count := pTable.first;
858   LOOP
859     l_table := pTable(l_count);
860     write_this(l_table, l_count, pSeverity, pForce);
861     exit when l_count = pTable.last;
862     l_count := pTable.next(l_count);
863   END LOOP;
864 END;
865 
866 PROCEDURE write_this(
867   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsLevels,
868   ind IN NUMBER default null,
869   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
870   pForce IN boolean default false)
871   IS
872 l_count NUMBER;
873 l_string VARCHAR2(30000);
874 BEGIN
875   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
876     writeTmp(ind||' key='||pTable.keyName||', dimTable='||pTable.dimTable||', Num='||pTable.Num
877       ||', Name='||pTable.Name||', TargetLevel='||pTable.TargetLevel||', parents1N='||pTable.Parents1N||
878       ', ParentsMN='||pTable.parentsMN, pSeverity, pForce);
879   END IF;
880 END;
881 
882 PROCEDURE write_this(
883   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevels,
884   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
885   pForce IN boolean default false) IS
886 l_count NUMBER;
887 l_table BSC_METADATA_OPTIMIZER_PKG.clsLevels;
888 BEGIN
889   IF (pTable.count=0) THEN
890     return;
891   END IF;
892   l_count := pTable.first;
893   LOOP
894     l_table := pTable(l_count);
895     write_this(l_table, l_count, pSeverity, pForce);
896     exit when l_count = pTable.last;
897     l_count := pTable.next(l_count);
898   END LOOP;
899 END;
900 
901 PROCEDURE write_this(
902   pTable IN BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevels,
903   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
904   pForce IN boolean default false)
905   IS
906 l_count NUMBER;
907 BEGIN
908   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
909     writeTmp(' group_id = '||pTable.group_id||', key='||pTable.keyName||', dimTable='||pTable.dimTable||', Num='||pTable.Num
910       ||', Name='||pTable.Name||', TgtLevel='||pTable.TargetLevel||', parents1N='||pTable.Parents1N||
911       ', ParentsMN='||pTable.parentsMN, pSeverity, pForce);
912   END IF;
913 END;
914 
915 PROCEDURE write_this(
916   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevels,
917   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
918   pForce IN boolean default false)
919   IS
920 l_count NUMBER;
921 l_table BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevels;
922 BEGIN
923   IF (pTable.count=0) THEN
924     return;
925   END IF;
926   l_count := pTable.first;
927   LOOP
928     l_table := pTable(l_count);
929     write_this(l_table, pSeverity, pForce);
930     exit when l_count = pTable.last;
931     l_count := pTable.next(l_count);
932   END LOOP;
933 END;
934 
935 
936 PROCEDURE write_this(
937   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsLevelCombinations,
938   ind IN NUMBER default null,
939   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
940   pForce IN boolean default false)
941   IS
942 l_count NUMBER;
943 l_string VARCHAR2(30000);
944 BEGIN
945   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
946     writeTmp(ind||' LevelConfig='||pTable.LevelConfig||', levels='||pTable.levels, pSeverity, pForce);
947   END IF;
948 END;
949 
950 PROCEDURE write_this(
951   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevelCombinations,
952   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
953   pForce IN boolean default false)
954   IS
955 l_count NUMBER;
956 l_table BSC_METADATA_OPTIMIZER_PKG.clsLevelCombinations;
957 BEGIN
958   IF (pTable.count=0) THEN
959     return;
960   END IF;
961   l_count := pTable.first;
962   LOOP
963     l_table := pTable(l_count);
964     write_this(l_table, l_count, pSeverity, pForce);
965     exit when l_count = pTable.last;
966     l_count := pTable.next(l_count);
967   END LOOP;
968 END;
969 
970 PROCEDURE write_this(
971   pTable IN BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevelCombinations,
972   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
973   pForce IN boolean default false)
974   IS
975 l_count NUMBER;
976 BEGIN
977   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
978     writeTmp(' group_id = '||pTable.group_id||', levels='||pTable.levels||', levelConfig='||pTable.levelConfig, pSeverity, pForce);
979   END IF;
980 END;
981 
982 PROCEDURE write_this(
983   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevelCombinations,
984   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
985   pForce IN boolean default false)
986   IS
987 l_count NUMBER;
988 l_table BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevelCombinations;
989 BEGIN
990   IF (pTable.count=0) THEN
991     return;
992   END IF;
993   l_count := pTable.first;
994   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
995     writeTmp('write_this for tab_tab_clsLevelCombinations, count = '||pTable.count);
996   END IF;
997   LOOP
998     l_table := pTable(l_count);
999     write_this(l_table, pSeverity, pForce);
1000     exit when l_count = pTable.last;
1001     l_count := pTable.next(l_count);
1002   END LOOP;
1003 END;
1004 PROCEDURE write_this(
1005   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsKeyField,
1006   ind IN NUMBER default null,
1007   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1008   pForce IN boolean default false)
1009   IS
1010 l_count NUMBER;
1011 l_string VARCHAR2(300) := null;
1012 l_error VARCHAR2(1000);
1013 BEGIN
1014   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1015     writeTmp(' '||ind||l_string||' key='||pTable.keyName||', origin='||pTable.origin||', 0code='||boolean_decode(pTable.needsCode0)
1016       ||', calc0Code='||boolean_decode(pTable.calculateCode0)||', FilterView='||pTable.FilterViewName||', dimIndex = '||pTable.dimIndex , pSeverity, pForce);
1017   END IF;
1018   EXCEPTION WHEN OTHERS THEN
1019     l_error := sqlerrm;
1020     writeTmp('Exception in write_this for tab_clsKeyField :' ||l_error, FND_LOG.LEVEL_EXCEPTION, true);
1021     raise;
1022 END;
1023 
1024 PROCEDURE write_this(
1025   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsKeyField,
1026   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1027   pForce IN boolean default false)
1028   IS
1029 l_count NUMBER;
1030 l_table BSC_METADATA_OPTIMIZER_PKG.clsKeyField;
1031 l_error VARCHAR2(1000);
1032 BEGIN
1033   IF (pTable.count=0) THEN
1034     return;
1035   END IF;
1036   l_count := pTable.first;
1037   LOOP
1038     l_table := pTable(l_count);
1039     write_this(l_table, l_count, pSeverity, pForce);
1040     exit when l_count = pTable.last;
1041     l_count := pTable.next(l_count);
1042   END LOOP;
1043   EXCEPTION WHEN OTHERS THEN
1044     l_error := sqlerrm;
1045     writeTmp('Exception in write_this for tab_clsKeyField :' ||l_error, FND_LOG.LEVEL_EXCEPTION, true);
1046     raise;
1047 END;
1048 
1049 
1050 PROCEDURE write_this(
1051   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsDataField,
1052   ind IN NUMBER default null,
1053   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1054   pForce IN boolean default false)
1055   IS
1056 l_count NUMBER;
1057 l_string VARCHAR2(300) := null;
1058 BEGIN
1059   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1060     writeTmp(ind||l_string||' field='||pTable.fieldName||', source='||pTable.source||', aggFon='||pTable.aggFunction||', Origin='||pTable.Origin
1061       ||', AvgLFlag='||pTable.AvgLFlag
1062 	  ||', AvgLTotalColumn='||pTable.AvgLTotalColumn
1063       ||', AvgLCounter='||pTable.AvgLCounterColumn
1064 	  ||', IntColumn='||pTable.InternalColumnType
1065       ||', IntColSource='||pTable.InternalColumnSource
1066 	  ||', changeType='||pTable.changeType,
1067 	   pSeverity, pForce);
1068   END IF;
1069 END;
1070 
1071 PROCEDURE write_this(
1072   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsDataField,
1073   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1074   pForce IN boolean default false)
1075   IS
1076 l_count NUMBER;
1077 l_table BSC_METADATA_OPTIMIZER_PKG.clsDataField;
1078 BEGIN
1079   IF (pTable.count=0) THEN
1080     return;
1081   END IF;
1082   l_count := pTable.first;
1083   LOOP
1084     l_table := pTable(l_count);
1085     write_this(l_table, l_count, pSeverity, pForce);
1086     exit when l_count = pTable.last;
1087     l_count := pTable.next(l_count);
1088   END LOOP;
1089 END;
1090 PROCEDURE write_this(
1091   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsBasicTable,
1092   ind IN NUMBER default null,
1093   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1094   pForce IN boolean default false)
1095   IS
1096 l_count NUMBER;
1097 l_string VARCHAR2(30000);
1098 BEGIN
1099   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1100     writeTmp(ind||' Name='||pTable.Name, pSeverity, pForce);
1101     writeTmp('   keyfields = ', pSeverity, pForce);
1102     --write_this(getAllkeyFields(pTable.name), pSeverity, pForce);
1103     write_this(pTable.keys, pSeverity, pForce);
1104     writeTmp('   Data = ', pSeverity, pForce);
1105 	--write_this(getAllDataFields(pTable.name), pSeverity, pForce);
1106 	write_this(pTable.data, pSeverity, pForce);
1107     writeTmp(' LevelConfig='||pTable.LevelConfig||', originTable='||pTable.originTable, pSeverity, pForce);
1108     writeTmp('----------------------------------', pSeverity, pForce);
1109   END IF;
1110 END;
1111 
1112 PROCEDURE write_this(
1113   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsBasicTable,
1114   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1115   pForce IN boolean default false)
1116   IS
1117 l_count NUMBER;
1118 l_table BSC_METADATA_OPTIMIZER_PKG.clsBasicTable;
1119 BEGIN
1120   IF (pTable.count=0) THEN
1121     return;
1122   END IF;
1123   l_count := pTable.first;
1124   LOOP
1125     l_table := pTable(l_count);
1126     write_this(l_table, l_count, pSeverity, pForce);
1127     exit when l_count = pTable.last;
1128     l_count := pTable.next(l_count);
1129   END LOOP;
1130 END;
1131 
1132 PROCEDURE write_this(
1133   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_string,
1134   ind IN NUMBER default null,
1135   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1136   pForce IN boolean default false)
1137   IS
1138 BEGIN
1139   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1140     writeTmp(pTable.value, pSeverity, pForce);
1141   END IF;
1142 END;
1143 
1144 PROCEDURE write_this(
1145   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_string,
1146   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1147   pForce IN boolean default false)
1148   IS
1149 l_count NUMBER;
1150 l_table BSC_METADATA_OPTIMIZER_PKG.tab_string;
1151 BEGIN
1152   IF (pTable.count=0) THEN
1153     return;
1154   END IF;
1155   l_count := pTable.first;
1156   LOOP
1157     l_table := pTable(l_count);
1158     IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1159       writeTmp(l_table.value, pSeverity, pForce);
1160     END IF;
1161     exit when l_count = pTable.last;
1162     l_count := pTable.next(l_count);
1163   END LOOP;
1164 END;
1165 
1166 PROCEDURE write_this(
1167   pTable IN BSC_METADATA_OPTIMIZER_PKG.number_table,
1168   ind IN NUMBER default null,
1169   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1170   pForce IN boolean default false)
1171   IS
1172 BEGIN
1173   write_this(pTable.value, pSeverity, pForce);
1174 END;
1175 
1176 PROCEDURE write_this(
1177   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsOriginTable,
1178   ind IN NUMBER default null,
1179   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1180   pForce IN boolean default false)
1181   IS
1182 l_count NUMBER;
1183 l_string VARCHAR2(30000);
1184 BEGIN
1185   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1186     writeTmp(ind||' Name='||pTable.Name, pSeverity, pForce);
1187   END IF;
1188 END;
1189 
1190 PROCEDURE write_this(
1191   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsOriginTable,
1192   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1193   pForce IN boolean default false)
1194   IS
1195 l_count NUMBER;
1196 l_table BSC_METADATA_OPTIMIZER_PKG.clsOriginTable;
1197 BEGIN
1198   IF (pTable.count=0) THEN
1199     return;
1200   END IF;
1201   l_count := pTable.first;
1202   LOOP
1203     l_table := pTable(l_count);
1204     write_this(l_table, l_count, pSeverity, pForce);
1205     exit when l_count = pTable.last;
1206     l_count := pTable.next(l_count);
1207   END LOOP;
1208 END;
1209 
1210 PROCEDURE write_this(
1211   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsTable,
1212   ind IN NUMBER default null,
1213   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1214   pForce IN boolean default false)
1215   IS
1216 l_count NUMBER;
1217 l_string VARCHAR2(30000);
1218 BEGIN
1219   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1220     writeTmp(ind||' Name='||pTable.Name||', Type ='||pTable.type||', Ind#='||pTable.indicator||
1221     ', DimSet='||pTable.configuration||', Per = '||pTable.periodicity||', EDW_Flag='||pTable.EDW_Flag||
1222     ', ProdTable='||boolean_decode(pTable.isProductionTable)||
1223     ', ProdTableAltered='||boolean_decode(pTable.isProductionTableAltered)||
1224     ', IsTargetTable='||boolean_decode(pTable.IsTargetTable)||
1225     ', HasTargets='||boolean_decode(pTable.HasTargets)||
1226     ', UsedForTargets='||boolean_decode(pTable.UsedForTargets)||',impl_type='||pTable.impl_type||', measure_group='||pTable.measureGroup, pSeverity, pForce);
1227     writeTmp('   KeyName=', pSeverity, pForce);
1228 	--write_this(getAllKeyFields(pTable.Name), pSeverity, pForce);
1229 	write_this(pTable.keys, pSeverity, pForce);
1230     writeTmp('   Data=', pSeverity, pForce);
1231 	--write_this(getAllDataFields(pTable.name), pSeverity, pForce);
1232 	write_this(pTable.data, pSeverity, pForce);
1233     writeTmp('   originTable='||pTable.originTable, pSeverity, pForce);
1234     writeTmp('   originTable1='||pTable.originTable1, pSeverity, pForce);
1235     writeTmp('   dbObjectType='||pTable.dbObjectType||
1236         ', MVName = '||pTable.MVName||
1237         ', upgradeFlag = '||pTable.upgradeFlag||
1238         ', currentPeriod = '||pTable.currentPeriod||
1239         ', projectionTable = '||pTable.projectionTable, pSeverity, pForce);
1240   END IF;
1241 END;
1242 
1243 PROCEDURE write_this(
1244   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsTable,
1245   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1246   pForce IN boolean default false,
1247   pIgonoreProduction IN boolean default false)
1248   IS
1249 l_count NUMBER;
1250 l_table BSC_METADATA_OPTIMIZER_PKG.clsTable;
1251 BEGIN
1252   IF (pTable.count=0) THEN
1253     return;
1254   END IF;
1255   l_count := pTable.first;
1256   LOOP
1257     l_table := pTable(l_count);
1258     IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1259       IF pIgonoreProduction AND (l_table.isProductionTable and NOT l_table.isProductionTableAltered) THEN
1260         null;
1261       ELSE
1262         writeTmp(' ', FND_LOG.LEVEL_STATEMENT, pForce);
1263         write_this(l_table, l_count, pSeverity, pForce);
1264         writeTmp(' ', FND_LOG.LEVEL_STATEMENT, pForce);
1265       END IF;
1266     END IF;
1267     exit when l_count = pTable.last;
1268     l_count := pTable.next(l_count);
1269   END LOOP;
1270 END;
1271 
1272 
1273 PROCEDURE write_this(
1274   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsDisAggField,
1275   ind IN NUMBER default null,
1276   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1277   pForce IN boolean default false)
1278   IS
1279 l_count NUMBER;
1280 l_string VARCHAR2(30000);
1281 l_table BSC_METADATA_OPTIMIZER_PKG.clsDisAggField;
1282 BEGIN
1283   IF (pTable.count=0) THEN
1284     return;
1285   END IF;
1286   l_count := pTable.first;
1287   LOOP
1288     l_table := pTable(l_count);
1289     write_this(l_table, ind, pSeverity, pForce);
1290     exit when l_count = pTable.last;
1291     l_count := pTable.next(l_count);
1292   END LOOP;
1293 END;
1294 
1295 PROCEDURE write_this(
1296   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsDisAggField,
1297   ind IN NUMBER default null,
1298   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1299   pForce IN boolean default false)
1300   IS
1301 l_count NUMBER;
1302 l_string VARCHAR2(30000);
1303 BEGIN
1304   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1305     writeTmp(
1306 	' Code='||pTable.Code||', Periodicity ='||pTable.Periodicity||', Origin='||pTable.Origin||
1307     ', Registered='||boolean_decode(pTable.Registered)||', isProduction='||boolean_decode(pTable.isProduction), pSeverity, pForce);
1308     writeTmp('  disagg keys =', pSeverity, pForce);
1309     write_this(
1310 	  pTable.keys,
1311 	  pSeverity, pForce);
1312   END IF;
1313 END;
1314 
1315 
1316 PROCEDURE write_this(
1317   pTableName IN VARCHAR2,
1318   pFieldName IN VARCHAR2,
1319   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsDisAggField,
1320   ind IN NUMBER default null,
1321   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1322   pForce IN boolean default false) IS
1323 l_count NUMBER;
1324 l_string VARCHAR2(30000);
1325 BEGIN
1326   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1327     writeTmp('    '||ind||' Code='||pTable.Code||', Periodicity ='||pTable.Periodicity||', Origin='||pTable.Origin||
1328     ', Registered='||boolean_decode(pTable.Registered), pSeverity, pForce);
1329     writeTmp('  disagg keys =', pSeverity, pForce);
1330     write_this(
1331 	--getDisaggKeys(pTableName, pFieldName,  pTable.code),
1332 	pTable.keys,
1333 	pSeverity, pForce);
1334   END IF;
1335 
1336 END;
1337 
1338 PROCEDURE write_this(
1339   pTableName IN VARCHAR2,
1340   pFieldName IN VARCHAR2,
1341   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsDisAggField,
1342   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1343   pForce IN boolean default false)
1344   IS
1345 l_count NUMBER;
1346 l_table BSC_METADATA_OPTIMIZER_PKG.clsDisAggField;
1347 BEGIN
1348   IF (pTable.count=0) THEN
1349     return;
1350   END IF;
1351   l_count := pTable.first;
1352   LOOP
1353     l_table := pTable(l_count);
1354     write_this(pTableName, pFieldName, l_table, l_count, pSeverity, pForce);
1355     exit when l_count = pTable.last;
1356     l_count := pTable.next(l_count);
1357   END LOOP;
1358 END;
1359 
1360 
1361 PROCEDURE write_this(
1362   pTableName IN VARCHAR2,
1363   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsUniqueField,
1364   ind IN NUMBER default null,
1365   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1366   pForce IN boolean default false)
1367   IS
1368 l_count NUMBER;
1369 l_string VARCHAR2(30000);
1370 BEGIN
1371   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1372     writeTmp(ind||' field='||pTable.fieldName||', source='||pTable.source||', group='||pTable.measureGroup||', aggFunction ='||pTable.aggFunction||', EDW_Flag='||pTable.EDW_Flag||',impl_type='||pTable.impl_type||' key_combinations=', pSeverity, pForce);
1373     write_this(pTableName, pTable.fieldName,
1374       pTable.key_Combinations,
1375       pSeverity, pForce);
1376   END IF;
1377 END;
1378 
1379 PROCEDURE write_this(
1380   pTableName IN VARCHAR2,
1381   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsUniqueField,
1382   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1383   pForce IN boolean default false)
1384   IS
1385 l_count NUMBER;
1386 l_table BSC_METADATA_OPTIMIZER_PKG.clsUniqueField;
1387 BEGIN
1388   IF (pTable.count=0) THEN
1389     return;
1390   END IF;
1391   l_count := pTable.first;
1392   LOOP
1393     l_table := pTable(l_count);
1394     write_this(pTableName, l_table, l_count, pSeverity, pForce);
1395     exit when l_count = pTable.last;
1396     l_count := pTable.next(l_count);
1397   END LOOP;
1398 END;
1399 
1400 
1401 PROCEDURE write_this(
1402   pTable IN BSC_METADATA_OPTIMIZER_PKG.clsDBColumn,
1403   ind IN NUMBER default null,
1404   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1405   pForce IN boolean default false)
1406   IS
1407 l_count NUMBER;
1408 l_string VARCHAR2(30000);
1409 BEGIN
1410   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1411     writeTmp(ind||' columnName='||pTable.columnName||', columnTYPE ='||pTable.columnTYPE||', columnLength='||pTable.columnLength
1412     ||' isKey='||boolean_decode(pTable.isKey), pSeverity, pForce);
1413   END IF;
1414 END;
1415 
1416 PROCEDURE write_this(
1417   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsDBColumn,
1418   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1419   pForce IN boolean default false)
1420   IS
1421 l_count NUMBER;
1422 l_table BSC_METADATA_OPTIMIZER_PKG.clsDBColumn;
1423 BEGIN
1424   IF (pTable.count=0) THEN
1425     return;
1426   END IF;
1427   l_count := pTable.first;
1428   LOOP
1429     l_table := pTable(l_count);
1430     write_this(l_table, l_count, pSeverity, pForce);
1431     exit when l_count = pTable.last;
1432     l_count := pTable.next(l_count);
1433   END LOOP;
1434 END;
1435 PROCEDURE write_this(
1436   pTable IN BSC_METADATA_OPTIMIZER_PKG.TNewITables,
1437   ind IN NUMBER default null,
1438   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1439   pForce IN boolean default false)
1440   IS
1441 l_count NUMBER;
1442 l_string VARCHAR2(30000);
1443 BEGIN
1444   IF BSC_METADATA_OPTIMIZER_PKG.g_log or pForce THEN
1445     writeTmp(ind||' Name='||pTable.Name||', periodicity ='||pTable.periodicity||', numFields='||pTable.numFields
1446     ||', NumIndicators='||pTable.NumIndicators ||',  Fields='||pTable.Fields|| ',   Indicators='||pTable.Indicators, pSeverity, pForce);
1447   END IF;
1448 END;
1449 
1450 PROCEDURE write_this(
1451   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_TNewITables,
1452   pSeverity IN NUMBER DEFAULT FND_LOG.LEVEL_STATEMENT,
1453   pForce IN boolean default false)
1454   IS
1455 l_count NUMBER;
1456 l_table BSC_METADATA_OPTIMIZER_PKG.TNewITables;
1457 BEGIN
1458   IF (pTable.count=0) THEN
1459     return;
1460   END IF;
1461   l_count := pTable.first;
1462   LOOP
1463     l_table := pTable(l_count);
1464     write_this(l_table, l_count, pSeverity, pForce);
1465     exit when l_count = pTable.last;
1466     l_count := pTable.next(l_count);
1467   END LOOP;
1468 END;
1469 
1470 
1471 --****************************************************************************
1472 --  addTable
1473 --  DESCRIPTION:
1474 --     Adds the table to the collection gTables
1475 --  PARAMETERS:
1476 --     pTable: Table to be added to gTables
1477 --     proc: Procedure that calls this API
1478 --****************************************************************************
1479 
1480 PROCEDURE addTable (pTable IN BSC_METADATA_OPTIMIZER_PKG.clsTable,
1481       proc IN VARCHAR2) IS
1482   l_temp1 NUMBER;
1483   lTable BSC_METADATA_OPTIMIZER_PKG.clsTable;
1484   l_stack VARCHAR2(32000);
1485 BEGIN
1486   l_stack := 'Inside addTable for Table name = '||pTable.name||' called from '||proc|| ', gTables_counter='||BSC_METADATA_OPTIMIZER_PKG.gTables_counter;
1487   lTable := pTable;
1488   IF findIndex(BSC_METADATA_OPTIMIZER_PKG.gTables, lTable.name) >=0 THEN -- exists
1489       return;
1490   END IF;
1491   l_temp1 := BSC_METADATA_OPTIMIZER_PKG.gTables_counter;
1492   BSC_METADATA_OPTIMIZER_PKG.gTables(l_temp1) := lTable;
1493   l_stack := l_stack ||newline||'Adding gTables('||l_temp1||') = '||lTable.name;
1494   BSC_METADATA_OPTIMIZER_PKG.gTables_counter := BSC_METADATA_OPTIMIZER_PKG.gTables_counter + 1;
1495   EXCEPTION WHEN OTHERS THEN
1496       writeTmp('Exception in addTable : '||sqlerrm, FND_LOG.LEVEL_UNEXPECTED, true);
1497       BSC_MO_HELPER_PKG.write_this(pTable, 1, FND_LOG.LEVEL_UNEXPECTED, true);
1498       writeTmp('l_stack is  : '||l_stack, FND_LOG.LEVEL_UNEXPECTED, true);
1499       raise;
1500 END;
1501 
1502 --****************************************************************************
1503 --  addTable
1504 --  DESCRIPTION:
1505 --     Adds the table to the collection gTables and inserts keys and data
1506 --     into temp tables
1507 --  PARAMETERS:
1508 --     pTable: Table to be added to gTables
1509 --     pKeyFields: Keyfields for the table
1510 --     pData : Data fields for the table
1511 --****************************************************************************
1512 
1513 
1514 PROCEDURE addTable (pTable IN BSC_METADATA_OPTIMIZER_PKG.clsTable,
1515         pKeyFields IN OUT NOCOPY BSC_METADATA_OPTIMIZER_PKG.tab_clsKeyField,
1516         pData     IN OUT NOCOPY BSC_METADATA_OPTIMIZER_PKG.tab_clsDataField,
1517       proc IN VARCHAR2) IS
1518   l_temp1 NUMBER;
1519   lTable BSC_METADATA_OPTIMIZER_PKG.clsTable;
1520 BEGIN
1521 
1522   lTable := pTable;
1523   IF findIndex(BSC_METADATA_OPTIMIZER_PKG.gTables, lTable.name) >=0 THEN -- exists
1524       return;
1525   END IF;
1526    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1527    --BSC_MO_HELPER_PKG.writeTmp('Adding gTables thru PROC '||proc||
1528    --     ', gTables('||BSC_METADATA_OPTIMIZER_PKG.gTables_counter||') is '||lTable.name||' with Data = '||pData.count||', Keys='||pKeyFields.count, FND_LOG.LEVEL_STATEMENT);
1529      null;
1530    END IF;
1531 
1532   lTable.keys := pKeyFields;
1533   lTable.data := pData;
1534    BSC_METADATA_OPTIMIZER_PKG.gTables(BSC_METADATA_OPTIMIZER_PKG.gTables_counter) := lTable;
1535    BSC_METADATA_OPTIMIZER_PKG.gTables_counter := BSC_METADATA_OPTIMIZER_PKG.gTables_counter + 1;
1536 
1537   EXCEPTION WHEN OTHERS THEN
1538       writeTmp('Exception in addTable : '||sqlerrm, FND_LOG.LEVEL_UNEXPECTED, true);
1539       write_this(pTable, 1, FND_LOG.LEVEL_UNEXPECTED, true);
1540       writeTmp('keys are :' , FND_LOG.LEVEL_UNEXPECTED, true);
1541       write_this(pKeyFields, FND_LOG.LEVEL_UNEXPECTED, true);
1542       writeTmp('Data :', FND_LOG.LEVEL_UNEXPECTED, true );
1543       write_this(pData, FND_LOG.LEVEL_UNEXPECTED, true);
1544       raise;
1545 END;
1546 
1547 --****************************************************************************
1548 --  CalcProjectionTable
1549 --
1550 --  DESCRIPTION:
1551 --     Return true if the projection is calculated on the table
1552 --****************************************************************************
1553 
1554 Function CalcProjectionTable(TableName IN VARCHAR2) return BOOLEAN IS
1555 
1556 CURSOR C1(p1 VARCHAR2) IS
1557 SELECT PROJECT_FLAG FROM BSC_DB_TABLES
1558 WHERE TABLE_NAME = p1;
1559 l_proj NUMBER ;
1560 l_ret  boolean;
1561 
1562 l_error VARCHAR2(400);
1563 BEGIN
1564   OPEN C1( Upper(tablename));
1565   FETCH c1 INTO l_proj;
1566 
1567   IF (c1%NOTFOUND) THEN
1568       l_ret := FALSE;
1569   Else
1570       IF l_proj = 0 THEN
1571         l_ret := false;
1572       Else
1573         l_ret := true;
1574       End IF;
1575   End IF;
1576 
1577   CLOSE c1;
1578   return l_ret;
1579       EXCEPTION WHEN OTHERS THEN
1580       l_error := sqlerrm;
1581       writeTmp('Exception in CalcProjectionTable for table= '||TableName||', Exception is :' ||l_error,
1582 		FND_LOG.LEVEL_EXCEPTION, true);
1583       raise;
1584 End;
1585 
1586 
1587 --****************************************************************************
1588 --  WriteInfoMatrix : EscribirMatrixInfo
1589 --
1590 --  DESCRIPTION:
1591 --     Write the given variable of the given indicator in BSC_KPI_PROPERTIES
1592 --     table.
1593 --
1594 --  PARAMETERS:
1595 --     Indic: indicator code
1596 --     Variable: variable name
1597 --     Valor: value
1598 --     db_obj: database
1599 --****************************************************************************
1600 PROCEDURE WriteInfoMatrix(Indic IN NUMBER, Variable IN VARCHAR2, Valor IN NUMBER) IS
1601 
1602   CURSOR C1 IS
1603   SELECT PROPERTY_CODE FROM BSC_KPI_PROPERTIES
1604   WHERE INDICATOR = Indic
1605   AND UPPER(PROPERTY_CODE) = UPPER(Variable);
1606   l_Value varchar2(20);
1607   l_error VARCHAR2(400);
1608 BEGIN
1609 
1610 
1611   OPEN c1;
1612   FETCH c1 INTO l_VALUE;
1613 
1614   IF c1%FOUND THEN
1615       UPDATE BSC_KPI_PROPERTIES SET PROPERTY_VALUE = Valor
1616           WHERE INDICATOR = Indic AND PROPERTY_CODE = Variable;
1617 
1618   Else
1619       INSERT INTO BSC_KPI_PROPERTIES (INDICATOR, PROPERTY_CODE, PROPERTY_VALUE)
1620           VALUES(Indic, Variable, Valor);
1621   End IF;
1622   Close c1;
1623 
1624   EXCEPTION WHEN OTHERS THEN
1625       l_error := sqlerrm;
1626       writeTmp('Exception in WriteInfoMatrix for Indic = '||indic||', variable = '||variable||', value = '||valor||' :'||l_error,
1627 		FND_LOG.LEVEL_EXCEPTION, true);
1628       raise;
1629 End ;
1630 
1631 --****************************************************************************
1632 --  SaveOptimizationMode: GuardarOptimizationMode
1633 --
1634 --   DESCRIPTION:
1635 --    Write in BSC_KPI_PROPERTIES the Optimization Mode of the kpis
1636 --
1637 --****************************************************************************
1638 
1639 PROCEDURE SaveOptimizationMode IS
1640   i NUMBER;
1641   l_error VARCHAR2(400);
1642 BEGIN
1643    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1644   BSC_MO_HELPER_PKG.writeTmp('Inside SaveOptimizationMode');
1645    END IF;
1646 
1647   IF (BSC_METADATA_OPTIMIZER_PKG.gINdicators.count = 0) THEN
1648       return;
1649   END IF;
1650 
1651   i := BSC_METADATA_OPTIMIZER_PKG.gIndicators.first;
1652 
1653   LOOP
1654       IF BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag <> 2 THEN
1655         --This is not a deleted Kpi
1656         WriteInfoMatrix(BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code, 'DB_TRANSFORM', BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).OptimizationMode);
1657       End IF;
1658       EXIT WHEN i = BSC_METADATA_OPTIMIZER_PKG.gIndicators.last;
1659       i := BSC_METADATA_OPTIMIZER_PKG.gIndicators.next(i);
1660   END LOOP;
1661    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1662   BSC_MO_HELPER_PKG.writeTmp('Completed SaveOptimizationMode');
1663    END IF;
1664 
1665 
1666   EXCEPTION WHEN OTHERS THEN
1667       l_error := sqlerrm;
1668       writeTmp('Exception in SaveOptimizationMode:'||l_error, FND_LOG.LEVEL_EXCEPTION, true);
1669       raise;
1670 
1671 END;
1672 
1673 --****************************************************************************
1674 --  table_column_exists
1675 --
1676 --  DESCRIPTION:
1677 --     Returns TRUE if the given column exists in the table.
1678 --
1679 --  PARAMETERS:
1680 --     Table: table name
1681 --     Column: column name
1682 --****************************************************************************
1683 Function table_column_exists(p_table IN VARCHAR2, p_Column IN VARCHAR2) RETURN boolean IS
1684   l_res boolean := false;
1685   l_table VARCHAR2(100);
1686   CURSOR c1 (p3 VARCHAR2) IS
1687   SELECT TABLE_NAME FROM ALL_TAB_COLUMNS
1688   WHERE TABLE_NAME = p_table AND COLUMN_NAME = upper(p_column) AND OWNER = p3;
1689   l_error VARCHAR2(400);
1690 BEGIN
1691    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1692   BSC_MO_HELPER_PKG.writeTmp('Inside table_column_exists', FND_LOG.LEVEL_STATEMENT);
1693    END IF;
1694 
1695   OPEN C1(UPPER(BSC_METADATA_OPTIMIZER_PKG.gBSCSchema));
1696   FETCH c1 INTO l_table;
1697   IF (c1%FOUND) THEN
1698       CLOSE c1;
1699    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1700       BSC_MO_HELPER_PKG.writeTmp('Completed table_column_exists, returning TRUE', FND_LOG.LEVEL_STATEMENT);
1701    END IF;
1702 
1703       return true;
1704   END IF;
1705   CLOSE c1;
1706    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1707   BSC_MO_HELPER_PKG.writeTmp('Completed table_column_exists, returning FALSE', FND_LOG.LEVEL_STATEMENT);
1708    END IF;
1709 
1710   return false;
1711   EXCEPTION WHEN OTHERS THEN
1712       l_error := sqlerrm;
1713       writeTmp('Exception in table_column_exists: '||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
1714       raise;
1715 End ;
1716 
1717 
1718 --****************************************************************************
1719 --  get_lookup_value
1720 --
1721 --  DESCRIPTION:
1722 --     Returns lookup value from fnd_lookup_values_vl
1723 --
1724 --  PARAMETERS:
1725 --     p_lookup_type: Lookup Type
1726 --     p_lookup_code: Lookup Code
1727 --****************************************************************************
1728 FUNCTION get_lookup_value(p_lookup_type IN VARCHAR2, p_lookup_code  IN VARCHAR2) return VARCHAR2 IS
1729 
1730 CURSOR c1 IS
1731 SELECT MEANING
1732 FROM fnd_lookup_values_vl
1733 WHERE LOOKUP_TYPE = p_lookup_type
1734 AND LOOKUP_CODE = p_lookup_code;
1735 
1736 l_val VARCHAR2(1000);
1737 BEGIN
1738   IF gLookup_value.exists(p_lookup_type||p_lookup_code) THEN
1739     return gLookup_value(p_lookup_type||p_lookup_code).value;
1740   ELSE
1741     OPEN C1;
1742     FETCH C1 INTO l_val;
1743     cLOSE c1;
1744     gLookup_value(p_lookup_type||p_lookup_code).value := l_val;
1745   END IF;
1746   return l_val;
1747 END;
1748 
1749 
1750 --****************************************************************************
1751 --  FindIndex
1752 --  DESCRIPTION:
1753 --     Returns position of the value within the array
1754 --  PARAMETERS:
1755 --     arrNum: Array to be searched
1756 --     num: Value to be searched within the array
1757 --****************************************************************************
1758 Function FindIndex(arrNum IN dbms_sql.NUMBER_TABLE, num IN NUMBER) RETURN NUMBER IS
1759   l_count Number := 0;
1760 BEGIN
1761 
1762   l_count := arrNum.Count;
1763   if l_count =0 then
1764 	   return -1;
1765   END IF;
1766 
1767   l_count := arrNum.first;
1768   LOOP
1769       IF (arrNum(l_count) = num) THEN
1770         return l_count;
1771       END IF;
1772  	  EXIT WHEN l_count = arrNum.Last;
1773 	  l_count := arrNum.next(l_count);
1774   END LOOP;
1775   return -1;
1776 END;
1777 
1778 --***************************************************************************
1779 -- Find Index
1780 --
1781 --  DESCRIPTION:
1782 --    Returns the index on the array arrStr() where the given string is
1783 --     found. Returns -1 if it is not found.
1784 --
1785 --  PARAMETERS:
1786 --     ArrStr : array
1787 --     str: string to look for
1788 --***************************************************************************
1789 
1790 Function FindIndexVARCHAR2(arrStr IN dbms_sql.varchar2_table, str in varchar2) return NUMBER IS
1791   i NUMBER :=0;
1792 BEGIN
1793 
1794   IF (arrStr.count =0) THEN
1795 	   return -1;
1796   END IF;
1797 
1798   i:= arrStr.first;
1799 
1800   LOOP
1801       IF UPPER(arrStr(i)) = UPPER(str) THEN
1802         return i;
1803       END IF;
1804 	EXIT WHEN i = arrStr.last;
1805 	i := arrStr.next(i);
1806   END LOOP;
1807   return -1;
1808 End;
1809 
1810 --***************************************************************************
1811 -- Find Index
1812 --
1813 --  DESCRIPTION:
1814 --    Returns the index on the array arrStr() where the given string is
1815 --     found. Returns -1 if it is not found.
1816 --
1817 --  PARAMETERS:
1818 --     ArrStr : array
1819 --     str: string to look for
1820 --***************************************************************************
1821 
1822 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsKeyField,  findThis in varchar2)
1823 return NUMBER IS
1824   i NUMBER :=0;
1825 BEGIN
1826   IF (arrStr.count =0) THEN
1827    	return -1;
1828   END IF;
1829   i:= arrStr.first;
1830 
1831   LOOP
1832       IF (UPPER(arrStr(i).keyName) = UPPER(findThis) )THEN
1833         return i;
1834       END IF;
1835 	EXIT WHEN i = arrStr.last;
1836 	i := arrStr.next(i);
1837   END LOOP;
1838   return -1;
1839 End;
1840 
1841 --***************************************************************************
1842 -- Find Index
1843 --
1844 --  DESCRIPTION:
1845 --    Returns the index on the array arrStr() where the given string is
1846 --     found. Returns -1 if it is not found.
1847 --
1848 --  PARAMETERS:
1849 --     ArrStr : array
1850 --     str: string to look for
1851 --***************************************************************************
1852 
1853 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevels,  findThis in varchar2)
1854 return NUMBER IS
1855   i NUMBER :=0;
1856 BEGIN
1857   IF (arrStr.count =0) THEN
1858    	return -1;
1859   END IF;
1860   i:= arrStr.first;
1861 
1862   LOOP
1863       IF (UPPER(arrStr(i).keyName) = UPPER(findThis) )THEN
1864         return i;
1865       END IF;
1866 	EXIT WHEN i = arrStr.last;
1867 	i := arrStr.next(i);
1868   END LOOP;
1869   return -1;
1870 End;
1871 
1872 
1873 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsMasterTable, findThis in varchar2) return NUMBER IS
1874   i NUMBER :=0;
1875 BEGIN
1876   i := arrStr.count;
1877   IF (i =0) THEN
1878       RETURN -1;
1879   END IF;
1880   i:= arrStr.first;
1881   LOOP
1882       IF UPPER(arrStr(i).Name) = UPPER(findThis) THEN
1883         return i;
1884       END IF;
1885 	EXIT WHEN i= arrStr.last;
1886 	i:= arrStr.next(i);
1887   END LOOP;
1888   return -1;
1889 End;
1890 
1891 Function FindKeyIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsMasterTable, keyName in varchar2) return NUMBER IS
1892   i NUMBER :=0;
1893 BEGIN
1894   i := arrStr.count;
1895   IF (i =0) THEN
1896       RETURN -1;
1897   END IF;
1898   i:= arrStr.first;
1899   LOOP
1900       IF UPPER(arrStr(i).keyName) = UPPER(keyName) THEN
1901         return i;
1902       END IF;
1903 	  EXIT WHEN i= arrStr.last;
1904 	  i:= arrStr.next(i);
1905   END LOOP;
1906   return -1;
1907 End;
1908 
1909 
1910 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsTable, findThis in varchar2) return NUMBER IS
1911   i NUMBER :=0;
1912 BEGIN
1913   i := arrStr.count;
1914 
1915   IF (i =0) THEN
1916    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
1917       writetmp('Done with FindIndex for tab_clsTable, zero count, returning -1, findThis = '||findThis);
1918    END IF;
1919 
1920       RETURN -1;
1921   END IF;
1922 
1923   i:= arrStr.first;
1924 
1925   LOOP
1926       IF UPPER(arrStr(i).Name) = UPPER(findThis) THEN
1927         return i;
1928       END IF;
1929 	EXIT WHEN i= arrStr.last;
1930 	i:= arrStr.next(i);
1931   END LOOP;
1932   return -1;
1933 End;
1934 
1935 
1936 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsBasicTable, findThis in varchar2) return NUMBER IS
1937   i NUMBER :=0;
1938 BEGIN
1939   i := arrStr.count;
1940   IF (i =0) THEN
1941       RETURN -1;
1942   END IF;
1943   i:= arrStr.first;
1944 
1945   LOOP
1946       IF UPPER(arrStr(i).Name) = UPPER(findThis) THEN
1947         return i;
1948       END IF;
1949 	   EXIT WHEN i= arrStr.last;
1950 	   i:= arrStr.next(i);
1951   END LOOP;
1952   return -1;
1953 End;
1954 
1955 
1956 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsIndicator, findThis in number) return NUMBER IS
1957   i NUMBER :=0;
1958 BEGIN
1959 
1960   i := arrStr.count;
1961 
1962   IF (i =0) THEN RETURN -1;
1963   END IF;
1964 
1965   i:= arrStr.first;
1966 
1967   LOOP
1968       IF arrStr(i).code = findThis THEN
1969         return i;
1970       END IF;
1971 	EXIT WHEN i= arrStr.last;
1972 	i:= arrStr.next(i);
1973   END LOOP;
1974   return -1;
1975 End;
1976 
1977 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsUniqueField,  findThis in varchar2, p_source IN VARCHAR2, p_impl_type IN NUMBER)
1978 return NUMBER IS
1979   i NUMBER :=0;
1980 BEGIN
1981   IF (arrStr.count =0) THEN
1982    	return -1;
1983   END IF;
1984   i:= arrStr.first;
1985   LOOP
1986     IF (UPPER(arrStr(i).fieldName) = UPPER(findThis)
1987 	    AND arrStr(i).impl_type = p_impl_type
1988 	    --BSC Autogen
1989 		AND arrStr(i).source = p_source) THEN
1990       return i;
1991     END IF;
1992 	EXIT WHEN i = arrStr.last;
1993 	i := arrStr.next(i);
1994   END LOOP;
1995   return -1;
1996 End;
1997 
1998 
1999 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsDisaggField,  findThis in NUMBER)
2000 return NUMBER IS
2001   i NUMBER :=0;
2002 BEGIN
2003   IF (arrStr.count =0) THEN
2004    	return -1;
2005   END IF;
2006   i:= arrStr.first;
2007 
2008   LOOP
2009       IF (arrStr(i).code = findThis)THEN
2010         return i;
2011       END IF;
2012 	EXIT WHEN i = arrStr.last;
2013 	i := arrStr.next(i);
2014   END LOOP;
2015   return -1;
2016 End;
2017 
2018 --BSC Autogen
2019 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsMeasureLOV,  findThis in VARCHAR2, p_source IN VARCHAR2, pIgnoreCase In Boolean)
2020 return NUMBER IS
2021   i NUMBER :=0;
2022   l_findThis VARCHAR2(100);
2023 BEGIN
2024   IF (arrStr.count =0) THEN
2025    	return -1;
2026   END IF;
2027   i:= arrStr.first;
2028   IF (pIgnoreCase) THEN
2029       l_findThis := UPPER(findThis);
2030       LOOP
2031         IF (UPPER(arrStr(i).fieldName) = l_findThis
2032             --BSC Autogen
2033 		    AND arrStr(i).source=p_source)THEN
2034           return i;
2035         END IF;
2036   	EXIT WHEN i = arrStr.last;
2037   	i := arrStr.next(i);
2038       END LOOP;
2039   ELSE
2040       LOOP
2041         IF (arrStr(i).fieldName = findThis
2042             --BSC Autogen
2043 		    AND arrStr(i).source=p_source)THEN
2044           return i;
2045         END IF;
2046   	EXIT WHEN i = arrStr.last;
2047   	i := arrStr.next(i);
2048       END LOOP;
2049   END IF;
2050   return -1;
2051 End;
2052 
2053 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsPeriodicity, findThis in NUMBER) return NUMBER  IS
2054 i NUMBER;
2055 l_error VARCHAR2(4000);
2056 BEGIN
2057   IF (arrStr.count =0) THEN
2058    	return -1;
2059   END IF;
2060   i:= arrStr.first;
2061 
2062   LOOP
2063       IF (arrStr(i).code = findThis)THEN
2064         return i;
2065       END IF;
2066 	EXIT WHEN i = arrStr.last;
2067 	i := arrStr.next(i);
2068   END LOOP;
2069   return -1;
2070 
2071   EXCEPTION WHEN OTHERS THEN
2072 
2073       writeTmp('Exception in FindIndex for tab_clsPeriodicity', FND_LOG.LEVEL_STATEMENT, true);
2074       l_error := sqlerrm;
2075       writeTmp('Exception is '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
2076       raise;
2077 End;
2078 
2079 Function FindIndex(arrStr IN BSC_METADATA_OPTIMIZER_PKG.tab_clsCalendar, findThis in NUMBER) return NUMBER  IS
2080 i NUMBER;
2081 BEGIN
2082   IF (arrStr.count =0) THEN
2083    	return -1;
2084   END IF;
2085   i:= arrStr.first;
2086 
2087   LOOP
2088       IF (arrStr(i).Code = findThis)THEN
2089         return i;
2090       END IF;
2091 	EXIT WHEN i = arrStr.last;
2092 	i := arrStr.next(i);
2093   END LOOP;
2094   return -1;
2095 End;
2096 
2097 --***************************************************************************
2098 -- new_clsUniqueField
2099 --
2100 --  DESCRIPTION:
2101 --    Returns an unitialized variable of class clsUniqueField.
2102 --    This is to clear up the memory of the object it is assigned to.
2103 --***************************************************************************
2104 
2105 FUNCTION new_clsUniqueField return BSC_METADATA_OPTIMIZER_PKG.clsUniqueField IS
2106 l_new BSC_METADATA_OPTIMIZER_PKG.clsUniqueField ;
2107 BEGIn
2108   return l_new;
2109 END;
2110 
2111 --***************************************************************************
2112 -- new_clsTable
2113 --
2114 --  DESCRIPTION:
2115 --    Returns an unitialized variable of class clsTable.
2116 --    This is to clear up the memory of the object it is assigned to.
2117 --***************************************************************************
2118 
2119 FUNCTION new_clsTable return BSC_METADATA_OPTIMIZER_PKG.clsTable IS
2120 l_new BSC_METADATA_OPTIMIZER_PKG.clsTable ;
2121 BEGIn
2122   l_new.isProductionTable := false;
2123   return l_new;
2124 END;
2125 
2126 --***************************************************************************
2127 -- new_clsDataField
2128 --
2129 --  DESCRIPTION:
2130 --    Returns an unitialized variable of class clsDataField.
2131 --    This is to clear up the memory of the object it is assigned to.
2132 --***************************************************************************
2133 FUNCTION new_clsDataField return BSC_METADATA_OPTIMIZER_PKG.clsDataField IS
2134 l_new BSC_METADATA_OPTIMIZER_PKG.clsDataField ;
2135 BEGIn
2136   return l_new;
2137 END;
2138 
2139 --***************************************************************************
2140 -- new_clsDisAggField
2141 --
2142 --  DESCRIPTION:
2143 --    Returns an unitialized variable of class clsDisAggField.
2144 --    This is to clear up the memory of the object it is assigned to.
2145 --***************************************************************************
2146 FUNCTION new_clsDisAggField return BSC_METADATA_OPTIMIZER_PKG.clsDisAggField IS
2147 l_new BSC_METADATA_OPTIMIZER_PKG.clsDisAggField ;
2148 BEGIn
2149   return l_new;
2150 END;
2151 --***************************************************************************
2152 -- new_clsKeyField
2153 --
2154 --  DESCRIPTION:
2155 --    Returns an unitialized variable of class clsKeyField.
2156 --    This is to clear up the memory of the object it is assigned to.
2157 --***************************************************************************
2158 FUNCTION new_clsKeyField return BSC_METADATA_OPTIMIZER_PKG.clsKeyField IS
2159 l_new BSC_METADATA_OPTIMIZER_PKG.clsKeyField ;
2160 BEGIn
2161   return l_new;
2162 END;
2163 
2164 --***************************************************************************
2165 -- new_clsOriginTable
2166 --
2167 --  DESCRIPTION:
2168 --    Returns an unitialized variable of class clsOriginTable.
2169 --    This is to clear up the memory of the object it is assigned to.
2170 --***************************************************************************
2171 FUNCTION new_clsOriginTable return BSC_METADATA_OPTIMIZER_PKG.clsOriginTable IS
2172 l_new BSC_METADATA_OPTIMIZER_PKG.clsOriginTable ;
2173 BEGIn
2174   return l_new;
2175 END;
2176 --***************************************************************************
2177 -- new_clsDBColumn
2178 --
2179 --  DESCRIPTION:
2180 --    Returns an unitialized variable of class clsDBColumn.
2181 --    This is to clear up the memory of the object it is assigned to.
2182 --***************************************************************************
2183 FUNCTION new_clsDBColumn return BSC_METADATA_OPTIMIZER_PKG.clsDBColumn IS
2184 l_new BSC_METADATA_OPTIMIZER_PKG.clsDBColumn ;
2185 BEGIn
2186   return l_new;
2187 END;
2188 
2189 --***************************************************************************
2190 -- new_clsMeasureLOV
2191 --
2192 --  DESCRIPTION:
2193 --    Returns an unitialized variable of class clsMeasureLOV.
2194 --    This is to clear up the memory of the object it is assigned to.
2195 --***************************************************************************
2196 FUNCTION new_clsMeasureLOV return BSC_METADATA_OPTIMIZER_PKG.clsMeasureLOV IS
2197 l_new BSC_METADATA_OPTIMIZER_PKG.clsMeasureLOV ;
2198 BEGIn
2199   return l_new;
2200 END;
2201 --***************************************************************************
2202 -- new_clsPeriodicity
2203 --
2204 --  DESCRIPTION:
2205 --    Returns an unitialized variable of class clsPeriodicity.
2206 --    This is to clear up the memory of the object it is assigned to.
2207 --***************************************************************************
2208 FUNCTION new_clsPeriodicity return BSC_METADATA_OPTIMIZER_PKG.clsPeriodicity IS
2209 l_new BSC_METADATA_OPTIMIZER_PKG.clsPeriodicity;
2210 BEGIn
2211   return l_new;
2212 END;
2213 --***************************************************************************
2214 -- new_clsCalendar
2215 --
2216 --  DESCRIPTION:
2217 --    Returns an unitialized variable of class clsCalendar.
2218 --    This is to clear up the memory of the object it is assigned to.
2219 --***************************************************************************
2220 FUNCTION new_clsCalendar return BSC_METADATA_OPTIMIZER_PKG.clsCalendar IS
2221 l_new BSC_METADATA_OPTIMIZER_PKG.clsCalendar;
2222 BEGIn
2223   return l_new;
2224 END;
2225 --***************************************************************************
2226 -- new_clsMasterTable
2227 --
2228 --  DESCRIPTION:
2229 --    Returns an unitialized variable of class clsMasterTable.
2230 --    This is to clear up the memory of the object it is assigned to.
2231 --***************************************************************************
2232 FUNCTION new_clsMasterTable return BSC_METADATA_OPTIMIZER_PKG.clsMasterTable IS
2233 l_new BSC_METADATA_OPTIMIZER_PKG.clsMasterTable;
2234 BEGIn
2235   return l_new;
2236 END;
2237 --***************************************************************************
2238 -- new_clsLevels
2239 --
2240 --  DESCRIPTION:
2241 --    Returns an unitialized variable of class clsLevels.
2242 --    This is to clear up the memory of the object it is assigned to.
2243 --***************************************************************************
2244 FUNCTION new_clsLevels return BSC_METADATA_OPTIMIZER_PKG.clsLevels IS
2245 l_new BSC_METADATA_OPTIMIZER_PKG.clsLevels;
2246 BEGIn
2247   return l_new;
2248 END;
2249 --***************************************************************************
2250 -- new_tabrec_clsLevels
2251 --
2252 --  DESCRIPTION:
2253 --    Returns an unitialized variable of class tabrec_clsLevels.
2254 --    This is to clear up the memory of the object it is assigned to.
2255 --***************************************************************************
2256 FUNCTION new_tabrec_clsLevels return BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevels IS
2257 l_new BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevels;
2258 BEGIn
2259   return l_new;
2260 END;
2261 --***************************************************************************
2262 -- new_clsBasicTable
2263 --
2264 --  DESCRIPTION:
2265 --    Returns an unitialized variable of class clsBasicTable.
2266 --    This is to clear up the memory of the object it is assigned to.
2267 --***************************************************************************
2268 FUNCTION new_clsBasicTable return BSC_METADATA_OPTIMIZER_PKG.clsBasicTable IS
2269 l_new BSC_METADATA_OPTIMIZER_PKG.clsBasicTable;
2270 BEGIn
2271   return l_new;
2272 END;
2273 --***************************************************************************
2274 -- new_clsLevelCombinations
2275 --
2276 --  DESCRIPTION:
2277 --    Returns an unitialized variable of class clsLevelCombinations.
2278 --    This is to clear up the memory of the object it is assigned to.
2279 --***************************************************************************
2280 FUNCTION new_clsLevelCombinations return BSC_METADATA_OPTIMIZER_PKG.clsLevelCombinations IS
2281 l_new BSC_METADATA_OPTIMIZER_PKG.clsLevelCombinations;
2282 BEGIn
2283   return l_new;
2284 END;
2285 --***************************************************************************
2286 -- new_TNewITables
2287 --
2288 --  DESCRIPTION:
2289 --    Returns an unitialized variable of class TNewITables.
2290 --    This is to clear up the memory of the object it is assigned to.
2291 --***************************************************************************
2292 FUNCTION new_TNewITables return BSC_METADATA_OPTIMIZER_PKG.TNewITables IS
2293 l_new BSC_METADATA_OPTIMIZER_PKG.TNewITables;
2294 BEGIn
2295   return l_new;
2296 END;
2297 
2298 --****************************************************************************
2299 --  InitArrReservedWords
2300 --
2301 --  DESCRIPTION:
2302 --     Initialize the array of reserved words
2303 --
2304 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
2305 --     Arun Santhanam 09 July 2003
2306 --****************************************************************************
2307 
2308 PROCEDURE InitArrReservedWords IS
2309 BEGIN
2310    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
2311   BSC_MO_HELPER_PKG.writeTmp('Inside InitArrReservedWords', FND_LOG.LEVEL_PROCEDURE);
2312    END IF;
2313 
2314   BSC_METADATA_OPTIMIZER_PKG.gNumArrReservedWords := 556;
2315 
2316   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(0) := 'ABORT';
2317   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(1) := 'ACCESS';
2318   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(2) := 'ACCOUNT';
2319   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(3) := 'ACCEPT';
2320   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(4) := 'ACCESS';
2321   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(5) := 'ACTIVATE';
2322   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(6) := 'ADD';
2323   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(7) := 'ADMIN';
2324   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(8) := 'AFTER';
2325   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(9) := 'ALL';
2326   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(10) := 'ALL_ROWS';
2327   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(11) := 'ALLOCATE';
2328   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(12) := 'ALTER';
2329   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(13) := 'ANALYZE';
2330   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(14) := 'AND';
2331   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(15) := 'ANY';
2332   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(16) := 'ARCHIVE';
2333   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(17) := 'ARCHIVELOG';
2334   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(18) := 'ARRAY';
2335   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(19) := 'ARRAYLEN';
2336   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(20) := 'AS';
2337   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(21) := 'ASC';
2338   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(22) := 'ASSERT';
2339   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(23) := 'ASSIGN';
2340   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(24) := 'AT';
2341   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(25) := 'AUDIT';
2342   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(26) := 'AUTHENTICATED';
2343   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(27) := 'AUTHORIZATION';
2344   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(28) := 'AUTOEXTEND';
2345   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(29) := 'AUTOMATIC';
2346   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(30) := 'AVG';
2347   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(31) := 'BACKUP';
2348   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(32) := 'BASE_TABLE';
2349   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(33) := 'BECOME';
2350   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(34) := 'BEFORE';
2351   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(35) := 'BEGIN';
2352   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(36) := 'BETWEEN';
2353   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(37) := 'BFILE';
2354   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(38) := 'BIGINTBY';
2355   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(39) := 'BINARY';
2356   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(40) := 'BINARY_INTEGER';
2357   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(41) := 'BIT';
2358   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(42) := 'BITMAP';
2359   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(43) := 'BLOB';
2360   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(44) := 'BLOCK';
2361   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(45) := 'BODY';
2362   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(46) := 'BOOLEAN';
2363   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(47) := 'BY';
2364   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(48) := 'CACHE';
2365   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(49) := 'CACHE_INSTANCES';
2366   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(50) := 'CANCEL';
2367   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(51) := 'CASCADE';
2368   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(52) := 'CASE';
2369   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(53) := 'CAST';
2370   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(54) := 'CFILE';
2371   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(55) := 'CHAINED';
2372   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(56) := 'CHANGE';
2373   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(57) := 'CHAR';
2374   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(58) := 'CHAR_BASE';
2375   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(59) := 'CHAR_CS';
2376   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(60) := 'CHARACTER';
2377   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(61) := 'CHARACTERS';
2378   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(62) := 'CHECK';
2379   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(63) := 'CHECKPOINT';
2380   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(64) := 'CHOOSE';
2381   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(65) := 'CHUNK';
2382   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(66) := 'CLEAR';
2383   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(67) := 'CLOB';
2384   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(68) := 'CLONE';
2385   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(69) := 'CLOSE';
2386   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(70) := 'CLOSED_CACHED_OPEN_';
2387   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(71) := 'CLUSTER';
2388   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(72) := 'CLUSTERS';
2389   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(73) := 'COALESCE';
2390   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(74) := 'COLAUTH';
2391   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(75) := 'COLUMN';
2392   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(76) := 'COLUMNS';
2393   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(77) := 'COMMENT';
2394   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(78) := 'COMMIT';
2395   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(79) := 'COMMITTED';
2396   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(80) := 'COMPATIBILITY';
2397   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(81) := 'COMPILE';
2398   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(82) := 'COMPLETE';
2399   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(83) := 'COMPOSITE_LIMIT';
2400   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(84) := 'COMPRESS';
2401   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(85) := 'COMPUTE';
2402   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(86) := 'CONNECT';
2403   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(87) := 'CONNECT_TIME';
2404   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(88) := 'CONNECTCREATE';
2405   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(89) := 'CONSTANT';
2406   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(90) := 'CONSTRAINT';
2407   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(91) := 'CONSTRAINTS';
2408   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(92) := 'CONTENTS';
2409   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(93) := 'CONTINUE';
2410   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(94) := 'CONTROLFILE';
2411   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(95) := 'CONVERT';
2412   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(96) := 'COST';
2413   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(97) := 'COUNT';
2414   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(98) := 'CPU_PER_CALL';
2415   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(99) := 'CPU_PER_SESSION';
2416   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(100) := 'CRASH';
2417   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(101) := 'CREATE';
2418   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(102) := 'CURRENT';
2419   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(103) := 'CURRENT_SCHEMA';
2420   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(104) := 'CURRENT_USER';
2421   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(105) := 'CURRVAL';
2422   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(106) := 'CURSOR';
2423   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(107) := 'CURSORS';
2424   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(108) := 'CYCLE';
2425   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(109) := 'DANGLING';
2426   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(110) := 'DATA_BASE';
2427   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(111) := 'DATABASE';
2428   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(112) := 'DATABASEDATE';
2429   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(113) := 'DATAFILE';
2430   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(114) := 'DATAFILES';
2431   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(115) := 'DATAOBJNO';
2432   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(116) := 'DATE';
2433   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(117) := 'DBA';
2434   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(118) := 'DEALLOCATE';
2435   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(119) := 'DEBUG';
2436   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(120) := 'DEBUGOFF';
2437   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(121) := 'DEBUGON';
2438   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(122) := 'DEC';
2439   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(123) := 'DECIMAL';
2440   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(124) := 'DECLARE';
2441   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(125) := 'DEFAULT';
2442   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(126) := 'DEFERRABLE';
2443   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(127) := 'DEFERRED';
2444   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(128) := 'DEFINITION';
2445   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(129) := 'DEGREE';
2446   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(130) := 'DELAY';
2447   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(131) := 'DELETE';
2448   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(132) := 'DEREF';
2449   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(133) := 'DESC';
2450   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(134) := 'DIGITS';
2451   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(135) := 'DIRECTORY';
2452   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(136) := 'DISABLE';
2453   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(137) := 'DISCONNECT';
2454   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(138) := 'DISMOUNT';
2455   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(139) := 'DISPOSE';
2456   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(140) := 'DISTINCT';
2457   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(141) := 'DISTRIBUTED';
2458   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(142) := 'DML';
2459   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(143) := 'DO';
2460   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(144) := 'DOUBLE';
2461   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(145) := 'DROP';
2462   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(146) := 'DUMP';
2463   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(147) := 'EACH';
2464   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(148) := 'ELSE';
2465   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(149) := 'ELSIF';
2466   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(150) := 'ENABLE';
2467   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(151) := 'END';
2468   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(152) := 'ENFORCE';
2469   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(153) := 'ENTRY';
2470   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(154) := 'ESCAPE';
2471   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(155) := 'ESTIMATE';
2472   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(156) := 'EVENTS';
2473   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(157) := 'EXCEPTION';
2474   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(158) := 'EXCEPTION_INIT';
2475   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(159) := 'EXCEPTIONS';
2476   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(160) := 'EXCHANGE';
2477   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(161) := 'EXCLUDING';
2478   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(162) := 'EXCLUSIVE';
2479   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(163) := 'EXECUTE';
2480   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(164) := 'EXEMPT';
2481   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(165) := 'EXISTS';
2482   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(166) := 'EXIT';
2483   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(167) := 'EXPIRE';
2484   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(168) := 'EXPLAIN';
2485   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(169) := 'EXTENT';
2486   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(170) := 'EXTENTS';
2487   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(171) := 'EXTERNALLY';
2488   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(172) := 'FAILED_LOGIN_ATTEMPTS';
2489   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(173) := 'FALSE';
2490   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(174) := 'FAST';
2491   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(175) := 'FETCH';
2492   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(176) := 'FILE';
2493   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(177) := 'FIRST_ROWS';
2494   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(178) := 'FLAGGER';
2495   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(179) := 'FLOAT';
2496   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(180) := 'FLUSH';
2497   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(181) := 'FOR';
2498   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(182) := 'FORCE';
2499   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(183) := 'FOREIGN';
2500   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(184) := 'FORM';
2501   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(185) := 'FREELIST';
2502   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(186) := 'FREELISTS';
2503   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(187) := 'FROM';
2504   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(188) := 'FULL';
2505   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(189) := 'FUNCTION';
2506   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(190) := 'GENERIC';
2507   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(191) := 'GLOBAL';
2508   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(192) := 'GLOBAL_NAME';
2509   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(193) := 'GLOBALLY';
2510   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(194) := 'GOTO';
2511   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(195) := 'GRANT';
2512   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(196) := 'GROUP';
2513   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(197) := 'GROUPS';
2514   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(198) := 'HASH';
2515   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(199) := 'HASHKEYS';
2516   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(200) := 'HAVING';
2517   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(201) := 'HEADER';
2518   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(202) := 'HEAP';
2519   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(203) := 'IDENTIFIED';
2520   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(204) := 'IDLE_TIME';
2521   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(205) := 'IF';
2522   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(206) := 'IMMEDIATE';
2523   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(207) := 'IN';
2524   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(208) := 'INCLUDING';
2525   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(209) := 'INCREMENT';
2526   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(210) := 'IND_PARTITION';
2527   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(211) := 'INDEX';
2528   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(212) := 'INDEXED';
2529   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(213) := 'INDEXES';
2530   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(214) := 'INDICATOR';
2531   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(215) := 'INITIAL';
2532   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(216) := 'INITIALLY';
2533   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(217) := 'INITRANS';
2534   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(218) := 'INSERT';
2535   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(219) := 'INSTANCE';
2536   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(220) := 'INSTANCES';
2537   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(221) := 'INSTEAD';
2538   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(222) := 'INT';
2539   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(223) := 'INTEGER';
2540   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(224) := 'INTERFACE';
2541   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(225) := 'INTERMEDIATE';
2542   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(226) := 'INTERSECT';
2543   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(227) := 'INTO';
2544   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(228) := 'IS';
2545   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(229) := 'ISOLATION';
2546   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(230) := 'ISOLATION_LEVEL';
2547   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(231) := 'KEEP';
2548   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(232) := 'KEY';
2549   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(233) := 'KILL';
2550   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(234) := 'LAYER';
2551   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(235) := 'LESS';
2552   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(236) := 'LEVEL';
2553   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(237) := 'LEVELLIKE';
2554   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(238) := 'LIBRARY';
2555   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(239) := 'LIKE';
2556   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(240) := 'LIMIT';
2557   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(241) := 'LIMITED';
2558   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(242) := 'LINK';
2559   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(243) := 'LIST';
2560   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(244) := 'LOB';
2561   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(245) := 'LOCAL';
2562   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(246) := 'LOCK';
2563   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(247) := 'LOG';
2564   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(248) := 'LOGFILE';
2565   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(249) := 'LOGGING';
2566   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(250) := 'LOGICAL_READS_PER_';
2567   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(251) := 'LOGICAL_READS_PER_CALL';
2568   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(252) := 'LONG';
2569   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(253) := 'LOOP';
2570   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(254) := 'MANAGE';
2571   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(255) := 'MASTER';
2572   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(256) := 'MAX';
2573   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(257) := 'MAXARCHLOGS';
2574   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(258) := 'MAXDATAFILES';
2575   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(259) := 'MAXEXTENTS';
2576   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(260) := 'MAXINSTANCES';
2577   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(261) := 'MAXLOGFILES';
2578   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(262) := 'MAXLOGHISTORY';
2579   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(263) := 'MAXLOGMEMBERS';
2580   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(264) := 'MAXSIZE';
2581   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(265) := 'MAXTRANS';
2582   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(266) := 'MAXVALUE';
2583   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(267) := 'MEMBER';
2584   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(268) := 'MIN';
2585   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(269) := 'MINEXTENTS';
2586   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(270) := 'MINIMUM';
2587   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(271) := 'MINUS';
2588   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(272) := 'MINVALUE';
2589   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(273) := 'MLSLABEL';
2590   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(274) := 'MOD';
2591   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(275) := 'MODE';
2592   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(276) := 'MODIFY';
2593   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(277) := 'MOUNT';
2594   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(278) := 'MOVE';
2595   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(279) := 'MTS_DISPATCHERS';
2596   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(280) := 'MULTISET';
2597   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(281) := 'NATIONAL';
2598   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(282) := 'NATURAL';
2599   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(283) := 'NATURALN';
2600   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(284) := 'NCHAR';
2601   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(285) := 'NCHAR_CS';
2602   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(286) := 'NCLOB';
2603   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(287) := 'NEEDED';
2604   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(288) := 'NESTED';
2605   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(289) := 'NETWORK';
2606   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(290) := 'NEW';
2607   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(291) := 'NEXT';
2608   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(292) := 'NEXTVAL';
2609   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(293) := 'NLS_CALENDAR';
2610   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(294) := 'NLS_CHARACTERSET';
2611   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(295) := 'NLS_ISO_CURRENCY';
2612   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(296) := 'NLS_LANGUAGE';
2613   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(297) := 'NLS_NUMERIC_';
2614   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(298) := 'NLS_SORT';
2615   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(299) := 'NLS_TERRITORY';
2616   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(300) := 'NOARCHIVELOG';
2617   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(301) := 'NOAUDIT';
2618   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(302) := 'NOCACHE';
2619   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(303) := 'NOCOMPRESS';
2620   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(304) := 'NOCYCLE';
2621   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(305) := 'NOFORCE';
2622   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(306) := 'NOLOGGING';
2623   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(307) := 'NOMAXVALUE';
2624   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(308) := 'NOMINVALUE';
2625   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(309) := 'NONE';
2626   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(310) := 'NOORDER';
2627   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(311) := 'NOOVERIDE';
2628   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(312) := 'NOPARALLEL';
2629   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(313) := 'NORESETLOGS';
2630   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(314) := 'NOREVERSE';
2631   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(315) := 'NORMAL';
2632   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(316) := 'NOS_SPECIAL_CHARS';
2633   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(317) := 'NOSORT';
2634   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(318) := 'NOT';
2635   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(319) := 'NOTHING';
2636   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(320) := 'NOWAIT';
2637   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(321) := 'NULL';
2638   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(322) := 'NUMBER';
2639   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(323) := 'NUMBER_BASE';
2640   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(324) := 'NUMERIC';
2641   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(325) := 'NVARCHAR2';
2642   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(326) := 'OBJECT';
2643   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(327) := 'OBJNO';
2644   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(328) := 'OBJNO_REUSE';
2645   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(329) := 'OF';
2646   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(330) := 'OFF';
2647   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(331) := 'OFFLINE';
2648   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(332) := 'OID';
2649   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(333) := 'OIDINDEX';
2650   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(334) := 'OLD';
2651   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(335) := 'ON';
2652   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(336) := 'ONLINE';
2653   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(337) := 'ONLY';
2654   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(338) := 'OPCODE';
2655   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(339) := 'OPEN';
2656   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(340) := 'OPTIMAL';
2657   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(341) := 'OPTIMIZER_GOAL';
2658   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(342) := 'OPTION';
2659   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(343) := 'OR';
2660   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(344) := 'ORDER';
2661   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(345) := 'ORGANIZATION';
2662   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(346) := 'OTHERS';
2663   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(347) := 'OUT';
2664   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(348) := 'OVERFLOW';
2665   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(349) := 'OWN';
2666   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(350) := 'PACKAGE';
2667   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(351) := 'PARALLEL';
2668   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(352) := 'PARTITION';
2669   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(353) := 'PASSWORD';
2670   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(354) := 'PASSWORD_GRACE_TIME';
2671   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(355) := 'PASSWORD_LIFE_TIME';
2672   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(356) := 'PASSWORD_LOCK_TIME';
2673   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(357) := 'PASSWORD_REUSE_MAX';
2674   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(358) := 'PASSWORD_REUSE_TIME';
2675   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(359) := 'PASSWORD_VERIFY_';
2676   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(360) := 'PCTFREE';
2677   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(361) := 'PCTINCREASE';
2678   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(362) := 'PCTTHRESHOLD';
2679   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(363) := 'PCTUSED';
2680   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(364) := 'PCTVERSION';
2681   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(365) := 'PERCENT';
2682   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(366) := 'PERMANENT';
2683   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(367) := 'PLAN';
2684   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(368) := 'PLS_INTEGER';
2685   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(369) := 'PLSQL_DEBUG';
2686   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(370) := 'POSITIVE';
2687   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(371) := 'POSITIVEN';
2688   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(372) := 'POST_TRANSACTION';
2689   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(373) := 'PRAGMA';
2690   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(374) := 'PRECISION';
2691   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(375) := 'PRESERVE';
2692   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(376) := 'PRIMARY';
2693   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(377) := 'PRIOR';
2694   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(378) := 'PRIVATE';
2695   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(379) := 'PRIVATE_SGA';
2696   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(380) := 'PRIVILEGE';
2697   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(381) := 'PRIVILEGES';
2698   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(382) := 'PROCEDURE';
2699   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(383) := 'PROFILE';
2700   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(384) := 'PUBLIC';
2701   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(385) := 'PURGE';
2702   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(386) := 'QUARTER';
2703   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(387) := 'QUEUE';
2704   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(388) := 'QUOTA';
2705   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(389) := 'RAISE';
2706   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(390) := 'RANGE';
2707   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(391) := 'RAW';
2708   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(392) := 'RBA';
2709   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(393) := 'READ';
2710   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(394) := 'REAL';
2711   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(395) := 'REBUILD';
2712   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(396) := 'RECORD';
2713   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(397) := 'RECOVER';
2714   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(398) := 'RECOVERABLE';
2715   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(399) := 'RECOVERY';
2716   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(400) := 'REF';
2717   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(401) := 'REFERENCES';
2718   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(402) := 'REFERENCING';
2719   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(403) := 'RELEASE';
2720   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(404) := 'REFRESH';
2721   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(405) := 'RENAME';
2722   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(406) := 'REMR';
2723   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(407) := 'REPLACE';
2724   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(408) := 'RESET';
2725   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(409) := 'RESETLOGS';
2726   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(410) := 'RESIZE';
2727   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(411) := 'RESOURCE';
2728   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(412) := 'RESTRICTED';
2729   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(413) := 'RETURN';
2730   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(414) := 'RETURNING';
2731   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(415) := 'REUSE';
2732   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(416) := 'REVERSE';
2733   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(417) := 'REVOKE';
2734   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(418) := 'ROLE';
2735   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(419) := 'ROLES';
2736   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(420) := 'ROLLBACK';
2737   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(421) := 'ROW';
2738   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(422) := 'ROWID';
2739   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(423) := 'ROWLABEL';
2740   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(424) := 'ROWNUM';
2741   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(425) := 'ROWS';
2742   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(426) := 'ROWTYPE';
2743   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(427) := 'RULE';
2744   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(428) := 'RUN';
2745   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(429) := 'SAMPLE';
2746   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(430) := 'SAVEPOINT';
2747   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(431) := 'SCAN_INSTANCES';
2748   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(432) := 'SCHEMA';
2749   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(433) := 'SCN';
2750   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(434) := 'SCOPE';
2751   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(435) := 'SD_ALL';
2752   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(436) := 'SD_INHIBIT';
2753   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(437) := 'SD_SHOW';
2754   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(438) := 'SEG_BLOCK';
2755   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(439) := 'SEG_FILE';
2756   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(440) := 'SEGMENT';
2757   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(441) := 'SELECT';
2758   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(442) := 'SEPARATE';
2759   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(443) := 'SEQUENCE';
2760   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(444) := 'SERIALIZABLE';
2761   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(445) := 'SESSION';
2762   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(446) := 'SESSION_CACHED_';
2763   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(447) := 'SESSIONS_PER_USER';
2764   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(448) := 'SET';
2765   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(449) := 'SHARE';
2766   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(450) := 'SHARED';
2767   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(451) := 'SHARED_POOL';
2768   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(452) := 'SHRINK';
2769   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(453) := 'SIZE';
2770   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(454) := 'SKIM_UNUSABLE_INDEXES';
2771   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(455) := 'SMALLINT';
2772   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(456) := 'SNAPSHOT';
2773   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(457) := 'SOME';
2774   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(458) := 'SORT';
2775   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(459) := 'SPACE';
2776   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(460) := 'SPECIFICATION';
2777   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(461) := 'SPLIT';
2778   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(462) := 'SQL';
2779   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(463) := 'SQL_TRACE';
2780   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(464) := 'SQLCODE';
2781   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(465) := 'SQLERRM';
2782   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(466) := 'SQLERROR';
2783   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(467) := 'STANDBY';
2784   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(468) := 'START';
2785   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(469) := 'STATE';
2786   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(470) := 'STATEMENT';
2787   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(471) := 'STATEMENT_ID';
2788   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(472) := 'STATISTICS';
2789   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(473) := 'STOP';
2790   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(474) := 'STORAGE';
2791   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(475) := 'STORE';
2792   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(476) := 'STRUCTURE';
2793   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(477) := 'STTDEV';
2794   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(478) := 'SUBTYPE';
2795   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(479) := 'SUCCESSFUL';
2796   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(480) := 'SUM';
2797   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(481) := 'SWITCH';
2798   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(482) := 'SYNONYM';
2799   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(483) := 'SYSDATE';
2800   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(484) := 'SYSDBA';
2801   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(485) := 'SYSOPER';
2802   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(486) := 'SYSTEM';
2803   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(487) := 'TABAUTH';
2804   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(488) := 'TABLE';
2805   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(489) := 'TABLES';
2806   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(490) := 'TABLESPACE';
2807   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(491) := 'TABLESPACE_NO';
2808   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(492) := 'TABNO';
2809   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(493) := 'TASK';
2810   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(494) := 'TEMPORARY';
2811   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(495) := 'TERMINATE';
2812   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(496) := 'THAN';
2813   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(497) := 'THE';
2814   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(498) := 'THEN';
2815   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(499) := 'THENTINYINT';
2816   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(500) := 'THREAD';
2817   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(501) := 'TIME';
2818   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(502) := 'TIMESTAMP';
2819   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(503) := 'TO';
2820   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(504) := 'TOPLEVEL';
2821   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(505) := 'TRACE';
2822   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(506) := 'TRACING';
2823   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(507) := 'TRANSACTION';
2824   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(508) := 'TRANSITIONAL';
2825   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(509) := 'TRIGGER';
2826   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(510) := 'TRIGGERS';
2827   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(511) := 'TRUE';
2828   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(512) := 'TRUNCATE';
2829   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(513) := 'TX';
2830   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(514) := 'TYPE';
2831   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(515) := 'UBA';
2832   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(516) := 'UID';
2833   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(517) := 'UNARCHIVED';
2834   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(518) := 'UNDER';
2835   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(519) := 'UNDO';
2836   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(520) := 'UNION';
2837   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(521) := 'UNIQUE';
2838   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(522) := 'UNLIMITED';
2839   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(523) := 'UNLOCK';
2840   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(524) := 'UNRECOVERABLE';
2841   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(525) := 'UNTIL';
2842   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(526) := 'UNUSABLE';
2843   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(527) := 'UNUSED';
2844   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(528) := 'UPDATABLE';
2845   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(529) := 'UPDATE';
2846   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(530) := 'USAGE';
2847   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(531) := 'USE';
2848   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(532) := 'USER';
2849   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(533) := 'USING';
2850   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(534) := 'VALIDATE';
2851   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(535) := 'VALIDATION';
2852   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(536) := 'VALUE';
2853   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(537) := 'VALUES';
2854   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(538) := 'VARBINARY';
2855   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(539) := 'VARCHAR';
2856   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(540) := 'VARCHAR2';
2857   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(541) := 'VARIANCE';
2858   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(542) := 'VARRAY';
2859   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(543) := 'VARYING';
2860   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(544) := 'VIEW';
2861   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(545) := 'VIEWS';
2862   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(546) := 'WHEN';
2863   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(547) := 'WHENEVER';
2864   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(548) := 'WHERE';
2865   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(549) := 'WHILE';
2866   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(550) := 'WITH';
2867   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(551) := 'WITHOUT';
2868   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(552) := 'WORK';
2869   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(553) := 'WRITE';
2870   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(554) := 'XID';
2871   BSC_METADATA_OPTIMIZER_PKG.gArrReservedWords(555) := 'XOR';
2872 
2873    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
2874   BSC_MO_HELPER_PKG.writeTmp('Completed InitArrReservedWords', FND_LOG.LEVEL_PROCEDURE);
2875    END IF;
2876 
2877 End;
2878 
2879 
2880 
2881 --****************************************************************************
2882 -- InitLOV
2883 --
2884 --  DESCRIPTION:
2885 --     Initialize collection gLUV with the unique list of variables
2886 --
2887 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
2888 --***************************************************************************
2889 PROCEDURE InitLOV IS
2890 
2891 	l_stmt varchar2(1000);
2892   FieldLOV BSC_METADATA_OPTIMIZER_PKG.clsMeasureLOV;
2893   --BSC-PMF Integration: It is not necessary to filter out PMF measures
2894   --because in BSC_DB_MEASURE_COLS_VL are only BSC measures
2895   --CURSOR c1 IS
2896   --SELECT MEASURE_COL, HELP, MEASURE_GROUP_ID, PROJECTION_ID, NVL(MEASURE_TYPE, 1) MTYPE
2897 	 --FROM BSC_DB_MEASURE_COLS_VL ORDER BY MEASURE_COL ;
2898 
2899   --BSC-PMF Integration: Need to filter out PMF measures
2900 
2901   /*CURSOR c1 IS
2902   SELECT MEASURE_COL, HELP, MEASURE_GROUP_ID, PROJECTION_ID, NVL(MEASURE_TYPE, 1) MTYPE
2903   FROM BSC_DB_MEASURE_COLS_VL
2904    WHERE MEASURE_COL NOT IN
2905    (
2906        SELECT MEASURE_COL FROM BSC_SYS_MEASURES M
2907        WHERE NVL(M.SOURCE, 'BSC') = 'PMF'
2908       and  not exists( select 1 from BSC_SYS_MEASURES P where p.Measure_Col = m.measure_col
2909 	           and NVL(p.SOURCE, 'BSC') = 'BSC')
2910    ) ORDER BY MEASURE_COL;*/
2911   --BSC autogen
2912 
2913   CURSOR c1 IS
2914   SELECT DB.MEASURE_COL, DB.HELP, DB.MEASURE_GROUP_ID, DB.PROJECTION_ID, NVL(DB.MEASURE_TYPE, 1) MTYPE, M.SOURCE
2915     FROM BSC_DB_MEASURE_COLS_VL DB,
2916          BSC_SYS_MEASURES M
2917    WHERE db.Measure_Col = m.measure_col
2918      AND M.SOURCE = 'BSC'
2919    UNION
2920   SELECT M.MEASURE_COL, null HELP, -1 MEASURE_GROUP_ID, 0 PROJECTION_ID, 1 MTYPE, M.SOURCE
2921     FROM BSC_SYS_MEASURES M
2922    WHERE M.SOURCE='PMF'
2923    ORDER BY MEASURE_COL;
2924 
2925   cRow c1%ROWTYPE;
2926 
2927 BEGIN
2928   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
2929     BSC_MO_HELPER_PKG.writeTmp('Inside InitLOV', FND_LOG.LEVEL_PROCEDURE);
2930   END IF;
2931   OPEN c1;
2932   LOOP
2933     FETCH c1 INTO cRow;
2934     EXIT WHEN c1%NOTFOUND;
2935     FieldLOV := bsc_mo_helper_pkg.new_clsMeasureLOV;
2936     FieldLOV.fieldName := cRow.MEASURE_COL;
2937     FieldLOV.source := nvl(cRow.Source, 'BSC');
2938 	IF (cRow.HELP IS NOT NULL) THEN
2939       FieldLOV.Description := cRow.HELP;
2940     END IF;
2941     IF (cRow.MEASURE_GROUP_ID IS NOT NULL) THEN
2942       FieldLOV.groupCode := cRow.MEASURE_GROUP_ID;
2943     Else
2944       FieldLOV.groupCode := -1;
2945     END IF;
2946     IF (cRow.PROJECTION_ID IS NOT NULL) THEN
2947       FieldLOV.prjMethod := cRow.PROJECTION_ID;
2948     Else
2949       FieldLOV.prjMethod := 0; --no projection
2950     END IF;
2951     FieldLOV.measureType := cRow.MTYPE;
2952     --BSC autogen
2953     BSC_METADATA_OPTIMIZER_PKG.gLOV(BSC_METADATA_OPTIMIZER_PKG.gLOV.Count) := FieldLOV;
2954   END Loop;
2955   CLOSE c1;
2956   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
2957       BSC_MO_HELPER_PKG.writeTmp('Completed InitLOV', FND_LOG.LEVEL_PROCEDURE);
2958   END IF;
2959   return;
2960   exception when others then
2961     bsc_mo_helper_pkg.writeTmp('Exception in InitLOV : '||sqlerrm, FND_LOG.LEVEL_UNEXPECTED, true);
2962     TerminateWithError('BSC_VAR_LIST_INIT_FAILED', 'InitLOV');
2963   	raise;
2964 End;
2965 
2966 --***************************************************************************
2967 --  getKPIPropertyValue : LeerMatrixINfo
2968 --  DESCRIPTION:
2969 --     Return the value oif the given variable of the given indicator from
2970 --     table BSC_KPI_PROPERTIES.
2971 --
2972 --  PARAMETERS:
2973 --     Indic: indicator code
2974 --     Variable: variable name
2975 --     Default: default value
2976 --     db_obj: database
2977 --
2978 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
2979 --***************************************************************************
2980 Function getKPIPropertyValue(Indic IN NUMBER, Variable IN VARCHAR2,
2981 	def IN NUMBER) return NUMBER IS
2982 l_temp number := null;
2983 l_stmt varchar2(1000);
2984 cv   CurTyp;
2985 l_error VARCHAR2(400);
2986 
2987 CURSOR cProperty IS
2988   SELECT PROPERTY_VALUE
2989   FROM BSC_KPI_PROPERTIES
2990   WHERE INDICATOR = Indic
2991   AND PROPERTY_CODE = Variable;
2992 
2993 BEGIN
2994   OPEN cProperty;
2995   FETCH cProperty INTO l_temp;
2996   CLOSE cProperty;
2997 
2998   -- if its not MV, ignore AW's IMPLEMENTATION_TYPE value, override it with 1
2999   If Variable=BSC_METADATA_OPTIMIZER_PKG.IMPL_TYPE AND BSC_METADATA_OPTIMIZER_PKG.g_BSC_MV =false Then
3000     l_temp := 1;
3001   END IF;
3002 
3003   IF l_temp is not null THEN
3004     return l_temp;
3005   END IF;
3006 
3007    return def;
3008    EXCEPTION WHEN OTHERS THEN
3009       writeTmp('Exception in getKPIPropertyValue for Indic='||Indic||', Variable='||Variable||', def='||def,
3010 		FND_LOG.LEVEL_EXCEPTION, true);
3011       l_error := sqlerrm;
3012       writeTmp('Exception is '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3013 
3014       raise;
3015 End;
3016 --===========================================================================+
3017 --
3018 --   Name:      IsNumber
3019 --   Description:   Returns true if the string is a number
3020 --   Parameters:
3021 --============================================================================*/
3022 FUNCTION IsNumber (str IN VARCHAR2) RETURN BOOLEAN IS
3023 l_temp NUMBER := -1;
3024 BEGIN
3025 	l_temp:= to_number(str);
3026 	return true;
3027 	exception when others then
3028 		return false;
3029 END;
3030 
3031 --===========================================================================+
3032 --
3033 --  Name:      Get_New_Big_In_Cond_Number
3034 --   Description:   Clean values for the given variable_id and return a 'IN'
3035 --            condition string.
3036 --   Parameters:  x_variable_id  variable id.
3037 --            x_column_name  column name (left part of the condition)
3038 --============================================================================
3039 
3040 Function Get_New_Big_In_Cond_Number( x_variable_id IN NUMBER, x_column_name IN VARCHAR2)
3041 return VARCHAR2 IS
3042   l_stmt varchar2(1000);
3043   l_cond varchar2(1000);
3044   l_error VARCHAR2(2000);
3045 BEGIN
3046 
3047 
3048   DELETE FROM BSC_TMP_BIG_IN_COND WHERE SESSION_ID = bsc_metadata_optimizer_pkg.g_session_id AND VARIABLE_ID = x_variable_id;
3049 
3050   l_cond := x_column_name || ' IN (' ||
3051   		' SELECT VALUE_N FROM BSC_TMP_BIG_IN_COND WHERE SESSION_ID = '||bsc_metadata_optimizer_pkg.g_session_id||
3052   		' AND VARIABLE_ID = ' || x_variable_id || ')';
3053 
3054   return l_cond;
3055   EXCEPTION WHEN OTHERS THEN
3056       l_error := sqlerrm;
3057       writeTmp( 'Exception in Get_New_Big_In_Cond_Number :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
3058       RAISE;
3059 End;
3060 
3061 PROCEDURE Add_Value_BULK(x_variable_id IN NUMBER, x_value IN DBMS_SQL.NUMBER_TABLE) IS
3062 
3063 BEGIN
3064   IF (x_value.count=0) THEN
3065     return;
3066   END IF;
3067   FORALL i IN x_value.first..x_value.last
3068    INSERT INTO BSC_TMP_BIG_IN_COND(session_id, variable_id, value_n)
3069    VALUES
3070    (bsc_metadata_optimizer_pkg.g_session_id, x_variable_id, x_value(i));
3071   exception when others then
3072    writeTmp('exception in add_value_bulk for number table', FND_LOG.LEVEL_EXCEPTION, true);
3073    raise;
3074 END;
3075 
3076 PROCEDURE Add_Value_BULK(x_variable_id IN NUMBER, x_value IN DBMS_SQL.VARCHAR2_TABLE) IS
3077 
3078 BEGIN
3079   IF (x_value.count=0) THEN
3080     return;
3081   END IF;
3082  FORALL i IN x_value.first..x_value.last
3083    INSERT INTO BSC_TMP_BIG_IN_COND(session_id, variable_id, value_v)
3084    VALUES
3085    (bsc_metadata_optimizer_pkg.g_session_id, x_variable_id, x_value(i));
3086  exception when others then
3087    writeTmp('exception in add_value_bulk for varchar2 table', FND_LOG.LEVEL_EXCEPTION, true);
3088    raise;
3089 END;
3090 --===========================================================================+
3091 --   Name:      Add_Value_Big_In_Cond_Number
3092 --   Description:   Insert the given value into the temporary table of big
3093 --            'in' conditions for the given variable_id.
3094 --   Parameters:  x_variable_id  variable id.
3095 --            x_value      value
3096 --============================================================================
3097 PROCEDURE Add_Value_Big_In_Cond_Number(x_variable_id IN NUMBER, x_value IN NUMBER) IS
3098 l_stmt varchar2(300);
3099 l_error varchar2(2000);
3100 BEGIN
3101 	bsc_apps.Add_Value_Big_In_Cond(x_variable_id , x_value);
3102 
3103   EXCEPTION WHEN OTHERS THEN
3104       l_error := sqlerrm;
3105       writeTmp( 'Exception in Add_Value_Big_In_Cond_Number :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
3106       RAISE;
3107 End;
3108 
3109 
3110 --===========================================================================+
3111 --   Name:      Get_New_Big_In_Cond_Varchar2
3112 --   Description:   Clean values for the given variable_id and return a 'IN'
3113 --            condition string.
3114 --   Parameters:  x_variable_id  variable id.
3115 --            x_column_name  column name (left part of the condition)
3116 --============================================================================
3117 Function Get_New_Big_In_Cond_Varchar2( x_variable_id in number, x_column_name in varchar2)
3118 return VARCHAR2 IS
3119 
3120   l_stmt varchar2(300);
3121   cond   varchar2(1000);
3122   l_error varchar2(1000);
3123 BEGIN
3124   DELETE FROM BSC_TMP_BIG_IN_COND WHERE SESSION_ID = bsc_metadata_optimizer_pkg.g_session_id AND VARIABLE_ID = x_variable_id;
3125   cond := 'UPPER('||  x_column_name  || ') IN ('||
3126   		' SELECT UPPER(VALUE_V) FROM BSC_TMP_BIG_IN_COND WHERE SESSION_ID = '||bsc_metadata_optimizer_pkg.g_session_id
3127                  ||' AND VARIABLE_ID = '||x_variable_id||')';
3128   return cond;
3129   EXCEPTION WHEN OTHERS THEN
3130       l_error := sqlerrm;
3131       writeTmp( 'Exception in Get_New_Big_In_Cond_Varchar2 :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
3132       RAISE;
3133 End;
3134 
3135 --===========================================================================+
3136 --   Name:      Add_Value_Big_In_Cond_Varchar2
3137 --   Description:   Insert the given value into the temporary table of big
3138 --            --in' conditions for the given variable_id.
3139 --   Parameters:  x_variable_id  variable id.
3140 --            x_value      value
3141 --============================================================================*/
3142 PROCEDURE Add_Value_Big_In_Cond_Varchar2(x_variable_id IN NUMBER, x_value IN VARCHAR2) IS
3143 l_stmt varchar2(300);
3144 l_error varchar2(2000);
3145 BEGIN
3146 
3147 	bsc_apps.Add_Value_Big_In_Cond(x_variable_id , x_value);
3148 
3149   EXCEPTION WHEN OTHERS THEN
3150       l_error := sqlerrm;
3151       writeTmp( 'Exception in Add_Value_Big_In_Cond_Varchar2 :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
3152       RAISE;
3153 End;
3154 
3155 
3156 /****************************************************************************
3157 --  InsertRelatedTables
3158 --  DESCRIPTION:
3159 --     Insert in the array garrTables() all the tables in the current
3160 --     graph that have any relation with the tables in the array
3161 --     arrTables().
3162 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
3163 --****************************************************************************/
3164 
3165 PROCEDURE InsertRelatedTables(arrTables in dbms_Sql.varchar2_table,
3166 		 numTables in number) IS
3167 
3168   arrNewTables dbms_sql.varchar2_table;
3169   numNewTables number := 0;
3170   strWhereInNewTables varchar2(1000);
3171   strWhereNotInNewTables varchar2(1000);
3172   l_stmt varchar2(1000);
3173   l_table varchar2(100);
3174   cv   CurTyp;
3175 
3176 
3177   strWhereInChildTables VARCHAR2(1000);
3178   strWhereInParentTables VARCHAR2(1000);
3179 
3180   l_error varchar2(1000);
3181   l_test number;
3182 
3183   l_arr_tables dbms_sql.varchar2_table;
3184 BEGIN
3185    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3186      writeTmp( 'Inside InsertRelatedTables, numTables='||numTables, fnd_log.level_procedure, false);
3187    END IF;
3188    writeTmp('Insert related tables, tables are ', fnd_log.level_statement, false);
3189    write_this(arrNewTables, fnd_log.level_statement, false);
3190 
3191    numNewTables := 0;
3192 
3193    --BSC-MV Note: Review this procedure. I changed the logic to improve performance
3194 
3195    If numTables > 0 Then
3196      strWhereInNewTables := Get_New_Big_In_Cond_Varchar2(3, 'TABLE_NAME');
3197      strWhereNotInNewTables := null;
3198      strWhereInChildTables := Get_New_Big_In_Cond_Varchar2(4, 'SOURCE_TABLE_NAME');
3199      strWhereInParentTables := Get_New_Big_In_Cond_Varchar2(5, 'TABLE_NAME');
3200      Add_Value_Bulk(4, arrTables);
3201      Add_Value_Bulk(5, arrTables);
3202 
3203      /*For i IN 0..numTables - 1 LOOP
3204        Add_Value_Big_In_Cond_Varchar2 (4, arrTables(i));
3205        Add_Value_Big_In_Cond_Varchar2 (5, arrTables(i));
3206      END LOOP; */
3207 
3208      --insert the children
3209      l_stmt := 'SELECT TABLE_NAME FROM BSC_DB_TABLES_RELS WHERE '|| strWhereInChildTables;
3210      OPEN cv FOR l_stmt;
3211      LOOP
3212        FETCH cv INTO l_table;
3213        EXIT WHEN cv%NOTFOUND;
3214        If Not SearchStringExists(BSC_METADATA_OPTIMIZER_PKG.garrTables, BSC_METADATA_OPTIMIZER_PKG.gnumTables, l_table) Then
3215          BSC_METADATA_OPTIMIZER_PKG.garrTables(BSC_METADATA_OPTIMIZER_PKG.gnumTables) := l_table;
3216          BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.gnumTables + 1;
3217          arrNewTables(numNewTables) := l_table;
3218          numNewTables := numNewTables + 1;
3219          --Add_Value_Big_In_Cond_Varchar2 (3, l_table);
3220        End If;
3221      END LOOP;
3222      Close cv;
3223      --Add_value_Bulk(3, arrNewTables);
3224      l_test := numNewTables;
3225      IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3226        writeTmp('No. of new children = '||   numNewTables);
3227      END IF;
3228      --insert the parents
3229      l_stmt := 'SELECT SOURCE_TABLE_NAME FROM BSC_DB_TABLES_RELS WHERE '|| strWhereInParentTables;
3230      l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'TABLE_NAME');
3231      l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'VALUE_V');
3232      OPEN cv FOR l_stmt;
3233      FETCH cv BULK COLLECT INTO l_arr_tables;
3234      CLOSE cv;
3235      FOR i IN 1..l_arr_tables.count LOOP
3236        l_table := l_arr_tables(i);
3237        If Not searchStringExists(BSC_METADATA_OPTIMIZER_PKG.garrTables, BSC_METADATA_OPTIMIZER_PKG.gnumTables, l_table) Then
3238          BSC_METADATA_OPTIMIZER_PKG.garrTables(BSC_METADATA_OPTIMIZER_PKG.gnumTables) := l_table;
3239          BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.gnumTables + 1;
3240          arrNewTables(numNewTables) := l_table;
3241          numNewTables := numNewTables + 1;
3242        End If;
3243      END LOOP;
3244 
3245      IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3246        writeTmp('No. of new parents = '||   (numNewTables-l_test));
3247      END IF;
3248      Add_Value_Bulk(3, arrNewTables);
3249 
3250      If numNewTables > 0 Then
3251      --if one table of one indicator is marked then all tables of this indicator are marked
3252      --EDW Integration note:
3253      --In BSC_KPI_DATA_TABLES, Metadata Optimizer is storing the name of the view (Example: BSC_3001_0_0_5_V)
3254      --and the name of the S table for BSC Kpis (Example: BSC_3002_0_0_5)
3255      --In this procedure we need to get tables names from a view BSC_KPI_DATA_TABLES_V.
3256 
3257      --BSC-MV Note: We are going to use BSC_KPI_DATA_TABLES in all the code.
3258      --EDW logic is not used and need to be reviewd in the future.
3259 
3260        strWhereNotInNewTables := 'NOT (' || strWhereInNewTables || ')';
3261        l_stmt := 'SELECT TABLE_NAME FROM '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' WHERE INDICATOR IN (
3262                 SELECT INDICATOR FROM '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' WHERE '|| strWhereInNewTables||')
3263                 AND '|| strWhereNotInNewTables ||' AND TABLE_NAME IS NOT NULL ';
3264        l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'TABLE_NAME');
3265        l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'VALUE_V');
3266        OPEN cv FOR l_stmt;
3267        FETCH cv BULK COLLECT INTO l_arr_tables;
3268        CLOSE cv;
3269        FOR i in 1..l_arr_tables.count LOOP
3270          l_table := l_arr_tables(i);
3271          If Not searchStringExists(BSC_METADATA_OPTIMIZER_PKG.garrTables, BSC_METADATA_OPTIMIZER_PKG.gnumTables, l_table) Then
3272            BSC_METADATA_OPTIMIZER_PKG.garrTables(BSC_METADATA_OPTIMIZER_PKG.gnumTables) := l_table;
3273            BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.gnumTables + 1;
3274            arrNewTables(numNewTables) := l_table;
3275            numNewTables := numNewTables + 1;
3276          End If;
3277        END Loop;
3278        InsertRelatedTables (arrNewTables, numNewTables);
3279      End If;
3280    End If;
3281 
3282    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3283      writeTmp( 'Compl. InsertRelatedTables', fnd_log.level_procedure, false);
3284    END IF;
3285 
3286 
3287   EXCEPTION WHEN OTHERS THEN
3288       l_error := sqlerrm;
3289       writeTmp( 'Exception in InsertRelatedTables :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
3290       RAISE;
3291 
3292 End;
3293 
3294 
3295 --***************************************************************************
3296 --  AddIndicator
3297 --  DESCRIPTION:
3298 --     Add the given indicator to the given indicator collection.
3299 --     The collection is made of objects of class clsIndicador
3300 --  PARAMETERS:
3301 --     collIndicadores: indicators collection
3302 --     Cod: indicator code
3303 --     Name: indicator name
3304 --     TipoIndic: type of indicator
3305 --     TipoConfig: type of configuration
3306 --     Per_Inter: periodicity in the panel
3307 --     OptimizationMode: 0- pre-calculated, 1- standard, 2-benchamarks at diff level.
3308 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
3309 --***************************************************************************
3310 
3311 PROCEDURE AddIndicator(collIndicadores IN OUT NOCOPY BSC_METADATA_OPTIMIZER_PKG.tab_clsIndicator, p_Code NUMBER,
3312 			p_Name varchar2, p_indicatorType NUMBER, p_configType NUMBER,
3313 			p_per_inter NUMBER, p_optMode NUMBER, p_action_flag NUMBER,
3314 			p_share_flag NUMBER, p_src_ind NUMBER, p_edw_flag NUMBER,
3315 			p_impl_type NUMBER) IS
3316   Indic BSC_METADATA_OPTIMIZER_PKG.clsIndicator;
3317   l_error varchar2(1000);
3318 BEGIN
3319 
3320   Indic.Code := p_code;
3321   Indic.Name := p_Name;
3322   Indic.IndicatorType := p_indicatorType;
3323   Indic.ConfigType := p_configType;
3324   Indic.Periodicity := p_Per_Inter;
3325   Indic.OptimizationMode := p_OptMode;
3326   Indic.Action_Flag := p_action_Flag;
3327   Indic.Share_Flag := p_share_Flag;
3328   Indic.Source_Indicator := p_Src_Ind ;
3329   Indic.EDW_Flag := p_EDW_Flag;
3330   Indic.Impl_type := p_impl_type;
3331   IF  (collIndicadores.count>0) THEN
3332       collIndicadores(collINdicadores.LAST+1) := indic;
3333   ELSE
3334       collIndicadores(0) := indic;
3335   END IF;
3336   EXCEPTION WHEN OTHERS THEN
3337       l_error := sqlerrm;
3338       writeTmp( 'Exception in AddIndicator :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
3339       RAISE;
3340 End;
3341 
3342 /****************************************************************************
3343 --  GetCamposExpresion
3344 --  DESCRIPTION:
3345 --     Get in an array the list of fields in the given expression.
3346 --     Return the number of fields.
3347 --     Example. Expresion = 'IIF(Not IsNull(SUM(A)), C, B)'
3348 --     CamposExpresion() = |A|C|B|, GetCamposExpresion = 2
3349 --  PARAMETERS:
3350 --     CamposExpresion(): array to be populated
3351 --     Expresion: expression
3352 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
3353 --***************************************************************************/
3354 Function GetFieldExpression(FieldExpresion IN OUT NOCOPY dbms_sql.varchar2_table, Expresion IN VARCHAR2)
3355 return NUMBER is
3356 
3357   i number;
3358   NumFieldsExpresion varchar2(1000);
3359   fields dbms_sql.varchar2_table;
3360   NumFields number;
3361   cExpresion varchar2(1000);
3362   l_error VARCHAR2(400);
3363 BEGIN
3364 
3365   cExpresion := Expresion;
3366   --Replace the operators by ' '
3367   i := 0;
3368   LOOP
3369 	EXIT WHEN i = BSC_METADATA_OPTIMIZER_PKG.gNumReservedOperators;
3370       cExpresion := replace(cExpresion, BSC_METADATA_OPTIMIZER_PKG.gReservedOperators(i), ' ');
3371       i:= i +1;
3372   END LOOP;
3373 
3374   --Break down the expression which is separated by ' '
3375   NumFields := DecomposeString(cExpresion,  ' ', fields);
3376 
3377   NumFieldsExpresion := 0;
3378 
3379   i:=0;
3380   LOOP
3381 	EXIT WHEN i= NumFields;
3382       IF fields(i) IS NOT NULL THEN
3383         IF FindIndexVARCHAR2(BSC_METADATA_OPTIMIZER_PKG.gReservedFunctions, Fields(i)) = -1 THEN
3384           --The word fields(i) is not a reserved function
3385           IF UPPER(Fields(i)) <> 'NULL' THEN
3386               --the word is not 'NULL'
3387               IF Not IsNumber(Fields(i)) THEN
3388                 --the word is not a constant
3389                 FieldExpresion(NumFieldsExpresion) := Fields(i);
3390                 NumFieldsExpresion := NumFieldsExpresion + 1;
3391               END IF;
3392           END IF;
3393         END IF;
3394       END IF;
3395 	i:= i+1;
3396   END LOOP;
3397 	return NumFieldsExpresion;
3398   EXCEPTION WHEN OTHERS THEN
3399       l_error := sqlerrm;
3400       writeTmp('Exception in GetFieldExpression : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3401       raise;
3402 
3403 End;
3404 
3405 
3406 
3407 --****************************************************************************
3408 --  MarkIndicsForNonStrucChanges
3409 --  DESCRIPTION:
3410 --     The array garrIndics4() is initialized with currently flagged indicators
3411 --     for non-structural changes. (Protoype_Flag = 4)
3412 --     This procedure adds to the same array the related indicators.
3413 --     Designer is only flagging the indicators
3414 --     that are using the measure direclty. We need to flag other indicators
3415 --     using the same measures alone or as part of a formula.
3416 --
3417 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
3418 --***************************************************************************
3419 PROCEDURE MarkIndicsForNonStrucChanges IS
3420   l_stmt Varchar2(1000);
3421   strWhereInIndics Varchar2(1000);
3422   strWhereNotInIndics Varchar2(1000);
3423   strWhereInMeasures Varchar2(1000);
3424   i NUMBER := 0;
3425   arrMeasuresCols  DBMS_SQL.VARCHAR2_TABLE;
3426   arrMeasures_src  DBMS_SQL.VARCHAR2_TABLE;
3427   numMeasures NUMBER;
3428   arrRelatedMeasuresIds DBMS_SQL.NUMBER_TABLE;
3429 
3430   --measureCol Varchar2(1000);
3431   Operands DBMS_SQL.VARCHAR2_TABLE;
3432   NumOperands NUMBER;
3433   l_measureID NUMBER;
3434   l_measureCol VARCHAR2(1000);
3435   l_source VARCHAR2(1000);
3436   cv   CurTyp;
3437   l_error varchar2(4000);
3438   l_stack VARCHAR2(32000);
3439   l_indicator NUMBER;
3440 BEGIN
3441   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3442     writeTmp('Inside MarkIndicsForNonStrucChanges', FND_LOG.LEVEL_PROCEDURE);
3443   END IF;
3444   IF BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 <= 0 THEN
3445     IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3446       writeTmp('Completed MarkIndicsForNonStrucChanges, count was 0', FND_LOG.LEVEL_PROCEDURE);
3447     END IF;
3448     return;
3449   END IF;
3450   --Init and array with the measures used by the indicators flagged for
3451   --non-structural changes
3452   numMeasures := 0;
3453   strWhereInIndics := Get_New_Big_In_Cond_Number(9, 'I.INDICATOR');
3454   /*i:= 0;
3455   LOOP
3456     EXIT WHEN i=BSC_METADATA_OPTIMIZER_PKG.gnumIndics4;
3457     Add_Value_Big_In_Cond_Number( 9, BSC_METADATA_OPTIMIZER_PKG.garrIndics4(i));
3458     i:=i+1;
3459   END LOOP;*/
3460 
3461   Add_value_BULK(9, BSC_METADATA_OPTIMIZER_PKG.garrIndics4);
3462   l_stmt := 'SELECT DISTINCT M.MEASURE_COL, M.SOURCE, M.MEASURE_ID FROM BSC_SYS_MEASURES M, '||
3463             BSC_METADATA_OPTIMIZER_PKG.g_dbmeasure_tmp_table||' I
3464             WHERE I.MEASURE_ID = M.MEASURE_ID AND ('|| strWhereInIndics ||' )
3465             AND M.TYPE = 0';
3466   OPEN cv FOR l_stmt;
3467   l_stack := l_stack ||' Going to execute l_stmt = '||l_stmt;
3468   l_stack := l_stack || newline||bsc_metadata_optimizer_pkg.gIndent;
3469   LOOP
3470     FETCH cv INTO l_measureCol, l_source, l_measureID;
3471     EXIT when cv%NOTFOUND;
3472     IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3473       writeTmp('Measure = '||l_measureCol, FND_LOG.LEVEL_PROCEDURE);
3474     END IF;
3475     arrMeasuresCols(numMeasures) := l_measureCol;
3476     arrMeasures_src(numMeasures) := l_source;
3477     numMeasures := numMeasures + 1;
3478     arrRelatedMeasuresIds(arrRelatedMeasuresIds.count) := l_measureID;
3479   END Loop;
3480   CLOSE cv;
3481   l_stack := l_stack ||' Check 1' ||newline||bsc_metadata_optimizer_pkg.gIndent;
3482   /*The measures in the array arrMeasuresCols are the ones that could be changed
3483     For that reason the indicators were flaged to 4
3484     We need to see in all system measures if there is a formula using that measure.
3485     IF that happen we need to add that measure. Any kpi using that meaure should be flaged too.*/
3486   strWhereNotInIndics := ' NOT ( ' || strWhereInIndics || ')';
3487   l_stmt := 'SELECT DISTINCT M.MEASURE_ID, M.MEASURE_COL FROM BSC_SYS_MEASURES M, '
3488             ||BSC_METADATA_OPTIMIZER_PKG.g_dbmeasure_tmp_table||
3489              ' I WHERE I.MEASURE_ID = M.MEASURE_ID
3490   	       AND ('|| strWhereNotInIndics ||' )
3491             AND M.TYPE = 0 ';
3492   OPEN cv FOR l_stmt ;
3493   LOOP
3494     FETCH cv into l_measureID, l_measureCol;
3495     EXIT WHEN cv%NOTFOUND;
3496     NumOperands := GetFieldExpression(Operands, l_measureCol);
3497     i:= Operands.first;
3498     LOOP
3499       EXIT WHEN Operands.count =0 ;
3500       IF SearchStringExists(arrMeasuresCols, numMeasures, Operands(i)) THEN
3501         --One operand of the formula is one of the measures of a indicator flagged with 4
3502         --We need to add this formula (measure) to the related ones
3503         arrRelatedMeasuresIds(arrRelatedMeasuresIds.count) := l_measureID;
3504         EXIT;
3505       END IF;
3506       EXIT WHEN i = Operands.last;
3507       i:= Operands.next(i);
3508     END LOOP;
3509   END Loop;
3510   CLOSE cv;
3511   l_stack := l_stack ||' Check 3,  arrRelatedMeasuresIds.count =  '|| arrRelatedMeasuresIds.count;
3512   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3513     writeTmp(' arrRelatedMeasuresIds.count = '||arrRelatedMeasuresIds.count);
3514   END IF;
3515   --Now we need to add to garrIndics4() all the indicators using any of the measures
3516   --in arrRelatedMeasuresIds()
3517   IF  arrRelatedMeasuresIds.count > 0 THEN
3518     strWhereInMeasures := Get_New_Big_In_Cond_Number( 9, 'MEASURE_ID');
3519     /*i:= arrRelatedMeasuresIds.first;
3520     LOOP
3521       EXIT WHEN arrRelatedMeasuresIds.count=0;
3522       Add_Value_Big_In_Cond_Number( 9, arrRelatedMeasuresIds(i));
3523       l_stack := l_stack || newline||' Added measure id '||arrRelatedMeasuresIds(i);
3524       EXIT WHEN i=arrRelatedMeasuresIds.last;
3525       i:= arrRelatedMeasuresIds.next(i);
3526       IF (length(l_stack) > 30000) THEN
3527          l_stack := substr(l_stack, 20000);
3528       END IF;
3529     END LOOP;*/
3530     Add_value_bulk(9, arrRelatedMeasuresIds);
3531     l_stmt := 'SELECT DISTINCT INDICATOR FROM BSC_DB_MEASURE_BY_DIM_SET_V WHERE ('|| strWhereInMeasures || ')';
3532     l_stack := l_stack ||' Check 4, l_stmt =  '||l_stmt ||newline;
3533     open cv for L_stmt;
3534     l_stack := l_stack ||newline ||'Opened cursor';
3535     LOOP
3536       FETCH cv into l_indicator;        /*Indicator*/
3537       l_stack := l_stack ||newline||' fetched';
3538       EXIT WHEN cv%NOTFOUND;
3539       -- PMD does not update the related indicators
3540       l_stack := l_stack ||newline||'going to update...';
3541       UPDATE BSC_KPIS_B
3542          SET PROTOTYPE_FLAG   = DECODE(PROTOTYPE_FLAG, 2, 2, 3, 3, 4),
3543              LAST_UPDATED_BY  = BSC_METADATA_OPTIMIZER_PKG.gUserId,
3544              LAST_UPDATE_DATE = SYSDATE
3545 	   WHERE INDICATOR = l_indicator
3546              AND prototype_flag not in (2,3);
3547       IF (SQL%rowcount>0) THEN
3548         l_stack := l_stack ||'updated '||l_indicator||' to 4';
3549         bsc_mo_helper_pkg.writeTmp('Updating prototype_flag for '||l_indicator ||' to 4');
3550       END IF;
3551       IF (length(l_stack)>30000) THEN
3552         l_stack := substr(l_stack, 20000);
3553       END IF;
3554     END Loop;
3555     CLOSE cv;
3556     l_stack := l_stack ||' Check 5 ';
3557   END IF;
3558   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3559     writeTmp('Completed MarkIndicsForNonStrucChanges', FND_LOG.LEVEL_PROCEDURE);
3560   END IF;
3561   EXCEPTION WHEN OTHERS THEN
3562     l_error := sqlerrm;
3563     writeTmp('Exception in MarkIndicsForNonStrucChanges : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3564     writeTmp('Local Stack dump = '||l_stack, FND_LOG.LEVEL_EXCEPTION, true);
3565     raise;
3566 End;
3567 
3568 
3569 
3570 --****************************************************************************
3571 --  Inic: getInitColumn
3572 --  DESCRIPTION:
3573 --     Read the given variable from BSC_SYS_INIT
3574 --
3575 --  PARAMETERS:
3576 --     Variable: variable name
3577 --****************************************************************************
3578 
3579 FUNCTION getInitColumn(p_column IN VARCHAR2) return VARCHAR2 IS
3580 l_stmt varchar2(1000);
3581 l_value varchar2(300);
3582 cv   CurTyp;
3583 l_error VARCHAR2(400);
3584 BEGIN
3585 	l_stmt := 'SELECT PROPERTY_VALUE FROM BSC_SYS_INIT WHERE UPPER(PROPERTY_CODE) = :1';
3586 	open cv for l_stmt using p_column;
3587 	FETCH cv into l_value;
3588 	CLOSE cv;
3589 	return l_value;
3590   EXCEPTION WHEN OTHERS THEN
3591       l_error := sqlerrm;
3592       writeTmp('Exception in getInitColumn : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3593       raise;
3594 END;
3595 
3596 --****************************************************************************
3597 --  decomposeString
3598 --  DESCRIPTION:
3599 --     Break up a comma separated string (or some separated string)
3600 --     into separate elements and return an array
3601 --
3602 --  PARAMETERS:
3603 --     p_string: Comma or character separated string
3604 --     p_separator: Separator
3605 --     p_return_array: return array
3606 --****************************************************************************
3607 
3608 FUNCTION decomposeString(p_string IN VARCHAR2, p_separator IN VARCHAR2, p_return_array OUT NOCOPY DBMS_SQL.VARCHAR2_TABLE)
3609 return NUMBER IS
3610 
3611 l_str VARCHAR2(32000);
3612 --l_substr VARCHAR2(4000) := null;
3613 position NUMBER := 0;
3614 l_count  NUMBER := 0 ;
3615 l_error VARCHAR2(400) := null;
3616 l_LOOP_stack VARCHAR2(32000) := null;
3617 l_value VARCHAR2(100);
3618 
3619 BEGIN
3620 
3621   IF p_string IS NOT NULL  THEN
3622 	   l_LOOP_stack := 'Check1';
3623      l_str := p_string;
3624      position := Instr(l_str, p_separator);
3625 	   l_LOOP_stack := 'Check2, position = '||position;
3626 	   IF (position = 0) THEN
3627         p_return_array(0) := p_string;
3628         return 1;
3629 	   END IF;
3630 
3631       LOOP
3632         l_LOOP_stack := l_LOOP_stack||newline||'l_count= '||l_count;
3633         EXIT WHEN POSITION = 0 OR position is NULL or trim(l_str) is null;
3634         l_value :=  Trim(substr(l_str,1, position - 1));
3635         l_LOOP_stack := l_LOOP_stack||newline||'l_value= '||l_value;
3636         IF (l_value IS NOT NULL) THEN
3637           p_return_array(l_count) := l_value;
3638           l_count := l_count + 1;
3639         END IF;
3640         l_LOOP_stack := l_LOOP_stack||newline||'l_count= '||l_count;
3641         l_str := substr(l_str, position+1, length(l_str)- position);
3642         l_LOOP_stack := l_LOOP_stack||newline||'Check 3';
3643         position := InStr(l_str, p_separator);
3644         l_LOOP_stack := l_LOOP_stack||newline||'Check 4';
3645 
3646         IF (length(l_LOOP_stack) > 20000) THEN
3647           l_LOOP_stack := null;
3648         END IF;
3649 
3650       END LOOP;
3651 
3652       IF (trim(l_str) IS NOT NULL) THEN
3653         p_return_array(l_count) := Trim(l_str);
3654       END IF;
3655       l_LOOP_stack := l_LOOP_stack||newline||' Going to assign return array';
3656       l_LOOP_stack := l_LOOP_stack||newline||' Going to return '||l_count;
3657       return p_return_array.count;
3658   Else
3659 	  return 0;
3660   END IF;
3661 
3662   EXCEPTION WHEN OTHERS THEN
3663       l_error := sqlerrm;
3664       writeTmp('Exception in decomposeString : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3665   	  WriteTmp('Parameters were p_string ='||p_string||'and  p_separator = '||p_separator, FND_LOG.LEVEL_EXCEPTION, true);
3666 	  writeTmp('Loop counter = '||l_count||' and Loop stack is '||l_LOOP_stack, FND_LOG.LEVEL_EXCEPTION, true);
3667       raise;
3668 
3669 END;
3670 
3671 --****************************************************************************
3672 --  decomposeStringtoNumber
3673 --  DESCRIPTION:
3674 --     Break up a comma separated string (or some separated string)
3675 --     into separate numbers and return an number array
3676 --
3677 --  PARAMETERS:
3678 --     p_string: Comma or character separated string
3679 --     p_separator: Separator
3680 --     p_return_array: return array of numbers
3681 --****************************************************************************
3682 
3683 
3684 FUNCTION decomposeStringtoNumber(p_string IN VARCHAR2, p_separator IN VARCHAR2 )
3685 return DBMS_SQL.NUMBER_TABLE IS
3686 
3687 l_str VARCHAR2(32000);
3688 l_substr VARCHAR2(32000);
3689 position NUMBER;
3690 l_count  NUMBER;
3691 l_return_array DBMS_SQL.NUMBER_TABLE;
3692 l_error VARCHAR2(400);
3693 BEGIN
3694 
3695   IF p_string IS NOT NULL  THEN
3696       l_str := p_string;
3697       position := Instr(l_str, p_separator);
3698       l_count := 0;
3699   	LOOP
3700 	      EXIT WHEN POSITION = 0;
3701         l_return_array(l_count) := to_number(Trim(substr(l_str,1, position - 1)));
3702         l_count := l_count + 1;
3703 	      l_str := substr(l_str, position+1, length(l_str)- position);
3704         position := InStr(l_str, p_separator);
3705       END Loop;
3706 
3707       l_return_array(l_count) := to_number(Trim(l_str));
3708 	  l_count := l_count + 1;
3709   END IF;
3710   return l_return_array;
3711   EXCEPTION WHEN OTHERS THEN
3712       l_error := sqlerrm;
3713       writeTmp('Exception in decomposeStringtoNumber : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3714       raise;
3715 END;
3716 
3717 --****************************************************************************
3718 --  getDecomposedString
3719 --  DESCRIPTION:
3720 --     Break up a comma separated string (or some separated string)
3721 --     into separate elements and return an array
3722 --
3723 --  PARAMETERS:
3724 --     p_string: Comma or character separated string
3725 --     p_separator: Separator
3726 --   RETURNS
3727 --     return array (this is a function as opposed to decomposeString)
3728 --****************************************************************************
3729 
3730 
3731 FUNCTION getDecomposedString(p_string IN VARCHAR2, p_separator IN VARCHAR2) RETURN
3732 DBMS_SQL.VARCHAR2_TABLE IS
3733 l_table DBMS_SQL.VARCHAR2_TABLE ;
3734 l_dummy NUMBER;
3735 BEGIN
3736   l_dummy := decomposeString(p_string, p_separator, l_table);
3737   return l_table;
3738 END;
3739 
3740 PROCEDURE insert_per(p_periodicity IN NUMBER, p_origin IN VARCHAR2) IS
3741 l_origin_list DBMS_SQL.NUMBER_TABLE;
3742 l_table_name VARCHAR2(100) := bsc_metadata_optimizer_pkg.g_period_circ_check ;
3743 l_stmt VARCHAR2(1000) := 'INSERT INTO '||l_table_name||'(periodicity, source) values (:1, :2)';
3744 l_index NUMBER;
3745 BEGIN
3746   l_origin_list := decomposeStringtoNumber(p_origin, ',');
3747   BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'p_origin='||p_origin||', l_origin_list.count='||l_origin_list.count);
3748   if (l_origin_list.count>0) then
3749     forall i in l_origin_list.first..l_origin_list.last
3750       execute immediate l_stmt USING p_periodicity, l_origin_list(i);
3751   end if;
3752   exception when others then
3753     writeTmp('Exception in insert_per:'||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
3754     raise;
3755 END;
3756 
3757 PROCEDURE check_circular_dependency IS
3758 l_table_name VARCHAR2(100) := bsc_metadata_optimizer_pkg.g_period_circ_check ;
3759 l_stmt VARCHAR2(1000) := 'CREATE TABLE '||l_table_name||'(periodicity NUMBER, source NUMBER)';
3760 --modified for bug 6052711
3761 -- we should check for all existing periodicities in the system. Because in
3762 -- Initialize_periodicities we initialize array for all the periodicities in the system
3763   CURSOR cPeriods IS
3764   SELECT distinct sysper.PERIODICITY_ID, sysper.SOURCE
3765   FROM BSC_SYS_PERIODICITIES sysper
3766   ORDER BY PERIODICITY_ID;
3767   cPeriodRow cPeriods%ROWTYPE;
3768   cv CurTyp;
3769   l_temp NUMBER;
3770 
3771 BEGIN
3772   BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'Inside check_circular_dependency');
3773   dropTable(l_table_name);
3774   IF BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName is NULL THEN
3775     InitTablespaceNames;
3776   END IF;
3777   l_stmt := l_stmt ||' TABLESPACE '|| BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName||' '|| BSC_METADATA_OPTIMIZER_PKG.gStorageClause;
3778   Do_DDL(l_stmt, ad_ddl.create_table, l_table_name);
3779   OPEN cPeriods;
3780   LOOP
3781       FETCH cPeriods INTO cPeriodRow;
3782       EXIT WHEN cPeriods%NOTFOUND;
3783       insert_per(cPeriodRow.periodicity_id, cPeriodRow.source);
3784   END LOOP;
3785   CLOSE cPeriods;
3786   commit;
3787 
3788   l_stmt := ' select periodicity from '||l_table_name||' connect by periodicity = prior source start with periodicity = :1';
3789   OPEN cPeriods;
3790   LOOP
3791       FETCH cPeriods INTO cPeriodRow;
3792       EXIT WHEN cPeriods%NOTFOUND;
3793 
3794       BEGIN
3795         OPEN cv FOR l_stmt USING cPeriodRow.PERIODICITY_ID;
3796         LOOP
3797           FETCH cv INTO l_temp;
3798           EXIT WHEN cv%NOTFOUND;
3799         END LOOP;
3800         CLOSE cv;
3801         EXCEPTION WHEN OTHERS THEN
3802         --IF (SQLCODE = -01436) THEN
3803           BSC_METADATA_OPTIMIZER_PKG.logprogress('ERROR', 'Ciruclar dependency for periodicity_id = '||cPeriodRow.PERIODICITY_ID);
3804           writeTmp('Ciruclar dependency for periodicity_id = '||cPeriodRow.PERIODICITY_ID, FND_LOG.LEVEL_EXCEPTION, true);
3805           terminateWithMsg('Ciruclar dependency for periodicity_id = '||cPeriodRow.PERIODICITY_ID);
3806         --END IF;
3807         raise;
3808       END ;
3809   END LOOP;
3810   CLOSE cPeriods;
3811   dropTable(l_table_name);
3812   BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'Completed check_circular_dependency');
3813   exception when others then
3814     writeTmp('Exception in check_circular_dependency:'||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
3815     raise;
3816 END;
3817 
3818 
3819 --****************************************************************************
3820 --  InitializePeriodicities
3821 --  DESCRIPTION:
3822 --     Read periodicities table and initialize variable gPeriodicities.
3823 --     Find parents for each periodicity too.
3824 --
3825 --  PARAMETERS:
3826 --     None
3827 --   RETURNS
3828 --     None
3829 --****************************************************************************
3830 
3831 PROCEDURE InitializePeriodicities IS
3832 
3833   L_Periodicity BSC_METADATA_OPTIMIZER_PKG.clsPeriodicity;
3834   PerOri NUMBER;
3835   Origen VARCHAR2(1000);
3836   arrPerOri DBMS_SQL.VARCHAR2_TABLE;
3837   NumPerOri NUMBER;
3838   i NUMBER;
3839   l_stmt VARCHAR2(1000);
3840 
3841   allSourcesCompleted Boolean;
3842   arrPerSourceCompleted DBMS_SQL.NUMBER_TABLE;
3843   numPerSourceCompleted NUMBER;
3844   srcPerOri NUMBER;
3845   newPerOri NUMBER;
3846 
3847   -- adding a distinct to avoid infinite loop
3848   -- in case of issues with BIS -> BSC calendar synching...
3849   CURSOR cPeriods IS
3850   SELECT distinct sysper.PERIODICITY_ID, sysper.SOURCE, sysper.EDW_FLAG, sysper.YEARLY_FLAG,
3851   sysper.CALENDAR_ID, NVL(sysper.PERIODICITY_TYPE, 0) AS PERIODICITY_TYPE
3852   FROM BSC_SYS_PERIODICITIES_VL sysper
3853   ORDER BY PERIODICITY_ID;
3854 
3855   cPeriodRow cPeriods%ROWTYPE;
3856 
3857   l_index NUMBER;
3858   l_origin_list DBMS_SQL.VARCHAR2_TABLE;
3859   l_origin_index NUMBER;
3860   l_src_origin_index NUMBER;
3861   l_src_origin_list DBMS_SQL.VARCHAR2_TABLE;
3862   l_error VARCHAR2(400);
3863   l_time date := sysdate;
3864   l_seconds number := 0;
3865   l_prev_counter number := 0;
3866 
3867   l_too_long boolean := false;
3868 BEGIN
3869 
3870   check_circular_dependency;
3871   OPEN cPeriods;
3872   LOOP
3873       FETCH cPeriods INTO cPeriodRow;
3874       EXIT WHEN cPeriods%NOTFOUND;
3875       L_Periodicity.Code := cPeriodRow.PERIODICITY_ID;
3876       L_Periodicity.EDW_Flag := cPeriodRow.EDW_FLAG;
3877       L_Periodicity.Yearly_Flag := cPeriodRow.YEARLY_FLAG;
3878       L_Periodicity.CalendarID := cPeriodRow.CALENDAR_ID;
3879       L_Periodicity.PeriodicityType := cPeriodRow.PERIODICITY_TYPE;
3880       L_Periodicity.periodicityOrigin := cPeriodRow.SOURCE ;
3881       BSC_METADATA_OPTIMIZER_PKG.gPeriodicities(BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.count) := L_Periodicity;
3882   END LOOP;
3883   CLOSE cPeriods;
3884 
3885   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
3886       bsc_mo_helper_pkg.writeTmp('# Periodicities = '||BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.count);
3887       bsc_mo_helper_pkg.write_this(BSC_METADATA_OPTIMIZER_PKG.gPeriodicities);
3888   END IF;
3889 
3890 
3891   --Completes the source of periodicities. For example
3892   --if periodicity A can be calculated from B and B can be calculated from C then
3893   --A also can be calculated from C
3894 
3895   numPerSourceCompleted := 0;
3896   WHILE (numPerSourceCompleted < BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.Count) LOOP
3897     l_seconds := (sysdate - l_time) *86400;
3898     l_index := BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.first;
3899     LOOP
3900       EXIT WHEN BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.count = 0;
3901       L_Periodicity := BSC_METADATA_OPTIMIZER_PKG.gPeriodicities(l_index);
3902       If Not SearchNumberExists(arrPerSourceCompleted, numPerSourceCompleted, L_Periodicity.Code) Then
3903         --We have not completed the sources of this periodicity
3904         --Check that all the source periodicities are completed
3905         if (mod(l_seconds, 100)=0 ) then -- more than 100 secs
3906           if (l_seconds <> l_prev_counter) then
3907            writetmp('Spent '||l_seconds ||' seconds inside InitializePeriodicities, periodicity w/o source = '||L_Periodicity.Code);
3908            l_prev_counter := l_seconds;
3909            BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'Spent '||l_seconds ||' seconds inside InitializePeriodicities, periodicity w/o source = '||L_Periodicity.Code);
3910            l_too_long:=true;
3911          end if;
3912         end if;
3913         allSourcesCompleted := True;
3914         l_origin_list := getDecomposedString (L_Periodicity.PeriodicityOrigin, ',');
3915         l_origin_index := l_origin_list.first;
3916         LOOP
3917           EXIT WHEN l_origin_list.count= 0;
3918           PerOri := l_origin_list(l_origin_index);
3919           If Not searchNumberExists(arrPerSourceCompleted, numPerSourceCompleted, PerOri) Then
3920             --This periodicity is not complete
3921             allSourcesCompleted := False;
3922             if findIndex(BSC_METADATA_OPTIMIZER_PKG.gPeriodicities, PerOri)=-1 then
3923               terminateWithMsg('Periodicity id '||L_Periodicity.Code||' has invalid source periodicity='||PerOri);
3924               raise bsc_metadata_optimizer_pkg.optimizer_exception;
3925               return; -- Mark as error in CP status
3926             end if;
3927             if(l_too_long) then
3928               bsc_metadata_optimizer_pkg.logProgress('ERROR?', 'Periodicity id='||L_Periodicity.Code||', origin ='||PerOri||' not completed');
3929             end if;
3930             Exit;
3931           End If;
3932           EXIT WHEN l_origin_index = l_origin_list.last;
3933           l_origin_index := l_origin_list.next(l_origin_index);
3934         END LOOP;
3935 
3936         If allSourcesCompleted Then
3937           --Add all the source periodicities of the sources in the list
3938           --of source of this periodicity
3939           l_origin_index := l_origin_list.first;
3940           LOOP
3941             EXIT WHEN l_origin_list.count= 0;
3942             PerOri := l_origin_list(l_origin_index);
3943             l_src_origin_index := findIndex(BSC_METADATA_OPTIMIZER_PKG.gPeriodicities, PerOri);
3944             l_src_origin_list := getDecomposedString(BSC_METADATA_OPTIMIZER_PKG.gPeriodicities(l_src_origin_index).periodicityOrigin, ',');
3945             l_src_origin_index := l_src_origin_list.first;
3946 
3947             LOOP
3948               EXIT WHEN l_src_origin_list.count = 0;
3949               srcPerOri := l_src_origin_list(l_src_origin_index);
3950               If instr(L_Periodicity.PeriodicityOrigin, to_char(srcPerOri)) = 0 Then
3951                 --The source periodicity is not already in the list of sources
3952                 newPerOri := srcPerOri;
3953                 BSC_METADATA_OPTIMIZER_PKG.gPeriodicities(l_index).periodicityOrigin :=
3954                 BSC_METADATA_OPTIMIZER_PKG.gPeriodicities(l_index).periodicityOrigin||','||newPerOri;
3955               End If;
3956               EXIT WHEN l_src_origin_index = l_src_origin_list.last;
3957               l_src_origin_index := l_src_origin_list.next(l_src_origin_index);
3958             END LOOP;
3959 
3960             EXIT WHEN l_origin_index = l_origin_list.last;
3961             l_origin_index := l_origin_list.next(l_origin_index);
3962           END LOOP;
3963           --Add this periodicity to the array arrPerSourceCompleted()
3964           arrPerSourceCompleted(numPerSourceCompleted) := L_Periodicity.Code;
3965           numPerSourceCompleted := numPerSourceCompleted + 1;
3966         End If; --allSourcesCompleted
3967       End If;
3968       EXIT WHEN l_index = BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.last;
3969       l_index := BSC_METADATA_OPTIMIZER_PKG.gPeriodicities.next(l_index);
3970     END LOOP;
3971   END LOOP;
3972 
3973   EXCEPTION WHEN OTHERS THEN
3974       l_error := sqlerrm;
3975       writeTmp('Exception in initializePeriodicities : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
3976       raise;
3977 END;
3978 
3979 PROCEDURE InitializeCalendars IS
3980 
3981 cursor cCal IS
3982 SELECT
3983 B.CALENDAR_ID,
3984 B.EDW_FLAG,
3985 B.NAME,
3986 B.FISCAL_YEAR,
3987 B.RANGE_YR_MOD,
3988 NVL(B.EDW_CALENDAR_TYPE_ID, 0) SOURCE,
3989 (
3990  NVL((SELECT MAX(NUM_OF_YEARS - PREVIOUS_YEARS)
3991  FROM BSC_KPI_PERIODICITIES
3992  WHERE NVL(NUM_OF_YEARS, 0) > 0 AND
3993      PERIODICITY_ID IN (SELECT PERIODICITY_ID
3994                   FROM BSC_SYS_PERIODICITIES S
3995                   WHERE S.CALENDAR_ID = B.CALENDAR_ID))
3996    , 1)
3997 ) AS MAX_FORYEAR,
3998 (
3999  NVL((SELECT MAX(PREVIOUS_YEARS)
4000  FROM BSC_KPI_PERIODICITIES
4001  WHERE NVL(NUM_OF_YEARS, 0) > 0 AND
4002      PERIODICITY_ID IN (SELECT PERIODICITY_ID
4003                   FROM BSC_SYS_PERIODICITIES S
4004                   WHERE S.CALENDAR_ID = B.CALENDAR_ID))
4005    , 1)
4006 ) AS MAX_PREVIOUS,
4007 --Added 05/18/2005 after conversation with Venu
4008 --DBI calendar ids should be 1001, 1002 or 1003
4009 EDW_CALENDAR_ID
4010 FROM
4011 BSC_SYS_CALENDARS_VL B;
4012 
4013 cRow cCal%ROWTYPE;
4014 l_count NUMBER := 0;
4015 l_calendar BSC_METADATA_OPTIMIZER_PKG.clsCalendar;
4016 l_error VARCHAR2(400);
4017 BEGIN
4018    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4019       writeTmp( 'Inside InitializeCalendars');--commit;
4020    END IF;
4021 
4022 	open cCal;
4023 
4024 	LOOP
4025 	  FETCH cCal into cRow;
4026 	  EXIT WHEN cCal%NOTFOUND;
4027       l_calendar := new_clsCalendar ;
4028 	  l_calendar.Code := cRow.calendar_id;
4029 	  l_calendar.EDW_Flag := cRow.edw_flag;
4030 	  l_calendar.CurrFiscalYear := cRow.Fiscal_Year;
4031 	  l_calendar.RangeYrMod := cRow.Range_Yr_Mod;
4032 	  l_calendar.NumOfYears := cRow.Max_foryear + cRow.Max_previous;
4033 	  l_calendar.previousYears := cRow.Max_Previous;
4034       --BIS DIMENSIONS: new property: source
4035       -- Changed 05/18/2005, added check for EDW_CALENDAR_ID to be in 1001, 1002 and 1003 for dBI calendars
4036       If cRow.SOURCE = 1 and cRow.EDW_CALENDAR_ID IN (1001,1002,1003) Then
4037         l_calendar.Source := 'PMF';
4038       Else
4039         l_calendar.Source := 'BSC';
4040       End If;
4041 	  BSC_METADATA_OPTIMIZER_PKG.gCalendars(l_count) := l_calendar;
4042 	  l_count := l_count+1;
4043 	END LOOP;
4044 	CLOSE cCal;
4045    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4046      writeTmp( 'Completed InitializeCalendars');
4047    END IF;
4048 
4049 
4050   EXCEPTION WHEN OTHERS THEN
4051      l_error := sqlerrm;
4052       writeTmp('Exception in InitializeCalendars : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
4053      TerminateWithError ('BSC_CALENDAR_INIT_FAILED', 'InitializeCalendars');
4054      raise;
4055 END;
4056 
4057 -- Given a list of S tables, find the list of tables in the tree
4058 -- starting from the S table going towards the I table. We need this to figure out which tables
4059 -- can be dropped safely while running the optimizer for a list
4060 -- of selected indicators
4061 
4062 PROCEDURE InsertDirectTables(arrTables in out nocopy dbms_Sql.varchar2_table, p_variable_id IN NUMBER) IS
4063 CURSOR cStoITables IS
4064 select distinct source_table_name from bsc_db_tables_rels
4065 connect by table_name = prior source_table_name
4066 start with table_name in (
4067     SELECT VALUE_V FROM BSC_TMP_BIG_IN_COND WHERE SESSION_ID = bsc_metadata_optimizer_pkg.g_session_id
4068     AND VARIABLE_ID = p_variable_id);
4069 lTable VARCHAR2(100);
4070 BEGIN
4071 	OPEN cStoITables;
4072 	LOOP
4073 		FETCH cStoITables INTO lTable;
4074 		EXIT WHEN cStoITables%NOTFOUND;
4075 		arrTables(arrTables.count) := lTable;
4076 	END LOOP;
4077 
4078 END;
4079 
4080 -- Given a list of production indicators, get the list of production tables they need
4081 -- Start with BSC_KPI_DATA_TABLES to get the S table name and then move from S to I table
4082 
4083 FUNCTION GetAffectedProductionTables(inIndicators in VARCHAR2) return dbms_Sql.varchar2_table IS
4084 
4085 cv CurTyp;
4086 
4087 l_stmt VARCHAR2(1000):= 'select distinct source_table_name from bsc_db_tables_rels
4088 connect by table_name = prior source_table_name
4089 start with table_name in (';
4090 
4091 l_tables dbms_Sql.varchar2_table ;
4092 l_table varchar2(100);
4093 BEGIN
4094 	l_stmt := l_stmt ||inIndicators ||' )';
4095 	OPEN cv for l_stmt;
4096 	LOOP
4097 		FETCH cv INTO l_table;
4098 		EXIT WHEN cv%NOTFOUND;
4099 		l_tables(l_tables.count) := l_table;
4100 	END LOOP;
4101 END;
4102 
4103 -- add to garrTables the list of tables that are used  ONLY by the specified indicators
4104 -- if two indicators share a table, but only one of them
4105 
4106 Procedure MarkTablesForSelectedKPIs IS
4107 
4108     l_stmt varchar2(1000);
4109     strWhereInIndics varchar2(1000);
4110     strWhereNotInIndics varchar2(1000);
4111     strWhereInTables varchar2(1000);
4112     i number := 0;
4113     lTable varchar2(100);
4114     cv CurTyp;
4115     lError VARCHAR2(400);
4116     arrayDirectTables dbms_sql.varchar2_table;
4117     strWhereInDirectTables varchar2(1000);
4118     strWhereInDirectIndics varchar2(1000);
4119 
4120     arrayAllAffectedTables dbms_sql.varchar2_table;
4121     l_varchar2_list dbms_sql.varchar2_table;
4122 
4123     l_dontProcessIndics VARCHAR2(1000);
4124     l_dontDropTables VARCHAR2(1000);
4125     l_DropTables VARCHAR2(1000);
4126     l_varchar2_table dbms_sql.varchar2_table;
4127 BEGIN
4128   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4129     writeTmp( 'Inside MarkTablesForSelectedKPIs', FND_LOG.LEVEL_PROCEDURE, false);
4130   END IF;
4131 
4132   --Initialize the array garrTables the tables used by the indicators in the array garrIndics()
4133   --EDW Integration note:
4134   --In BSC_KPI_DATA_TABLES, Metadata Optimizer is storing the name of the view (Example: BSC_3001_0_0_5_V)
4135   --and the name of the S table for BSC Kpis (Example: BSC_3002_0_0_5)
4136   --In this procedure we need to get tables names from a view BSC_KPI_DATA_TABLES_V.
4137 
4138   BSC_METADATA_OPTIMIZER_PKG.gnumTables := 0;
4139   BSC_METADATA_OPTIMIZER_PKG.garrTables.delete;
4140 
4141   IF BSC_METADATA_OPTIMIZER_PKG.gnumIndics > 0 THEN
4142     strWhereInIndics := Get_New_Big_In_Cond_Number( 20, 'INDICATOR');
4143     strWhereNotInIndics := null;
4144     i:= 0;
4145     IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4146       writeTmp( 'gnumIndics is '||BSC_METADATA_OPTIMIZER_PKG.gnumIndics);
4147     END IF;
4148     Add_Value_Bulk(20, BSC_METADATA_OPTIMIZER_PKG.garrIndics);
4149     strWhereNotInIndics := 'NOT ('|| strWhereInIndics ||')';
4150     --Bug 5138449, dont use tmp table, use kpi_data_tables as we need all S tables, not just the lowest level S tables
4151     l_stmt := ' SELECT DISTINCT TABLE_NAME FROM BSC_KPI_DATA_TABLES WHERE ('||
4152        	 strWhereInIndics|| ') AND TABLE_NAME IS NOT NULL';
4153     writeTmp( 'l_stmt = '||l_stmt, FND_LOG.LEVEL_STATEMENT, false);
4154     OPEN cv for l_stmt;
4155     LOOP
4156       FETCH cv into lTable;
4157       EXIT WHEN cv%NOTFOUND;
4158       BSC_METADATA_OPTIMIZER_PKG.garrTables(BSC_METADATA_OPTIMIZER_PKG.gnumTables) := lTable;
4159       BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.gnumTables + 1;
4160       --Add_Value_Big_In_Cond_VARCHAR2( 21, lTable);
4161       l_varchar2_list(l_varchar2_list.count+1) := lTable;
4162     END Loop;
4163     CLOSE cv;
4164     -- just in case garrTables is  already populated ahead
4165     Add_Value_Bulk(21, l_varchar2_list);
4166   END IF;
4167   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4168     writeTmp( 'gnumTables is '||BSC_METADATA_OPTIMIZER_PKG.gnumTables);
4169   END IF;
4170   IF BSC_METADATA_OPTIMIZER_PKG.gnumTables > 0 THEN
4171     -- we need to follow this algorithm to find which tables can be dropped :
4172     --0. Get List of Indicators to be processed
4173     --1. Find list of tables for 0. going from S to I tables
4174     --2. Find list of inter-related tables for 1.
4175     --3. Find list of indicators using any table from 2.
4176     --4. Affected inter-related indicators 3 - 0
4177     --5. For indicators in 4, get list of tables going from S to I tables
4178     --6. Subtract 1-5
4179     --7. Drop tables in 6
4180 
4181     --0. Get List of Indicators to be processed
4182     -- Step 0 is already taken care of in InitIndicators
4183     ---------------------------------------------------------------
4184     -- Step 1. Find list of tables for 0. going from S to I tables
4185     ---------------------------------------------------------------
4186     writeTmp( 'Calling InsertDirectTables', FND_LOG.LEVEL_STATEMENT, false);
4187     InsertDirectTables(BSC_METADATA_OPTIMIZER_PKG.garrTables, 21);
4188     writeTmp( 'Done with InsertDirectTables', FND_LOG.LEVEL_STATEMENT, false);
4189     strWhereInDirectTables := Get_New_Big_In_Cond_Varchar2( 22, 'TABLE_NAME');
4190     BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.garrTables.count;
4191     Add_Value_Bulk(22, BSC_METADATA_OPTIMIZER_PKG.garrTables);
4192     arrayDirectTables := BSC_METADATA_OPTIMIZER_PKG.garrTables;
4193     ---------------------------------------------------
4194     -- Step 2. Find list of inter-related tables for 1.
4195     ---------------------------------------------------
4196     writeTmp( 'Calling InsertRelatedTables', FND_LOG.LEVEL_STATEMENT, false);
4197     InsertRelatedTables( arrayDirectTables, BSC_METADATA_OPTIMIZER_PKG.gnumTables);
4198     writeTmp( 'Done InsertRelatedTables', FND_LOG.LEVEL_STATEMENT, false);
4199     --Mark the indicators affected by those tables
4200     strWhereInTables := Get_New_Big_In_Cond_Varchar2( 23, 'TABLE_NAME');
4201     i:= 0;
4202     writeTmp( 'strWhereInTables='||strWhereInTables, FND_LOG.LEVEL_STATEMENT, false);
4203     writeTmp( 'BSC_METADATA_OPTIMIZER_PKG.garrTables.count='||BSC_METADATA_OPTIMIZER_PKG.garrTables.count, FND_LOG.LEVEL_STATEMENT, false);
4204     l_varchar2_list.delete;
4205     LOOP
4206       EXIT WHEN BSC_METADATA_OPTIMIZER_PKG.garrTables.count=0;
4207       IF searchStringExists(arrayDirectTables, arrayDirectTables.count, BSC_METADATA_OPTIMIZER_PKG.garrTables(i)) THEN
4208         null;
4209       ELSE
4210         l_varchar2_list(l_varchar2_list.count+1):= BSC_METADATA_OPTIMIZER_PKG.garrTables(i);
4211       END IF;
4212       EXIT WHEN i = BSC_METADATA_OPTIMIZER_PKG.garrTables.last;
4213       i := BSC_METADATA_OPTIMIZER_PKG.garrTables.next(i);
4214     END LOOP;
4215     Add_Value_Bulk(23, l_varchar2_list);
4216     l_varchar2_list.delete;
4217     writeTmp( 'Done loop', FND_LOG.LEVEL_STATEMENT, false);
4218     writeTmp( 'strWhereInTables ='||strWhereInTables, FND_LOG.LEVEL_STATEMENT, false);
4219     writeTmp( 'strWhereNotInIndics ='||strWhereNotInIndics, FND_LOG.LEVEL_STATEMENT, false);
4220     ----------------------------------------------------------
4221     --Step 3. Find list of indicators using any table from 2.
4222     ----------------------------------------------------------
4223     l_dontProcessIndics  := 'SELECT DISTINCT INDICATOR FROM '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' WHERE ('||strWhereInTables|| ')';
4224     --------------------------------------------------
4225     --Step 4. Affected inter-related indicators 3 - 0
4226     --------------------------------------------------
4227     l_dontProcessIndics := l_dontProcessIndics||' AND ('||strWhereNotInIndics||')';
4228     writeTmp( 'l_dontProcessIndics ='||l_dontProcessIndics, FND_LOG.LEVEL_STATEMENT, false);
4229     -- for the indicators that are impacted but are not being processed, we need to preserve
4230     -- the tables. so get the list of tables used by these indicators
4231     ---------------------------------------------------------------------
4232     --Step 5. For indicators in 4, get list of tables going from S to I tables
4233     ---------------------------------------------------------------------
4234     l_dontDropTables := ' select source_table_name from bsc_db_tables_rels
4235                   connect by table_name = prior source_table_name start with table_name in
4236                  (select table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' where indicator in ('||l_dontProcessIndics||') )';
4237     writeTmp( 'l_dontDropTables ='||l_dontDropTables, FND_LOG.LEVEL_STATEMENT, false);
4238     ---------------------------------------------------
4239     --Step 6. Subtract 1-5
4240     ---------------------------------------------------
4241     l_dropTables := 'select table_name from bsc_db_tables where ('||strWhereInDirectTables||') '||' and table_name not in ('||
4242                       l_dontDropTables||')';
4243     writeTmp( 'l_dropTables ='||l_dropTables, FND_LOG.LEVEL_STATEMENT, false);
4244     BSC_METADATA_OPTIMIZER_PKG.gnumTables := 0;
4245     BSC_METADATA_OPTIMIZER_PKG.garrTables.delete;
4246     l_dropTables := replace(l_dropTables, 'UPPER(TABLE_NAME)', 'TABLE_NAME');
4247     l_dropTables := replace(l_dropTables, 'UPPER(VALUE_V)', 'VALUE_V');
4248     OPEN cv for l_dropTables;
4249     FETCH cv BULK COLLECT INTO l_varchar2_table;
4250     CLOSE cv;
4251     FOR k in 1..l_varchar2_table.count LOOP
4252       lTable := l_varchar2_table(k);
4253       BSC_METADATA_OPTIMIZER_PKG.garrTables(BSC_METADATA_OPTIMIZER_PKG.gnumTables) := lTable;
4254       BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.gnumTables + 1;
4255       writeTmp( 'will drop ' || lTable, FND_LOG.LEVEL_STATEMENT, false);
4256     END Loop;
4257   END IF;
4258   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4259     writeTmp( 'Completed MarkTablesForSelectedKPIs', FND_LOG.LEVEL_PROCEDURE, false);
4260   END IF;
4261   EXCEPTION WHEN OTHERS THEN
4262     lError := sqlerrm;
4263     IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4264       writeTmp('Exception in MarkTablesForSelectedKPIs : '||lError);
4265     END IF;
4266     raise;
4267 End;
4268 
4269 /****************************************************************************
4270 --  CheckAllIndicsHaveSystem
4271 --
4272 --  DESCRIPTION:
4273 --     Check that all indicators in BSC_KPIS_B have been assigned to some Tab.
4274 --     IF some indicator has not been assigned the GAA cannot continue.
4275 --
4276 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4277 --     Arun Santhanam
4278 --***************************************************************************/
4279 Procedure CheckAllIndicsHaveSystem IS
4280 	l_stmt varchar2(4000);
4281 	kpilist varchar2(32000);
4282 	l_indicator varchar2(100);
4283  cv   CurTyp;
4284   l_error VARCHAR2(4000);
4285 
4286   CURSOR cIndics IS
4287   SELECT DISTINCT K.INDICATOR
4288   FROM BSC_KPIS_B K, BSC_TAB_INDICATORS T WHERE K.INDICATOR = T.INDICATOR (+)
4289   AND T.INDICATOR IS NULL AND K.PROTOTYPE_FLAG <> 2 ORDER BY K.INDICATOR;
4290 
4291 BEGIN
4292    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4293   	      writeTmp( 'Inside CheckAllIndicsHaveSystem');   --commit;
4294    END IF;
4295 
4296   IF (getInitColumn('MODEL_TYPE') = 6) THEN
4297       --only if the system is a Tab panel
4298      kpilist := null;
4299      OPEN cIndics;
4300      LOOP
4301        FETCH cIndics INTO l_indicator;
4302        EXIT when cIndics%NOTFOUND;
4303        IF kpilist IS NULL THEN
4304          kpilist := l_indicator;
4305        Else
4306          kpilist := kpilist || ', '|| l_indicator;
4307        END IF;
4308      END Loop;
4309      CLOSE cIndics;
4310     IF kpilist IS NOT NULL THEN
4311       fnd_message.set_name('BSC','BSC_MISSING_KPI_TAB_ASSIG');
4312       l_indicator := fnd_message.get;
4313       IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4314         writeTmp( 'Compl. CheckAllIndicsHaveSystem, error BSC_MISSING_KPI_TAB_ASSIG');
4315       END IF;
4316       FND_FILE.put_line(FND_FILE.LOG, l_indicator||':'||kpilist);
4317       terminateWithError('BSC_MISSING_KPI_TAB_ASSIG', 'CheckAllIndicsHaveSystem');
4318       terminateWithMsg(kpiList);
4319       raise bsc_metadata_optimizer_pkg.optimizer_exception;
4320       return; -- Mark as error in CP status
4321     END IF;
4322   END IF;
4323   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4324     writeTmp( 'Compl. CheckAllIndicsHaveSystem');
4325   END IF;
4326   EXCEPTION WHEN OTHERS THEN
4327       l_error := sqlerrm;
4328       	writeTmp('Exception in CheckAllIndicsHaveSystem : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
4329       raise;
4330 End;
4331 
4332 /****************************************************************************
4333 --  CheckAllSharedIndicsSync : CheckAllSharedIndicsSynchronyzed
4334 --
4335 --  DESCRIPTION:
4336 --     Check that all shared indicators in BSC_KPIS_B have been synchronized
4337 --     IF some shared indicator has not been synchronized,GAA cannot continue.
4338 --
4339 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4340 --     Arun Santhanam
4341 --***************************************************************************/
4342 PROCEDURE CheckAllSharedIndicsSync IS
4343 l_error varchar2(1000);
4344 	kpilist varchar2(1000);
4345 	l_indicator number;
4346 	l_source_indicator number;
4347 
4348   CURSOR cSharedIndics IS
4349   SELECT DISTINCT INDICATOR, SOURCE_INDICATOR FROM BSC_KPIS_B
4350   WHERE SHARE_FLAG = 3 AND SOURCE_INDICATOR IS NOT NULL AND PROTOTYPE_FLAG <> 2 ;
4351 
4352 BEGIN
4353   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4354     writeTmp( 'Inside CheckAllSharedIndicsSync');   --commit;
4355   END IF;
4356   OPEN cSharedIndics;
4357   --Try to re-syncronized those indicators
4358   LOOP
4359     FETCH cSharedIndics INTO l_indicator, l_source_indicator;
4360     EXIT WHEN cSharedIndics%NOTFOUND;
4361     BSC_DESIGNER_PVT.Duplicate_KPI_Metadata(l_source_indicator, l_indicator, 0, NULL);
4362     CheckError('Duplicate_KPI_Metadata');
4363   END Loop;
4364   CLOSE cSharedIndics;
4365   --Check again to see which indicator are still not synchronized
4366   kpilist := null;
4367   OPEN cSharedIndics;
4368   LOOP
4369     FETCH cSharedIndics into l_indicator, l_source_indicator;
4370     EXIT WHEN cSharedIndics%NOTFOUND;
4371     IF kpilist IS NULL THEN
4372       kpilist := l_indicator;
4373     Else
4374       kpilist := kpilist ||','||l_indicator;
4375     END IF;
4376   END Loop;
4377   CLOSE cSharedIndics;
4378   IF kpilist IS NOT NULL THEN
4379     fnd_message.set_name('BSC','BSC_SHARED_NOT_SYNCR' );
4380     l_error := fnd_message.get || '('||kpilist||')';
4381     terminateWithMsg(l_error);
4382   END IF;
4383   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4384     writeTmp( 'Compl CheckAllSharedIndicsSync');   --commit;
4385   END IF;
4386 End;
4387 
4388 /****************************************************************************
4389 --  CheckAllEDWIndicsFullyMapped
4390 --  DESCRIPTION:
4391 --     Check all EDW kpis have been fully mapped. Dimensions, Periodicities,
4392 --     Datasets are from EDW
4393 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4394 --***************************************************************************/
4395 PROCEDURE CheckAllEDWIndicsFullyMapped IS
4396 
4397  kpilist varchar2(1000);
4398  l_indicator number;
4399 cv   CurTyp;
4400 l_error varchar2(1000);
4401 
4402   CURSOR cEDWIndics IS
4403   SELECT DISTINCT K.INDICATOR
4404   FROM BSC_KPIS_B K
4405   WHERE EDW_FLAG = 1
4406 		AND EXISTS ( SELECT P.PROPERTY_CODE FROM BSC_KPI_PROPERTIES P
4407 		WHERE P.INDICATOR = K.INDICATOR AND P.PROPERTY_VALUE = 0
4408 		AND P.PROPERTY_CODE IN ('EDW_DATASET_STATUS', 'EDW_CALENDAR_STATUS', 'EDW_DIMENSION_STATUS'));
4409 
4410 BEGIN
4411   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4412     writeTmp( 'Inside CheckAllEDWIndicsFullyMapped');--commit;
4413   END IF;
4414   --There are 3 flags in BSC_KPI_PROPERTIES to check when a EDW Kpi
4415   --is fully mapped
4416 
4417   kpilist := null;
4418   OPEN cEDWIndics;
4419   LOOP
4420     FETCH cEDWIndics INTO  l_indicator;
4421     EXIT WHEN cEDWIndics%NOTFOUND;
4422     IF kpilist IS NULL THEN
4423       kpilist := to_char(l_indicator);
4424     Else
4425       kpilist := kpilist || ', ' ||to_char(l_indicator);
4426     END IF;
4427   END LOOP;
4428   CLOSE cEDWIndics;
4429   IF kpilist IS NOT NULL THEN
4430     terminateWithError('BSC_EDW_KPIS_NOT_FULL_MAP', 'CheckAllEDWIndicsFullyMapped');
4431     --Get_Message('BSC_EDW_KPIS_NOT_FULL_MAP')  ' (' kpilist ')')
4432   END IF;
4433   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4434     writeTmp( 'Compl CheckAllEDWIndicsFullyMapped');--commit;
4435   END IF;
4436 End;
4437 
4438 Procedure InitIndicators IS
4439   l_stmt varchar2(1000);
4440   l_Code number;
4441   l_Name BSC_KPIS_VL.NAME%TYPE;
4442   l_IndicatorType number;
4443   l_ConfigType number;
4444   l_per_inter number;
4445   l_OptimizationMode number;
4446   l_Action_Flag number;
4447   l_Share_Flag number;
4448   l_Source_Indicator number;
4449   l_EDW_Flag number;
4450   strWhereInIndics Varchar2(1000);
4451   strWhereNotInIndics Varchar2(1000);
4452   strWhereInIndics4 Varchar2(1000);
4453   strWhereNotInIndics4 Varchar2(1000);
4454   i number;
4455   cv   CurTyp;
4456   l_indicator number;
4457   l_indicator4 number;
4458 
4459   l_table VARCHAR2(100);
4460   l_error VARCHAR2(400);
4461 
4462   CURSOR cTables IS
4463   SELECT TABLE_NAME FROM BSC_DB_TABLES WHERE TABLE_TYPE <> 2;
4464   CURSOR cIndics4 IS
4465   SELECT INDICATOR FROM BSC_KPIS_B WHERE PROTOTYPE_FLAG = 4 ORDER BY INDICATOR;
4466 
4467   l_original_count number := 0;
4468   l_impl_type NUMBER := 1;
4469 
4470   l_total_count NUMBER := 0;
4471   l_objectives_count NUMBER:=0;
4472   l_counter number;
4473   l_aw_kpi_list dbms_sql.varchar2_table;
4474 
4475 BEGIN
4476 
4477 
4478   writeTmp( 'Inside InitIndicators, system time is '||get_time, FND_LOG.LEVEL_PROCEDURE, true);
4479 
4480   BSC_METADATA_OPTIMIZER_PKG.garrIndics.delete;
4481   BSC_METADATA_OPTIMIZER_PKG.gnumIndics := 0;
4482 
4483   BSC_METADATA_OPTIMIZER_PKG.garrIndics4.delete;
4484   BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 := 0;
4485 
4486   BSC_METADATA_OPTIMIZER_PKG.garrTables.delete;
4487   BSC_METADATA_OPTIMIZER_PKG.gnumTables := 0;
4488 
4489 
4490   --If we are running optimizer for the first time, the prototype_flag will be 1, so treat it as 3.
4491   IF BSC_METADATA_OPTIMIZER_PKG.gSYSTEM_STAGE = 1  THEN
4492     UPDATE bsc_kpis_b
4493 	   SET prototype_flag = 3
4494 	 WHERE prototype_flag=1;
4495   END IF;
4496 
4497   l_stmt := 'SELECT DISTINCT INDICATOR, NAME, PROTOTYPE_FLAG,
4498       INDICATOR_TYPE, CONFIG_TYPE, PERIODICITY_ID,
4499       SHARE_FLAG, SOURCE_INDICATOR,
4500       EDW_FLAG FROM BSC_KPIS_VL ';
4501 
4502   IF BSC_METADATA_OPTIMIZER_PKG.gGAA_RUN_MODE = 0 THEN
4503     l_stmt := l_stmt || ' where short_name is null OR
4504 	 (short_name is not null and BSC_DBGEN_UTILS.Get_Objective_Type(short_name) = ''OBJECTIVE'')';
4505 	 -- NOTE NOTE NOTE
4506 	 -- Change MODE to modified as ALL doesnt make sense anymore
4507 	 -- as ALL should now exclude KPIs created using report designer
4508      DELETE FROM BSC_TMP_OPT_UI_KPIS WHERE process_id = BSC_METADATA_OPTIMIZER_PKG.g_processID;
4509 	 INSERT INTO BSC_TMP_OPT_UI_KPIS (INDICATOR, PROTOTYPE_FLAG, PROCESS_ID)
4510 	 SELECT INDICATOR, PROTOTYPE_FLAG, BSC_METADATA_OPTIMIZER_PKG.g_processID
4511 	 FROM BSC_KPIS_VL
4512 	 where short_name is null OR
4513 	 (short_name is not null and BSC_DBGEN_UTILS.Get_Objective_Type(short_name) = 'OBJECTIVE');
4514 	 l_objectives_count := SQL%ROWCOUNT;
4515 	 commit;
4516 	 SELECT COUNT(1) INTO l_total_count FROM BSC_KPIS_VL;
4517 	 IF (l_objectives_count <> l_total_count) THEN -- there are autogenerated reports, dont process them
4518 	   BSC_METADATA_OPTIMIZER_PKG.gGAA_RUN_MODE := 1;
4519 	 ELSE
4520 	   writeTmp('Entire system consists of objectives, no autogenerated reports found', FND_LOG.LEVEL_PROCEDURE, true);
4521 	 END IF;
4522   ELSE-- Modified or Selected indicators
4523     l_stmt := l_stmt || ' where prototype_flag in (2,3) and indicator in (SELECT INDICATOR FROM BSC_TMP_OPT_UI_KPIS WHERE process_id = '||BSC_METADATA_OPTIMIZER_PKG.g_processID||')';
4524   END IF;
4525   l_Stmt := l_stmt || ' ORDER BY INDICATOR ';
4526   writeTmp(l_Stmt, FND_LOG.LEVEL_STATEMENT, false);
4527   open cv for l_stmt;
4528   LOOP
4529     FETCH cv into l_code, l_name, l_action_flag,
4530     l_IndicatorType, l_configType, l_per_inter, l_share_flag,
4531     l_source_indicator, l_edw_flag;
4532     EXIT WHEN cv%NOTFOUND;
4533     IF (l_SOURCE_INDICATOR is null) THEN
4534       l_Source_Indicator := 0;
4535     END IF;
4536     l_optimizationMode := getKPIPropertyValue(l_Code, 'DB_TRANSFORM', 1);
4537     If BSC_METADATA_OPTIMIZER_PKG.g_BSC_MV Then
4538       l_impl_type := getKPIPropertyValue(l_Code, BSC_METADATA_OPTIMIZER_PKG.IMPL_TYPE, 1);
4539     END IF;
4540 	IF l_Action_Flag <> 2 THEN
4541       l_Action_Flag := 3;
4542       BSC_METADATA_OPTIMIZER_PKG.gThereisStructureChange := True;
4543     END IF;
4544     AddIndicator( BSC_METADATA_OPTIMIZER_PKG.gIndicators, l_Code, l_name, l_indicatorType, l_ConfigType,
4545 			l_per_inter, l_OptimizationMode, l_action_flag, l_share_flag, l_source_indicator, l_edw_flag, l_impl_type);
4546     BSC_METADATA_OPTIMIZER_PKG.garrIndics(BSC_METADATA_OPTIMIZER_PKG.gnumIndics) := l_code;
4547     BSC_METADATA_OPTIMIZER_PKG.gnumIndics := BSC_METADATA_OPTIMIZER_PKG.gnumIndics + 1;
4548   END Loop;
4549   CLOSE cv;
4550 
4551   --With the array garrIndics() initialized, the following function initialize
4552   --the array arrTables() with all tables related to the tables used directly by the indicators
4553   --in the array garrIndics(). Additionally, add in the array garrIndics() the related indicators.
4554   --BSC-MV Note: Performance fix: if metadata is running for all indicators we do not need
4555   --that complex logic to figure out all the affected tables
4556   IF BSC_METADATA_OPTIMIZER_PKG.gGAA_RUN_MODE = 0 THEN
4557     --Metadata is running for the whole system
4558     BSC_METADATA_OPTIMIZER_PKG.gnumTables := 0;
4559     OPEN cTables;
4560     LOOP
4561       FETCH cTables INTO l_table;
4562       EXIT WHEN cTables%NOTFOUND;
4563       BSC_METADATA_OPTIMIZER_PKG.garrTables(BSC_METADATA_OPTIMIZER_PKG.gnumTables) := l_table;
4564       BSC_METADATA_OPTIMIZER_PKG.gnumTables := BSC_METADATA_OPTIMIZER_PKG.gnumTables + 1;
4565     END LOOP;
4566     CLOSE cTables;
4567   ELSE -- incremental mode or selected mode
4568 
4569     MarkTablesForSelectedKPIs;
4570     writeTmp(' # of indicators now = '||BSC_METADATA_OPTIMIZER_PKG.gIndicators.count, fnd_log.level_statement, false);
4571     BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'Getting Indics with non structural changes ');
4572 	--Add indicators with flag = 4 (reconfigure update)
4573     --in the collection gIndicadores
4574     --Of course if the indicator is already in gIndicadores (Structural changes) we do not change it.
4575     --Init an array with the Kpis in prototype 4 (changes in loader configuration)
4576     l_stmt := 'SELECT DISTINCT INDICATOR, NAME, PROTOTYPE_FLAG,
4577       INDICATOR_TYPE, CONFIG_TYPE, PERIODICITY_ID,
4578       SHARE_FLAG, SOURCE_INDICATOR,
4579       EDW_FLAG FROM BSC_KPIS_VL WHERE INDICATOR in
4580 	  (select indicator from bsc_tmp_opt_ui_kpis where prototype_flag =4 and process_id= :1) ORDER BY INDICATOR';
4581     open cv for l_stmt using BSC_METADATA_OPTIMIZER_PKG.g_processID;
4582     BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'Indics with non structural changes are');
4583     LOOP
4584       FETCH cv into l_code, l_name, l_action_flag,
4585       l_IndicatorType, l_configType, l_per_inter, l_share_flag,
4586       l_source_indicator, l_edw_flag;
4587       exit when cv%NOTFOUND;
4588       BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', l_code);
4589       l_indicator4 := l_code;
4590       BSC_METADATA_OPTIMIZER_PKG.garrIndics4(BSC_METADATA_OPTIMIZER_PKG.gnumIndics4) := l_indicator4;
4591       BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 := BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 + 1;
4592       IF (l_SOURCE_INDICATOR is null) THEN
4593           l_Source_Indicator := 0;
4594       END IF;
4595       IF l_Action_Flag <> 2 THEN
4596           l_Action_Flag := 4;
4597       END IF;
4598       l_OptimizationMode := getKPIPropertyValue(l_Code, 'DB_TRANSFORM', 1);
4599       l_impl_type := getKPIPropertyValue(l_Code, BSC_METADATA_OPTIMIZER_PKG.IMPL_TYPE, 1);
4600       AddIndicator( BSC_METADATA_OPTIMIZER_PKG.gIndicators, l_Code, l_name, l_indicatorType, l_ConfigType,
4601 			l_per_inter, l_OptimizationMode, l_action_flag, l_share_flag, l_source_indicator, l_edw_flag, l_impl_type);
4602     END Loop;
4603     CLOSE cv;
4604     BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', '# of Indics now 2 '||BSC_METADATA_OPTIMIZER_PKG.gIndicators.count||', BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 ='||BSC_METADATA_OPTIMIZER_PKG.gnumIndics4);
4605     writeTmp(' # of indicators now 2= '||BSC_METADATA_OPTIMIZER_PKG.gIndicators.count||
4606                ', BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 ='||BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 , fnd_log.level_statement, false);
4607     strWhereInIndics := Get_New_Big_In_Cond_Number( 1, 'INDICATOR');
4608     strWhereNotInIndics := null;
4609     IF (BSC_METADATA_OPTIMIZER_PKG.garrIndics.count>0) THEN
4610       /*FOR i IN BSC_METADATA_OPTIMIZER_PKG.garrIndics.first..BSC_METADATA_OPTIMIZER_PKG.garrIndics.last LOOP
4611         Add_Value_Big_In_Cond_Number( 1, BSC_METADATA_OPTIMIZER_PKG.garrIndics(i));
4612       END LOOP;*/
4613       Add_value_bulk(1, BSC_METADATA_OPTIMIZER_PKG.garrIndics);
4614     END IF;
4615     strWhereNotInIndics := 'NOT ('|| strWhereInIndics ||')';
4616 
4617     --We need to update the related indicators' prototype_flag as 4 in bsc_kpis_b .
4618     -- Designer is only flagging the indicators
4619     --that are using the measure direclty. We need to flag other indicators
4620     --using the same measures alone or as part of a formula.
4621     BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', 'Mark indics for non struc changes');
4622     IF BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 > 0 THEN
4623       MarkIndicsForNonStrucChanges;
4624       --Add the indicators from garrIndics4() to gIndicadores
4625       strWhereInIndics4 := Get_New_Big_In_Cond_Number( 2, 'INDICATOR');
4626       /*i:= 0;
4627       LOOP
4628         exit when i = BSC_METADATA_OPTIMIZER_PKG.gnumIndics4;
4629         Add_Value_Big_In_Cond_Number( 2, BSC_METADATA_OPTIMIZER_PKG.garrIndics4(i));
4630         i:= i+1;
4631       END LOOP;*/
4632       Add_Value_Bulk(2, BSC_METADATA_OPTIMIZER_PKG.garrIndics4);
4633       strWhereNotInIndics4 := 'NOT (' || strWhereInIndics4 || ')';
4634     END IF; -- numIndics4 >0
4635 
4636     --BSC-MV Note: IF the summarization level was changed, we need to add all indicators
4637     --in production (all indicators not for structural changes or for non-structural changes)
4638     --to the collection of indicators
4639     IF BSC_METADATA_OPTIMIZER_PKG.g_Sum_Level_Change <> 0 THEN
4640       --There is change of summarization level
4641       l_stmt := 'SELECT DISTINCT INDICATOR, NAME, PROTOTYPE_FLAG, INDICATOR_TYPE,
4642                   CONFIG_TYPE, PERIODICITY_ID, SHARE_FLAG, SOURCE_INDICATOR,
4643                   EDW_FLAG FROM BSC_KPIS_VL ';
4644       -- added for selected indicators
4645       l_stmt := l_stmt ||' WHERE INDICATOR IN (SELECT INDICATOR FROM BSC_TMP_OPT_UI_KPIS WHERE process_id=:1) ';
4646       IF (BSC_METADATA_OPTIMIZER_PKG.gnumIndics > 0) And (BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 > 0) THEN
4647         l_stmt := l_stmt ||' AND (' || strWhereNotInIndics || ')  AND ('|| strWhereNotInIndics4 || ')';
4648       ELSIF (BSC_METADATA_OPTIMIZER_PKG.gnumIndics > 0) THEN
4649         l_stmt := l_stmt ||' AND (' || strWhereNotInIndics || ')';
4650       ELSIF (BSC_METADATA_OPTIMIZER_PKG.gnumIndics4 > 0) THEN
4651         l_stmt := l_stmt ||' AND (' || strWhereNotInIndics4 || ')';
4652       End IF;
4653       l_stmt := l_stmt ||' ORDER BY INDICATOR';
4654       writeTmp(' Finding indicators for MV level change : '||l_stmt, fnd_log.level_statement, false);
4655       OPEN cv FOR l_stmt using BSC_METADATA_OPTIMIZER_PKG.g_processID;
4656       LOOP
4657         FETCH cv INTO l_code, l_name, l_action_flag, l_indicatorType,
4658                       l_configType, l_per_inter, l_share_flag, l_source_indicator, l_edw_flag;
4659         EXIT WHEN cv%NOTFOUND;
4660         l_OptimizationMode := getKPIPropertyValue(l_Code, 'DB_TRANSFORM', 1);
4661         l_impl_type := getKPIPropertyValue(l_Code, BSC_METADATA_OPTIMIZER_PKG.IMPL_TYPE, 1);
4662         IF l_Action_Flag <> 2 THEN
4663           l_Action_Flag := 0;
4664         End IF;
4665         AddIndicator( BSC_METADATA_OPTIMIZER_PKG.gIndicators, l_Code, l_Name, l_IndicatorType, l_ConfigType,
4666     				l_Per_Inter, l_OptimizationMode, l_Action_Flag, l_Share_Flag, l_Source_Indicator, l_EDW_Flag, l_impl_type);
4667       END LOOP;
4668       CLOSE CV;
4669     END IF;
4670   END IF; -- mode <>0
4671   BSC_METADATA_OPTIMIZER_PKG.logProgress('INIT', ' # of indicators to process = '||BSC_METADATA_OPTIMIZER_PKG.gIndicators.count);
4672   writeTmp(' # of indicators to process = '||BSC_METADATA_OPTIMIZER_PKG.gIndicators.count,FND_LOG.LEVEL_STATEMENT, true);
4673 
4674   -- populate the variables in bsc_dbgen_metadata_reader as it needs to consider the
4675   -- objectives in the current run as also production
4676   writeTmp('Checking if AW objectives exists and marking them');
4677   l_counter := BSC_METADATA_OPTIMIZER_PKG.gIndicators.first;
4678   loop
4679     exit when BSC_METADATA_OPTIMIZER_PKG.gIndicators.count=0;
4680     if (BSC_METADATA_OPTIMIZER_PKG.gIndicators(l_counter).impl_type =2 AND
4681         BSC_METADATA_OPTIMIZER_PKG.gIndicators(l_counter).action_flag<>2) then -- aw
4682       l_aw_kpi_list(l_aw_kpi_list.count+1):= to_char(BSC_METADATA_OPTIMIZER_PKG.gIndicators(l_counter).code);
4683     end if;
4684     EXIT WHEN l_counter=BSC_METADATA_OPTIMIZER_PKG.gIndicators.last;
4685     l_counter := BSC_METADATA_OPTIMIZER_PKG.gIndicators.next(l_counter);
4686   end loop;
4687 
4688   if (l_aw_kpi_list.count>0) then
4689     bsc_dbgen_metadata_reader.mark_facts_in_process(l_aw_kpi_list);
4690   end if;
4691 
4692   writeTmp( 'Completed InitIndicators, system time is '||get_time, FND_LOG.LEVEL_STATEMENT, true);
4693   write_this(BSC_METADATA_OPTIMIZER_PKG.gIndicators, FND_LOG.LEVEL_STATEMENT, false);
4694 
4695   EXCEPTION WHEN OTHERS THEN
4696       l_error := sqlerrm;
4697       writeTmp('Exception in InitIndicators : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
4698       raise;
4699 End;
4700 
4701 
4702 
4703 /****************************************************************************
4704   DBObjectExists
4705   DESCRIPTION:
4706      Returns TRUE if the given database object exists. Otherwise,
4707      returns FALSE.
4708 
4709   PARAMETERS:
4710      ObjectName: Object Name
4711      db_obj: database
4712 
4713   AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4714 ****************************************************************************/
4715 Function DBObjectExists(ObjectName IN VARCHAR2)return boolean IS
4716   l_count NUMBER;
4717   l_stmt varchar2(1000);
4718 
4719   CURSOR cObject IS
4720   SELECT count(1) FROM USER_OBJECTS
4721   WHERE OBJECT_NAME = upper(ObjectName);
4722 BEGIN
4723   l_count := 0;
4724   --The object name is searched in USER_OBJECTS. It works for APPS or Personal
4725   --mode. IF the object is in BSC schema in APPS schema should exist a SYNONYM.
4726 
4727   open cObject;
4728   FETCH cObject into l_count;
4729   CLOSE cObject;
4730 
4731   IF (l_count =0) THEN
4732       return false;
4733   END IF;
4734   return true;
4735 End;
4736 
4737 /****************************************************************************
4738   TableExists
4739 
4740   DESCRIPTION:
4741      Returns TRUE if the given table exists in the database.
4742   PARAMETERS:
4743      Tabla: table name
4744      db_obj: database
4745   AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4746 ****************************************************************************/
4747 Function TableExists(Table_Name IN VARCHAR2) return Boolean IS
4748 
4749 l_count NUMBER;
4750 cv   CurTyp;
4751 
4752 CURSOR cTables(pTableName IN VARCHAR2, pOwner IN VARCHAR2) IS
4753 SELECT 1 FROM ALL_TABLES
4754 WHERE TABLE_NAME = pTableName
4755 AND OWNER = pOwner;
4756 
4757 BEGIN
4758 	l_count := 0;
4759 
4760   IF (BSC_METADATA_OPTIMIZER_PKG.gBscSchema IS NULL) THEN
4761       BSC_METADATA_OPTIMIZER_PKG.gBscSchema := getBSCSchema ;
4762   END IF;
4763 
4764 	open cTables(table_name, BSC_METADATA_OPTIMIZER_PKG.gBscSchema);
4765 	FETCH cTables into l_count;
4766 	IF (cTables%NOTFOUND) THEN
4767       CLOSE cTables;
4768 		return false;
4769 	ELSE
4770       CLOSE cTables;
4771 		return true;
4772 	END IF;
4773 
4774 End;
4775 
4776 
4777 /****************************************************************************
4778   CreateCopyTable
4779 --
4780 --  DESCRIPTION:
4781 --     Create a copy of the given table. It copies the data too.
4782 --
4783 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4784 ****************************************************************************/
4785 
4786 PROCEDURE CreateCopyTable(TableName IN VARCHAR2, CopyTableName IN VARCHAR2, TbsName IN VARCHAR2, p_where_clause IN VARCHAR2 default null) IS
4787   l_stmt VARCHAR2(32000) := null;
4788   l_val NUMBER;
4789   cv CurTyp;
4790 BEGIN
4791   IF (BSC_METADATA_OPTIMIZER_PKG.gStorageClause IS NULL) THEN
4792       BSC_METADATA_OPTIMIZER_PKG.gStorageClause := getStorageClause;
4793   END IF;
4794   l_stmt := 'create table ' ||CopyTableName ||' TABLESPACE ';
4795   IF (TbsName IS NULL) THEN
4796       l_stmt := l_stmt ||BSC_APPS.get_tablespace_name(BSC_APPS.other_table_tbs_type);
4797   ELSE
4798       l_stmt := l_stmt ||TbsName;
4799   END IF;
4800   l_stmt := l_stmt||' AS SELECT * FROM '||TableName||' '||p_where_clause;
4801   Do_DDL(l_stmt, ad_ddl.create_table, CopyTableName);
4802   l_stmt := 'select count(1) from '||CopyTableName;
4803   OPEN cv FOR l_stmt;
4804   FETCH cv INTO l_Val;
4805   CLOSE cv;
4806   writeTmp(l_stmt);
4807   writeTmp('# of rows inserted into '||CopyTableName||':'||l_val, FND_LOG.LEVEL_STATEMENT, false);
4808   exception when others then
4809     bsc_metadata_optimizer_pkg.logprogress('INIT', 'Error while creating '||CopyTableName);
4810     writeTmp('Exception in CreateCopyTable : '||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
4811     writeTmp('Statement executed was : '||l_stmt, FND_LOG.LEVEL_EXCEPTION, true);
4812     raise;
4813 
4814 End;
4815 
4816 --****************************************************************************
4817 --  CreateCopyIndexes
4818 --
4819 --  DESCRIPTION:
4820 --     Create same indexes on TableName for CopyTableName
4821 --
4822 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4823 --****************************************************************************
4824 PROCEDURE CreateCopyIndexes(TableName IN VARCHAR2, CopyTableName IN VARCHAR2, TbsName IN VARCHAR2) IS
4825 
4826   LstColumns VARCHAR2(1000);
4827   IndexName  VARCHAR2(100);
4828   isUnique VARCHAR2(100);
4829   newIndexName VARCHAR2(100);
4830 
4831   CURSOR cIndex(pOwner IN VARCHAR2) IS
4832   SELECT index_name, uniqueness
4833   FROM all_indexes
4834   WHERE table_name = TableName
4835   AND owner = pOwner;
4836 
4837   CURSOR cIndexCols(pIndex IN VARCHAR2, pOwner IN VARCHAR2) IS
4838   SELECT column_name
4839   FROM all_ind_columns
4840   WHERE index_name = pIndex
4841   AND table_owner = pOwner
4842   AND column_name not like 'SYS%$'
4843   ORDER BY column_position;
4844 
4845   l_column_name VARCHAR2(100);
4846   uIndex NUMBER := 1;
4847   nIndex NUMBER := 1;
4848 
4849   l_stmt VARCHAR2(1000);
4850   l_tmp_index number;
4851   l_len_ses  number;
4852   l_tmp_ses  varchar2(30);
4853 BEGIN
4854   uIndex := 1;
4855   nIndex := 1;
4856 
4857   IF (BSC_METADATA_OPTIMIZER_PKG.gBscSchema IS NULL) THEN
4858       BSC_METADATA_OPTIMIZER_PKG.gBscSchema := BSC_MO_HELPER_PKG.getBSCSchema;
4859   END IF;
4860 
4861   IF (BSC_METADATA_OPTIMIZER_PKG.gStorageClause IS NULL) THEN
4862       BSC_METADATA_OPTIMIZER_PKG.gStorageClause := getStorageClause;
4863   END IF;
4864 
4865   OPEN cIndex (BSC_METADATA_OPTIMIZER_PKG.gBscSchema);
4866 
4867   LOOP
4868       FETCH cIndex INTO IndexName, isUnique;
4869       EXIT WHEN cIndex%NOTFOUND;
4870       LstColumns := null;
4871 
4872       OPEN cIndexCols(IndexName, BSC_METADATA_OPTIMIZER_PKG.gBscSchema);
4873 
4874       LOOP
4875         FETCH cIndexCols INTO l_column_name;
4876         EXIT WHEN cIndexCols%NOTFOUND;
4877 
4878         If LstColumns IS NOT NULL Then
4879           LstColumns := LstColumns ||', ';
4880         End If;
4881         LstColumns := LstColumns || l_column_name;
4882       END LOOP;
4883       CLOSE cIndexCols;
4884 
4885       --bug fix 5416808 amitgupt, index name len should not exceed 30 chars
4886       -- assuming that table will not have MORE THAN 99 INDEXES
4887       if(length(CopyTableName)>26) then
4888         l_tmp_index := INSTR(CopyTableName,'_',-1,1);
4889         l_tmp_ses   := to_char(BSC_METADATA_OPTIMIZER_PKG.g_session_id);
4890         l_len_ses   := length(l_tmp_ses);
4891         newIndexName :=
4892           substr(CopyTableName,1,l_tmp_index)||substr(l_tmp_ses,l_len_ses-(25-l_tmp_index));
4893       else
4894         newIndexName := CopyTableName;
4895       end if;
4896 
4897       If LstColumns IS NOT NULL Then
4898         If isUnique = 'UNIQUE' Then
4899           newIndexName :=  newIndexName || '_U' || uIndex;
4900           uIndex := uIndex + 1;
4901           l_stmt := 'CREATE UNIQUE INDEX '|| newIndexName;
4902         Else
4903           newIndexName := newIndexName || '_N' || nIndex;
4904           nIndex := nIndex + 1;
4905           l_stmt := 'CREATE INDEX ' || newIndexName;
4906         End If;
4907         l_stmt := l_stmt||' ON ' || CopyTableName || ' (' || LstColumns || ')';
4908         IF (TbsName IS NULL) THEN
4909           l_stmt := l_stmt||' TABLESPACE '||  BSC_APPS.get_tablespace_name(BSC_APPS.other_table_tbs_type);
4910         ELSE
4911           l_stmt := l_stmt||' TABLESPACE '||  TbsName;
4912         END IF;
4913         l_stmt := l_stmt|| ' ' || BSC_METADATA_OPTIMIZER_PKG.gStorageClause;
4914         Do_DDL(l_stmt, ad_ddl.create_index, newIndexName);
4915       End If;
4916 
4917   END LOOP;
4918   Close cIndex;
4919   exception when others then
4920     bsc_metadata_optimizer_pkg.logprogress('INIT', 'Error while creating index'||IndexName);
4921     writeTmp('Exception in CreateCopyIndexes : '||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
4922     writeTmp('Statement executed was : '||l_stmt, FND_LOG.LEVEL_EXCEPTION, true);
4923     raise;
4924 
4925 End ;
4926 
4927 
4928 /****************************************************************************
4929   CreateBackupBaseTables
4930 
4931   DESCRIPTION:
4932      Create backup tables of all base tables
4933 
4934   AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
4935 ****************************************************************************/
4936 /*Procedure CreateBackupBaseTables IS
4937 
4938   i  NUMBER;
4939   l_stmt VARCHAR2(1000);
4940   BaseTable VARCHAR2(1000);
4941   cv   CurTyp;
4942 
4943   CURSOR cBaseTables IS
4944   SELECT R.TABLE_NAME
4945 	FROM BSC_DB_TABLES_RELS R, BSC_DB_TABLES T
4946 	WHERE R.SOURCE_TABLE_NAME = T.TABLE_NAME
4947 	AND T.TABLE_TYPE = 0;
4948 
4949 BEGIN
4950    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4951        writeTmp( 'Inside CreateBackupBaseTables');
4952    END IF;
4953 
4954 
4955   open cBaseTables;
4956   LOOP
4957     FETCH cBaseTables INTO BaseTable;
4958     EXIT when cBaseTables%NOTFOUND;
4959     IF TableExists(BaseTable) THEN
4960       DropTable( BaseTable|| '_BAK');
4961       bsc_metadata_optimizer_pkg.logprogress('INIT', 'Backing up '||BaseTable);
4962       CreateCopyTable(BaseTable, BaseTable|| '_BAK', BSC_METADATA_OPTIMIZER_PKG.gBaseTableTbsName);
4963     END IF;
4964   END LOOP;
4965   CLOSE cBaseTables;
4966   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4967     writeTmp( 'Compl CreateBackupBaseTables');
4968   END IF;
4969 End;
4970 */
4971 Procedure backup_b_table(p_table IN VARCHAR2)
4972 IS
4973 
4974   i  NUMBER;
4975   l_stmt VARCHAR2(1000);
4976   cv   CurTyp;
4977   l_backup_name varchar2(100);
4978   l_index_name varchar2(30);
4979   CURSOR cv_index IS
4980      SELECT index_name FROM ALL_INDEXES WHERE
4981      table_name = UPPER(p_table) AND table_owner = bsc_metadata_optimizer_pkg.gBscSchema;
4982 BEGIN
4983   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
4984     writeTmp( 'Inside backup_b_table : '||p_table);
4985   END IF;
4986   l_backup_name := p_table||'_BAK';
4987   IF TableExists(p_table) THEN
4988     BEGIN
4989       EXECUTE IMMEDIATE 'DROP TABLE '||bsc_metadata_optimizer_pkg.gBscSchema||'.'||l_backup_name||' CASCADE CONSTRAINTS';
4990     EXCEPTION
4991       WHEN OTHERS THEN
4992         NULL;
4993     END;
4994     BEGIN
4995      EXECUTE IMMEDIATE 'DROP SYNONYM '||l_backup_name;
4996     EXCEPTION
4997       WHEN OTHERS THEN
4998          NULL;
4999     END;
5000     bsc_metadata_optimizer_pkg.logprogress('INIT', 'Backing up '||p_table);
5001     --CreateCopyTable(p_table, p_table|| '_BAK', BSC_METADATA_OPTIMIZER_PKG.gBaseTableTbsName);
5002     begin
5003     --dropping indexes first
5004     --bug fix 5647971
5005     FOR rec IN cv_index LOOP
5006        IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5007            writeTmp( 'Dropping index '||rec.index_name);
5008        END IF;
5009        EXECUTE IMMEDIATE 'DROP INDEX '||bsc_metadata_optimizer_pkg.gBscSchema||'.'||rec.index_name;
5010     END LOOP;
5011     execute immediate 'alter table '||bsc_metadata_optimizer_pkg.gBscSchema||'.'||p_table||' rename to '||l_backup_name;
5012     execute immediate 'drop synonym '||p_table;
5013     execute immediate 'create synonym '||l_backup_name||' for '||bsc_metadata_optimizer_pkg.gBscSchema||'.'||l_backup_name;
5014     exception when others then
5015       if sqlcode=-26563 then -- rneame not allowed, dunno why
5016         CreateCopyTable(p_table, p_table|| '_BAK', BSC_METADATA_OPTIMIZER_PKG.gBaseTableTbsName);
5017       else
5018         raise;
5019       end if;
5020     end;
5021   END IF;
5022   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5023     writeTmp( 'Compl backup_b_table : '||p_table);
5024   END IF;
5025 End;
5026 
5027 /****************************************************************************
5028   CreateLastTables
5029 
5030   DESCRIPTION:
5031      Creates the tables BSC_DB_TABLES_LAST, BSC_DB_TABLES_RELS_LAST,
5032      BSC_KPI_DATA_TABLES_LAST
5033 
5034   AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
5035 ***************************************************************************/
5036 PROCEDURE CreateLastTables IS
5037   TableName varchar2(30);
5038   l_stmt varchar2(1000);
5039   l_where_clause varchar2(1000);
5040   l_threshold number := 100;
5041   i number;
5042   strWhereInTables VARCHAR2(1000);
5043 BEGIN
5044   l_where_clause := null;
5045   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5046     writeTmp( 'Inside CreateLastTables, time is '||get_time);
5047   END IF;
5048   IF (BSC_METADATA_OPTIMIZER_PKG.gBscSchema IS NULL) THEN
5049       BSC_METADATA_OPTIMIZER_PKG.gBscSchema := getBSCSchema ;
5050   END IF;
5051 
5052   TableName := 'BSC_DB_TABLES';
5053 
5054   IF BSC_METADATA_OPTIMIZER_PKG.gGAA_RUN_MODE <>0 AND  BSC_METADATA_OPTIMIZER_PKG.gIndicators.count < l_threshold THEN
5055     l_where_clause := ' WHERE table_name in (
5056 	  SELECT SOURCE_TABLE_NAME FROM BSC_DB_TABLES_RELS
5057 	  CONNECT BY TABLE_NAME=prior SOURCE_TABLE_NAME
5058 	  start with table_name in
5059 	    (select distinct table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' where indicator in
5060 	         (select indicator from bsc_tmp_opt_ui_kpis where process_id='||BSC_METADATA_OPTIMIZER_PKG.g_processID||')
5061 	     )
5062 	  UNION
5063 	  SELECT TABLE_NAME FROM BSC_DB_TABLES_RELS
5064 	  CONNECT BY TABLE_NAME=prior SOURCE_TABLE_NAME
5065 	  start with table_name in
5066 	    (select distinct table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' where indicator in
5067 	         (select indicator from bsc_tmp_opt_ui_kpis where process_id='||BSC_METADATA_OPTIMIZER_PKG.g_processID||')
5068 	     )
5069       )';
5070   END IF;
5071   CreateCopyTable(TableName, BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName, l_where_clause);
5072   CreateCopyIndexes (TableName, BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName);
5073   dbms_stats.gather_table_stats(BSC_METADATA_OPTIMIZER_PKG.gBscSchema, BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last);
5074   TableName := 'BSC_DB_TABLES_RELS';
5075   CreateCopyTable(TableName, BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName, l_where_clause);
5076   CreateCopyIndexes(TableName, BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName);
5077   dbms_stats.gather_table_stats(BSC_METADATA_OPTIMIZER_PKG.gBscSchema, BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last);
5078   IF BSC_METADATA_OPTIMIZER_PKG.gGAA_RUN_MODE <>0 AND BSC_METADATA_OPTIMIZER_PKG.gIndicators.count < l_threshold  THEN
5079     l_where_clause := ' WHERE indicator in
5080 	         (select indicator from bsc_tmp_opt_ui_kpis where process_id='||BSC_METADATA_OPTIMIZER_PKG.g_processID||')';
5081   END IF;
5082   TableName := 'BSC_KPI_DATA_TABLES';
5083   --DropTable(TableName||'_LAST');
5084   CreateCopyTable(TableName, BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName, l_where_clause);
5085   CreateCopyIndexes(TableName, BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName);
5086   dbms_stats.gather_table_stats(BSC_METADATA_OPTIMIZER_PKG.gBscSchema, BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last);
5087 
5088   IF BSC_METADATA_OPTIMIZER_PKG.gGAA_RUN_MODE <>0 AND BSC_METADATA_OPTIMIZER_PKG.gIndicators.count < l_threshold  THEN
5089     l_where_clause := ' WHERE table_name in
5090     (select source_table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last||'
5091     connect by table_name = prior source_table_name
5092     start with table_name in (select table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last||'))';
5093   END IF;
5094   TableName := 'BSC_DB_TABLES_COLS';
5095   CreateCopyTable(TableName, BSC_METADATA_OPTIMIZER_PKG.g_db_tables_cols_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryTableTbsName, l_where_clause);
5096   CreateCopyIndexes(TableName, BSC_METADATA_OPTIMIZER_PKG.g_db_tables_cols_last, BSC_METADATA_OPTIMIZER_PKG.gSummaryIndexTbsName);
5097   dbms_stats.gather_table_stats(BSC_METADATA_OPTIMIZER_PKG.gBscSchema, BSC_METADATA_OPTIMIZER_PKG.g_db_tables_cols_last);
5098 
5099   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5100     writeTmp( 'Compl CreateLastTables, time is '||get_time);
5101   END IF;
5102     EXCEPTION WHEN OTHERS THEN
5103       writeTmp('Exception in CreateLastTables '||TableName||' : '||sqlerrm, FND_LOG.LEVEL_EXCEPTION, true);
5104       raise;
5105 End;
5106 /****************************************************************************
5107   DropTable
5108 
5109   DESCRIPTION:
5110      Drop a given table using Ad_ddl.do_ddl, ignore errors
5111 ***************************************************************************/
5112 
5113 PROCEDURE DropTable(p_table_name in VARCHAR2) IS
5114 BEGIN
5115   BSC_METADATA_OPTIMIZER_PKG.gDropTable := BSC_METADATA_OPTIMIZER_PKG.gDropTable +1;
5116 
5117   IF (mod(BSC_METADATA_OPTIMIZER_PKG.gDropTable, 500) = 0) THEN
5118    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5119       writeTmp('Call # '||BSC_METADATA_OPTIMIZER_PKG.gDropTable||' to API DropTable');
5120    END IF;
5121 
5122   END IF;
5123 
5124   BEGIN
5125       do_ddl('DROP TABLE '||p_table_name|| ' CASCADE CONSTRAINTS', ad_ddl.drop_table, p_table_name);
5126   EXCEPTION WHEN OTHERS THEN
5127       null;
5128   END;
5129 END;
5130 
5131 /****************************************************************************
5132   DropTable
5133 
5134   DESCRIPTION:
5135      Drop a given view using Ad_ddl.do_ddl, ignore errors
5136 ***************************************************************************/
5137 
5138 PROCEDURE DropView(p_view_name in VARCHAR2) IS
5139 BEGIN
5140 
5141 	do_ddl('DROP VIEW '||p_view_name, ad_ddl.drop_view, p_view_name);
5142   EXCEPTION WHEN OTHERS THEN
5143       null;
5144 
5145 END;
5146 
5147 /****************************************************************************
5148   Do_DDL
5149 
5150   DESCRIPTION:
5151      Wrapper for ad_ddl.do_ddl
5152 ***************************************************************************/
5153 
5154 PROCEDURE Do_DDL(
5155 	x_statement IN VARCHAR2,
5156       x_statement_type IN INTEGER := 0,
5157       x_object_name IN VARCHAR2
5158 	) IS
5159 BEGIN
5160   IF (BSC_METADATA_OPTIMIZER_PKG.gApplsysSchema IS NULL) THEN
5161       BSC_METADATA_OPTIMIZER_PKG.gApplsysSchema := BSC_MO_HELPER_PKG.getApplsysSchema;
5162   END IF;
5163   BSC_APPS.DO_DDL(x_statement=>x_statement ,
5164         x_statement_type => x_statement_type,
5165         x_object_name=> x_object_name);
5166 
5167 END Do_DDL;
5168 
5169 /*---------------------------------------------------------------------
5170  Get the actual schema name for the 'APPS' schema as it could be different
5171  in different implementations.
5172 
5173 ---------------------------------------------------------------------*/
5174 
5175 Function getAppsSchema  RETURN VARCHAR2 IS
5176 
5177 
5178 BEGIN
5179   if (	bsc_metadata_optimizer_pkg.gAppsSchema is not null) then
5180     return bsc_metadata_optimizer_pkg.gAppsSchema;
5181   end if;
5182   if ( bsc_metadata_optimizer_pkg.g_bsc_apps_initialized=false) then
5183     bsc_apps.init_bsc_apps;
5184      bsc_metadata_optimizer_pkg.g_bsc_apps_initialized := true;
5185   end if;
5186   bsc_metadata_optimizer_pkg.gAppsSchema :=  bsc_apps.get_user_schema('APPS');
5187   return bsc_metadata_optimizer_pkg.gAppsSchema;
5188 
5189 END;
5190 
5191 
5192 /****************************************************************************
5193   Do_DDL
5194 
5195   DESCRIPTION:
5196      Returns the BSC schema name
5197 ***************************************************************************/
5198 FUNCTION getBSCSchema  return varchar2 is
5199 begin
5200   if (bsc_metadata_optimizer_pkg.gBSCSchema is not null) then
5201     return bsc_metadata_optimizer_pkg.gBSCSchema;
5202   end if;
5203   if ( bsc_metadata_optimizer_pkg.g_bsc_apps_initialized=false) then
5204     bsc_apps.init_bsc_apps;
5205      bsc_metadata_optimizer_pkg.g_bsc_apps_initialized := true;
5206   end if;
5207   bsc_metadata_optimizer_pkg.gBSCSchema:= bsc_apps.get_user_schema('BSC');
5208   return bsc_metadata_optimizer_pkg.gBSCSchema;
5209 
5210 END;
5211 
5212 
5213 /****************************************************************************
5214   Do_DDL
5215 
5216   DESCRIPTION:
5217      Returns the FND schema name
5218 ***************************************************************************/
5219 FUNCTION getApplsysSchema  return varchar2 is
5220 begin
5221  if (bsc_metadata_optimizer_pkg.gApplsysSchema is not null) then
5222    return bsc_metadata_optimizer_pkg.gApplsysSchema;
5223  end if;
5224 
5225  if ( bsc_metadata_optimizer_pkg.g_bsc_apps_initialized=false) then
5226     bsc_apps.init_bsc_apps;
5227      bsc_metadata_optimizer_pkg.g_bsc_apps_initialized := true;
5228   end if;
5229   bsc_metadata_optimizer_pkg.gApplsysSchema := bsc_apps.get_user_schema('FND');
5230   return bsc_metadata_optimizer_pkg.gApplsysSchema;
5231 END;
5232 
5233 --****************************************************************************
5234 --  PerteneceArregloStr: searchStringExists
5235 --
5236 --  DESCRIPTION:
5237 --     Return TRUE if the given string belong to the given array.
5238 --
5239 --  PARAMETERS:
5240 --     arrStr(): array of strings
5241 --     Num: Size of the array (not used)
5242 --     Cadena: String to look for.
5243 --****************************************************************************
5244 
5245 Function searchStringExists(arrStr dbms_sql.varchar2_table, Num number, str varchar2)
5246 return Boolean IS
5247 l_count number := 0;
5248 l_error Varchar2(1000);
5249 
5250 BEGIN
5251   IF (arrStr.count = 0) THEN
5252       return false;
5253   END IF;
5254   l_count := arrStr.first;
5255   LOOP
5256       IF (upper(arrStr(l_count)) = upper(str)) THEN
5257 	     return true;
5258       END IF;
5259 	   EXIT WHEN l_count = arrStr.last;
5260 	   l_count := arrStr.next(l_count);
5261   END LOOP;
5262 
5263   return false;
5264 
5265   EXCEPTION WHEN OTHERS THEN
5266       l_error := sqlerrm;
5267       writeTmp('Exception in searchStringExists : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
5268       raise;
5269 End;
5270 
5271 --****************************************************************************
5272 --  PerteneceArregloStr: searchStringExists
5273 --
5274 --  DESCRIPTION:
5275 --     Return TRUE if the given number belong to the given array.
5276 --
5277 --  PARAMETERS:
5278 --     arrStr(): array of numbers
5279 --     Num: Size of the array (not used)
5280 --     Cadena: Number to look for.
5281 --****************************************************************************
5282 Function searchNumberExists(arrStr dbms_sql.number_table, Num number, l_findThis NUMBER)
5283 return Boolean IS
5284 l_count number := 0;
5285 l_error Varchar2(1000);
5286 
5287 BEGIN
5288   IF (arrStr.count = 0) THEN
5289       return false;
5290   END IF;
5291   l_count := arrStr.first;
5292   LOOP
5293 	IF (upper(arrStr(l_count)) = upper(l_findThis)) THEN
5294 	  return true;
5295   END IF;
5296 	EXIT WHEN l_count = arrStr.last;
5297 	l_count := arrStr.next(l_count);
5298   END LOOP;
5299   return false;
5300 
5301 
5302   EXCEPTION WHEN OTHERS THEN
5303       l_error := sqlerrm;
5304       writeTmp('Exception in searchNumberExists : '||l_error, FND_LOG.LEVEL_EXCEPTION, true);
5305       raise;
5306 End;
5307 
5308 
5309 --*****************************************************************************
5310 --  InsertChildTables_LAST
5311 --  DESCRIPTION:
5312 --     Insert in the arry arrChildTables() all the tables in the graph
5313 --     that are affected by the tables in the array arrTables(), including
5314 --     themself.
5315 --     Note: This procedure uses BSC_DB_TABLES_RELS_LAST
5316 --
5317 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
5318 --****************************************************************************
5319 
5320 
5321 PROCEDURE InsertChildTables_LAST(arrTables IN dbms_sql.varchar2_table,
5322                        numTables IN OUT NOCOPY number,
5323            				 arrChildTables IN OUT NOCOPY dbms_sql.varchar2_table,
5324                        numChildTables IN OUT NOCOPY number) IS
5325 
5326 l_table_name varchar2(300);
5327 l_source_table_name VARCHAR2(300);
5328 arrTablesAux dbms_sql.varchar2_table;
5329 numTablesAux NUMBER;
5330 
5331 --l_stmt VARCHAR2(2000) := 'SELECT TABLE_NAME FROM BSC_DB_TABLES_RELS_LAST WHERE UPPER(SOURCE_TABLE_NAME) = :1' ;
5332 CURSOR cChildTables (pOriginTable IN VARCHAR2) IS
5333 select  table_name  from bsc_db_tables_rels
5334 connect by prior table_name = source_Table_name
5335 start with source_table_name = pOriginTable;
5336 l_error VARCHAR2(4000);
5337 
5338 BEGIN
5339 
5340   For i IN 0..(numTables - 1) LOOP
5341       If Not searchStringExists(arrChildTables, numChildTables, arrTables(i)) Then
5342         arrChildTables(numChildTables) := arrTables(i);
5343         numChildTables := numChildTables + 1;
5344       End If;
5345 
5346       OPEN cChildTables(upper(arrTables(i)));
5347 
5348       arrTablesAux.delete;
5349       numTablesAux := 0;
5350       LOOP
5351         FETCH cChildTables INTO l_table_name;
5352         EXIT WHEN cChildTables%NOTFOUND;
5353         arrTablesAux(numTablesAux) := l_table_name;
5354         numTablesAux := numTablesAux + 1;
5355       END Loop;
5356       Close cChildTables;
5357 
5358       InsertChildTables_LAST (arrTablesAux, numTablesAux, arrChildTables, numChildTables);
5359   END LOOP;
5360 
5361   EXCEPTION WHEN OTHERS THEN
5362       l_error := sqlerrm;
5363       writeTmp( 'Exception  in InsertChildTables_LAST :'||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
5364       RAISE;
5365 
5366 END;
5367 
5368 
5369 --===========================================================================+
5370 --   Name:      Add_Value_Big_In_Cond_Varchar2
5371 --   Description:   Insert the given value into the temporary table of big
5372 --            'in' conditions for the given variable_id.
5373 --   Parameters:  x_variable_id  variable id.
5374 --            x_value      value
5375 --
5376 --============================================================================
5377 PROCEDURE Add_Value_Big_In_Cond_Varchar2(x_variable_id number, x_value number) IS
5378 BEGIN
5379   bsc_apps.Add_Value_Big_In_Cond(x_variable_id, x_value);
5380 End;
5381 
5382 --****************************************************************************
5383 --  InitInfoOldSystem
5384 --  DESCRIPTION:
5385 --     Initialize the array garrOldBTables() with base tables existing in the
5386 --     system before run metadata.
5387 --     Initialize the array garrOldIndicators() with the indicators existing
5388 --     in the system before run metadata.
5389 --     Because the metdata can be canceled in the middle and the metdata tables
5390 --     are overwritten, we keep a set of _LAST tables and we delete them when
5391 --     Metadata finish sucessfully.
5392 --****************************************************************************
5393 
5394 
5395 PROCEDURE  InitInfoOldSystem IS
5396   i  PLS_Integer;
5397   j  PLS_INTEGER;
5398 
5399   BaseTable VARCHAR2(1000);
5400   BakTable VARCHAR2(100);
5401   l_InputTable varchar2(100);
5402   periodicity pls_Integer;
5403   arrChildTables dbms_sql.varchar2_table;
5404   numChildTables pls_Integer;
5405   arrTables dbms_sql.varchar2_table;
5406   numTables pls_Integer;
5407   strWhereInChildTables varchar2(1000);
5408 
5409   l_stmt VARCHAR2(1000):='SELECT R.TABLE_NAME, R.SOURCE_TABLE_NAME, BT.PERIODICITY_ID
5410 	FROM '||BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last||' R, '||
5411 	BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last||' IT, '||
5412 	BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last||' BT
5413 	WHERE R.SOURCE_TABLE_NAME = IT.TABLE_NAME
5414 	AND IT.TABLE_TYPE = 0
5415 	AND R.TABLE_NAME = BT.TABLE_NAME
5416 	AND IT.TABLE_NAME IN
5417 	 (SELECT SOURCE_TABLE_NAME FROM BSC_DB_TABLES_RELS
5418 	  CONNECT BY TABLE_NAME=prior SOURCE_TABLE_NAME
5419 	  start with table_name in
5420 	    (select distinct table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' where indicator in
5421 	         (select indicator from bsc_tmp_opt_ui_kpis where process_id=:1)
5422 	     )
5423       )
5424 	ORDER BY R.SOURCE_TABLE_NAME';
5425   l_table_name varchar2(300);
5426   l_source_table_name varchar2(300);
5427   l_periodicity_id number;
5428   l_column VARCHAR2(100);
5429   l_indicator VARCHAR2(100);
5430   cv   CurTyp;
5431   cv1   CurTyp;
5432   CURSOR cColumns (pTableName IN VARCHAR2, pOwner IN VARCHAR2) IS
5433   SELECT column_name FROM all_tab_columns
5434 			WHERE table_name = pTableName
5435 			AND owner = pOwner
5436 			ORDER BY column_id;
5437 
5438   l_error varchar2(1000);
5439   l_arr_indicators dbms_sql.number_table;
5440 BEGIN
5441 
5442    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5443      writeTmp( 'Inside InitInfoOldSystem, time is '||get_time);  --commit;
5444    END IF;
5445    open cv1 for l_stmt using BSC_METADATA_OPTIMIZER_PKG.g_processID;
5446    LOOP
5447      FETCH cv1 into l_table_name, l_source_table_name, l_periodicity_id;
5448 	 EXIT when cv1%NOTFOUND;
5449      BaseTable := l_table_name;
5450      BakTable := BaseTable||'_BAK';
5451      l_InputTable := l_SOURCE_TABLE_NAME;
5452      periodicity := l_PERIODICITY_ID;
5453      --Add base table to array garrOldBTables
5454      BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Name := BaseTable;
5455      BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).periodicity := periodicity;
5456      BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).InputTable := l_InputTable;
5457      OPEN cColumns(UPPER(BakTable), UPPER(BSC_METADATA_OPTIMIZER_PKG.gBscSchema));
5458      BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).numFields := 0;
5459      LOOP
5460        FETCH cColumns into l_column;
5461        EXIT WHEN cColumns%NOTFOUND;
5462        IF (BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Fields IS NOT NULL) THEN
5463          BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Fields :=
5464                 BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Fields||',';
5465        END IF;
5466        BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Fields :=
5467                 BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Fields||l_column;
5468        BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).numFields :=
5469               BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).numFields + 1;
5470      END LOOP;
5471      CLOSE cColumns;
5472      numChildTables := 0;
5473      arrTables(0) := BaseTable;
5474      numTables := 1;
5475      --get all the tables affected by the base table
5476      InsertChildTables_LAST(arrTables, numTables, arrChildTables, numChildTables);
5477      --get all the indicator affected by these tables
5478      strWhereInChildTables := Get_New_Big_In_Cond_Varchar2(1, 'TABLE_NAME');
5479      Add_Value_Bulk(1, arrChildTables);
5480      l_stmt := 'SELECT DISTINCT INDICATOR FROM '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' WHERE '||strWhereInChildTables;
5481      l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'TABLE_NAME');
5482      l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'VALUE_V');
5483      BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).NumIndicators := 0;
5484      open cv for l_stmt;
5485      FETCH cv BULK COLLECT into l_arr_indicators;
5486      close cv;
5487      FOR i IN 1..l_arr_indicators.count LOOP
5488        l_indicator := l_arr_indicators(i);
5489        IF (BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Indicators IS NOT NULL) THEN
5490           BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Indicators :=
5491              BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Indicators|| ',';
5492        END IF;
5493        BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Indicators :=
5494           BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Indicators||l_indicator;
5495        BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).NumIndicators :=
5496            BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).NumIndicators + 1;
5497      END LOOP;
5498      IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5499        writeTmp('Indicator list for table '||BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(
5500           BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).name||' - '|| BSC_METADATA_OPTIMIZER_PKG.garrOldBTables(
5501           BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables).Indicators);
5502      END IF;
5503      BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables := BSC_METADATA_OPTIMIZER_PKG.gnumOldBTables + 1;
5504   END Loop;
5505   Close cv1;
5506   --Initialize array of old indicators
5507   l_stmt := 'SELECT DISTINCT INDICATOR FROM '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||' WHERE TABLE_NAME IS NOT NULL';
5508   BSC_METADATA_OPTIMIZER_PKG.gnumOldIndicators := 0;
5509   BSC_METADATA_OPTIMIZER_PKG.garrOldIndicators.delete;
5510   l_arr_indicators.delete;
5511   open cv for l_stmt;
5512   fetch cv bulk collect into l_arr_indicators;
5513   close cv;
5514   FOR i in 1..l_arr_indicators.count LOOP
5515     l_indicator := l_arr_indicators(i);
5516     BSC_METADATA_OPTIMIZER_PKG.garrOldIndicators(BSC_METADATA_OPTIMIZER_PKG.gnumOldIndicators) := l_indicator;
5517     BSC_METADATA_OPTIMIZER_PKG.gnumOldIndicators := BSC_METADATA_OPTIMIZER_PKG.gnumOldIndicators + 1;
5518   END Loop;
5519 
5520   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5521     writeTmp( 'Compl InitInfoOldSystem, time is '||get_time);
5522   END IF;
5523   EXCEPTION WHEN OTHERS THEN
5524     l_ERROR := sqlerrm;
5525     bsc_mo_helper_pkg.writeTmp( 'Exception in InitInfoOldSystem '||l_ERROR, FND_LOG.LEVEL_UNEXPECTED, true);
5526     RAISE;
5527 END;
5528 
5529 
5530 --***************************************************************************
5531 --  deletePreviousRunTables
5532 --
5533 --   DESCRIPTION:
5534 --     Delete all tables and records created by a previous execution of
5535 --    Metadatada Optimizer.
5536 --
5537 --  AUTHOR/DATE  -  MODIFICATIONS (AUTHOR/DATE/DESCRIPTION):
5538 --****************************************************************************
5539 
5540 PROCEDURE deletePreviousRunTables IS
5541   l_stmt varchar2(1000);
5542   l_table varchar2(100);
5543   strWhereInTables varchar2(1000);
5544   strWhereInIndics varchar2(1000);
5545   strWhereNotInIndics varchar2(1000);
5546   strWhereInIndics4 varchar2(1000);
5547   i number;
5548   mv_name varchar2(100);
5549   uv_name varchar2(100);
5550   pt_name varchar2(100);
5551   cv   CurTyp;
5552   l_error VARCHAR2(1000);
5553   l_drop_list_aw DBMS_SQL.VARCHAR2_TABLE;
5554   l_drop_list_number DBMS_SQL.NUMBER_TABLE;
5555 
5556   l_child_table VARCHAR2(1000);
5557 BEGIN
5558   writeTmp( 'Inside deletePreviousRunTables, time is '||get_time, FND_LOG.LEVEL_STATEMENT, true);
5559   -- drop UI table used for getRelatedIndicators
5560   begin
5561     bsc_mo_helper_pkg.dropTable('BSC_TMP_OPT_KPI_DATA');
5562      exception when others then
5563      null;
5564   end;
5565   strWhereInIndics := Get_New_Big_In_Cond_Number( 1, 'INDICATOR');
5566   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5567     writeTmp('Will Loop '||BSC_METADATA_OPTIMIZER_PKG.garrIndics.count||' times for garrIndics');
5568   END IF;
5569   i:= BSC_METADATA_OPTIMIZER_PKG.garrIndics.first;
5570   LOOP
5571     EXIT when BSC_METADATA_OPTIMIZER_PKG.garrIndics.count = 0;
5572     --Add_Value_Big_In_Cond_Number(1, BSC_METADATA_OPTIMIZER_PKG.garrIndics(i));
5573     -- Feb 16, 2006, AW attach/detach taking too long in 9i
5574     -- first check if objective was implemented as AW previously
5575     -- Needed for AW call out , start with index = 1 for Venu :)
5576     if   BSC_AW_MD_API.is_kpi_present(to_char(BSC_METADATA_OPTIMIZER_PKG.garrIndics(i))) then
5577       l_drop_list_aw(l_drop_list_aw.count+1) := BSC_METADATA_OPTIMIZER_PKG.garrIndics(i);
5578     end if;
5579     l_drop_list_number(l_drop_list_number.count+1) := BSC_METADATA_OPTIMIZER_PKG.garrIndics(i);
5580     EXIT WHEN i = BSC_METADATA_OPTIMIZER_PKG.garrIndics.last;
5581     i:= BSC_METADATA_OPTIMIZER_PKG.garrIndics.next(i);
5582   END LOOP;
5583   Add_Value_Bulk(1, l_drop_list_number);
5584   strWhereNotInIndics := ' NOT (' || strWhereInIndics ||')';
5585   strWhereInIndics4 := Get_New_Big_In_Cond_Number( 3, 'INDICATOR');
5586   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5587     writeTmp('Will Loop '||BSC_METADATA_OPTIMIZER_PKG.garrIndics4.count||' times for garrIndics4');
5588   END IF;
5589 
5590   Add_Value_Bulk(3, BSC_METADATA_OPTIMIZER_PKG.garrIndics4);
5591   strWhereInTables := Get_New_Big_In_Cond_Varchar2( 2, 'TABLE_NAME');
5592   Add_Value_Bulk(2, BSC_METADATA_OPTIMIZER_PKG.garrTables);
5593   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
5594     writeTmp( 'Loop thru and drop all tables');
5595   END IF;
5596 
5597   IF BSC_METADATA_OPTIMIZER_PKG.garrIndics.count  > 0 THEN
5598     --Set the prototype flag to 3 for the indicators that are going to be re-created
5599     --So, if Metadata fail, those indicators are marked and the next time
5600     --will be recreated and no matter that the configuration of BSC_KPI_DATA_TABLES
5601     --had been deleted.
5602     --Also, since the documentation is done for all indicators, the documentation
5603     --re-load all indicator from the database. So, it is necessary to update the
5604     --prototype flag with the correct one (remember that due to the relations between
5605     --kpi, some kpi could be flagged too)
5606     IF BSC_METADATA_OPTIMIZER_PKG.gSYSTEM_STAGE = 2 THEN
5607       l_stmt := ' UPDATE BSC_KPIS_B
5608                   SET PROTOTYPE_FLAG = DECODE(PROTOTYPE_FLAG, 2, 2, 3),
5609                   LAST_UPDATED_BY = :1,
5610                   LAST_UPDATE_DATE = SYSDATE  WHERE '|| strWhereInIndics;
5611       execute immediate l_stmt using BSC_METADATA_OPTIMIZER_PKG.gUserId;
5612     END IF;
5613     --BSC-MV Note: Drop all the MV used for those KPis
5614     l_stmt := 'SELECT DISTINCT MV_NAME FROM BSC_KPI_DATA_TABLES WHERE ('||  strWhereInIndics ||')  AND MV_NAME IS NOT NULL';
5615     writeTmp(l_stmt);
5616     OPEN cv FOR l_stmt;
5617     LOOP
5618       FETCH cv INTO mv_name;
5619       EXIT WHEN cv%NOTFOUND;
5620       writeTmp('Drop mv '||mv_name, 1, true);
5621       BSC_BIA_WRAPPER.Drop_Summary_MV_VB(mv_name);
5622       BSC_MO_HELPER_PKG.CheckError('BSC_BIA_WRAPPER.Drop_Summary_MV_VB');
5623     END LOOP;
5624     CLOSE cv;
5625     --BSC-MV Note: Drop all MV used for targets for those KPIs
5626     l_stmt := 'SELECT DISTINCT BSC_BIA_WRAPPER.Get_Sum_Table_MV_Name(SOURCE_TABLE_NAME) MV_NAME
5627             FROM BSC_DB_TABLES_RELS WHERE TABLE_NAME IN (
5628               SELECT TABLE_NAME
5629               FROM '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table||'
5630               WHERE (' || strWhereInIndics || ') AND TABLE_NAME IS NOT NULL ) AND RELATION_TYPE = 1';
5631 
5632     OPEN cv FOR l_stmt;
5633     LOOP
5634       FETCH cv INTO mv_name;
5635       EXIT WHEN cv%NOTFOUND;
5636       BSC_BIA_WRAPPER.Drop_Summary_MV_VB(mv_name);
5637       BSC_MO_HELPER_PKG.CheckError('BSC_BIA_WRAPPER.Drop_Summary_MV_VB');
5638     END LOOP;
5639     Close cv;
5640     --BSC-MV Note: Drop all tables created for projections
5641     l_stmt := 'SELECT DISTINCT PROJECTION_DATA FROM BSC_KPI_DATA_TABLES  WHERE ('|| strWhereInIndics || ')
5642               AND PROJECTION_DATA IS NOT NULL';
5643     OPEN cv FOR l_stmt;
5644     LOOP
5645       FETCH cv INTO pt_name;
5646       EXIT WHEN cv%NOTFOUND;
5647       If TableExists(pt_name) Then
5648         Droptable( pt_name);
5649       End If;
5650     END LOOP;
5651     CLOSE cv;
5652     --Update column TABLE_NAME to NULL in BSC_KPI_DATA_TABLES
5653     --BSC-MV Note: Set MV_NAME to NULL in BSC_KPI_DATA_TABLES
5654     l_stmt := 'UPDATE BSC_KPI_DATA_TABLES
5655 		       SET   TABLE_NAME = NULL, MV_NAME = NULL, DATA_SOURCE = NULL,
5656                  SQL_STMT = NULL, PROJECTION_SOURCE = 0, PROJECTION_DATA = NULL
5657 		       WHERE '|| strWhereInIndics;
5658     writeTmp(l_stmt, fnd_log.level_statement, false);
5659     Execute immediate l_stmt;
5660   END IF;
5661   IF BSC_METADATA_OPTIMIZER_PKG.garrIndics4.count > 0 THEN
5662     --Set the prototype flag to 4 for the indicators that are going to be re-configured
5663     --So, if Metadata fail, those indicators are marked and the next time
5664     --will be re-configured no matter that the configuration of BSC_KPI_DATA_TABLES
5665     --had been deleted.
5666     --Also, since the documentation is done for all indicators, the documentation
5667     --re-load all indicator from the database. So, it is necessary to update the
5668     --prototype flag with the correct one (remember that due to the relations between
5669     --kpi, some kpi could be flagged too)
5670 
5671     IF BSC_METADATA_OPTIMIZER_PKG.gSYSTEM_STAGE = 2 THEN
5672       l_stmt := 'UPDATE BSC_KPIS_B SET PROTOTYPE_FLAG = DECODE(PROTOTYPE_FLAG, 2, 2, 4), '||
5673 			' LAST_UPDATED_BY = :1 ,'||
5674 			' LAST_UPDATE_DATE = SYSDATE '||
5675 			' WHERE (' || strWhereInIndics4 || ')';
5676       IF BSC_METADATA_OPTIMIZER_PKG.garrIndics.count > 0 THEN
5677         l_stmt:= l_stmt|| ' AND ('||  strWhereNotInIndics ||')';
5678       END IF;
5679       Execute immediate l_stmt using BSC_METADATA_OPTIMIZER_PKG.gUserId;
5680     END IF;
5681     --BSC-MV Note: If there is summarization level change (example from 3 to 2 or 2 to 3)
5682     --It is necessary to drop the existing MV of the indicator. They will be re-created
5683     --and bSC_KPI_DATA_TABLES will be reconfigured
5684     If BSC_METADATA_OPTIMIZER_PKG.g_Sum_Level_Change = 2 Then
5685       --BSC-MV Note: Drop all the MV used for those KPis
5686       l_stmt := 'SELECT DISTINCT MV_NAME FROM BSC_KPI_DATA_TABLES WHERE ('|| strWhereInIndics4 ||')';
5687       If BSC_METADATA_OPTIMIZER_PKG.garrIndics.count > 0 Then
5688         l_stmt := l_stmt ||' AND (' || strWhereNotInIndics || ')';
5689       End If;
5690       l_stmt := l_stmt ||' AND MV_NAME IS NOT NULL';
5691 
5692       OPEN cv FOR l_stmt;
5693       LOOP
5694         FETCH cv INTO mv_name;
5695         EXIT WHEN cv%NOTFOUND;
5696         BSC_BIA_WRAPPER.Drop_Summary_MV_VB(mv_name);
5697         IF (bsc_metadata_optimizer_pkg.g_log) then
5698           writeTmp('Dropping summary mv '||mv_name, fnd_log.level_statement, false);
5699         END IF;
5700         BSC_MO_HELPER_PKG.CheckError('BSC_BIA_WRAPPER.Drop_Summary_MV_VB');
5701       END LOOP;
5702       CLOSE cv;
5703 
5704       --BSC-MV Note: Drop all MV used for targets for those KPIs
5705       l_stmt := 'SELECT DISTINCT BSC_BIA_WRAPPER.Get_Sum_Table_MV_Name(SOURCE_TABLE_NAME) MV_NAME
5706                 FROM BSC_DB_TABLES_RELS WHERE TABLE_NAME IN (
5707                 SELECT TABLE_NAME FROM BSC_KPI_DATA_TABLES WHERE ('|| strWhereInIndics4 || ')';
5708       If BSC_METADATA_OPTIMIZER_PKG.garrIndics.count > 0 Then
5709         l_stmt := l_stmt || ' AND (' || strWhereNotInIndics || ')';
5710       End If;
5711 
5712       l_stmt := l_stmt || ' AND TABLE_NAME IS NOT NULL  ) AND RELATION_TYPE = 1';
5713       OPEN cv FOR l_stmt;
5714       LOOP
5715         FETCH cv INTO mv_name;
5716         EXIT WHEN cv%NOTFOUND;
5717         BSC_BIA_WRAPPER.Drop_Summary_MV_VB(mv_name);
5718         writeTmp('Dropping mv '||mv_name, fnd_log.level_statement, false);
5719         BSC_MO_HELPER_PKG.CheckError('BSC_BIA_WRAPPER.Drop_Summary_MV_VB');
5720       END LOOP;
5721       Close cv;
5722     END IF;
5723     --BSC-MV Note: Do NOT drop tables created for projections. For non-structural
5724     --changes those tables are not going to be re-created
5725   END IF;
5726   --Delete all input, base, temporal and summary tables
5727   i:= BSC_METADATA_OPTIMIZER_PKG.garrTables.first;
5728   writeTmp('Dropping Table and related metadata for ', FND_LOG.LEVEL_STATEMENT, true);
5729   LOOP
5730     EXIT WHEN BSC_METADATA_OPTIMIZER_PKG.garrTables.count = 0;
5731     IF substr(BSC_METADATA_OPTIMIZER_PKG.garrTables(i), 1, 6)=  'BSC_B_' THEN
5732       IF is_base_table(BSC_METADATA_OPTIMIZER_PKG.garrTables(i)) THEN
5733         backup_b_table(BSC_METADATA_OPTIMIZER_PKG.garrTables(i));
5734         BSC_METADATA_OPTIMIZER_PKG.gBackedUpBTables(BSC_METADATA_OPTIMIZER_PKG.gBackedUpBTables.count):= BSC_METADATA_OPTIMIZER_PKG.garrTables(i);
5735         IF BSC_DBGEN_UTILS.get_objective_type_for_b_table(BSC_METADATA_OPTIMIZER_PKG.garrTables(i))='AW' THEN
5736           bsc_aw_load.drop_bt_change_vector(BSC_METADATA_OPTIMIZER_PKG.garrTables(i));
5737         END IF;
5738         -- drop B_PRJ table if it exists
5739         writeTmp('Table Type=B, child_table='||l_child_table);
5740         l_child_table:= BSC_DBGEN_METADATA_READER.get_table_properties(BSC_METADATA_OPTIMIZER_PKG.garrTables(i),
5741                                                                        BSC_DBGEN_STD_METADATA.BSC_B_PRJ_TABLE) ;
5742         if (l_child_table is not null) then
5743           DropTable(l_child_table);
5744         end if;
5745       END IF;
5746     END IF;
5747     -- drop i_rowid table if it exists
5748     IF (bsc_dbgen_utils.get_table_type(bsc_metadata_optimizer_pkg.garrTables(i))='I') THEN
5749       l_child_table := BSC_DBGEN_METADATA_READER.get_table_properties(BSC_METADATA_OPTIMIZER_PKG.garrTables(i),
5750                                                                       BSC_DBGEN_STD_METADATA.BSC_I_ROWID_TABLE) ;
5751       writeTmp('Table Type=I, child_table='||l_child_table);
5752       if (l_child_table is not null) then
5753         DropTable(l_child_table);
5754       end if;
5755     END IF;
5756     DropTable( BSC_METADATA_OPTIMIZER_PKG.garrTables(i));
5757     -- force this to the output.
5758     l_error := l_error || BSC_METADATA_OPTIMIZER_PKG.garrTables(i) ||', ';
5759     IF (i>0 AND mod(i, 10) = 0) THEN
5760       writeTmp(l_error, FND_LOG.LEVEL_STATEMENT, true);
5761       l_error := null;
5762     END IF;
5763     EXIT WHEN i=BSC_METADATA_OPTIMIZER_PKG.garrTables.last;
5764     i := BSC_METADATA_OPTIMIZER_PKG.garrTables.next(i);
5765   END LOOP;
5766   IF BSC_METADATA_OPTIMIZER_PKG.garrTables.count > 0 THEN
5767     --BSC_DB_TABLES
5768     l_stmt := 'DELETE FROM BSC_DB_TABLES WHERE '||strWhereInTables;
5769     l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'table_name');
5770     l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'value_v');
5771     Execute immediate l_stmt;
5772     --BSC_DB_TABLES_RELS
5773     l_stmt := 'DELETE FROM BSC_DB_TABLES_RELS WHERE '|| strWhereInTables;
5774     l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'table_name');
5775     l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'value_v');
5776     Execute immediate l_stmt;
5777     --BSC_DB_TABLES_COLS
5778     l_stmt := 'DELETE FROM BSC_DB_TABLES_COLS WHERE '||  strWhereInTables;
5779     l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'table_name');
5780     l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'value_v');
5781     Execute immediate l_stmt;
5782     --BSC_DB_CALCULATIONS
5783     l_stmt := 'DELETE FROM BSC_DB_CALCULATIONS WHERE '||  strWhereInTables;
5784     l_stmt := replace(l_stmt, 'UPPER(TABLE_NAME)', 'table_name');
5785     l_stmt := replace(l_stmt, 'UPPER(VALUE_V)', 'value_v');
5786     Execute immediate l_stmt;
5787   END IF;
5788 
5789   IF (bsc_metadata_optimizer_pkg.g_bsc_mv and l_drop_list_aw.count>0) then
5790       -- DROP ALL OBJECTS IMPLEMENTED AS AW
5791     l_stmt := null;
5792     IF (BSC_METADATA_OPTIMIZER_PKG.g_log) THEN
5793       l_stmt := 'DEBUG LOG';
5794     END IF;
5795     BEGIN
5796     BSC_AW_ADAPTER.drop_kpi(l_drop_list_aw, l_stmt);
5797      EXCEPTION WHEN OTHERS THEN
5798       null;
5799     END;
5800   END IF;
5801 
5802   writeTmp( 'Compl deletePreviousRunTables, system time is '||get_time, FND_LOG.LEVEL_STATEMENT, true);
5803   EXCEPTION WHEN OTHERS THEN
5804   l_ERROR := sqlerrm;
5805   bsc_mo_helper_pkg.writeTmp( 'Exception in deletePreviousRunTables '||l_ERROR, FND_LOG.LEVEL_UNEXPECTED, true);
5806   RAISE;
5807 End;
5808 
5809 --****************************************************************************
5810 --  EscribirInic : WriteInitTable
5811 --
5812 --  DESCRIPTION:
5813 --     Write the given variable in BSC_SYS_INIT table.
5814 --  PARAMETERS:
5815 --     Variable: variable name
5816 --     Valor: value
5817 --     db_obj: database
5818 --****************************************************************************
5819 PROCEDURE WriteInitTable(propertyCode IN VARCHAR2, propertyValue IN VARCHAR2) IS
5820   l_stmt VARCHAR2(3000);
5821   l_count NUMBER;
5822 BEGIN
5823 
5824   IF propertyValue IS NOT NULL THEN
5825     SELECT Count(1) INTO l_count FROM BSC_SYS_INIT
5826     WHERE UPPER(PROPERTY_CODE) = UPPER(propertyCode);
5827 
5828     IF l_count > 0 THEN
5829       UPDATE BSC_SYS_INIT SET PROPERTY_VALUE = propertyValue, LAST_UPDATED_BY = BSC_METADATA_OPTIMIZER_PKG.gUserID, LAST_UPDATE_DATE = SYSDATE
5830       WHERE UPPER(PROPERTY_CODE) = UPPER(propertyCode);
5831         --Execute IMMEDIATE l_stmt using propertyValue, BSC_METADATA_OPTIMIZER_PKG.gUserID, UPPER(propertyCode);
5832     Else
5833       INSERT INTO BSC_SYS_INIT (PROPERTY_CODE, PROPERTY_VALUE, CREATED_BY, CREATION_DATE, LAST_UPDATED_BY, LAST_UPDATE_DATE)
5834       VALUES(propertyCode, propertyValue, BSC_METADATA_OPTIMIZER_PKG.gUserID, SYSDATE, BSC_METADATA_OPTIMIZER_PKG.gUserID, SYSDATE);
5835     End IF;
5836   End IF;
5837 End;
5838 
5839 
5840 
5841 --****************************************************************************
5842 --  Inic_ano: InitializeYear
5843 --
5844 --  DESCRIPTION:
5845 --     Initialize the year for indicators and BSC_DB_CALENDAR table
5846 --****************************************************************************
5847 PROCEDURE InitializeYear IS
5848 
5849   l_stmt VARCHAR2(3000);
5850   Indicador BSC_METADATA_OPTIMIZER_PKG.clsIndicator;
5851   Calendar BSC_METADATA_OPTIMIZER_PKG.clsCalendar;
5852   num_anos NUMBER;
5853   num_anosant NUMBER;
5854   table_name VARCHAR2(100);
5855   mv_name VARCHAR2(100);
5856   Indic NUMBER;
5857   doit Boolean;
5858   l_index1 NUMBER;
5859   l_index2 NUMBER;
5860 
5861   l_temp NUMBER;
5862 BEGIN
5863   IF (BSC_METADATA_OPTIMIZER_PKG.gSYSTEM_STAGE = 1) THEN
5864     --Initilaize BSC Calendar if this is the first time
5865     --Populate calendar tables according to fiscal year
5866     l_index1 := BSC_METADATA_OPTIMIZER_PKG.gCalendars.first;
5867 
5868     LOOP
5869       EXIT WHEN BSC_METADATA_OPTIMIZER_PKG.gCalendars.count=0;
5870       Calendar := BSC_METADATA_OPTIMIZER_PKG.gCalendars(l_index1);
5871       --BIS DIMENSIONS: We cannot call Populate_Calendar_Tables for BIS Calendars
5872       --The API that imported the BIS Calendars already populated BSC_DB_CALENDAR and
5873       --BSC_SYS_PERIODS_TL, etc
5874       IF Calendar.Source = 'BSC' THEN
5875         --BSC Calendar
5876         BSC_UPDATE_UTIL.Populate_Calendar_Tables(Calendar.Code);
5877         BSC_MO_HELPER_PKG.CheckError('BSC_UPDATE_UTIL.Populate_Calendar_Tables');
5878       End IF;
5879       EXIT WHEN l_index1 = BSC_METADATA_OPTIMIZER_PKG.gCalendars.last;
5880       l_index1 := BSC_METADATA_OPTIMIZER_PKG.gCalendars.next(l_index1);
5881     END LOOP;
5882   Else
5883     --gSYSTEM_STAGE = 2
5884     --Check for any change in year range of all calendars
5885     IF (BSC_METADATA_OPTIMIZER_PKG.gCalendars.count >0) THEN
5886       l_index1 := BSC_METADATA_OPTIMIZER_PKG.gCalendars.first;
5887       LOOP
5888         Calendar := BSC_METADATA_OPTIMIZER_PKG.gCalendars(l_index1);
5889         IF Calendar.RangeYrMod = 1 THEN
5890           --There was a change in the range of years
5891           num_anos := Calendar.NumOfYears;
5892           num_anosant := Calendar.PreviousYears;
5893           --Update the range of years in BSC_DB_TABLES for tables
5894           --belonging to this calendar.
5895           --Remember that BSC Calendar is code -1 in gCalendars
5896           UPDATE BSC_DB_TABLES SET NUM_OF_YEARS = num_anos, PREVIOUS_YEARS = num_anosant
5897                   WHERE PERIODICITY_ID IN (
5898                   SELECT PERIODICITY_ID FROM BSC_SYS_PERIODICITIES
5899                   WHERE CALENDAR_ID = Calendar.Code );
5900           IF Calendar.Source = 'BSC' THEN
5901             --BSC Calendar
5902             BSC_UPDATE_UTIL.Populate_Calendar_Tables(Calendar.Code);
5903             BSC_MO_HELPER_PKG.CheckError('BSC_UPDATE_UTIL.Populate_Calendar_Tables');
5904           End IF;
5905 
5906           --BIS DIMENSIONS: We cannot call Populate_Calendar_Tables for BIS Calendars
5907           --The API that imported the BIS Calendars already populated BSC_DB_CALENDAR and
5908           --BSC_SYS_PERIODS_TL, etc
5909 
5910         End IF;
5911         EXIT WHEN l_index1 = BSC_METADATA_OPTIMIZER_PKG.gCalendars.last;
5912         l_index1 := BSC_METADATA_OPTIMIZER_PKG.gCalendars.next(l_index1);
5913       END LOOP;
5914     END IF; -- OF (BSC_METADATA_OPTIMIZER_PKG.gCalendars.count >0)
5915   End IF;
5916 
5917   IF BSC_METADATA_OPTIMIZER_PKG.gThereisStructureChange THEN
5918     IF (BSC_METADATA_OPTIMIZER_PKG.gIndicators.count >0) THEN
5919       l_index1 := BSC_METADATA_OPTIMIZER_PKG.gIndicators.first;
5920     END IF;
5921     LOOP
5922       EXIT WHEN BSC_METADATA_OPTIMIZER_PKG.gIndicators.count = 0;
5923       Indicador := BSC_METADATA_OPTIMIZER_PKG.gIndicators(l_index1);
5924       IF Indicador.Action_Flag = 3 THEN
5925         --Update indicators current period in BSC_KPI_PERIODICITIES
5926         --IF the periodicity is not yearly then the period need to be 1,
5927         --otherwise the period ned to be the current fiscal year of the calendar
5928         UPDATE BSC_KPI_PERIODICITIES K
5929            SET CURRENT_PERIOD =
5930 		       (SELECT  DECODE(P.YEARLY_FLAG, 1, C.FISCAL_YEAR, 1)
5931                   FROM BSC_SYS_PERIODICITIES P, BSC_SYS_CALENDARS_B C
5932                  WHERE K.PERIODICITY_ID = P.PERIODICITY_ID
5933 				   AND P.CALENDAR_ID = C.CALENDAR_ID
5934 				)
5935          WHERE INDICATOR = Indicador.Code;
5936         --All colors in the panel have to be gray
5937         UPDATE BSC_SYS_KPI_COLORS
5938           SET  KPI_COLOR = BSC_METADATA_OPTIMIZER_PKG.ColorG,
5939                ACTUAL_DATA = NULL,
5940                BUDGET_DATA = NULL
5941           WHERE INDICATOR = Indicador.Code;
5942         UPDATE bsc_sys_objective_colors
5943            SET obj_color = BSC_METADATA_OPTIMIZER_PKG.ColorG
5944            WHERE indicator = Indicador.Code;
5945         --Update the name of period of indicators in BSC_KPI_DEFAULTS_TL table
5946         --BSC Kpi => BSC Periodicity
5947         --Labels are in BSC_SYS_PERIODS_TL
5948         BEGIN
5949          UPDATE BSC_KPI_DEFAULTS_TL D
5950              SET PERIOD_NAME = (
5951                SELECT
5952                  CASE WHEN NVL(C.EDW_CALENDAR_TYPE_ID, 0) = 0 AND P.YEARLY_FLAG = 1  THEN
5953                  K.PERIODICITY_ID||'-'||C.FISCAL_YEAR
5954                  ELSE
5955                  (SELECT
5956                     K.PERIODICITY_ID||'-'||L.NAME
5957                   FROM
5958                     BSC_KPI_PERIODICITIES KP,
5959                     BSC_SYS_PERIODS_TL L
5960                   WHERE
5961                     K.INDICATOR = KP.INDICATOR AND
5962                     K.PERIODICITY_ID = KP.PERIODICITY_ID AND
5963                     C.FISCAL_YEAR = L.YEAR AND
5964                     KP.PERIODICITY_ID = L.PERIODICITY_ID AND
5965                     KP.CURRENT_PERIOD = L.PERIOD_ID AND
5966                     D.LANGUAGE = L.LANGUAGE
5967                  )
5968                  END
5969                FROM
5970                  BSC_DB_COLOR_KPI_V K,
5971                  BSC_SYS_PERIODICITIES P,
5972                  BSC_SYS_CALENDARS_B C
5973                WHERE
5974                  K.TAB_ID = D.TAB_ID AND
5975                  K.INDICATOR = D.INDICATOR AND
5976                  K.PERIODICITY_ID = P.PERIODICITY_ID AND
5977                  P.CALENDAR_ID = C.CALENDAR_ID
5978              )
5979             WHERE
5980             INDICATOR = Indicador.Code;
5981           EXCEPTION WHEN OTHERS THEN
5982               writeTmp('Ignoring Error while updating BSC_KPI_DEFAULTS_TL in InitializeYear for Indic= '||Indicador.code||':'||sqlerrm);
5983           END;
5984 		  --Update date of indicator
5985           UPDATE BSC_KPI_DEFAULTS_B SET LAST_UPDATE_DATE = SYSDATE  WHERE INDICATOR = Indicador.Code;
5986           --EXECUTE IMMEDIATE l_stmt USING Indicador.Code;
5987       End IF;
5988       EXIT WHEN l_index1 = BSC_METADATA_OPTIMIZER_PKG.gIndicators.last;
5989       l_index1 := BSC_METADATA_OPTIMIZER_PKG.gIndicators.next(l_index1);
5990     END LOOP;
5991   End IF;
5992 
5993   --Update BSC_SYS_INIT
5994   WriteInitTable( 'UPDATE_DATE', to_char(sysdate, 'dd/mm/yyyy'));
5995 
5996   --TerminarPorError (Get_Message('BSC_TABLES_INIT_FAILED'))
5997 End ;
5998 
5999 FUNCTION all_columns_used(p_arr_source_table DBMS_SQL.VARCHAR2_TABLE, p_table_name OUT NOCOPY DBMS_SQL.VARCHAR2_TABLE, p_unused_columns OUT NOCOPY DBMS_SQL.VARCHAR2_TABLE) return boolean IS
6000 
6001 l_stmt VARCHAR2(1000):=
6002 'SELECT last.table_name, last.column_name
6003    FROM '||bsc_metadata_optimizer_pkg.g_db_tables_cols_last||' last
6004       , bsc_tmp_big_in_cond cond
6005   WHERE last.table_name = cond.value_v
6006     AND cond.variable_id = :1
6007     AND cond.session_id = :2
6008     AND last.column_type = :3
6009   MINUS
6010  SELECT cols.table_name, cols.column_name
6011    FROM bsc_db_tables_cols cols
6012       , bsc_db_tables_rels rels
6013       , bsc_tmp_big_in_cond cond
6014   WHERE cond.value_v = rels.source_table_name
6015     AND rels.table_name = cols.table_name
6016     AND cond.variable_id = :4
6017     AND cond.session_id = :5
6018     AND cols.column_type = :6';
6019 b_all_columns_used boolean;
6020 cv CurTyp;
6021 l_col VARCHAR2(100);
6022 
6023 l_dummy varchar2(1000);
6024 BEGIN
6025   b_all_columns_used := true;
6026 
6027   l_dummy := Get_New_Big_In_Cond_varchar2(11, 'table_name');
6028   Add_Value_Bulk(11, p_table_name);
6029 
6030   OPEN cv FOR l_stmt using 11, userenv('SESSIONID'), 'A', 11, userenv('SESSIONID'), 'A';
6031   FETCH cv BULK COLLECT INTO p_table_name, p_unused_columns;
6032   CLOSE cv;
6033   if (p_table_name.count>0) then
6034     b_all_columns_used := false;
6035   end if;
6036   return b_all_columns_used ;
6037   EXCEPTION WHEN OTHERS THEN
6038    writeTmp('Exception in all_columns_used:'||sqlerrm||', l_stmt='||l_stmt,  FND_LOG.LEVEL_UNEXPECTED, true);
6039    raise;
6040 END;
6041 
6042 PROCEDURE drop_column(p_Table_name IN VARCHAR2, p_column_name IN VARCHAR2) IS
6043 l_stmt VARCHAR2(1000);
6044 
6045 BEGIN
6046   l_stmt := 'alter table '||p_Table_name ||' drop column '||p_column_name;
6047   --writeTmp(l_stmt);
6048   IF (table_column_exists(p_table_name, p_column_name)) THEN
6049     writeTmp(l_stmt);
6050     BSC_MO_HELPER_PKG.Do_DDL(l_stmt, ad_ddl.alter_table, p_Table_name );
6051   ELSE
6052     writeTmp(p_table_name||'.'||p_column_name||' doesnt exist, so not calling alter table as this was possibly dropped earlier');
6053   END IF;
6054   DELETE bsc_db_tables_cols
6055    WHERE table_name = p_Table_name
6056      AND column_name = p_column_name;
6057 END;
6058 
6059 PROCEDURE drop_unused_columns_for_tables(p_table_name IN DBMS_SQL.VARCHAR2_TABLE) IS
6060   strWhereInIndics VARCHAR2(1000);
6061   cv CurTyp;
6062   l_stmt VARCHAR2(1000):=
6063     'select distinct source_table_name from '||BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last||'
6064     connect by table_name = prior source_table_name
6065     start with table_name in (select value_v from bsc_tmp_big_in_cond where variable_id=:1 and session_id=:2)';
6066   l_unused_columns DBMS_SQL.VARCHAR2_TABLE;
6067   l_mvlog_name VARCHAR2(100);
6068   l_source_table_name VARCHAR2(100);
6069   l_i_table DBMS_SQL.VARCHAR2_TABLE;
6070 
6071   l_arr_source_table dbms_sql.varchar2_table;
6072   l_arr_table_name  dbms_sql.varchar2_table;
6073 
6074   l_dummy varchar2(1000);
6075 BEGIN
6076   writeTmp('Drop unused columns for tables');
6077 
6078   l_dummy  := Get_New_Big_In_Cond_varchar2(11, 'table_name');
6079   Add_Value_Bulk(11, p_table_name);
6080 
6081   OPEN cv FOR l_stmt USING 11, userenv('SESSIONID');
6082   FETCH cv BULK COLLECT INTO l_arr_source_table;
6083   CLOSE cv;
6084   writeTmp('Drop unused columns for tables ');
6085   IF all_columns_used(l_arr_source_table, l_arr_table_name, l_unused_columns)=false THEN
6086       for j in l_unused_columns.first..l_unused_columns.last loop
6087         drop_column(l_arr_table_name(j), l_unused_columns(j));
6088         IF bsc_dbgen_utils.get_table_type(l_arr_table_name(j)) = 'B' THEN -- drop mv log column
6089           BEGIN
6090             l_mvlog_name := bsc_dbgen_utils.get_mvlog_for_table(l_arr_table_name(j));
6091             IF (l_mvlog_name IS NOT NULL) THEN
6092               drop_column(l_mvlog_name, l_unused_columns(j));
6093             END IF;
6094             EXCEPTION WHEN OTHERS THEN
6095               null;
6096           END;
6097         END IF;
6098       end loop;
6099   END IF;
6100 
6101   EXCEPTION
6102   WHEN OTHERS THEN
6103   IF (SQLCODE <> -942) THEN -- table doesnt exist, so ignore
6104    writeTmp('Exception in drop_unused_columns_for_table:'||sqlerrm,  FND_LOG.LEVEL_UNEXPECTED, true);
6105    writeTmp('drop_unused_columns_for_table, l_stmt='||l_stmt,  FND_LOG.LEVEL_UNEXPECTED, true);
6106    raise;
6107   END IF;
6108 END;
6109 
6110 PROCEDURE drop_unused_columns(p_drop_tables_sql IN VARCHAR2) IS
6111   strWhereInIndics VARCHAR2(1000);
6112   l_stmt varchar2(4000);
6113   cv CurTyp;
6114   L_TABLE_NAME VARCHAR2(100);
6115   l_number_list dbms_sql.number_table;
6116   l_arr_table_names dbms_sql.varchar2_table;
6117 BEGIN
6118 
6119   writeTmp('Starting drop_unused_columns');
6120   strWhereInIndics := Get_New_Big_In_Cond_Number(11, 'INDICATOR');
6121   FOR i IN BSC_METADATA_OPTIMIZER_PKG.gIndicators.first..BSC_METADATA_OPTIMIZER_PKG.gIndicators.last LOOP
6122     l_number_list(l_number_list.count+1):= BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).code;
6123   END LOOP;
6124   Add_Value_Bulk(11, l_number_list);
6125 
6126   l_stmt := '
6127   SELECT distinct table_name FROM '||BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last||' last
6128    WHERE table_name LIKE ''BSC_S%'' AND source_table_name NOT like ''BSC_S%''
6129      AND table_name in
6130          (select distinct table_name
6131             from '||BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last||' )';
6132 
6133   writeTmp('Drop table SQL in drop unused columns is :'||l_stmt, FND_LOG.LEVEL_STATEMENT, FALSE);
6134   writeTmp(BSC_METADATA_OPTIMIZER_PKG.gBSCSchema||','|| BSC_METADATA_OPTIMIZER_PKG.gAppsSchema,
6135      FND_LOG.LEVEL_STATEMENT, FALSE);
6136   OPEN cv FOR l_stmt ;
6137   FETCH cv BULK COLLECT INTO l_arr_table_names;
6138   CLOSE cv;
6139 
6140   drop_unused_columns_for_Tables(l_arr_Table_names);
6141   EXCEPTION WHEN OTHERS THEN
6142    writeTmp('Exception in drop_unused_columns:'||sqlerrm,  FND_LOG.LEVEL_UNEXPECTED, true);
6143    writeTmp('drop_unused_columns:l_stmt='||l_stmt,  FND_LOG.LEVEL_UNEXPECTED, true);
6144    --raise;
6145 
6146 END;
6147 
6148 
6149 PROCEDURE drop_unused_mvlogs IS
6150 CURSOR cDropThese IS
6151 select distinct level_table_name
6152 from bsc_sys_dim_levels_b lvl
6153    , all_snapshot_logs log
6154 where log.log_owner=BSC_METADATA_OPTIMIZER_PKG.gBSCSchema
6155   and log.master = lvl.level_Table_name
6156 minus
6157 select distinct level_table_name
6158 from bsc_sys_dim_levels_b lvl
6159    , all_snapshot_logs log
6160    , all_dependencies db
6161    , all_mviews mv
6162 where log.log_owner=BSC_METADATA_OPTIMIZER_PKG.gBSCSchema
6163   and log.master = lvl.level_Table_name
6164   and db.referenced_owner=BSC_METADATA_OPTIMIZER_PKG.gBSCSchema
6165   and db.referenced_type = 'TABLE'
6166   and db.referenced_name = lvl.level_table_name
6167   and db.type = 'MATERIALIZED VIEW'
6168   and db.owner=mv.owner
6169   and db.name=mv.mview_name
6170   and mv.owner = BSC_METADATA_OPTIMIZER_PKG.gAppsSchema
6171   and mv.fast_refreshable<>'NO';
6172 BEGIN
6173   FOR i IN cDropThese LOOP
6174     execute immediate 'drop materialized view log on '||BSC_METADATA_OPTIMIZER_PKG.gBSCSchema||'.'||i.level_table_name;
6175   END LOOP;
6176   EXCEPTION WHEN OTHERS THEN
6177    writeTmp('Exception in drop_unused_mvlogs:'||sqlerrm,  FND_LOG.LEVEL_UNEXPECTED, true);
6178    raise;
6179 END;
6180 
6181 --****************************************************************************
6182 --  CleanDatabase
6183 --
6184 --  DESCRIPTION:
6185 --     Clean un-used tables from the database
6186 --     This is just to make sure that the system is clean after user run Metadata Optmizer
6187 --     It will drop all tables that are not being used by any indidator.
6188 --     This situation should not happen, but due to some unkown issue in the past
6189 --     some tables could be there but no indicator is using it.
6190 --****************************************************************************
6191 PROCEDURE CleanDatabase IS
6192   arrAllTables DBMS_SQL.VARCHAR2_TABLE;
6193   numAllTables NUMBER;
6194 
6195   l_stmt VARCHAR2(1000);
6196   i NUMBER;
6197   arrNotUsedTables DBMS_SQL.VARCHAR2_TABLE;
6198   numNotUsedTables NUMBER;
6199   strWhereInCondition VARCHAR2(1000);
6200 
6201   mv_name VARCHAR2(100);
6202   uv_name VARCHAR2(100);
6203   l_table VARCHAR2(100);
6204 
6205   cv   CurTyp;
6206   l_index NUMBER;
6207 
6208   /*CURSOR cAllTables IS
6209     with kpi_data as(SELECT DISTINCT TABLE_NAME
6210     FROM BSC_KPI_DATA_TABLES
6211     WHERE TABLE_NAME IS NOT NULL )
6212     SELECT table_name from kpi_data
6213     UNION
6214     SELECT DISTINCT SOURCE_TABLE_NAME FROM BSC_DB_TABLES_RELS
6215     START WITH table_name IN (SELECT TABLE_NAME from kpi_data)
6216     CONNECT BY PRIOR source_table_name = table_name ; */
6217    CURSOR cAllTables IS
6218     select table_name from bsc_db_tables where table_type=0
6219     union all
6220     SELECT DISTINCT table_name
6221     from BSC_DB_TABLES_RELS
6222     START WITH source_TABLE_NAME IN
6223     (select table_name from bsc_db_tables where table_type=0)
6224     CONNECT BY PRIOR TABLE_NAME = source_TABLE_NAME;
6225 
6226   l_drop_these VARCHAR2(32000);
6227   l_drop_threshold NUMBER := 200;
6228 
6229   CURSOR cDropThese IS
6230   WITH btable as (
6231   SELECT table_name, owner
6232     FROM all_tables
6233    WHERE (table_name like BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table_pfx||'%'
6234       OR table_name like BSC_METADATA_OPTIMIZER_PKG.g_period_circ_check_pfx||'%'
6235       OR table_name like BSC_METADATA_OPTIMIZER_PKG.g_filtered_indics_pfx||'%'
6236       OR table_name like BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last_pfx||'%'
6237       OR table_name like BSC_METADATA_OPTIMIZER_PKG.g_db_tables_rels_last_pfx||'%'
6238       OR table_name like BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last_pfx||'%'
6239       OR table_name like BSC_METADATA_OPTIMIZER_PKG.g_db_tables_cols_last_pfx||'%'
6240       OR table_name like 'BSC_TMP_COL_TYPE%'
6241 	   )
6242 	 AND owner in (BSC_METADATA_OPTIMIZER_PKG.gAppsSchema, BSC_METADATA_OPTIMIZER_PKG.gBSCSchema))
6243    SELECT table_name, owner
6244     FROM btable
6245    MINUS
6246    SELECT table_name, owner
6247     FROM btable, v$session
6248 	WHERE substr(table_name, instr(table_name, '_', -1)+1, 100) in
6249         (select to_char(audsid) from v$session where status<>'KILLED');
6250 
6251 	l_table_name VARCHAR2(100);
6252 	l_owner   VARCHAR2(100);
6253 BEGIN
6254   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6255     BSC_MO_HELPER_PKG.writeTmp('Inside cleanDatabase '||get_time, FND_LOG.LEVEL_PROCEDURE);
6256   END IF;
6257   -- Applicable only for MV architecture and non-upgrade scenario
6258   IF (bsc_metadata_optimizer_pkg.g_bsc_mv and bsc_metadata_optimizer_pkg.g_Sum_Level_Change<>1) then
6259     -- Bug 4318566:drop unused MV logs
6260     drop_unused_mvlogs;
6261   END IF;
6262   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6263     BSC_MO_HELPER_PKG.writeTmp('Dropped unused mv logs '||get_time, FND_LOG.LEVEL_PROCEDURE);
6264   END IF;
6265 
6266   numAllTables := 0;
6267   --Get all the tables used by all indicators
6268   OPEN cAllTables;
6269   FETCH cAllTables BULK COLLECT INTO arrAllTables;
6270   --LOOP
6271     --  FETCH cAllTables into l_table;
6272     --  EXIT WHEN cAllTables%NOTFOUND;
6273     --  arrAllTables(arrAllTables.count) := l_table;
6274   --END Loop;
6275   Close cAllTables;
6276   --Bug Fix#4071757, No need to call InsertOriginTables
6277   --BSC_MO_LOADER_CONFIG_PKG.InsertOriginTables (arrKpiTables, arrAllTables);
6278   numAllTables := arrAllTables.count;
6279   --So far the array arrAllTables() contains all input, base and summary tables
6280   --used in the whole system
6281   --Tables that are in BSC_DB_TABLES (excluding input tables for dimensions) and are not
6282   --in the array arrAllTables() are not used. We need to delete those tables from database
6283   -- and BSC metadata.
6284   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6285     BSC_MO_HELPER_PKG.writeTmp('numAllTables = '||numAllTables||', arrAllTables.count = '||arrAllTables.count||' '||get_time);
6286   END IF;
6287   --So far the array arrAllTables() contains all input, base and summary tables
6288   --used in the whole system
6289   --Tables that are in BSC_DB_TABLES (excluding input tables for dimensions) and are not
6290   --in the array arrAllTables() are not used. We need to delete those tables from database
6291   -- and BSC metadata.
6292   numNotUsedTables := 0;
6293   strWhereInCondition := Get_New_Big_In_Cond_Varchar2(1, 'TABLE_NAME');
6294   Add_Value_Bulk(1, arrAllTables);
6295 
6296   l_stmt := 'SELECT DISTINCT TABLE_NAME FROM BSC_DB_TABLES WHERE TABLE_TYPE <> 2 AND NOT (' ||
6297            strWhereInCondition || ')';
6298 
6299   l_stmt := 'SELECT DISTINCT TABLE_NAME FROM BSC_DB_TABLES WHERE TABLE_TYPE <> :1
6300    minus
6301    select upper(value_v) from bsc_tmp_big_in_cond where variable_id=:2 and session_id = :3';
6302   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6303     BSC_MO_HELPER_PKG.writeTmp('l_stmt = '||l_stmt||' '||get_time);
6304   END IF;
6305 
6306   OPEN cv FOR L_stmt using 2, 1, bsc_metadata_optimizer_pkg.g_session_id;
6307   LOOP
6308     FETCH cv INTO l_table;
6309     IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6310       BSC_MO_HELPER_PKG.writeTmp('after fetch '||get_time);
6311     END IF;
6312     EXIT WHEN CV%NOTFOUND;
6313     arrNotUsedTables(arrNotUsedTables.count) := l_table;
6314   END Loop;
6315   Close cv;
6316 
6317   numNotUsedTables := arrNotUsedTables.count;
6318   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6319     writeTmp('numNotUsedTables = '||numNotUsedTables||' '||get_time);
6320   END IF;
6321 
6322   strWhereInCondition := Get_New_Big_In_Cond_Varchar2(1, 'TABLE_NAME');
6323   l_drop_these := '(';
6324   --Drop the table from the database
6325   If numNotUsedTables >  0 Then
6326     For i IN 0..numNotUsedTables - 1 LOOP
6327       writeTmp('Dropping unused table = '||arrNotUsedTables(i)||' '||get_time, FND_LOG.LEVEL_STATEMENT, true);
6328       bsc_metadata_optimizer_pkg.logProgress('MISC', 'Dropping unused table = '||arrNotUsedTables(i));
6329       DropTable(arrNotUsedTables(i));
6330       IF (numNotUsedTables>l_drop_threshold) THEN
6331         null;
6332       ELSE
6333         l_drop_these := l_drop_these|| ''''||arrNotUsedTables(i)||''''||',';
6334       END IF;
6335     END LOOP;
6336     IF (numNotUsedTables>l_drop_threshold) THEN
6337       Add_Value_Bulk(1, arrNotUsedTables);
6338     END IF;
6339     --Delete tables from BSC metadata
6340     --BSC_DB_TABLES
6341 
6342     IF (numNotUsedTables>l_drop_threshold) THEN
6343       writeTmp('Deleting entries from BSC_DB_TABLES '||get_time);
6344       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_TABLES');
6345       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_TABLES WHERE '||strWhereInCondition;
6346       writeTmp('Deleting entries from BSC_DB_TABLES_RELS '||get_time);
6347       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_TABLES_RELS');
6348       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_TABLES_RELS WHERE '|| strWhereInCondition;
6349       writeTmp('Deleting entries from BSC_DB_TABLES_COLS '||get_time);
6350       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_TABLES_COLS');
6351       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_TABLES_COLS WHERE '|| strWhereInCondition;
6352       writeTmp('Deleting entries from BSC_DB_CALCULATIONS '||get_time);
6353       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_CALCULATIONS');
6354       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_CALCULATIONS WHERE '|| strWhereInCondition;
6355     ELSE
6356       l_drop_these := substr(l_drop_these, 1, length(l_drop_these)-1)||')';
6357       writeTmp('Deleting entries from BSC_DB_TABLES '||get_time);
6358       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_TABLES');
6359       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_TABLES WHERE table_name IN '||l_drop_these;
6360       writeTmp('Deleting entries from BSC_DB_TABLES_RELS '||get_time);
6361       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_TABLES_RELS');
6362       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_TABLES_RELS WHERE table_name IN '||l_drop_these;
6363       writeTmp('Deleting entries from BSC_DB_TABLES_COLS '||get_time);
6364       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_TABLES_COLS');
6365       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_TABLES_COLS WHERE table_name IN '||l_drop_these;
6366       writeTmp('Deleting entries from BSC_DB_CALCULATIONS '||get_time);
6367       bsc_metadata_optimizer_pkg.logProgress('CLEANUP', 'Deleting entries from BSC_DB_CALCULATIONS');
6368       EXECUTE IMMEDIATE ' DELETE FROM BSC_DB_CALCULATIONS WHERE table_name IN '||l_drop_these;
6369     END IF;
6370   END IF;
6371   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6372     BSC_MO_HELPER_PKG.writeTmp('Deleted invalid entries from metadata tables '||get_time, FND_LOG.LEVEL_PROCEDURE);
6373   END IF;
6374   -- If the system is in summary tables mode, then bsc_kpi_properties.implementation_type should be 1
6375   -- clean up any corruption caused by foll. case
6376   -- System in in Summary tables. User changes MV level to 2. User sets KPI as AW impl.
6377   -- Then user changes MV level to null (note that he may have NOT run database generator)
6378   IF (BSC_METADATA_OPTIMIZER_PKG.g_BSC_mv=false) THEN
6379     UPDATE BSC_KPI_PROPERTIES set property_value = 1 where property_code = BSC_METADATA_OPTIMIZER_PKG.IMPL_TYPE;
6380   END IF;
6381   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6382     BSC_MO_HELPER_PKG.writeTmp('Updated kpi_properties '||get_time, FND_LOG.LEVEL_PROCEDURE);
6383   END IF;
6384   --DropTable(BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table);
6385   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_dbmeasure_tmp_table );
6386   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_period_circ_check);
6387   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_filtered_indics);
6388   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_kpi_tmp_table);
6389   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_db_tables_last);
6390   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_db_table_rels_last);
6391   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_kpi_data_last);
6392   DropTable(BSC_METADATA_OPTIMIZER_PKG.g_db_tables_cols_last);
6393   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6394     BSC_MO_HELPER_PKG.writeTmp('Dropped temp tables '||get_time, FND_LOG.LEVEL_PROCEDURE);
6395   END IF;
6396   OPEN cDropThese;
6397   LOOP
6398     FETCH cDropThese INTO l_table_name, l_owner;
6399     IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6400       BSC_MO_HELPER_PKG.writeTmp('After fetching cursor time is '||get_time, FND_LOG.LEVEL_PROCEDURE);
6401     END IF;
6402     EXIT WHEN cDropThese%NOTFOUND;
6403     IF (l_owner = BSC_METADATA_OPTIMIZER_PKG.gAppsSchema) THEN -- table in apps schema
6404       execute immediate 'drop table '||l_table_name;
6405     ELSE
6406       DropTable(l_table_name);
6407     END IF;
6408     BSC_MO_HELPER_PKG.writeTmp('Dropped left over table '||l_table_name||' '||get_time, FND_LOG.LEVEL_STATEMENT, false);
6409   END LOOP;
6410   CLOSE cDropThese;
6411   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6412     BSC_MO_HELPER_PKG.writeTmp('Completed cleanDatabase '||get_time, FND_LOG.LEVEL_PROCEDURE);
6413   END IF;
6414   EXCEPTION WHEN OTHERS THEN
6415     writeTmp('Exception in cleanDatabase:'||sqlerrm,  FND_LOG.LEVEL_UNEXPECTED, true);
6416     raise;
6417 End;
6418 
6419 
6420 -- Stack to store the last 150 * 2000 characters of the log file
6421 PROCEDURE write_to_stack(msg IN VARCHAR2) IS
6422 l_msg_length number;
6423 BEGIN
6424   IF msg IS NULL THEN
6425     return;
6426   END IF;
6427 
6428   l_msg_length := length(msg);
6429   IF (g_stack_length + l_msg_length > 2000) THEN
6430     g_stack_index := g_stack_index + 1;
6431     g_stack_length := 0;
6432   END IF;
6433   IF g_stack_length <> 0 THEN
6434     g_stack(g_stack_index) := g_stack(g_stack_index) ||newline||msg;
6435   ELSE
6436     g_stack(g_stack_index) := msg;
6437   END IF;
6438   g_stack_length := g_stack_length + g_newline_length+l_msg_length;
6439   IF (g_stack.count > 150) THEN
6440     g_stack.delete(g_stack.first);
6441   END IF;
6442   EXCEPTION WHEN OTHERS THEN
6443       fnd_file.put_line(FND_FILE.LOG, 'Exception in write_to_stack:'||sqlerrm);
6444       fnd_file.put_line(FND_FILE.LOG, 'Stack length='||length(g_stack(g_stack_index)));
6445       fnd_file.put_line(FND_FILE.LOG, 'g_stack_length='||g_stack_length);
6446       fnd_file.put_line(FND_FILE.LOG, 'length(msg) = '||length(msg));
6447 	  fnd_file.put_line(FND_FILE.LOG, 'msg = '||msg);
6448       raise;
6449 END;
6450 
6451 PROCEDURE dump_stack IS
6452 l_msg VARCHAR2(2000);
6453 l_chunk VARCHAR2(256);
6454 l_varchar2_table DBMS_SQL.VARCHAR2_TABLE;
6455 BEGIN
6456   fnd_file.put_line(FND_FILE.LOG, ' ');
6457   BSC_MO_HELPER_PKG.TerminateWithMsg( 'Dumping stack contents ');
6458   fnd_file.put_line(FND_FILE.LOG, '-------------START OF STACK CONTENTS------------ ');
6459   IF g_stack.count = 0 THEN
6460     return;
6461   END IF;
6462   FOR i IN g_stack.first..g_stack.last LOOP
6463     l_msg := g_stack(i);
6464     --fnd_file.put_line(FND_FILE.LOG, g_stack(i));
6465     IF length(l_msg) <=256 THEN
6466       fnd_file.put_line(FND_FILE.LOG, l_msg);
6467     ELSE
6468       l_varchar2_table := bsc_dbgen_utils.get_char_chunks(l_msg, 256);
6469       FOR j in l_varchar2_table.first..l_varchar2_table.last LOOP
6470         fnd_file.put_line(FND_FILE.LOG, l_varchar2_table(j));
6471       END LOOP;
6472     END IF;
6473   END LOOP;
6474   fnd_file.put_line(FND_FILE.LOG, '-------------END OF STACK CONTENTS--------------- ');
6475 END;
6476 
6477 
6478 PROCEDURE write_debug (
6479   msg IN VARCHAR2,
6480   pSeverity IN NUMBER DEFAULT NULL) IS
6481   l_severity NUMBER;
6482 BEGIN
6483 
6484   IF pSeverity IS NULL THEN
6485     l_severity := FND_LOG.LEVEL_STATEMENT;
6486   ELSE
6487     l_severity := pSeverity;
6488   END IF;
6489   if( l_severity >= FND_LOG.G_CURRENT_RUNTIME_LEVEL) then
6490     FND_LOG.STRING(l_severity, 'bsc.pma.opt.optimize', msg);
6491   end if;
6492   EXCEPTION WHEN OTHERS THEN
6493       fnd_file.put_line(FND_FILE.LOG, 'Exception in write_debug:'||sqlerrm);
6494       raise;
6495 END;
6496 
6497 
6498 PROCEDURE writeTmp (
6499   msg IN VARCHAR2,
6500   pSeverity IN NUMBER DEFAULT NULL,
6501   pForce IN boolean default false)
6502   IS
6503 
6504   l_msg VARCHAR2(32767);
6505   l_chunk VARCHAR2(4000);
6506   l_severity NUMBER;
6507   l_force_logging boolean := false;
6508   l_varchar2_table DBMS_SQL.VARCHAR2_TABLE;
6509 BEGIN
6510   IF (msg is null) THEN
6511     return;
6512   END IF;
6513   IF (pForce is null) then
6514     l_force_logging := false;
6515   ELSE
6516     l_force_logging := pForce;
6517   END IF;
6518   IF (pSeverity IS NULL) THEN
6519     l_severity := FND_LOG.LEVEL_STATEMENT;
6520   ELSE
6521     l_severity := pSeverity;
6522   END IF;
6523   IF (l_force_logging=false) THEN
6524     IF (NOT BSC_METADATA_OPTIMIZER_PKG.g_log) THEN
6525       write_to_stack(msg);
6526       write_debug(msg);
6527       return;
6528     END IF;
6529     IF (l_severity < BSC_METADATA_OPTIMIZER_PKG.g_log_level) THEN
6530       write_to_stack(msg);
6531       write_debug(msg);
6532       return;
6533     END IF;
6534   END IF;
6535   bsc_metadata_optimizer_pkg.gSequence := bsc_metadata_optimizer_pkg.gSequence  +1 ;
6536   l_msg := substr(msg, 1, 32767);
6537   IF (l_msg IS NULL) THEN
6538     l_msg := ' ';
6539   END IF;
6540   IF (l_msg like 'Completed %' OR l_msg like 'Compl %' OR l_msg like 'Compl. %') THEN
6541       bsc_metadata_optimizer_pkg.gIndent := substr(bsc_metadata_optimizer_pkg.gIndent,
6542               1, length(bsc_metadata_optimizer_pkg.gIndent) - length(bsc_metadata_optimizer_pkg.gSpacing));
6543   END IF;
6544 
6545   IF (NOT BSC_METADATA_OPTIMIZER_PKG.g_fileOpened) THEN
6546       BSC_METADATA_OPTIMIZER_PKG.g_dir:=fnd_profile.value('UTL_FILE_LOG');
6547       BSC_METADATA_OPTIMIZER_PKG.g_dir := null;
6548       IF BSC_METADATA_OPTIMIZER_PKG.g_dir is null THEN
6549         BSC_METADATA_OPTIMIZER_PKG.g_dir:=BSC_METADATA_OPTIMIZER_PKG.getUtlFileDir;
6550       END IF;
6551       fnd_file.put_names(BSC_METADATA_OPTIMIZER_PKG.g_filename||'.log', BSC_METADATA_OPTIMIZER_PKG.g_filename||'.out', BSC_METADATA_OPTIMIZER_PKG.g_dir);
6552       BSC_METADATA_OPTIMIZER_PKG.g_file := utl_file.fopen(BSC_METADATA_OPTIMIZER_PKG.g_dir, 'METADATA.log' ,'w');
6553       BSC_METADATA_OPTIMIZER_PKG.g_fileOpened := true;
6554   END IF;
6555   IF (length(l_msg) <=256) THEN
6556     fnd_file.put_line(FND_FILE.LOG, bsc_metadata_optimizer_pkg.gIndent||l_msg);
6557   ELSE
6558     l_varchar2_table := bsc_dbgen_utils.get_char_chunks(l_msg, 256);
6559     FOR i IN l_varchar2_table.first..l_varchar2_table.last LOOP
6560       fnd_file.put_line(FND_FILE.LOG, bsc_metadata_optimizer_pkg.gIndent||l_varchar2_table(i));
6561     END LOOP;
6562   END IF;
6563   IF (l_msg like 'Inside%') THEN
6564       bsc_metadata_optimizer_pkg.gIndent := bsc_metadata_optimizer_pkg.gIndent || bsc_metadata_optimizer_pkg.gSpacing;
6565   END IF;
6566   IF length(bsc_metadata_optimizer_pkg.gIndent) > 256 THEN
6567       bsc_metadata_optimizer_pkg.gIndent := substr(bsc_metadata_optimizer_pkg.gIndent, 1, 64);
6568   END IF;
6569   EXCEPTION WHEN OTHERS THEN
6570       fnd_file.put_line(FND_FILE.LOG, 'Exception in writeTmp:'||sqlerrm);
6571       raise;
6572 END;
6573 
6574 
6575 PROCEDURE UpdateFlags IS
6576 l_stmt VARCHAR2(300);
6577 i NUMBER;
6578 l_index NUMBER;
6579 BEGIN
6580 
6581   BSC_MO_HELPER_PKG.writeTmp('Inside UpdateFlags '||get_time, FND_LOG.LEVEL_PROCEDURE, true);
6582 
6583   IF  (BSC_METADATA_OPTIMIZER_PKG.gIndicators.count>0) THEN
6584       i := BSC_METADATA_OPTIMIZER_PKG.gIndicators.first;
6585   END IF;
6586   LOOP
6587       EXIT WHEN BSC_METADATA_OPTIMIZER_PKG.gIndicators.count = 0;
6588 
6589       IF (BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag=2) THEN
6590         --Case 2
6591           DELETE FROM BSC_KPIS_B WHERE INDICATOR = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6592           DELETE FROM BSC_KPIS_TL WHERE INDICATOR = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).code;
6593           DELETE FROM BSC_KPI_DATA_TABLES WHERE INDICATOR = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).code;
6594           writeTmp('Deleting entries for indicator='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code||', old value='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag, FND_LOG.LEVEL_STATEMENT, false);
6595       ELSIF (BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag=1 OR BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag=3) THEN
6596         --Case 1, 3
6597           UPDATE BSC_KPIS_B SET PROTOTYPE_FLAG = 0,
6598                   LAST_UPDATED_BY = BSC_METADATA_OPTIMIZER_PKG.gUserId,
6599                   LAST_UPDATE_DATE = SYSDATE
6600                   WHERE INDICATOR = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6601           -- Color By KPI: Mark KPIs to Production mode in tendem with Objective's prototype flag.
6602           -- This is done so that both Objective and underlying KPIs come with the same color in IViewer,
6603           -- once GDB is run for the Objective. i.e. DARK_GRAY color
6604 	  UPDATE bsc_kpi_analysis_measures_b
6605 	    SET prototype_flag = 0
6606             WHERE indicator = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6607           --Execute IMMEDIATE l_stmt USING BSC_METADATA_OPTIMIZER_PKG.gUserId, BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6608           writeTmp('Updating prototype_flag=0 for indicator='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code||' from old value='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag, FND_LOG.LEVEL_STATEMENT, false);
6609       ELSIF (BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag=4) THEN
6610         --Case 4
6611           UPDATE BSC_KPIS_B SET PROTOTYPE_FLAG = 6,
6612                   LAST_UPDATED_BY = BSC_METADATA_OPTIMIZER_PKG.gUserId,
6613                   LAST_UPDATE_DATE = SYSDATE
6614                   WHERE INDICATOR = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6615           -- Color By KPI: Mark KPIs for color re-calculation
6616 	  UPDATE bsc_kpi_analysis_measures_b
6617 	    SET prototype_flag = 7
6618             WHERE indicator = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6619           --Execute IMMEDIATE l_stmt USING BSC_METADATA_OPTIMIZER_PKG.gUserId, BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6620           writeTmp('Updating prototype_flag=6 for indicator='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code||' from old value='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag, FND_LOG.LEVEL_STATEMENT, false);
6621       ELSE
6622         --BSC_MV Note: If summarizarion level changed then update prototype flag to 6
6623           If BSC_METADATA_OPTIMIZER_PKG.g_Sum_Level_Change <> 0 Then
6624               UPDATE BSC_KPIS_B SET PROTOTYPE_FLAG = 6,
6625                       LAST_UPDATED_BY = BSC_METADATA_OPTIMIZER_PKG.gUserId,
6626                       LAST_UPDATE_DATE = SYSDATE
6627                       WHERE INDICATOR = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6628               -- Color By KPI: Mark KPIs for color re-calculation
6629 	      UPDATE bsc_kpi_analysis_measures_b
6630 	        SET prototype_flag = 7
6631                 WHERE indicator = BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code;
6632               writeTmp('Updating prototype_flag=6 for indicator='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Code||' from old value='||BSC_METADATA_OPTIMIZER_PKG.gIndicators(i).Action_Flag, FND_LOG.LEVEL_STATEMENT, false);
6633           END IF;
6634       END IF;
6635       EXIT WHEN i = BSC_METADATA_OPTIMIZER_PKG.gIndicators.last;
6636       i := BSC_METADATA_OPTIMIZER_PKG.gIndicators.next(i);
6637   END LOOP;
6638 
6639   --BSC-PMF Integration: Update ALL PMF measures to production mode
6640   -- no need
6641   /*UPDATE BSC_KPI_ANALYSIS_MEASURES_B
6642           SET PROTOTYPE_FLAG = 0
6643           WHERE DATASET_ID IN (
6644           SELECT DATASET_ID FROM BSC_SYS_DATASETS_B
6645           WHERE NVL(SOURCE, 'BSC') = 'PMF')
6646 		  AND INDICATOR IN (SELECT INDICATOR FROM BSC_TMP_OPT_UI_KPIS WHERE process_id = BSC_METADATA_OPTIMIZER_PKG.g_processID);*/
6647 
6648   WriteInitTable('SYSTEM_STAGE', '2');
6649 
6650   --BSC-MV Note: Store new summarization level into BSC_SYS_INIT
6651   If BSC_METADATA_OPTIMIZER_PKG.g_BSC_MV Then
6652       WriteInitTable('ADV_SUM_LEVEL', BSC_METADATA_OPTIMIZER_PKG.g_Adv_Summarization_Level);
6653   End If;
6654 
6655 
6656   --Update range_yr_mod in BSC_SYS_CALENDARS_B
6657   UPDATE BSC_SYS_CALENDARS_B SET RANGE_YR_MOD = 0;
6658 
6659 
6660   IF BSC_METADATA_OPTIMIZER_PKG.gSYSTEM_STAGE = 2 THEN
6661       DropAppsTables;
6662   End IF;
6663   execute immediate 'delete bsc_tmp_opt_ui_kpis where process_id=:1' using BSC_METADATA_OPTIMIZER_PKG.g_processID;
6664 
6665   BSC_MO_HELPER_PKG.writeTmp('Completed UpdateFlags'||get_time, FND_LOG.LEVEL_PROCEDURE, true);
6666   EXCEPTION WHEN OTHERS THEN
6667       writeTmp('Exception in UpdateFlags:'||sqlerrm,  FND_LOG.LEVEL_UNEXPECTED, true);
6668       raise;
6669 
6670 END;
6671 
6672 
6673 /*
6674 FUNCTION getOneKeyField(table_name IN VARCHAR2, key_name IN VARCHAR2) RETURN BSC_METADATA_OPTIMIZER_PKG.clsKeyField IS
6675 
6676 CURSOR cKey IS
6677 SELECT key_name, Origin, Need_zero_code, Calc_zero_code,
6678 Filter_View_Name, dim_index
6679 from BSC_TMP_OPT_KEY_COLS
6680 WHERE
6681 table_name = table_name
6682 and key_name = key_name;
6683 
6684 keyfield BSC_METADATA_OPTIMIZER_PKG.clsKeyField;
6685 cv   CurTyp;
6686 l_start_time date := sysdate;
6687 l_needsCode0 NUMBER := 0;
6688 l_calcCode0 NUMBER := 0;
6689 
6690 BEGIN
6691    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6692   writeTmp('Inside getOneKeyField');
6693    END IF;
6694 
6695 
6696   BSC_METADATA_OPTIMIZER_PKG.ggetOneKeyField := BSC_METADATA_OPTIMIZER_PKG.ggetOneKeyField +1;
6697 
6698   IF (mod(BSC_METADATA_OPTIMIZER_PKG.ggetOneKeyField, 500) = 0) THEN
6699    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6700       writeTmp('Call # '||BSC_METADATA_OPTIMIZER_PKG.ggetOneKeyField||' to API getOneKeyField');
6701    END IF;
6702 
6703   END IF;
6704 
6705 
6706   OPEN cKey;
6707   FETCH cKey INTO keyField.keyName, keyField.origin,
6708   l_needsCode0, l_calcCode0,
6709   keyField.FilterViewName, keyField.dimIndex;
6710   CLOSE cKey;
6711    IF (l_needsCode0 = 1) THEN
6712    keyField.needsCode0 := true;
6713    ELSE
6714    keyField.needsCode0 := false;
6715    END IF;
6716 
6717    IF (l_calcCode0 = 1) THEN
6718    keyField.calculateCode0 := true;
6719    ELSE
6720    keyField.calculateCode0 := false;
6721    END IF;
6722 
6723    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6724   writeTmp('Completed getOneKeyField');
6725    END IF;
6726 
6727   BSC_METADATA_OPTIMIZER_PKG.g_time_getOneKeyField := BSC_METADATA_OPTIMIZER_PKG.g_time_getOneKeyField + (sysdate-l_start_time) * 86400;
6728   return keyfield;
6729 END;
6730 
6731 FUNCTION getAllKeyFields(pTableName IN VARCHAR2) RETURN BSC_METADATA_OPTIMIZER_PKG.tab_clsKeyField IS
6732 
6733 keyfield BSC_METADATA_OPTIMIZER_PKG.clsKeyField;
6734 keyFields BSC_METADATA_OPTIMIZER_PKG.tab_clsKeyField;
6735 cv   CurTyp;
6736 l_needsCode0 NUMBER;
6737 l_calcCode0 NUMBER;
6738 
6739 CURSOR cKeys IS SELECT key_name, Origin, Need_zero_code, Calc_zero_code,
6740 Filter_View_Name, dim_index from BSC_TMP_OPT_KEY_COLS WHERE table_name = pTableName
6741 order by seqnum;
6742 
6743 cKeysRow cKeys%ROWTYPE;
6744 l_error VARCHAR2(1000);
6745 l_start_time date := sysdate;
6746 BEGIN
6747 
6748 
6749   BSC_METADATA_OPTIMIZER_PKG.ggetAllKeyFields := BSC_METADATA_OPTIMIZER_PKG.ggetAllKeyFields +1;
6750 
6751   IF (mod(BSC_METADATA_OPTIMIZER_PKG.ggetAllKeyFields, 1000) = 0) THEN
6752    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6753       writeTmp('Call # '||BSC_METADATA_OPTIMIZER_PKG.ggetAllKeyFields||' to API getAllKeyFields');
6754    END IF;
6755 
6756   END IF;
6757 
6758 	OPEN cKeys;
6759 	LOOP
6760 		FETCH cKeys INTO cKeysRow;
6761 		EXIT WHEN cKeys%NOTFOUND;
6762 		keyField.keyName :=  cKeysRow.key_name;
6763 		keyField.origin := cKeysRow.Origin;
6764 		keyField.filterViewName := cKeysRow.Filter_View_Name;
6765       keyField.dimIndex := cKeysRow.dim_index;
6766 
6767 		IF (cKeysRow.need_zero_code = 0) THEN
6768 	        keyField.needsCode0 := false;
6769       ELSE
6770 	        keyField.needsCode0 := true;
6771 	  END IF;
6772 
6773       IF (cKeysRow.calc_zero_code = 0) THEN
6774 	        keyField.calculateCode0 := false;
6775       ELSE
6776 	        keyField.calculateCode0 := true;
6777 	  END IF;
6778 		keyFields(keyFields.count) := keyField;
6779 	END LOOP;
6780 	CLOSE cKeys;
6781   BSC_METADATA_OPTIMIZER_PKG.g_time_getAllKeyFields := BSC_METADATA_OPTIMIZER_PKG.g_time_getAllKeyFields + (sysdate - l_start_time) * 86400;
6782   return keyFields;
6783   EXCEPTION WHEN OTHERS THEN
6784       l_error := sqlerrm;
6785       writeTmp('Exception in getAllKeyFields for table='||pTableName||' : '||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
6786       raise;
6787 
6788 END;
6789 
6790 
6791 FUNCTION getOneDataField(table_name IN VARCHAR2, field_name IN VARCHAR2) RETURN BSC_METADATA_OPTIMIZER_PKG.clsDataField IS
6792 CURSOR cData IS
6793 SELECT
6794   field_name, aggfunction, origin, avglflag, avgltotalcolumn, avglcountercolumn,
6795   Internal_Column_Type, Internal_Column_Source
6796 from BSC_TMP_OPT_DATA_COLS
6797 WHERE
6798 table_name = table_name
6799 and upper(field_name) = upper(field_name);
6800 
6801 dataField BSC_METADATA_OPTIMIZER_PKG.clsDataField;
6802 cv   CurTyp;
6803 l_error VARCHAR2(1000);
6804 l_start_time date := sysdate;
6805 BEGIN
6806   BSC_METADATA_OPTIMIZER_PKG.ggetOneDataField := BSC_METADATA_OPTIMIZER_PKG.ggetOneDataField +1;
6807 
6808   IF (mod(BSC_METADATA_OPTIMIZER_PKG.ggetOneDataField, 500) = 0) THEN
6809    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6810       writeTmp('Call # '||BSC_METADATA_OPTIMIZER_PKG.ggetOneDataField||' to API ggetOneDataField');
6811    END IF;
6812 
6813   END IF;
6814 
6815 
6816 
6817    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6818   writeTmp('Inside getOneDataField');
6819    END IF;
6820 
6821   OPEN cData;
6822   FETCH cData INTO dataField.fieldName, dataField.aggFunction, dataField.origin, dataField.avglFlag,
6823       dataField.avglTotalColumn, dataField.avglCounterColumn, dataField.internalColumnType, dataField.internalColumnSource;
6824   CLOSE cData;
6825    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6826   writeTmp('Completed getOneDataField');
6827    END IF;
6828 
6829 
6830 
6831   BSC_METADATA_OPTIMIZER_PKG.g_time_updateOneDisagg := BSC_METADATA_OPTIMIZER_PKG.g_time_updateOneDisagg + (sysdate - l_start_time) * 86400;
6832   return dataField;
6833 
6834   EXCEPTION WHEN OTHERS THEN
6835       l_error := sqlerrm;
6836       writeTmp('Exception in getOneDataField for table='||table_name||', field = '||field_name||' : '||l_error, FND_LOG.LEVEL_UNEXPECTED, true);
6837       raise;
6838 END;
6839 
6840 FUNCTION getAllDataFields(pTableName IN VARCHAR2) RETURN BSC_METADATA_OPTIMIZER_PKG.tab_clsDataField IS
6841 
6842 dataFields BSC_METADATA_OPTIMIZER_PKG.tab_clsDataField;
6843 dataField BSC_METADATA_OPTIMIZER_PKG.clsDataField;
6844 cv   CurTyp;
6845 
6846 cursor cData is
6847 SELECT field_name, aggfunction, origin, avglflag, avgltotalcolumn, avglcountercolumn,
6848       Internal_Column_Type, Internal_Column_Source
6849 from BSC_TMP_OPT_DATA_COLS WHERE
6850 table_name = pTableName
6851 order by seqnum;
6852 cDataRow cData%ROWTYPE;
6853 l_error varchar2(1000);
6854 
6855 l_start_time date := sysdate;
6856 BEGIN
6857   BSC_METADATA_OPTIMIZER_PKG.ggetAllDataFields := BSC_METADATA_OPTIMIZER_PKG.ggetAllDataFields +1;
6858 
6859   IF (mod(BSC_METADATA_OPTIMIZER_PKG.ggetAllDataFields, 1000) = 0) THEN
6860    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
6861       writeTmp('Call # '||BSC_METADATA_OPTIMIZER_PKG.ggetAllDataFields||' to API getAllDataFields');
6862    END IF;
6863 
6864   END IF;
6865 
6866 	OPEN cData;
6867 	LOOP
6868 		FETCH cData INTO cDataRow;
6869 		EXIT WHEN cData%NOTFOUND;
6870 		dataField.fieldName := cDataRow.field_name;
6871 		dataField.aggFunction := cDataRow.aggFunction;
6872 		dataField.origin := cDataRow.origin;
6873 		dataField.avglFlag := cDataRow.avglflag;
6874 	      dataField.avglTotalColumn := cDataRow.avgltotalcolumn;
6875 		dataField.avglCounterColumn:= cDataRow.avglcountercolumn;
6876 		dataField.internalColumnType := cDataRow.Internal_Column_Type;
6877 		dataField.internalColumnSource := cDataRow.Internal_Column_Source;
6878 		dataFields(dataFields.count) := dataField;
6879 	END LOOP;
6880 	CLOSE cData;
6881 
6882   BSC_METADATA_OPTIMIZER_PKG.g_time_getAllDataFields := BSC_METADATA_OPTIMIZER_PKG.g_time_getAllDataFields + (sysdate - l_start_time) * 86400;
6883   return dataFields;
6884 
6885   EXCEPTION WHEN OTHERS THEN
6886       l_error := sqlerrm;
6887       writeTmp('Exception getAllDataFields for table_name ='||pTableName||' : '||l_error, fnd_log.LEVEL_UNEXPECTED, true);
6888       raise;
6889 END;
6890 */
6891 
6892 FUNCTION getGroupIds (levels IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevels) RETURN DBMS_SQL.NUMBER_TABLE IS
6893 l_groups DBMS_SQL.NUMBER_TABLE;
6894 l_count NUMBER := 0;
6895 i NUMBER;
6896 BEGIN
6897   i := levels.first;
6898   LOOP
6899       EXIT WHEN levels.count=0;
6900       IF (BSC_MO_HELPER_PKG.findIndex(l_groups, levels(i).group_id) = -1 ) THEN -- new entry
6901         l_groups(l_count) := levels(i).group_id;
6902         l_count := l_count+1;
6903       END IF;
6904       EXIT WHEN i = levels.last;
6905       i := levels.next(i);
6906   END LOOP;
6907   return l_groups;
6908 END;
6909 
6910 FUNCTION getGroupIds (levels IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevelCombinations) RETURN DBMS_SQL.NUMBER_TABLE IS
6911 l_groups DBMS_SQL.NUMBER_TABLE;
6912 l_count NUMBER := 0;
6913 i NUMBER;
6914 BEGIN
6915   i := levels.first;
6916   LOOP
6917       EXIT WHEN levels.count=0;
6918       IF (BSC_MO_HELPER_PKG.findIndex(l_groups, levels(i).group_id) = -1 ) THEN -- new entry
6919         l_groups(l_count) := levels(i).group_id;
6920         l_count := l_count+1;
6921       END IF;
6922       EXIT WHEN i = levels.last;
6923       i := levels.next(i);
6924   END LOOP;
6925   return l_groups;
6926 END;
6927 
6928 FUNCTION get_tab_clsLevels (Coll IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevels, group_id IN NUMBER)
6929 RETURN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevels IS
6930 l_levels BSC_METADATA_OPTIMIZER_PKG.tab_clsLevels ;
6931 l_lvl BSC_METADATA_OPTIMIZER_PKG.clsLevels;
6932 l_counter NUMBER;
6933 BEGIN
6934   IF (Coll.count=0) THEN
6935       return l_levels;
6936   END IF;
6937 
6938   l_counter := Coll.first;
6939   LOOP
6940       IF (Coll(l_counter).group_id = group_id) THEN -- add this record to the list
6941         l_lvl.keyName := Coll(l_counter).keyName;
6942         l_lvl.dimTable := Coll(l_counter).dimTable;
6943         l_lvl.Num := Coll(l_counter).Num;
6944         l_lvl.Name := Coll(l_counter).Name;
6945         l_lvl.TargetLevel := Coll(l_counter).TargetLevel;
6946         l_lvl.Parents1N := Coll(l_counter).Parents1N;
6947         l_lvl.ParentsMN := Coll(l_counter).ParentsMN;
6948 
6949         l_levels(l_levels.count) := l_lvl;
6950       END IF;
6951       EXIT WHEN l_counter  = Coll.last;
6952       l_counter := Coll.next(l_counter);
6953   END LOOP;
6954   return l_levels;
6955 END;
6956 
6957 
6958 FUNCTION get_tab_clsLevelCombinations (Coll IN BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevelCombinations, group_id IN NUMBER)
6959 RETURN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevelCombinations IS
6960 l_levelCombinations BSC_METADATA_OPTIMIZER_PKG.tab_clsLevelCombinations ;
6961 l_lvl BSC_METADATA_OPTIMIZER_PKG.clsLevelCombinations;
6962 l_counter NUMBER;
6963 BEGIN
6964   IF (Coll.count=0) THEN
6965       return l_levelCombinations;
6966   END IF;
6967 
6968   l_counter := Coll.first;
6969   LOOP
6970       IF (Coll(l_counter).group_id = group_id) THEN -- add this record to the list
6971         l_lvl.levels := Coll(l_counter).levels;
6972         l_lvl.LevelConfig := Coll(l_counter).levelConfig;
6973         l_levelCombinations(l_levelCombinations.count) := l_lvl;
6974       END IF;
6975       EXIT WHEN l_counter = Coll.last;
6976       l_counter := Coll.next(l_counter);
6977   END LOOP;
6978   return l_levelCombinations;
6979 END;
6980 
6981 
6982 
6983 PROCEDURE add_tabrec_clsLevelComb(
6984   pInput IN OUT NOCOPY BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevelCombinations,
6985   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevelCombinations,
6986   l_group_id IN NUMBER)  IS
6987 l_tabrec BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevelCombinations;
6988 i NUMBER;
6989 BEGIN
6990   IF (pTable.count = 0) THEN
6991       return;
6992   END IF;
6993   i := pTable.first;
6994 
6995   LOOP
6996       l_tabrec.group_id := l_group_id;
6997       l_tabrec.levels := pTable(i).levels;
6998       l_tabrec.levelConfig := pTable(i).levelConfig;
6999       IF (pInput.count = 0) THEN
7000         pInput(0) := l_tabrec;
7001       ELSE
7002         pInput(pInput.last+1) := l_tabrec;
7003       END IF;
7004 
7005       EXIT WHEN i = pTable.last;
7006       i := pTable.next(i);
7007   END LOOP;
7008 END;
7009 
7010 PROCEDURE add_tabrec_clsLevels(
7011   pInput IN OUT NOCOPY BSC_METADATA_OPTIMIZER_PKG.tab_tab_clsLevels,
7012   pTable IN BSC_METADATA_OPTIMIZER_PKG.tab_clsLevels,
7013   l_group_id IN NUMBER) IS
7014 l_tabrec BSC_METADATA_OPTIMIZER_PKG.tabrec_clsLevels;
7015 i NUMBER;
7016 BEGIN
7017   IF (pTable.count = 0) THEN
7018       return;
7019   END IF;
7020 
7021   i := pTable.first;
7022   LOOP
7023       l_tabrec.group_id := l_group_id;
7024       l_tabrec.keyname := pTable(i).keyname;
7025       l_tabrec.dimTable := pTable(i).dimTable;
7026       l_tabrec.Num := pTable(i).Num;
7027       l_tabrec.Name := pTable(i).Name;
7028       l_tabrec.TargetLevel := pTable(i).targetLevel;
7029       l_tabrec.Parents1N := pTable(i).Parents1N;
7030       l_tabrec.ParentsMN := pTable(i).ParentsMN;
7031       IF (pInput.count = 0) THEN
7032         pInput(0) := l_tabrec;
7033       ELSE
7034         pInput(pInput.last+1) := l_tabrec;
7035       END IF;
7036       EXIT WHEN i = pTable.last;
7037       i := pTable.next(i);
7038   END LOOP;
7039 
7040 END;
7041 
7042 -- Opposite of decompose
7043 -- Given a VARCHAR2_TABLE, this API will return a comma separated string
7044 
7045 FUNCTION consolidateString (pTable IN DBMS_SQL.VARCHAR2_TABLE, pSeparator IN VARCHAR2) RETURN VARCHAR2 IS
7046 l_return VARCHAR2(32000) := null;
7047 l_count NUMBER;
7048 BEGIN
7049 
7050   BSC_METADATA_OPTIMIZER_PKG.gconsolidateString := BSC_METADATA_OPTIMIZER_PKG.gconsolidateString +1;
7051 
7052   IF (mod(BSC_METADATA_OPTIMIZER_PKG.gconsolidateString, 500) = 0) THEN
7053    IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
7054       writeTmp('Call # '||BSC_METADATA_OPTIMIZER_PKG.gconsolidateString||' to API consolidateString');
7055    END IF;
7056 
7057   END IF;
7058 
7059 
7060   IF (pTable.count=0) THEN
7061       return null;
7062   END IF;
7063   l_count := pTable.first;
7064 
7065   LOOP
7066       IF (l_return IS NOT NULL) THEN
7067         l_return := l_return || pSeparator;
7068       END IF;
7069       l_return := l_return ||pTable(l_count);
7070       EXIT WHEN l_count = pTable.last;
7071       l_count := pTable.next(l_count);
7072   END LOOP;
7073   return l_return;
7074 END;
7075 
7076 PROCEDURE terminateWithError(pErrorShortName IN VARCHAR2, pAPI IN VARCHAR2 default null) IS
7077 l_error VARCHAR2(1000);
7078 BEGIN
7079 
7080 
7081 	fnd_message.set_name('BSC', pErrorShortName);
7082   l_error := fnd_message.get;
7083   BSC_METADATA_OPTIMIZER_PKG.logProgress('ERROR', pAPI||' '||l_error);
7084   FND_FILE.put_line(FND_FILE.log, 'Exception '||pAPI||' : '||l_error);
7085   --fnd_file.release_names(bsc_metadata_optimizer_pkg.g_filename||'.log', bsc_metadata_optimizer_pkg.g_filename||'.out');
7086 	fnd_message.set_name('BSC', pErrorShortName);
7087 	BSC_METADATA_OPTIMIZER_PKG.g_retcode := 2;
7088 	BSC_METADATA_OPTIMIZER_PKG.g_errbuf := l_error;
7089 
7090 END;
7091 
7092 PROCEDURE terminateWithMsg(pMessage IN VARCHAR2, pAPI in varchar2 default null)
7093 IS
7094 BEGIN
7095 
7096    BSC_METADATA_OPTIMIZER_PKG.logProgress('ERROR', pAPI||' '||pMessage);
7097    FND_FILE.put_line(FND_FILE.log, ' -------------------');
7098    FND_FILE.put_line(FND_FILE.log, ' ERROR ');
7099    FND_FILE.put_line(FND_FILE.log, ' -------------------');
7100    FND_FILE.put_line(FND_FILE.log, pMessage);
7101    BSC_METADATA_OPTIMIZER_PKG.g_retcode := 2;
7102    BSC_METADATA_OPTIMIZER_PKG.g_errbuf := pMessage;
7103 END;
7104 
7105 PROCEDURE writeKeysTest IS
7106 BEGIN
7107   null;
7108 END;
7109 
7110 
7111 PROCEDURE InitializeMasterTables IS
7112 l_stmt varchar2(1000);
7113 cv   CurTyp;
7114 cursor c1 is
7115 SELECT S.DIM_LEVEL_ID, S.LEVEL_TABLE_NAME, S.TABLE_TYPE, S.source,
7116         S.LEVEL_PK_COL, S.USER_KEY_SIZE, S.DISP_KEY_SIZE, NVL(S.EDW_FLAG, 0) AS EDW_FLAG, R.SOURCE_TABLE_NAME
7117         FROM BSC_SYS_DIM_LEVELS_B S, BSC_DB_TABLES_RELS R
7118       WHERE S.LEVEL_TABLE_NAME  = R.TABLE_NAME (+)
7119       ORDER BY LEVEL_TABLE_NAME;
7120 cRow1 c1%ROWTYPE;
7121 
7122 l_count_master NUMBER := 0;
7123 masterTable BSC_METADATA_OPTIMIZER_PKG.clsMasterTable;
7124 parents_rel_col    VARCHAR2(32000);--tab_clsParent;
7125 parents_name       VARCHAR2(32000);--tab_clsParent;
7126 l_count_parents NUMBER := 0;
7127 auxillaryField VARCHAR2(32000);--tab_clsAuxillaryField;
7128 l_count_aux NUMBER := 0;
7129 
7130 
7131 cursor C2 (p_dimID IN NUMBER, p_relation_type number)is
7132   SELECT D.LEVEL_TABLE_NAME, D.LEVEL_PK_COL
7133   FROM BSC_SYS_DIM_LEVELS_B D, BSC_SYS_DIM_LEVEL_RELS R
7134   WHERE D.DIM_LEVEL_ID = R.PARENT_DIM_LEVEL_ID
7135   AND R.DIM_LEVEL_ID =  p_dimID
7136   AND R.RELATION_TYPE = p_relation_type;
7137 
7138 cRow2 c2%ROWTYPE;
7139 
7140 RelMN BSC_METADATA_OPTIMIZER_PKG.clsRelationMN;
7141 
7142 cursor C3 (p_dim_level_id IN NUMBER) IS
7143   SELECT COLUMN_NAME
7144   FROM BSC_SYS_DIM_LEVEL_COLS
7145   WHERE DIM_LEVEL_ID = p_DIM_LEVEL_ID
7146   AND UPPER(COLUMN_TYPE) = 'A';
7147 
7148 cRow3 c3%ROWTYPE;
7149 
7150 cursor c4 is
7151   SELECT DISTINCT D.RELATION_COL, T.SOURCE_TABLE_NAME
7152   FROM BSC_SYS_DIM_LEVEL_RELS D, BSC_DB_TABLES_RELS T
7153   WHERE D.RELATION_TYPE = 2 AND D.RELATION_COL = T.TABLE_NAME (+);
7154 
7155 cRow4 c4%ROWTYPE;
7156 
7157 cursor c5 (pRelation VARCHAR2) is
7158   SELECT A.LEVEL_TABLE_NAME AS TABLE_A,
7159   A.LEVEL_PK_COL AS PK_COL_A,
7160   B.LEVEL_TABLE_NAME AS TABLE_B,
7161   B.LEVEL_PK_COL AS PK_COL_B
7162   FROM BSC_SYS_DIM_LEVELS_B A,
7163        BSC_SYS_DIM_LEVEL_RELS R,
7164        BSC_SYS_DIM_LEVELS_B B
7165   WHERE
7166       A.DIM_LEVEL_ID = R.DIM_LEVEL_ID AND
7167       R.PARENT_DIM_LEVEL_ID = B.DIM_LEVEL_ID AND
7168       UPPER(R.RELATION_COL) = upper(pRelation);
7169 
7170 cRow5 c5%ROWTYPE;
7171 
7172 
7173 
7174 BEGIN
7175   bsc_mo_helper_pkg.writeTmp('Inside InitializeMasterTables', FND_LOG.LEVEL_PROCEDURE, false);
7176   OPEN c1;
7177   LOOP
7178     FETCH c1 INTO cRow1;
7179     EXIT when c1%NOTFOUND;
7180     masterTable := bsc_mo_helper_pkg.new_clsMasterTable;
7181     masterTable.Name := cRow1.LEVEL_TABLE_NAME;
7182     masterTable.keyName := cRow1.LEVEL_PK_COL;
7183     IF (cRow1.Table_TYPE = 1) THEN
7184       masterTable.userTable := true;
7185     ELSE
7186       masterTable.userTable := false;
7187     END IF;
7188     masterTable.EDW_Flag := cRow1.EDW_FLAG;
7189     masterTable.InputTable := CRow1.SOURCE_TABLE_NAME;
7190     masterTable.source := cRow1.source;
7191     parents_name := null; -- comma separated
7192     parents_rel_col := null; -- comma separated
7193     Open c2 (cRow1.DIM_LEVEL_ID, 1);
7194     LOOP
7195       FETCH c2 into cRow2;
7196       EXIT WHEN c2%NOTFOUND;
7197       IF (parents_name IS NOT NULL) THEN
7198         parents_name := parents_name || ',';
7199       END IF;
7200       parents_name := parents_name|| nvl(cRow2.LEVEL_TABLE_NAME, ' ');
7201       parents_rel_col := parents_rel_col||nvl(cRow2.LEVEL_PK_COL, ' ');
7202     END LOOP;
7203     CLOSE c2;
7204     masterTable.parent_name := parents_name;
7205     masterTable.parent_rel_col := parents_rel_col;
7206     auxillaryField := null;
7207     IF masterTable.Source = 'BSC' THEN
7208       Open c3(cRow1.DIM_LEVEL_ID);
7209       LOOP
7210       	FETCH c3 into cRow3;
7211       	EXIT WHEN c3%NOTFOUND;
7212         IF (auxillaryField IS NOT NULL) THEN
7213           auxillaryField := auxillaryField || ',';
7214         END IF;
7215       	auxillaryField := auxillaryField||cRow3.COLUMN_NAME;
7216       END LOOP;
7217       CLOSE c3;
7218     END IF;
7219     masterTable.auxillaryFields := auxillaryField;
7220     bsc_metadata_optimizer_pkg.gMasterTable(bsc_metadata_optimizer_pkg.gMasterTable.count) := masterTable;
7221     l_count_master := l_count_master + 1;
7222   END LOOP;
7223   CLOSE c1;
7224   IF BSC_METADATA_OPTIMIZER_PKG.g_log THEN
7225     bsc_mo_helper_pkg.writeTmp('Starting MN ');--commit;
7226   END IF;
7227   --gRelacionesMN
7228   --EDW Note: There are no M-N Relations in EDW
7229   --BSC-PMF Integration: There are no M-N Relations in PMF
7230   OPEN c4;
7231   LOOP
7232     FETCH c4 into cRow4;
7233 	EXIT WHEN c4%NOTFOUND;
7234     RelMN.TableRel := cRow4.RELATION_COL;
7235     If (cRow4.SOURCE_TABLE_NAME IS NOT NULL) Then
7236       RelMN.InputTable := cRow4.SOURCE_TABLE_NAME;
7237     Else
7238       RelMN.InputTable := null;
7239     End If;
7240   	OPEN c5(cRow4.Relation_col);
7241     FETCH C5 INTO cRow5;
7242     RelMN.TableA := cRow5.TABLE_A;
7243     RelMN.keyNameA := cRow5.PK_COL_A;
7244     RelMN.TableB := cRow5.TABLE_B;
7245     RelMN.keyNameB := cRow5.PK_COL_B;
7246     BSC_METADATA_OPTIMIZER_PKG.gRelationsMN(bsc_metadata_optimizer_pkg.gRelationsMN.count):= RelMN;
7247     CLOSE C5;
7248   END Loop;
7249   CLOSE c4;
7250   bsc_mo_helper_pkg.writeTmp('Completed InitializeMasterTables', FND_LOG.LEVEL_PROCEDURE, false);
7251   Exception when others then
7252   bsc_mo_helper_pkg.writeTmp('exception in InitializeMasterTables', FND_LOG.LEVEL_UNEXPECTED, true);
7253   bsc_mo_helper_pkg.writeTmp('gMasterTables are ', FND_LOG.LEVEL_EXCEPTION, true);
7254   bsc_mo_helper_pkg.write_this(bsc_metadata_optimizer_pkg.gMasterTable, FND_LOG.LEVEL_EXCEPTION, true);
7255 	raise;
7256 
7257 END;
7258 
7259 
7260 --consider only production objectives
7261 FUNCTION aw_objective_exists return boolean is
7262 l_count number;
7263 begin
7264   select count(1) into l_count
7265     from bsc_kpi_properties p
7266        , bsc_kpis_vl k
7267    where p.indicator=k.indicator
7268      and p.property_code=bsc_metadata_optimizer_pkg.impl_type
7269      and p.property_value = 2
7270          -- only production objectives
7271      and k.prototype_flag not in (1,2,3,4)
7272       ;
7273   if (l_count>0) then
7274     return true;
7275   else
7276     return false;
7277   end if;
7278 end;
7279 
7280 PROCEDURE load_reporting_calendars IS
7281 
7282 l_lud_stmt varchar2(1000):= 'select last_update_date
7283 from bsc_reporting_calendar
7284 where calendar_id=:1 and rownum=1';
7285 
7286 cursor cCalendars is
7287 select calendar_id, last_update_date
7288 from bsc_sys_calendars_b;
7289 
7290 l_option_string varchar2(100);
7291 l_error_message varchar2(4000);
7292 
7293 l_dropped_aw_objectives dbms_sql.varchar2_table;
7294 l_rpt_lud date;
7295 
7296 cv CurTyp;
7297 
7298 BEGIN
7299   writeTmp('In bsc_mo_helper_pkg.load_reporting_calendars '||get_time);
7300   IF BSC_METADATA_OPTIMIZER_PKG.g_bsc_mv THEN
7301     writeTmp('going to loop for calendars');
7302     FOR i IN cCalendars LOOP
7303       open cv for l_lud_stmt using i.calendar_id;
7304       fetch cv into l_rpt_lud;
7305       close cv;
7306       writeTmp('LUD for sys calendar '||i.calendar_id ||':'||to_char(i.last_update_date, 'mm/dd/yy hh24:mi:ss')||
7307         ' and rpt calendar:'||to_char( l_rpt_lud, 'mm/dd/yy hh24:mi:ss' ));
7308       -- IF last update date in rpt cal is not null, then check if its > calendar's last update date
7309       -- IF rpt lud is null, it hasnt been refreshed even once, so refresh
7310       IF (l_rpt_lud is not null and l_rpt_lud>=i.last_update_date) then
7311         null;
7312       ELSE
7313         writeTmp('Attempting to refresh Calendar id '||i.calendar_id ||
7314           ' changed, calling load reporting calendar for this:'||get_time);
7315         IF NOT BSC_BIA_WRAPPER.Load_Reporting_Calendar(i.calendar_id, l_error_message) THEN
7316           writeTmp('Error Loading reporting calendar :'||l_error_message, FND_LOG.LEVEL_UNEXPECTED, true);
7317           BSC_MO_HELPER_PKG.TerminateWithMsg(l_error_message);
7318           raise BSC_METADATA_OPTIMIZER_PKG.optimizer_exception;
7319         END IF;
7320         writeTmp('Done refreshing Calendar id '||i.calendar_id ||' '||get_time);
7321         -- AW_INTEGRATION: Call aw api to import calendar into aw world
7322         -- Fix bug#4360037: load calendar into aw only if there are aw indicators
7323         IF aw_objective_exists THEN
7324           if (bsc_metadata_optimizer_pkg.g_log) then
7325             l_option_string := 'DEBUG LOG';
7326           end if;
7327           bsc_aw_calendar.create_calendar
7328                 (    i.calendar_id
7329                    , l_option_string
7330                  );
7331           bsc_aw_calendar.load_calendar(
7332                      p_calendar => i.calendar_id,
7333                      p_options => l_option_string
7334                  );
7335         END IF;
7336       END IF;
7337     END LOOP;
7338   END IF;
7339 END;
7340 
7341 PROCEDURE implement_aws (p_objectives in dbms_Sql.varchar2_table) IS
7342 
7343 BEGIN
7344   bsc_aw_adapter.implement_kpi_aw(
7345                   p_objectives,
7346                   'DEBUG LOG,RECREATE KPI,SUMMARIZATION LEVEL=1000');
7347 END;
7348 
7349 /*BUG FIX 5647971
7350   this function added so any future change in naming convention of index does not impact code much
7351   we will have one place to change the code
7352   this function can be flexibly extended for other tyype of tables as well
7353   currently this is written for B tables indexes only*/
7354 FUNCTION generate_index_name(p_table_name IN VARCHAR2,
7355                       p_table_type IN VARCHAR2,p_index_type IN VARCHAR2) RETURN VARCHAR2 IS
7356 BEGIN
7357   IF (p_table_type = 'B') THEN
7358     RETURN p_table_name||'_N' || p_index_type;
7359   END IF;
7360 END;
7361 
7362 END BSC_MO_HELPER_PKG;