msi/tests: Remove win9x hacks.
[wine] / dlls / msi / table.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2002-2005 Mike McCormack for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22 #include <assert.h>
23
24 #define COBJMACROS
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
27
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "winnls.h"
36 #include "msipriv.h"
37 #include "query.h"
38
39 #include "wine/debug.h"
40 #include "wine/unicode.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
43
44 #define MSITABLE_HASH_TABLE_SIZE 37
45
46 typedef struct tagMSICOLUMNHASHENTRY
47 {
48     struct tagMSICOLUMNHASHENTRY *next;
49     UINT value;
50     UINT row;
51 } MSICOLUMNHASHENTRY;
52
53 typedef struct tagMSICOLUMNINFO
54 {
55     LPWSTR tablename;
56     UINT   number;
57     LPWSTR colname;
58     UINT   type;
59     UINT   offset;
60     INT    ref_count;
61     BOOL   temporary;
62     MSICOLUMNHASHENTRY **hash_table;
63 } MSICOLUMNINFO;
64
65 typedef struct tagMSIORDERINFO
66 {
67     UINT *reorder;
68     UINT num_cols;
69     UINT cols[1];
70 } MSIORDERINFO;
71
72 struct tagMSITABLE
73 {
74     BYTE **data;
75     BOOL *data_persistent;
76     UINT row_count;
77     struct list entry;
78     MSICOLUMNINFO *colinfo;
79     UINT col_count;
80     MSICONDITION persistent;
81     INT ref_count;
82     WCHAR name[1];
83 };
84
85 static const WCHAR szStringData[] = {
86     '_','S','t','r','i','n','g','D','a','t','a',0 };
87 static const WCHAR szStringPool[] = {
88     '_','S','t','r','i','n','g','P','o','o','l',0 };
89
90 /* information for default tables */
91 static WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
92 static WCHAR szTable[]  = { 'T','a','b','l','e',0 };
93 static WCHAR szName[]    = { 'N','a','m','e',0 };
94 static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
95 static WCHAR szNumber[]  = { 'N','u','m','b','e','r',0 };
96 static WCHAR szType[]    = { 'T','y','p','e',0 };
97
98 static const MSICOLUMNINFO _Columns_cols[4] = {
99     { szColumns, 1, szTable,  MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
100     { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2,     2, 0, 0, NULL },
101     { szColumns, 3, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
102     { szColumns, 4, szType,   MSITYPE_VALID | 2,                   6, 0, 0, NULL },
103 };
104
105 static const MSICOLUMNINFO _Tables_cols[1] = {
106     { szTables,  1, szName,   MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
107 };
108
109 #define MAX_STREAM_NAME 0x1f
110
111 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
112        MSICOLUMNINFO **pcols, UINT *pcount );
113 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
114        DWORD count );
115 static UINT get_tablecolumns( MSIDATABASE *db,
116        LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
117 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
118
119 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
120 {
121     if( MSITYPE_IS_BINARY(col->type) )
122         return 2;
123
124     if( col->type & MSITYPE_STRING )
125         return bytes_per_strref;
126
127     if( (col->type & 0xff) <= 2)
128         return 2;
129
130     if( (col->type & 0xff) != 4 )
131         ERR("Invalid column size!\n");
132
133     return 4;
134 }
135
136 static int utf2mime(int x)
137 {
138     if( (x>='0') && (x<='9') )
139         return x-'0';
140     if( (x>='A') && (x<='Z') )
141         return x-'A'+10;
142     if( (x>='a') && (x<='z') )
143         return x-'a'+10+26;
144     if( x=='.' )
145         return 10+26+26;
146     if( x=='_' )
147         return 10+26+26+1;
148     return -1;
149 }
150
151 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
152 {
153     DWORD count = MAX_STREAM_NAME;
154     DWORD ch, next;
155     LPWSTR out, p;
156
157     if( !bTable )
158         count = lstrlenW( in )+2;
159     if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
160     p = out;
161
162     if( bTable )
163     {
164          *p++ = 0x4840;
165          count --;
166     }
167     while( count -- ) 
168     {
169         ch = *in++;
170         if( !ch )
171         {
172             *p = ch;
173             return out;
174         }
175         if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
176         {
177             ch = utf2mime(ch) + 0x4800;
178             next = *in;
179             if( next && (next<0x80) )
180             {
181                 next = utf2mime(next);
182                 if( next != -1 )
183                 {
184                      next += 0x3ffffc0;
185                      ch += (next<<6);
186                      in++;
187                 }
188             }
189         }
190         *p++ = ch;
191     }
192     ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
193     msi_free( out );
194     return NULL;
195 }
196
197 static int mime2utf(int x)
198 {
199     if( x<10 )
200         return x + '0';
201     if( x<(10+26))
202         return x - 10 + 'A';
203     if( x<(10+26+26))
204         return x - 10 - 26 + 'a';
205     if( x == (10+26+26) )
206         return '.';
207     return '_';
208 }
209
210 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
211 {
212     WCHAR ch;
213     DWORD count = 0;
214
215     while ( (ch = *in++) )
216     {
217         if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
218         {
219             if( ch >= 0x4800 )
220                 ch = mime2utf(ch-0x4800);
221             else
222             {
223                 ch -= 0x3800;
224                 *out++ = mime2utf(ch&0x3f);
225                 count++;
226                 ch = mime2utf((ch>>6)&0x3f);
227             }
228         }
229         *out++ = ch;
230         count++;
231     }
232     *out = 0;
233     return count;
234 }
235
236 void enum_stream_names( IStorage *stg )
237 {
238     IEnumSTATSTG *stgenum = NULL;
239     HRESULT r;
240     STATSTG stat;
241     ULONG n, count;
242     WCHAR name[0x40];
243
244     r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
245     if( FAILED( r ) )
246         return;
247
248     n = 0;
249     while( 1 )
250     {
251         count = 0;
252         r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
253         if( FAILED( r ) || !count )
254             break;
255         decode_streamname( stat.pwcsName, name );
256         TRACE("stream %2d -> %s %s\n", n,
257               debugstr_w(stat.pwcsName), debugstr_w(name) );
258         CoTaskMemFree( stat.pwcsName );
259         n++;
260     }
261
262     IEnumSTATSTG_Release( stgenum );
263 }
264
265 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
266                        BYTE **pdata, UINT *psz )
267 {
268     HRESULT r;
269     UINT ret = ERROR_FUNCTION_FAILED;
270     VOID *data;
271     ULONG sz, count;
272     IStream *stm = NULL;
273     STATSTG stat;
274     LPWSTR encname;
275
276     encname = encode_streamname(table, stname);
277
278     TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
279
280     r = IStorage_OpenStream(stg, encname, NULL, 
281             STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
282     msi_free( encname );
283     if( FAILED( r ) )
284     {
285         WARN("open stream failed r = %08x - empty table?\n", r);
286         return ret;
287     }
288
289     r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
290     if( FAILED( r ) )
291     {
292         WARN("open stream failed r = %08x!\n", r);
293         goto end;
294     }
295
296     if( stat.cbSize.QuadPart >> 32 )
297     {
298         WARN("Too big!\n");
299         goto end;
300     }
301         
302     sz = stat.cbSize.QuadPart;
303     data = msi_alloc( sz );
304     if( !data )
305     {
306         WARN("couldn't allocate memory r=%08x!\n", r);
307         ret = ERROR_NOT_ENOUGH_MEMORY;
308         goto end;
309     }
310         
311     r = IStream_Read(stm, data, sz, &count );
312     if( FAILED( r ) || ( count != sz ) )
313     {
314         msi_free( data );
315         WARN("read stream failed r = %08x!\n", r);
316         goto end;
317     }
318
319     *pdata = data;
320     *psz = sz;
321     ret = ERROR_SUCCESS;
322
323 end:
324     IStream_Release( stm );
325
326     return ret;
327 }
328
329 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
330                         LPCVOID data, UINT sz, BOOL bTable )
331 {
332     HRESULT r;
333     UINT ret = ERROR_FUNCTION_FAILED;
334     ULONG count;
335     IStream *stm = NULL;
336     ULARGE_INTEGER size;
337     LARGE_INTEGER pos;
338     LPWSTR encname;
339
340     encname = encode_streamname(bTable, stname );
341     r = IStorage_OpenStream( stg, encname, NULL, 
342             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
343     if( FAILED(r) )
344     {
345         r = IStorage_CreateStream( stg, encname,
346                 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
347     }
348     msi_free( encname );
349     if( FAILED( r ) )
350     {
351         WARN("open stream failed r = %08x\n", r);
352         return ret;
353     }
354
355     size.QuadPart = sz;
356     r = IStream_SetSize( stm, size );
357     if( FAILED( r ) )
358     {
359         WARN("Failed to SetSize\n");
360         goto end;
361     }
362
363     pos.QuadPart = 0;
364     r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
365     if( FAILED( r ) )
366     {
367         WARN("Failed to Seek\n");
368         goto end;
369     }
370
371     if (sz)
372     {
373         r = IStream_Write(stm, data, sz, &count );
374         if( FAILED( r ) || ( count != sz ) )
375         {
376             WARN("Failed to Write\n");
377             goto end;
378         }
379     }
380
381     ret = ERROR_SUCCESS;
382
383 end:
384     IStream_Release( stm );
385
386     return ret;
387 }
388
389 static void free_table( MSITABLE *table )
390 {
391     UINT i;
392     for( i=0; i<table->row_count; i++ )
393         msi_free( table->data[i] );
394     msi_free( table->data );
395     msi_free( table->data_persistent );
396     msi_free_colinfo( table->colinfo, table->col_count );
397     msi_free( table->colinfo );
398     msi_free( table );
399 }
400
401 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
402 {
403     const MSICOLUMNINFO *last_col;
404
405     if (!count)
406         return 0;
407
408     if (bytes_per_strref != LONG_STR_BYTES)
409     {
410         UINT i, size = 0;
411         for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
412         return size;
413     }
414     last_col = &cols[count - 1];
415     return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
416 }
417
418 /* add this table to the list of cached tables in the database */
419 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
420 {
421     BYTE *rawdata = NULL;
422     UINT rawsize = 0, i, j, row_size, row_size_mem;
423
424     TRACE("%s\n",debugstr_w(t->name));
425
426     row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
427     row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
428
429     /* if we can't read the table, just assume that it's empty */
430     read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
431     if( !rawdata )
432         return ERROR_SUCCESS;
433
434     TRACE("Read %d bytes\n", rawsize );
435
436     if( rawsize % row_size )
437     {
438         WARN("Table size is invalid %d/%d\n", rawsize, row_size );
439         goto err;
440     }
441
442     t->row_count = rawsize / row_size;
443     t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
444     if( !t->data )
445         goto err;
446     t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
447     if ( !t->data_persistent )
448         goto err;
449
450     /* transpose all the data */
451     TRACE("Transposing data from %d rows\n", t->row_count );
452     for (i = 0; i < t->row_count; i++)
453     {
454         UINT ofs = 0, ofs_mem = 0;
455
456         t->data[i] = msi_alloc( row_size_mem );
457         if( !t->data[i] )
458             goto err;
459         t->data_persistent[i] = TRUE;
460
461         for (j = 0; j < t->col_count; j++)
462         {
463             UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
464             UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
465             UINT k;
466
467             if ( n != 2 && n != 3 && n != 4 )
468             {
469                 ERR("oops - unknown column width %d\n", n);
470                 goto err;
471             }
472             if (t->colinfo[j].type & MSITYPE_STRING && n < m)
473             {
474                 for (k = 0; k < m; k++)
475                 {
476                     if (k < n)
477                         t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
478                     else
479                         t->data[i][ofs_mem + k] = 0;
480                 }
481             }
482             else
483             {
484                 for (k = 0; k < n; k++)
485                     t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
486             }
487             ofs_mem += m;
488             ofs += n;
489         }
490     }
491
492     msi_free( rawdata );
493     return ERROR_SUCCESS;
494 err:
495     msi_free( rawdata );
496     return ERROR_FUNCTION_FAILED;
497 }
498
499 void free_cached_tables( MSIDATABASE *db )
500 {
501     while( !list_empty( &db->tables ) )
502     {
503         MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
504
505         list_remove( &t->entry );
506         free_table( t );
507     }
508 }
509
510 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
511 {
512     MSITABLE *t;
513
514     LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
515         if( !strcmpW( name, t->name ) )
516             return t;
517
518     return NULL;
519 }
520
521 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
522 {
523     UINT r, column_count = 0;
524     MSICOLUMNINFO *columns;
525
526     /* get the number of columns in this table */
527     column_count = 0;
528     r = get_tablecolumns( db, name, NULL, &column_count );
529     if( r != ERROR_SUCCESS )
530         return r;
531
532     *pcount = column_count;
533
534     /* if there's no columns, there's no table */
535     if( column_count == 0 )
536         return ERROR_INVALID_PARAMETER;
537
538     TRACE("Table %s found\n", debugstr_w(name) );
539
540     columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
541     if( !columns )
542         return ERROR_FUNCTION_FAILED;
543
544     r = get_tablecolumns( db, name, columns, &column_count );
545     if( r != ERROR_SUCCESS )
546     {
547         msi_free( columns );
548         return ERROR_FUNCTION_FAILED;
549     }
550
551     *pcols = columns;
552
553     return r;
554 }
555
556 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
557                        MSICONDITION persistent, MSITABLE **table_ret)
558 {
559     UINT r, nField;
560     MSIVIEW *tv = NULL;
561     MSIRECORD *rec = NULL;
562     column_info *col;
563     MSITABLE *table;
564     UINT i;
565
566     /* only add tables that don't exist already */
567     if( TABLE_Exists(db, name ) )
568     {
569         WARN("table %s exists\n", debugstr_w(name));
570         return ERROR_BAD_QUERY_SYNTAX;
571     }
572
573     table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
574     if( !table )
575         return ERROR_FUNCTION_FAILED;
576
577     table->ref_count = 1;
578     table->row_count = 0;
579     table->data = NULL;
580     table->data_persistent = NULL;
581     table->colinfo = NULL;
582     table->col_count = 0;
583     table->persistent = persistent;
584     lstrcpyW( table->name, name );
585
586     for( col = col_info; col; col = col->next )
587         table->col_count++;
588
589     table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
590     if (!table->colinfo)
591     {
592         free_table( table );
593         return ERROR_FUNCTION_FAILED;
594     }
595
596     for( i = 0, col = col_info; col; i++, col = col->next )
597     {
598         table->colinfo[ i ].tablename = strdupW( col->table );
599         table->colinfo[ i ].number = i + 1;
600         table->colinfo[ i ].colname = strdupW( col->column );
601         table->colinfo[ i ].type = col->type;
602         table->colinfo[ i ].offset = 0;
603         table->colinfo[ i ].ref_count = 0;
604         table->colinfo[ i ].hash_table = NULL;
605         table->colinfo[ i ].temporary = col->temporary;
606     }
607     table_calc_column_offsets( db, table->colinfo, table->col_count);
608
609     r = TABLE_CreateView( db, szTables, &tv );
610     TRACE("CreateView returned %x\n", r);
611     if( r )
612     {
613         free_table( table );
614         return r;
615     }
616
617     r = tv->ops->execute( tv, 0 );
618     TRACE("tv execute returned %x\n", r);
619     if( r )
620         goto err;
621
622     rec = MSI_CreateRecord( 1 );
623     if( !rec )
624         goto err;
625
626     r = MSI_RecordSetStringW( rec, 1, name );
627     if( r )
628         goto err;
629
630     r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
631     TRACE("insert_row returned %x\n", r);
632     if( r )
633         goto err;
634
635     tv->ops->delete( tv );
636     tv = NULL;
637
638     msiobj_release( &rec->hdr );
639     rec = NULL;
640
641     if( persistent != MSICONDITION_FALSE )
642     {
643         /* add each column to the _Columns table */
644         r = TABLE_CreateView( db, szColumns, &tv );
645         if( r )
646             return r;
647
648         r = tv->ops->execute( tv, 0 );
649         TRACE("tv execute returned %x\n", r);
650         if( r )
651             goto err;
652
653         rec = MSI_CreateRecord( 4 );
654         if( !rec )
655             goto err;
656
657         r = MSI_RecordSetStringW( rec, 1, name );
658         if( r )
659             goto err;
660
661         /*
662          * need to set the table, column number, col name and type
663          * for each column we enter in the table
664          */
665         nField = 1;
666         for( col = col_info; col; col = col->next )
667         {
668             r = MSI_RecordSetInteger( rec, 2, nField );
669             if( r )
670                 goto err;
671
672             r = MSI_RecordSetStringW( rec, 3, col->column );
673             if( r )
674                 goto err;
675
676             r = MSI_RecordSetInteger( rec, 4, col->type );
677             if( r )
678                 goto err;
679
680             r = tv->ops->insert_row( tv, rec, -1, FALSE );
681             if( r )
682                 goto err;
683
684             nField++;
685         }
686         if( !col )
687             r = ERROR_SUCCESS;
688     }
689
690 err:
691     if (rec)
692         msiobj_release( &rec->hdr );
693     /* FIXME: remove values from the string table on error */
694     if( tv )
695         tv->ops->delete( tv );
696
697     if (r == ERROR_SUCCESS)
698     {
699         list_add_head( &db->tables, &table->entry );
700         *table_ret = table;
701     }
702     else
703         free_table( table );
704
705     return r;
706 }
707
708 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
709 {
710     MSITABLE *table;
711     UINT r;
712
713     /* first, see if the table is cached */
714     table = find_cached_table( db, name );
715     if( table )
716     {
717         *table_ret = table;
718         return ERROR_SUCCESS;
719     }
720
721     /* nonexistent tables should be interpreted as empty tables */
722     table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
723     if( !table )
724         return ERROR_FUNCTION_FAILED;
725
726     table->row_count = 0;
727     table->data = NULL;
728     table->data_persistent = NULL;
729     table->colinfo = NULL;
730     table->col_count = 0;
731     table->persistent = MSICONDITION_TRUE;
732     lstrcpyW( table->name, name );
733
734     if ( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) )
735         table->persistent = MSICONDITION_NONE;
736
737     r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
738     if (r != ERROR_SUCCESS)
739     {
740         free_table ( table );
741         return r;
742     }
743
744     r = read_table_from_storage( db, table, db->storage );
745     if( r != ERROR_SUCCESS )
746     {
747         free_table( table );
748         return r;
749     }
750
751     list_add_head( &db->tables, &table->entry );
752     *table_ret = table;
753     return ERROR_SUCCESS;
754 }
755
756 static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
757 {
758     UINT ret = 0, i;
759
760     for (i = 0; i < bytes; i++)
761         ret += data[row][col + i] << i * 8;
762
763     return ret;
764 }
765
766 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
767 {
768     BYTE *rawdata = NULL;
769     UINT rawsize, i, j, row_size, row_count;
770     UINT r = ERROR_FUNCTION_FAILED;
771
772     /* Nothing to do for non-persistent tables */
773     if( t->persistent == MSICONDITION_FALSE )
774         return ERROR_SUCCESS;
775
776     TRACE("Saving %s\n", debugstr_w( t->name ) );
777
778     row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
779     row_count = t->row_count;
780     for (i = 0; i < t->row_count; i++)
781     {
782         if (!t->data_persistent[i])
783         {
784             row_count = 1; /* yes, this is bizarre */
785             break;
786         }
787     }
788     rawsize = row_count * row_size;
789     rawdata = msi_alloc_zero( rawsize );
790     if( !rawdata )
791     {
792         r = ERROR_NOT_ENOUGH_MEMORY;
793         goto err;
794     }
795
796     rawsize = 0;
797     for (i = 0; i < t->row_count; i++)
798     {
799         UINT ofs = 0, ofs_mem = 0;
800
801         if (!t->data_persistent[i]) break;
802
803         for (j = 0; j < t->col_count; j++)
804         {
805             UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
806             UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
807             UINT k;
808
809             if (n != 2 && n != 3 && n != 4)
810             {
811                 ERR("oops - unknown column width %d\n", n);
812                 goto err;
813             }
814             if (t->colinfo[j].type & MSITYPE_STRING && n < m)
815             {
816                 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
817                 if (id > 1 << bytes_per_strref * 8)
818                 {
819                     ERR("string id %u out of range\n", id);
820                     goto err;
821                 }
822             }
823             for (k = 0; k < n; k++)
824             {
825                 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
826             }
827             ofs_mem += m;
828             ofs += n;
829         }
830         rawsize += row_size;
831     }
832
833     TRACE("writing %d bytes\n", rawsize);
834     r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
835
836 err:
837     msi_free( rawdata );
838     return r;
839 }
840
841 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
842 {
843     DWORD i;
844
845     for( i=0; colinfo && (i<count); i++ )
846     {
847          assert( (i+1) == colinfo[ i ].number );
848          if (i)
849              colinfo[i].offset = colinfo[ i - 1 ].offset
850                                + bytes_per_column( db, &colinfo[ i - 1 ], LONG_STR_BYTES );
851          else
852              colinfo[i].offset = 0;
853          TRACE("column %d is [%s] with type %08x ofs %d\n",
854                colinfo[i].number, debugstr_w(colinfo[i].colname),
855                colinfo[i].type, colinfo[i].offset);
856     }
857 }
858
859 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
860                                      MSICOLUMNINFO *colinfo, UINT *sz)
861 {
862     const MSICOLUMNINFO *p;
863     DWORD i, n;
864
865     TRACE("%s\n", debugstr_w(name));
866
867     if (!strcmpW( name, szTables ))
868     {
869         p = _Tables_cols;
870         n = 1;
871     }
872     else if (!strcmpW( name, szColumns ))
873     {
874         p = _Columns_cols;
875         n = 4;
876     }
877     else
878         return ERROR_FUNCTION_FAILED;
879
880     /* duplicate the string data so we can free it in msi_free_colinfo */
881     for (i=0; i<n; i++)
882     {
883         if (colinfo && (i < *sz) )
884         {
885             colinfo[i] = p[i];
886             colinfo[i].tablename = strdupW( p[i].tablename );
887             colinfo[i].colname = strdupW( p[i].colname );
888         }
889         if( colinfo && (i >= *sz) )
890             break;
891     }
892     table_calc_column_offsets( db, colinfo, n );
893     *sz = n;
894     return ERROR_SUCCESS;
895 }
896
897 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
898 {
899     UINT i;
900
901     for( i=0; i<count; i++ )
902     {
903         msi_free( colinfo[i].tablename );
904         msi_free( colinfo[i].colname );
905         msi_free( colinfo[i].hash_table );
906     }
907 }
908
909 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
910 {
911     return strdupW(msi_string_lookup_id( db->strings, stringid ));
912 }
913
914 static UINT get_tablecolumns( MSIDATABASE *db,
915        LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
916 {
917     UINT r, i, n=0, table_id, count, maxcount = *sz;
918     MSITABLE *table = NULL;
919
920     TRACE("%s\n", debugstr_w(szTableName));
921
922     /* first check if there is a default table with that name */
923     r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
924     if( ( r == ERROR_SUCCESS ) && *sz )
925         return r;
926
927     r = get_table( db, szColumns, &table );
928     if( r != ERROR_SUCCESS )
929     {
930         ERR("couldn't load _Columns table\n");
931         return ERROR_FUNCTION_FAILED;
932     }
933
934     /* convert table and column names to IDs from the string table */
935     r = msi_string2idW( db->strings, szTableName, &table_id );
936     if( r != ERROR_SUCCESS )
937     {
938         WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
939         return r;
940     }
941
942     TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
943
944     /* Note: _Columns table doesn't have non-persistent data */
945
946     /* if maxcount is non-zero, assume it's exactly right for this table */
947     memset( colinfo, 0, maxcount*sizeof(*colinfo) );
948     count = table->row_count;
949     for( i=0; i<count; i++ )
950     {
951         if( read_table_int(table->data, i, 0, LONG_STR_BYTES) != table_id )
952             continue;
953         if( colinfo )
954         {
955             UINT id = read_table_int(table->data, i, table->colinfo[2].offset, LONG_STR_BYTES);
956             UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
957
958             /* check the column number is in range */
959             if (col<1 || col>maxcount)
960             {
961                 ERR("column %d out of range\n", col);
962                 continue;
963             }
964
965             /* check if this column was already set */
966             if (colinfo[ col - 1 ].number)
967             {
968                 ERR("duplicate column %d\n", col);
969                 continue;
970             }
971
972             colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
973             colinfo[ col - 1 ].number = col;
974             colinfo[ col - 1 ].colname = msi_makestring( db, id );
975             colinfo[ col - 1 ].type = read_table_int(table->data, i,
976                                                      table->colinfo[3].offset,
977                                                      sizeof(USHORT)) - (1<<15);
978             colinfo[ col - 1 ].offset = 0;
979             colinfo[ col - 1 ].ref_count = 0;
980             colinfo[ col - 1 ].hash_table = NULL;
981         }
982         n++;
983     }
984
985     TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
986
987     if (colinfo && n != maxcount)
988     {
989         ERR("missing column in table %s\n", debugstr_w(szTableName));
990         msi_free_colinfo(colinfo, maxcount );
991         return ERROR_FUNCTION_FAILED;
992     }
993
994     table_calc_column_offsets( db, colinfo, n );
995     *sz = n;
996
997     return ERROR_SUCCESS;
998 }
999
1000 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
1001 {
1002     MSITABLE *table;
1003     LPWSTR tablename;
1004     UINT size, offset, old_count;
1005     UINT n;
1006
1007     /* We may free name in msi_free_colinfo. */
1008     tablename = strdupW( name );
1009
1010     table = find_cached_table( db, tablename );
1011     old_count = table->col_count;
1012     msi_free_colinfo( table->colinfo, table->col_count );
1013     msi_free( table->colinfo );
1014     table->colinfo = NULL;
1015
1016     table_get_column_info( db, tablename, &table->colinfo, &table->col_count );
1017     if (!table->col_count)
1018         goto done;
1019
1020     size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
1021     offset = table->colinfo[table->col_count - 1].offset;
1022
1023     for ( n = 0; n < table->row_count; n++ )
1024     {
1025         table->data[n] = msi_realloc( table->data[n], size );
1026         if (old_count < table->col_count)
1027             memset( &table->data[n][offset], 0, size - offset );
1028     }
1029
1030 done:
1031     msi_free(tablename);
1032 }
1033
1034 /* try to find the table name in the _Tables table */
1035 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1036 {
1037     UINT r, table_id, i;
1038     MSITABLE *table;
1039
1040     if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
1041         !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
1042         return TRUE;
1043
1044     r = msi_string2idW( db->strings, name, &table_id );
1045     if( r != ERROR_SUCCESS )
1046     {
1047         TRACE("Couldn't find id for %s\n", debugstr_w(name));
1048         return FALSE;
1049     }
1050
1051     r = get_table( db, szTables, &table );
1052     if( r != ERROR_SUCCESS )
1053     {
1054         ERR("table %s not available\n", debugstr_w(szTables));
1055         return FALSE;
1056     }
1057
1058     for( i = 0; i < table->row_count; i++ )
1059     {
1060         if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
1061             return TRUE;
1062     }
1063
1064     return FALSE;
1065 }
1066
1067 /* below is the query interface to a table */
1068
1069 typedef struct tagMSITABLEVIEW
1070 {
1071     MSIVIEW        view;
1072     MSIDATABASE   *db;
1073     MSITABLE      *table;
1074     MSICOLUMNINFO *columns;
1075     MSIORDERINFO  *order;
1076     UINT           num_cols;
1077     UINT           row_size;
1078     WCHAR          name[1];
1079 } MSITABLEVIEW;
1080
1081 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1082 {
1083     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1084     UINT offset, n;
1085
1086     if( !tv->table )
1087         return ERROR_INVALID_PARAMETER;
1088
1089     if( (col==0) || (col>tv->num_cols) )
1090         return ERROR_INVALID_PARAMETER;
1091
1092     /* how many rows are there ? */
1093     if( row >= tv->table->row_count )
1094         return ERROR_NO_MORE_ITEMS;
1095
1096     if( tv->columns[col-1].offset >= tv->row_size )
1097     {
1098         ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1099         ERR("%p %p\n", tv, tv->columns );
1100         return ERROR_FUNCTION_FAILED;
1101     }
1102
1103     if (tv->order)
1104         row = tv->order->reorder[row];
1105
1106     n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1107     if (n != 2 && n != 3 && n != 4)
1108     {
1109         ERR("oops! what is %d bytes per column?\n", n );
1110         return ERROR_FUNCTION_FAILED;
1111     }
1112
1113     offset = tv->columns[col-1].offset;
1114     *val = read_table_int(tv->table->data, row, offset, n);
1115
1116     /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1117
1118     return ERROR_SUCCESS;
1119 }
1120
1121 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1122 {
1123     LPWSTR p, stname = NULL;
1124     UINT i, r, type, ival;
1125     DWORD len;
1126     LPCWSTR sval;
1127     MSIVIEW *view = (MSIVIEW *) tv;
1128
1129     TRACE("%p %d\n", tv, row);
1130
1131     len = lstrlenW( tv->name ) + 1;
1132     stname = msi_alloc( len*sizeof(WCHAR) );
1133     if ( !stname )
1134     {
1135        r = ERROR_OUTOFMEMORY;
1136        goto err;
1137     }
1138
1139     lstrcpyW( stname, tv->name );
1140
1141     for ( i = 0; i < tv->num_cols; i++ )
1142     {
1143         type = tv->columns[i].type;
1144         if ( type & MSITYPE_KEY )
1145         {
1146             r = TABLE_fetch_int( view, row, i+1, &ival );
1147             if ( r != ERROR_SUCCESS )
1148                 goto err;
1149
1150             if ( tv->columns[i].type & MSITYPE_STRING )
1151             {
1152                 sval = msi_string_lookup_id( tv->db->strings, ival );
1153                 if ( !sval )
1154                 {
1155                     r = ERROR_INVALID_PARAMETER;
1156                     goto err;
1157                 }
1158             }
1159             else
1160             {
1161                 static const WCHAR fmt[] = { '%','d',0 };
1162                 WCHAR number[0x20];
1163                 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1164
1165                 switch( n )
1166                 {
1167                 case 2:
1168                     sprintfW( number, fmt, ival-0x8000 );
1169                     break;
1170                 case 4:
1171                     sprintfW( number, fmt, ival^0x80000000 );
1172                     break;
1173                 default:
1174                     ERR( "oops - unknown column width %d\n", n );
1175                     r = ERROR_FUNCTION_FAILED;
1176                     goto err;
1177                 }
1178                 sval = number;
1179             }
1180
1181             len += lstrlenW( szDot ) + lstrlenW( sval );
1182             p = msi_realloc ( stname, len*sizeof(WCHAR) );
1183             if ( !p )
1184             {
1185                 r = ERROR_OUTOFMEMORY;
1186                 goto err;
1187             }
1188             stname = p;
1189
1190             lstrcatW( stname, szDot );
1191             lstrcatW( stname, sval );
1192         }
1193         else
1194            continue;
1195     }
1196
1197     *pstname = stname;
1198     return ERROR_SUCCESS;
1199
1200 err:
1201     msi_free( stname );
1202     *pstname = NULL;
1203     return r;
1204 }
1205
1206 /*
1207  * We need a special case for streams, as we need to reference column with
1208  * the name of the stream in the same table, and the table name
1209  * which may not be available at higher levels of the query
1210  */
1211 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1212 {
1213     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1214     UINT r;
1215     LPWSTR encname, full_name = NULL;
1216
1217     if( !view->ops->fetch_int )
1218         return ERROR_INVALID_PARAMETER;
1219
1220     r = msi_stream_name( tv, row, &full_name );
1221     if ( r != ERROR_SUCCESS )
1222     {
1223         ERR("fetching stream, error = %d\n", r);
1224         return r;
1225     }
1226
1227     encname = encode_streamname( FALSE, full_name );
1228     r = db_get_raw_stream( tv->db, encname, stm );
1229     if( r )
1230         ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1231
1232     msi_free( full_name );
1233     msi_free( encname );
1234     return r;
1235 }
1236
1237 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1238 {
1239     UINT offset, n, i;
1240
1241     if( !tv->table )
1242         return ERROR_INVALID_PARAMETER;
1243
1244     if( (col==0) || (col>tv->num_cols) )
1245         return ERROR_INVALID_PARAMETER;
1246
1247     if( row >= tv->table->row_count )
1248         return ERROR_INVALID_PARAMETER;
1249
1250     if( tv->columns[col-1].offset >= tv->row_size )
1251     {
1252         ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1253         ERR("%p %p\n", tv, tv->columns );
1254         return ERROR_FUNCTION_FAILED;
1255     }
1256
1257     msi_free( tv->columns[col-1].hash_table );
1258     tv->columns[col-1].hash_table = NULL;
1259
1260     n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1261     if ( n != 2 && n != 3 && n != 4 )
1262     {
1263         ERR("oops! what is %d bytes per column?\n", n );
1264         return ERROR_FUNCTION_FAILED;
1265     }
1266
1267     offset = tv->columns[col-1].offset;
1268     for ( i = 0; i < n; i++ )
1269         tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1270
1271     return ERROR_SUCCESS;
1272 }
1273
1274 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1275 {
1276     MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1277
1278     if (!tv->table)
1279         return ERROR_INVALID_PARAMETER;
1280
1281     if (tv->order)
1282         row = tv->order->reorder[row];
1283
1284     return msi_view_get_row(tv->db, view, row, rec);
1285 }
1286
1287 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1288 {
1289     UINT r;
1290     MSIQUERY *query = NULL;
1291     MSIRECORD *rec = NULL;
1292
1293     static const WCHAR insert[] = {
1294        'I','N','S','E','R','T',' ','I','N','T','O',' ',
1295           '`','_','S','t','r','e','a','m','s','`',' ',
1296          '(','`','N','a','m','e','`',',',
1297              '`','D','a','t','a','`',')',' ',
1298          'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1299
1300     TRACE("%p %s %p\n", db, debugstr_w(name), data);
1301
1302     rec = MSI_CreateRecord( 2 );
1303     if ( !rec )
1304         return ERROR_OUTOFMEMORY;
1305
1306     r = MSI_RecordSetStringW( rec, 1, name );
1307     if ( r != ERROR_SUCCESS )
1308        goto err;
1309
1310     r = MSI_RecordSetIStream( rec, 2, data );
1311     if ( r != ERROR_SUCCESS )
1312        goto err;
1313
1314     r = MSI_DatabaseOpenViewW( db, insert, &query );
1315     if ( r != ERROR_SUCCESS )
1316        goto err;
1317
1318     r = MSI_ViewExecute( query, rec );
1319
1320 err:
1321     msiobj_release( &query->hdr );
1322     msiobj_release( &rec->hdr );
1323
1324     return r;
1325 }
1326
1327 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1328 {
1329     MSICOLUMNINFO columninfo;
1330     UINT r;
1331
1332     if ( (iField <= 0) ||
1333          (iField > tv->num_cols) ||
1334           MSI_RecordIsNull( rec, iField ) )
1335         return ERROR_FUNCTION_FAILED;
1336
1337     columninfo = tv->columns[ iField - 1 ];
1338
1339     if ( MSITYPE_IS_BINARY(columninfo.type) )
1340     {
1341         *pvalue = 1; /* refers to the first key column */
1342     }
1343     else if ( columninfo.type & MSITYPE_STRING )
1344     {
1345         LPCWSTR sval = MSI_RecordGetString( rec, iField );
1346         if (sval)
1347         {
1348             r = msi_string2idW(tv->db->strings, sval, pvalue);
1349             if (r != ERROR_SUCCESS)
1350                 return ERROR_NOT_FOUND;
1351         }
1352         else *pvalue = 0;
1353     }
1354     else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1355     {
1356         *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1357         if ( *pvalue & 0xffff0000 )
1358         {
1359             ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1360             return ERROR_FUNCTION_FAILED;
1361         }
1362     }
1363     else
1364     {
1365         INT ival = MSI_RecordGetInteger( rec, iField );
1366         *pvalue = ival ^ 0x80000000;
1367     }
1368
1369     return ERROR_SUCCESS;
1370 }
1371
1372 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1373 {
1374     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1375     UINT i, val, r = ERROR_SUCCESS;
1376
1377     if ( !tv->table )
1378         return ERROR_INVALID_PARAMETER;
1379
1380     /* test if any of the mask bits are invalid */
1381     if ( mask >= (1<<tv->num_cols) )
1382         return ERROR_INVALID_PARAMETER;
1383
1384     for ( i = 0; i < tv->num_cols; i++ )
1385     {
1386         BOOL persistent;
1387
1388         /* only update the fields specified in the mask */
1389         if ( !(mask&(1<<i)) )
1390             continue;
1391
1392         persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1393                      (tv->table->data_persistent[row]);
1394         /* FIXME: should we allow updating keys? */
1395
1396         val = 0;
1397         if ( !MSI_RecordIsNull( rec, i + 1 ) )
1398         {
1399             r = get_table_value_from_record (tv, rec, i + 1, &val);
1400             if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1401             {
1402                 IStream *stm;
1403                 LPWSTR stname;
1404
1405                 if ( r != ERROR_SUCCESS )
1406                     return ERROR_FUNCTION_FAILED;
1407
1408                 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1409                 if ( r != ERROR_SUCCESS )
1410                     return r;
1411
1412                 r = msi_stream_name( tv, row, &stname );
1413                 if ( r != ERROR_SUCCESS )
1414                 {
1415                     IStream_Release( stm );
1416                     return r;
1417                 }
1418
1419                 r = msi_addstreamW( tv->db, stname, stm );
1420                 IStream_Release( stm );
1421                 msi_free ( stname );
1422
1423                 if ( r != ERROR_SUCCESS )
1424                     return r;
1425             }
1426             else if ( tv->columns[i].type & MSITYPE_STRING )
1427             {
1428                 UINT x;
1429
1430                 if ( r != ERROR_SUCCESS )
1431                 {
1432                     LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1433                     val = msi_addstringW( tv->db->strings, sval, -1, 1,
1434                       persistent ? StringPersistent : StringNonPersistent );
1435                 }
1436                 else
1437                 {
1438                     TABLE_fetch_int(&tv->view, row, i + 1, &x);
1439                     if (val == x)
1440                         continue;
1441                 }
1442             }
1443             else
1444             {
1445                 if ( r != ERROR_SUCCESS )
1446                     return ERROR_FUNCTION_FAILED;
1447             }
1448         }
1449
1450         r = TABLE_set_int( tv, row, i+1, val );
1451         if ( r != ERROR_SUCCESS )
1452             break;
1453     }
1454     return r;
1455 }
1456
1457 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1458 {
1459     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1460     BYTE **p, *row;
1461     BOOL *b;
1462     UINT sz;
1463     BYTE ***data_ptr;
1464     BOOL **data_persist_ptr;
1465     UINT *row_count;
1466
1467     TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1468
1469     if( !tv->table )
1470         return ERROR_INVALID_PARAMETER;
1471
1472     row = msi_alloc_zero( tv->row_size );
1473     if( !row )
1474         return ERROR_NOT_ENOUGH_MEMORY;
1475
1476     row_count = &tv->table->row_count;
1477     data_ptr = &tv->table->data;
1478     data_persist_ptr = &tv->table->data_persistent;
1479     if (*num == -1)
1480         *num = tv->table->row_count;
1481
1482     sz = (*row_count + 1) * sizeof (BYTE*);
1483     if( *data_ptr )
1484         p = msi_realloc( *data_ptr, sz );
1485     else
1486         p = msi_alloc( sz );
1487     if( !p )
1488     {
1489         msi_free( row );
1490         return ERROR_NOT_ENOUGH_MEMORY;
1491     }
1492
1493     sz = (*row_count + 1) * sizeof (BOOL);
1494     if( *data_persist_ptr )
1495         b = msi_realloc( *data_persist_ptr, sz );
1496     else
1497         b = msi_alloc( sz );
1498     if( !b )
1499     {
1500         msi_free( row );
1501         msi_free( p );
1502         return ERROR_NOT_ENOUGH_MEMORY;
1503     }
1504
1505     *data_ptr = p;
1506     (*data_ptr)[*row_count] = row;
1507
1508     *data_persist_ptr = b;
1509     (*data_persist_ptr)[*row_count] = !temporary;
1510
1511     (*row_count)++;
1512
1513     return ERROR_SUCCESS;
1514 }
1515
1516 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1517 {
1518     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1519
1520     TRACE("%p %p\n", tv, record);
1521
1522     TRACE("There are %d columns\n", tv->num_cols );
1523
1524     return ERROR_SUCCESS;
1525 }
1526
1527 static UINT TABLE_close( struct tagMSIVIEW *view )
1528 {
1529     TRACE("%p\n", view );
1530     
1531     return ERROR_SUCCESS;
1532 }
1533
1534 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1535 {
1536     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1537
1538     TRACE("%p %p %p\n", view, rows, cols );
1539
1540     if( cols )
1541         *cols = tv->num_cols;
1542     if( rows )
1543     {
1544         if( !tv->table )
1545             return ERROR_INVALID_PARAMETER;
1546         *rows = tv->table->row_count;
1547     }
1548
1549     return ERROR_SUCCESS;
1550 }
1551
1552 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1553                 UINT n, LPWSTR *name, UINT *type, BOOL *temporary,
1554                 LPWSTR *table_name )
1555 {
1556     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1557
1558     TRACE("%p %d %p %p\n", tv, n, name, type );
1559
1560     if( ( n == 0 ) || ( n > tv->num_cols ) )
1561         return ERROR_INVALID_PARAMETER;
1562
1563     if( name )
1564     {
1565         *name = strdupW( tv->columns[n-1].colname );
1566         if( !*name )
1567             return ERROR_FUNCTION_FAILED;
1568     }
1569
1570     if( table_name )
1571     {
1572         *table_name = strdupW( tv->columns[n-1].tablename );
1573         if( !*table_name )
1574             return ERROR_FUNCTION_FAILED;
1575     }
1576
1577     if( type )
1578         *type = tv->columns[n-1].type;
1579
1580     if( temporary )
1581         *temporary = tv->columns[n-1].temporary;
1582
1583     return ERROR_SUCCESS;
1584 }
1585
1586 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1587
1588 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1589 {
1590     UINT r, row, i;
1591
1592     /* check there's no null values where they're not allowed */
1593     for( i = 0; i < tv->num_cols; i++ )
1594     {
1595         if ( tv->columns[i].type & MSITYPE_NULLABLE )
1596             continue;
1597
1598         if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1599             TRACE("skipping binary column\n");
1600         else if ( tv->columns[i].type & MSITYPE_STRING )
1601         {
1602             LPCWSTR str;
1603
1604             str = MSI_RecordGetString( rec, i+1 );
1605             if (str == NULL || str[0] == 0)
1606                 return ERROR_INVALID_DATA;
1607         }
1608         else
1609         {
1610             UINT n;
1611
1612             n = MSI_RecordGetInteger( rec, i+1 );
1613             if (n == MSI_NULL_INTEGER)
1614                 return ERROR_INVALID_DATA;
1615         }
1616     }
1617
1618     /* check there's no duplicate keys */
1619     r = msi_table_find_row( tv, rec, &row );
1620     if (r == ERROR_SUCCESS)
1621         return ERROR_FUNCTION_FAILED;
1622
1623     return ERROR_SUCCESS;
1624 }
1625
1626 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1627 {
1628     UINT r, i, ivalue, x;
1629
1630     for (i = 0; i < tv->num_cols; i++ )
1631     {
1632         r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1633         if (r != ERROR_SUCCESS)
1634             return 1;
1635
1636         r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1637         if (r != ERROR_SUCCESS)
1638         {
1639             WARN("TABLE_fetch_int should not fail here %u\n", r);
1640             return -1;
1641         }
1642         if (ivalue > x)
1643         {
1644             return 1;
1645         }
1646         else if (ivalue == x)
1647         {
1648             if (i < tv->num_cols - 1) continue;
1649             return 0;
1650         }
1651         else
1652             return -1;
1653     }
1654     return 1;
1655 }
1656
1657 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1658 {
1659     int idx, c, low = 0, high = tv->table->row_count - 1;
1660
1661     TRACE("%p %p\n", tv, rec);
1662
1663     while (low <= high)
1664     {
1665         idx = (low + high) / 2;
1666         c = compare_record( tv, idx, rec );
1667
1668         if (c < 0)
1669             high = idx - 1;
1670         else if (c > 0)
1671             low = idx + 1;
1672         else
1673         {
1674             TRACE("found %u\n", idx);
1675             return idx;
1676         }
1677     }
1678     TRACE("found %u\n", high + 1);
1679     return high + 1;
1680 }
1681
1682 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1683 {
1684     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1685     UINT i, r;
1686
1687     TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1688
1689     /* check that the key is unique - can we find a matching row? */
1690     r = table_validate_new( tv, rec );
1691     if( r != ERROR_SUCCESS )
1692         return ERROR_FUNCTION_FAILED;
1693
1694     if (row == -1)
1695         row = find_insert_index( tv, rec );
1696
1697     r = table_create_new_row( view, &row, temporary );
1698     TRACE("insert_row returned %08x\n", r);
1699     if( r != ERROR_SUCCESS )
1700         return r;
1701
1702     /* shift the rows to make room for the new row */
1703     for (i = tv->table->row_count - 1; i > row; i--)
1704     {
1705         memmove(&(tv->table->data[i][0]),
1706                 &(tv->table->data[i - 1][0]), tv->row_size);
1707         tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1708     }
1709
1710     /* Re-set the persistence flag */
1711     tv->table->data_persistent[row] = !temporary;
1712     return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1713 }
1714
1715 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1716 {
1717     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1718     UINT r, num_rows, num_cols, i;
1719
1720     TRACE("%p %d\n", tv, row);
1721
1722     if ( !tv->table )
1723         return ERROR_INVALID_PARAMETER;
1724
1725     r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1726     if ( r != ERROR_SUCCESS )
1727         return r;
1728
1729     if ( row >= num_rows )
1730         return ERROR_FUNCTION_FAILED;
1731
1732     num_rows = tv->table->row_count;
1733     tv->table->row_count--;
1734
1735     /* reset the hash tables */
1736     for (i = 0; i < tv->num_cols; i++)
1737     {
1738         msi_free( tv->columns[i].hash_table );
1739         tv->columns[i].hash_table = NULL;
1740     }
1741
1742     for (i = row + 1; i < num_rows; i++)
1743     {
1744         memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1745         tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1746     }
1747
1748     msi_free(tv->table->data[num_rows - 1]);
1749
1750     return ERROR_SUCCESS;
1751 }
1752
1753 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1754 {
1755     MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1756     UINT r, new_row;
1757
1758     /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1759      * sets the fetched record apart from other records
1760      */
1761
1762     if (!tv->table)
1763         return ERROR_INVALID_PARAMETER;
1764
1765     r = msi_table_find_row(tv, rec, &new_row);
1766     if (r != ERROR_SUCCESS)
1767     {
1768         ERR("can't find row to modify\n");
1769         return ERROR_FUNCTION_FAILED;
1770     }
1771
1772     /* the row cannot be changed */
1773     if (row != new_row + 1)
1774         return ERROR_FUNCTION_FAILED;
1775
1776     return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1777 }
1778
1779 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1780 {
1781     MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1782     UINT r, row;
1783
1784     if (!tv->table)
1785         return ERROR_INVALID_PARAMETER;
1786
1787     r = msi_table_find_row(tv, rec, &row);
1788     if (r == ERROR_SUCCESS)
1789         return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1790     else
1791         return TABLE_insert_row( view, rec, -1, FALSE );
1792 }
1793
1794 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1795 {
1796     MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1797     UINT row, r;
1798
1799     r = msi_table_find_row(tv, rec, &row);
1800     if (r != ERROR_SUCCESS)
1801         return r;
1802
1803     return TABLE_delete_row(view, row);
1804 }
1805
1806 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1807 {
1808     MSIRECORD *curr;
1809     UINT r, i, count;
1810
1811     r = TABLE_get_row(view, row - 1, &curr);
1812     if (r != ERROR_SUCCESS)
1813         return r;
1814
1815     /* Close the original record */
1816     MSI_CloseRecord(&rec->hdr);
1817
1818     count = MSI_RecordGetFieldCount(rec);
1819     for (i = 0; i < count; i++)
1820         MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1821
1822     msiobj_release(&curr->hdr);
1823     return ERROR_SUCCESS;
1824 }
1825
1826 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1827                           MSIRECORD *rec, UINT row)
1828 {
1829     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1830     UINT r;
1831
1832     TRACE("%p %d %p\n", view, eModifyMode, rec );
1833
1834     switch (eModifyMode)
1835     {
1836     case MSIMODIFY_DELETE:
1837         r = modify_delete_row( view, rec );
1838         break;
1839     case MSIMODIFY_VALIDATE_NEW:
1840         r = table_validate_new( tv, rec );
1841         break;
1842
1843     case MSIMODIFY_INSERT:
1844         r = table_validate_new( tv, rec );
1845         if (r != ERROR_SUCCESS)
1846             break;
1847         r = TABLE_insert_row( view, rec, -1, FALSE );
1848         break;
1849
1850     case MSIMODIFY_INSERT_TEMPORARY:
1851         r = table_validate_new( tv, rec );
1852         if (r != ERROR_SUCCESS)
1853             break;
1854         r = TABLE_insert_row( view, rec, -1, TRUE );
1855         break;
1856
1857     case MSIMODIFY_REFRESH:
1858         r = msi_refresh_record( view, rec, row );
1859         break;
1860
1861     case MSIMODIFY_UPDATE:
1862         r = msi_table_update( view, rec, row );
1863         break;
1864
1865     case MSIMODIFY_ASSIGN:
1866         r = msi_table_assign( view, rec );
1867         break;
1868
1869     case MSIMODIFY_REPLACE:
1870     case MSIMODIFY_MERGE:
1871     case MSIMODIFY_VALIDATE:
1872     case MSIMODIFY_VALIDATE_FIELD:
1873     case MSIMODIFY_VALIDATE_DELETE:
1874         FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1875         r = ERROR_CALL_NOT_IMPLEMENTED;
1876         break;
1877
1878     default:
1879         r = ERROR_INVALID_DATA;
1880     }
1881
1882     return r;
1883 }
1884
1885 static UINT TABLE_delete( struct tagMSIVIEW *view )
1886 {
1887     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1888
1889     TRACE("%p\n", view );
1890
1891     tv->table = NULL;
1892     tv->columns = NULL;
1893
1894     if (tv->order)
1895     {
1896         msi_free( tv->order->reorder );
1897         msi_free( tv->order );
1898         tv->order = NULL;
1899     }
1900
1901     msi_free( tv );
1902
1903     return ERROR_SUCCESS;
1904 }
1905
1906 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1907     UINT val, UINT *row, MSIITERHANDLE *handle )
1908 {
1909     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1910     const MSICOLUMNHASHENTRY *entry;
1911
1912     TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1913
1914     if( !tv->table )
1915         return ERROR_INVALID_PARAMETER;
1916
1917     if( (col==0) || (col > tv->num_cols) )
1918         return ERROR_INVALID_PARAMETER;
1919
1920     if( !tv->columns[col-1].hash_table )
1921     {
1922         UINT i;
1923         UINT num_rows = tv->table->row_count;
1924         MSICOLUMNHASHENTRY **hash_table;
1925         MSICOLUMNHASHENTRY *new_entry;
1926
1927         if( tv->columns[col-1].offset >= tv->row_size )
1928         {
1929             ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1930             ERR("%p %p\n", tv, tv->columns );
1931             return ERROR_FUNCTION_FAILED;
1932         }
1933
1934         /* allocate contiguous memory for the table and its entries so we
1935          * don't have to do an expensive cleanup */
1936         hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1937             num_rows * sizeof(MSICOLUMNHASHENTRY));
1938         if (!hash_table)
1939             return ERROR_OUTOFMEMORY;
1940
1941         memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1942         tv->columns[col-1].hash_table = hash_table;
1943
1944         new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1945
1946         for (i = 0; i < num_rows; i++, new_entry++)
1947         {
1948             UINT row_value;
1949
1950             if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1951                 continue;
1952
1953             new_entry->next = NULL;
1954             new_entry->value = row_value;
1955             new_entry->row = i;
1956             if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1957             {
1958                 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1959                 while (prev_entry->next)
1960                     prev_entry = prev_entry->next;
1961                 prev_entry->next = new_entry;
1962             }
1963             else
1964                 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1965         }
1966     }
1967
1968     if( !*handle )
1969         entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1970     else
1971         entry = (*handle)->next;
1972
1973     while (entry && entry->value != val)
1974         entry = entry->next;
1975
1976     *handle = entry;
1977     if (!entry)
1978         return ERROR_NO_MORE_ITEMS;
1979
1980     *row = entry->row;
1981
1982     return ERROR_SUCCESS;
1983 }
1984
1985 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1986 {
1987     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1988     UINT i;
1989
1990     TRACE("%p %d\n", view, tv->table->ref_count);
1991
1992     for (i = 0; i < tv->table->col_count; i++)
1993     {
1994         if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1995             InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1996     }
1997
1998     return InterlockedIncrement(&tv->table->ref_count);
1999 }
2000
2001 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
2002 {
2003     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2004     MSIRECORD *rec = NULL;
2005     MSIVIEW *columns = NULL;
2006     UINT row, r;
2007
2008     rec = MSI_CreateRecord(2);
2009     if (!rec)
2010         return ERROR_OUTOFMEMORY;
2011
2012     MSI_RecordSetStringW(rec, 1, table);
2013     MSI_RecordSetInteger(rec, 2, number);
2014
2015     r = TABLE_CreateView(tv->db, szColumns, &columns);
2016     if (r != ERROR_SUCCESS)
2017         return r;
2018
2019     r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
2020     if (r != ERROR_SUCCESS)
2021         goto done;
2022
2023     r = TABLE_delete_row(columns, row);
2024     if (r != ERROR_SUCCESS)
2025         goto done;
2026
2027     msi_update_table_columns(tv->db, table);
2028
2029 done:
2030     msiobj_release(&rec->hdr);
2031     columns->ops->delete(columns);
2032     return r;
2033 }
2034
2035 static UINT TABLE_release(struct tagMSIVIEW *view)
2036 {
2037     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2038     INT ref = tv->table->ref_count;
2039     UINT i, r;
2040
2041     TRACE("%p %d\n", view, ref);
2042
2043     for (i = 0; i < tv->table->col_count; i++)
2044     {
2045         if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2046         {
2047             ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2048             if (ref == 0)
2049             {
2050                 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2051                                         tv->table->colinfo[i].number);
2052                 if (r != ERROR_SUCCESS)
2053                     break;
2054             }
2055         }
2056     }
2057
2058     ref = InterlockedDecrement(&tv->table->ref_count);
2059     if (ref == 0)
2060     {
2061         if (!tv->table->row_count)
2062         {
2063             list_remove(&tv->table->entry);
2064             free_table(tv->table);
2065             TABLE_delete(view);
2066         }
2067     }
2068
2069     return ref;
2070 }
2071
2072 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2073                              LPCWSTR column, UINT type, BOOL hold)
2074 {
2075     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2076     MSITABLE *msitable;
2077     MSIRECORD *rec;
2078     UINT r, i;
2079
2080     rec = MSI_CreateRecord(4);
2081     if (!rec)
2082         return ERROR_OUTOFMEMORY;
2083
2084     MSI_RecordSetStringW(rec, 1, table);
2085     MSI_RecordSetInteger(rec, 2, number);
2086     MSI_RecordSetStringW(rec, 3, column);
2087     MSI_RecordSetInteger(rec, 4, type);
2088
2089     r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2090     if (r != ERROR_SUCCESS)
2091         goto done;
2092
2093     msi_update_table_columns(tv->db, table);
2094
2095     if (!hold)
2096         goto done;
2097
2098     msitable = find_cached_table(tv->db, table);
2099     for (i = 0; i < msitable->col_count; i++)
2100     {
2101         if (!strcmpW( msitable->colinfo[i].colname, column ))
2102         {
2103             InterlockedIncrement(&msitable->colinfo[i].ref_count);
2104             break;
2105         }
2106     }
2107
2108 done:
2109     msiobj_release(&rec->hdr);
2110     return r;
2111 }
2112
2113 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2114 {
2115     UINT n, r, count;
2116     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2117
2118     r = TABLE_get_dimensions(view, NULL, &count);
2119     if (r != ERROR_SUCCESS)
2120         return r;
2121
2122     if (order->num_cols >= count)
2123         return ERROR_FUNCTION_FAILED;
2124
2125     r = VIEW_find_column(view, name, tv->name, &n);
2126     if (r != ERROR_SUCCESS)
2127         return r;
2128
2129     order->cols[order->num_cols] = n;
2130     TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2131
2132     order->num_cols++;
2133
2134     return ERROR_SUCCESS;
2135 }
2136
2137 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2138                           UINT a, UINT b, UINT *swap)
2139 {
2140     UINT r, i, a_val = 0, b_val = 0;
2141
2142     *swap = 0;
2143     for (i = 0; i < order->num_cols; i++)
2144     {
2145         r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2146         if (r != ERROR_SUCCESS)
2147             return r;
2148
2149         r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2150         if (r != ERROR_SUCCESS)
2151             return r;
2152
2153         if (a_val != b_val)
2154         {
2155             if (a_val > b_val)
2156                 *swap = 1;
2157             break;
2158         }
2159     }
2160
2161     return ERROR_SUCCESS;
2162 }
2163
2164 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2165                             UINT left, UINT right)
2166 {
2167     UINT r, i, j, temp;
2168     UINT swap = 0, center = (left + right) / 2;
2169     UINT *array = order->reorder;
2170
2171     if (left == right)
2172         return ERROR_SUCCESS;
2173
2174     /* sort the left half */
2175     r = order_mergesort(view, order, left, center);
2176     if (r != ERROR_SUCCESS)
2177         return r;
2178
2179     /* sort the right half */
2180     r = order_mergesort(view, order, center + 1, right);
2181     if (r != ERROR_SUCCESS)
2182         return r;
2183
2184     for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2185     {
2186         r = order_compare(view, order, array[i], array[j], &swap);
2187         if (r != ERROR_SUCCESS)
2188             return r;
2189
2190         if (swap)
2191         {
2192             temp = array[j];
2193             memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2194             array[i] = temp;
2195             j++;
2196             center++;
2197         }
2198     }
2199
2200     return ERROR_SUCCESS;
2201 }
2202
2203 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2204 {
2205     UINT i, swap, r;
2206
2207     for (i = 1; i < num_rows; i++)
2208     {
2209         r = order_compare(view, order, order->reorder[i - 1],
2210                           order->reorder[i], &swap);
2211         if (r != ERROR_SUCCESS)
2212             return r;
2213
2214         if (!swap)
2215             continue;
2216
2217         ERR("Bad order! %d\n", i);
2218         return ERROR_FUNCTION_FAILED;
2219     }
2220
2221     return ERROR_SUCCESS;
2222 }
2223
2224 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2225 {
2226     MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2227     MSIORDERINFO *order;
2228     column_info *ptr;
2229     UINT r, i;
2230     UINT rows, cols;
2231
2232     TRACE("sorting table %s\n", debugstr_w(tv->name));
2233
2234     r = TABLE_get_dimensions(view, &rows, &cols);
2235     if (r != ERROR_SUCCESS)
2236         return r;
2237
2238     if (rows == 0)
2239         return ERROR_SUCCESS;
2240
2241     order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2242     if (!order)
2243         return ERROR_OUTOFMEMORY;
2244
2245     for (ptr = columns; ptr; ptr = ptr->next)
2246         order_add_column(view, order, ptr->column);
2247
2248     order->reorder = msi_alloc(rows * sizeof(UINT));
2249     if (!order->reorder)
2250         return ERROR_OUTOFMEMORY;
2251
2252     for (i = 0; i < rows; i++)
2253         order->reorder[i] = i;
2254
2255     r = order_mergesort(view, order, 0, rows - 1);
2256     if (r != ERROR_SUCCESS)
2257         return r;
2258
2259     r = order_verify(view, order, rows);
2260     if (r != ERROR_SUCCESS)
2261         return r;
2262
2263     tv->order = order;
2264
2265     return ERROR_SUCCESS;
2266 }
2267
2268 static UINT TABLE_drop(struct tagMSIVIEW *view)
2269 {
2270     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2271     MSIVIEW *tables = NULL;
2272     MSIRECORD *rec = NULL;
2273     UINT r, row;
2274     INT i;
2275
2276     TRACE("dropping table %s\n", debugstr_w(tv->name));
2277
2278     for (i = tv->table->col_count - 1; i >= 0; i--)
2279     {
2280         r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2281                                 tv->table->colinfo[i].number);
2282         if (r != ERROR_SUCCESS)
2283             return r;
2284     }
2285
2286     rec = MSI_CreateRecord(1);
2287     if (!rec)
2288         return ERROR_OUTOFMEMORY;
2289
2290     MSI_RecordSetStringW(rec, 1, tv->name);
2291
2292     r = TABLE_CreateView(tv->db, szTables, &tables);
2293     if (r != ERROR_SUCCESS)
2294         return r;
2295
2296     r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
2297     if (r != ERROR_SUCCESS)
2298         goto done;
2299
2300     r = TABLE_delete_row(tables, row);
2301     if (r != ERROR_SUCCESS)
2302         goto done;
2303
2304     list_remove(&tv->table->entry);
2305     free_table(tv->table);
2306
2307 done:
2308     msiobj_release(&rec->hdr);
2309     tables->ops->delete(tables);
2310
2311     return r;
2312 }
2313
2314 static const MSIVIEWOPS table_ops =
2315 {
2316     TABLE_fetch_int,
2317     TABLE_fetch_stream,
2318     TABLE_get_row,
2319     TABLE_set_row,
2320     TABLE_insert_row,
2321     TABLE_delete_row,
2322     TABLE_execute,
2323     TABLE_close,
2324     TABLE_get_dimensions,
2325     TABLE_get_column_info,
2326     TABLE_modify,
2327     TABLE_delete,
2328     TABLE_find_matching_rows,
2329     TABLE_add_ref,
2330     TABLE_release,
2331     TABLE_add_column,
2332     TABLE_remove_column,
2333     TABLE_sort,
2334     TABLE_drop,
2335 };
2336
2337 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2338 {
2339     MSITABLEVIEW *tv ;
2340     UINT r, sz;
2341
2342     TRACE("%p %s %p\n", db, debugstr_w(name), view );
2343
2344     if ( !strcmpW( name, szStreams ) )
2345         return STREAMS_CreateView( db, view );
2346     else if ( !strcmpW( name, szStorages ) )
2347         return STORAGES_CreateView( db, view );
2348
2349     sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2350     tv = msi_alloc_zero( sz );
2351     if( !tv )
2352         return ERROR_FUNCTION_FAILED;
2353
2354     r = get_table( db, name, &tv->table );
2355     if( r != ERROR_SUCCESS )
2356     {
2357         msi_free( tv );
2358         WARN("table not found\n");
2359         return r;
2360     }
2361
2362     TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2363
2364     /* fill the structure */
2365     tv->view.ops = &table_ops;
2366     tv->db = db;
2367     tv->columns = tv->table->colinfo;
2368     tv->num_cols = tv->table->col_count;
2369     tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2370
2371     TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2372
2373     *view = (MSIVIEW*) tv;
2374     lstrcpyW( tv->name, name );
2375
2376     return ERROR_SUCCESS;
2377 }
2378
2379 UINT MSI_CommitTables( MSIDATABASE *db )
2380 {
2381     UINT r, bytes_per_strref;
2382     HRESULT hr;
2383     MSITABLE *table = NULL;
2384
2385     TRACE("%p\n",db);
2386
2387     r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2388     if( r != ERROR_SUCCESS )
2389     {
2390         WARN("failed to save string table r=%08x\n",r);
2391         return r;
2392     }
2393
2394     LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2395     {
2396         r = save_table( db, table, bytes_per_strref );
2397         if( r != ERROR_SUCCESS )
2398         {
2399             WARN("failed to save table %s (r=%08x)\n",
2400                   debugstr_w(table->name), r);
2401             return r;
2402         }
2403     }
2404
2405     /* force everything to reload next time */
2406     free_cached_tables( db );
2407
2408     hr = IStorage_Commit( db->storage, 0 );
2409     if (FAILED( hr ))
2410     {
2411         WARN("failed to commit changes 0x%08x\n", hr);
2412         r = ERROR_FUNCTION_FAILED;
2413     }
2414     return r;
2415 }
2416
2417 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2418 {
2419     MSITABLE *t;
2420     UINT r;
2421
2422     TRACE("%p %s\n", db, debugstr_w(table));
2423
2424     if (!table)
2425         return MSICONDITION_ERROR;
2426
2427     r = get_table( db, table, &t );
2428     if (r != ERROR_SUCCESS)
2429         return MSICONDITION_NONE;
2430
2431     return t->persistent;
2432 }
2433
2434 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2435 {
2436     UINT ret = 0, i;
2437
2438     for (i = 0; i < bytes; i++)
2439         ret += (data[col + i] << i * 8);
2440
2441     return ret;
2442 }
2443
2444 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2445 {
2446     LPWSTR stname = NULL, sval, p;
2447     DWORD len;
2448     UINT i, r;
2449
2450     TRACE("%p %p\n", tv, rec);
2451
2452     len = lstrlenW( tv->name ) + 1;
2453     stname = msi_alloc( len*sizeof(WCHAR) );
2454     if ( !stname )
2455     {
2456        r = ERROR_OUTOFMEMORY;
2457        goto err;
2458     }
2459
2460     lstrcpyW( stname, tv->name );
2461
2462     for ( i = 0; i < tv->num_cols; i++ )
2463     {
2464         if ( tv->columns[i].type & MSITYPE_KEY )
2465         {
2466             sval = msi_dup_record_field( rec, i + 1 );
2467             if ( !sval )
2468             {
2469                 r = ERROR_OUTOFMEMORY;
2470                 goto err;
2471             }
2472
2473             len += lstrlenW( szDot ) + lstrlenW ( sval );
2474             p = msi_realloc ( stname, len*sizeof(WCHAR) );
2475             if ( !p )
2476             {
2477                 r = ERROR_OUTOFMEMORY;
2478                 goto err;
2479             }
2480             stname = p;
2481
2482             lstrcatW( stname, szDot );
2483             lstrcatW( stname, sval );
2484
2485             msi_free( sval );
2486         }
2487         else
2488             continue;
2489     }
2490
2491     *pstname = encode_streamname( FALSE, stname );
2492     msi_free( stname );
2493
2494     return ERROR_SUCCESS;
2495
2496 err:
2497     msi_free ( stname );
2498     *pstname = NULL;
2499     return r;
2500 }
2501
2502 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2503                                             IStorage *stg,
2504                                             const BYTE *rawdata, UINT bytes_per_strref )
2505 {
2506     UINT i, val, ofs = 0;
2507     USHORT mask;
2508     MSICOLUMNINFO *columns = tv->columns;
2509     MSIRECORD *rec;
2510
2511     mask = rawdata[0] | (rawdata[1] << 8);
2512     rawdata += 2;
2513
2514     rec = MSI_CreateRecord( tv->num_cols );
2515     if( !rec )
2516         return rec;
2517
2518     TRACE("row ->\n");
2519     for( i=0; i<tv->num_cols; i++ )
2520     {
2521         if ( (mask&1) && (i>=(mask>>8)) )
2522             break;
2523         /* all keys must be present */
2524         if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2525             continue;
2526
2527         if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2528         {
2529             LPWSTR encname;
2530             IStream *stm = NULL;
2531             UINT r;
2532
2533             ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2534
2535             r = msi_record_encoded_stream_name( tv, rec, &encname );
2536             if ( r != ERROR_SUCCESS )
2537                 return NULL;
2538
2539             r = IStorage_OpenStream( stg, encname, NULL,
2540                      STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2541             msi_free( encname );
2542             if ( r != ERROR_SUCCESS )
2543                 return NULL;
2544
2545             MSI_RecordSetStream( rec, i+1, stm );
2546             TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2547         }
2548         else if( columns[i].type & MSITYPE_STRING )
2549         {
2550             LPCWSTR sval;
2551
2552             val = read_raw_int(rawdata, ofs, bytes_per_strref);
2553             sval = msi_string_lookup_id( st, val );
2554             MSI_RecordSetStringW( rec, i+1, sval );
2555             TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2556             ofs += bytes_per_strref;
2557         }
2558         else
2559         {
2560             UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2561             switch( n )
2562             {
2563             case 2:
2564                 val = read_raw_int(rawdata, ofs, n);
2565                 if (val)
2566                     MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2567                 TRACE(" field %d [0x%04x]\n", i+1, val );
2568                 break;
2569             case 4:
2570                 val = read_raw_int(rawdata, ofs, n);
2571                 if (val)
2572                     MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2573                 TRACE(" field %d [0x%08x]\n", i+1, val );
2574                 break;
2575             default:
2576                 ERR("oops - unknown column width %d\n", n);
2577                 break;
2578             }
2579             ofs += n;
2580         }
2581     }
2582     return rec;
2583 }
2584
2585 static void dump_record( MSIRECORD *rec )
2586 {
2587     UINT i, n;
2588
2589     n = MSI_RecordGetFieldCount( rec );
2590     for( i=1; i<=n; i++ )
2591     {
2592         LPCWSTR sval = MSI_RecordGetString( rec, i );
2593
2594         if( MSI_RecordIsNull( rec, i ) )
2595             TRACE("row -> []\n");
2596         else if( (sval = MSI_RecordGetString( rec, i )) )
2597             TRACE("row -> [%s]\n", debugstr_w(sval));
2598         else
2599             TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2600     }
2601 }
2602
2603 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2604 {
2605     LPCWSTR sval;
2606     UINT i;
2607
2608     for( i=0; i<(rawsize/2); i++ )
2609     {
2610         sval = msi_string_lookup_id( st, rawdata[i] );
2611         MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2612     }
2613 }
2614
2615 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2616 {
2617     LPCWSTR str;
2618     UINT i, r, *data;
2619
2620     data = msi_alloc( tv->num_cols *sizeof (UINT) );
2621     for( i=0; i<tv->num_cols; i++ )
2622     {
2623         data[i] = 0;
2624
2625         if ( ~tv->columns[i].type & MSITYPE_KEY )
2626             continue;
2627
2628         /* turn the transform column value into a row value */
2629         if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2630              ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2631         {
2632             str = MSI_RecordGetString( rec, i+1 );
2633             if (str)
2634             {
2635                 r = msi_string2idW( tv->db->strings, str, &data[i] );
2636
2637                 /* if there's no matching string in the string table,
2638                    these keys can't match any record, so fail now. */
2639                 if (r != ERROR_SUCCESS)
2640                 {
2641                     msi_free( data );
2642                     return NULL;
2643                 }
2644             }
2645             else data[i] = 0;
2646         }
2647         else
2648         {
2649             data[i] = MSI_RecordGetInteger( rec, i+1 );
2650
2651             if (data[i] == MSI_NULL_INTEGER)
2652                 data[i] = 0;
2653             else if ((tv->columns[i].type&0xff) == 2)
2654                 data[i] += 0x8000;
2655             else
2656                 data[i] += 0x80000000;
2657         }
2658     }
2659     return data;
2660 }
2661
2662 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2663 {
2664     UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2665
2666     for( i=0; i<tv->num_cols; i++ )
2667     {
2668         if ( ~tv->columns[i].type & MSITYPE_KEY )
2669             continue;
2670
2671         /* turn the transform column value into a row value */
2672         r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2673         if ( r != ERROR_SUCCESS )
2674         {
2675             ERR("TABLE_fetch_int shouldn't fail here\n");
2676             break;
2677         }
2678
2679         /* if this key matches, move to the next column */
2680         if ( x != data[i] )
2681         {
2682             ret = ERROR_FUNCTION_FAILED;
2683             break;
2684         }
2685
2686         ret = ERROR_SUCCESS;
2687     }
2688
2689     return ret;
2690 }
2691
2692 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
2693 {
2694     UINT i, r = ERROR_FUNCTION_FAILED, *data;
2695
2696     data = msi_record_to_row( tv, rec );
2697     if( !data )
2698         return r;
2699     for( i = 0; i < tv->table->row_count; i++ )
2700     {
2701         r = msi_row_matches( tv, i, data );
2702         if( r == ERROR_SUCCESS )
2703         {
2704             *row = i;
2705             break;
2706         }
2707     }
2708     msi_free( data );
2709     return r;
2710 }
2711
2712 typedef struct
2713 {
2714     struct list entry;
2715     LPWSTR name;
2716 } TRANSFORMDATA;
2717
2718 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2719                                       string_table *st, TRANSFORMDATA *transform,
2720                                       UINT bytes_per_strref )
2721 {
2722     UINT rawsize = 0;
2723     BYTE *rawdata = NULL;
2724     MSITABLEVIEW *tv = NULL;
2725     UINT r, n, sz, i, mask;
2726     MSIRECORD *rec = NULL;
2727     UINT colcol = 0;
2728     WCHAR coltable[32];
2729     LPWSTR name;
2730
2731     if (!transform)
2732         return ERROR_SUCCESS;
2733
2734     name = transform->name;
2735
2736     coltable[0] = 0;
2737     TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2738
2739     /* read the transform data */
2740     read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2741     if ( !rawdata )
2742     {
2743         TRACE("table %s empty\n", debugstr_w(name) );
2744         return ERROR_INVALID_TABLE;
2745     }
2746
2747     /* create a table view */
2748     r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2749     if( r != ERROR_SUCCESS )
2750         goto err;
2751
2752     r = tv->view.ops->execute( &tv->view, NULL );
2753     if( r != ERROR_SUCCESS )
2754         goto err;
2755
2756     TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2757           debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2758
2759     /* interpret the data */
2760     r = ERROR_SUCCESS;
2761     for( n=0; n < rawsize;  )
2762     {
2763         mask = rawdata[n] | (rawdata[n+1] << 8);
2764
2765         if (mask&1)
2766         {
2767             /*
2768              * if the low bit is set, columns are continuous and
2769              * the number of columns is specified in the high byte
2770              */
2771             sz = 2;
2772             for( i=0; i<tv->num_cols; i++ )
2773             {
2774                 if( (tv->columns[i].type & MSITYPE_STRING) &&
2775                     ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2776                     sz += bytes_per_strref;
2777                 else
2778                     sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2779             }
2780         }
2781         else
2782         {
2783             /*
2784              * If the low bit is not set, mask is a bitmask.
2785              * Excepting for key fields, which are always present,
2786              *  each bit indicates that a field is present in the transform record.
2787              *
2788              * mask == 0 is a special case ... only the keys will be present
2789              * and it means that this row should be deleted.
2790              */
2791             sz = 2;
2792             for( i=0; i<tv->num_cols; i++ )
2793             {
2794                 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2795                 {
2796                     if( (tv->columns[i].type & MSITYPE_STRING) &&
2797                         ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2798                         sz += bytes_per_strref;
2799                     else
2800                         sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2801                 }
2802             }
2803         }
2804
2805         /* check we didn't run of the end of the table */
2806         if ( (n+sz) > rawsize )
2807         {
2808             ERR("borked.\n");
2809             dump_table( st, (USHORT *)rawdata, rawsize );
2810             break;
2811         }
2812
2813         rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2814         if (rec)
2815         {
2816             WCHAR table[32];
2817             DWORD sz = 32;
2818             UINT number = MSI_NULL_INTEGER;
2819             UINT row = 0;
2820
2821             if (!strcmpW( name, szColumns ))
2822             {
2823                 MSI_RecordGetStringW( rec, 1, table, &sz );
2824                 number = MSI_RecordGetInteger( rec, 2 );
2825
2826                 /*
2827                  * Native msi seems writes nul into the Number (2nd) column of
2828                  * the _Columns table, only when the columns are from a new table
2829                  */
2830                 if ( number == MSI_NULL_INTEGER )
2831                 {
2832                     /* reset the column number on a new table */
2833                     if (strcmpW( coltable, table ))
2834                     {
2835                         colcol = 0;
2836                         lstrcpyW( coltable, table );
2837                     }
2838
2839                     /* fix nul column numbers */
2840                     MSI_RecordSetInteger( rec, 2, ++colcol );
2841                 }
2842             }
2843
2844             if (TRACE_ON(msidb)) dump_record( rec );
2845
2846             r = msi_table_find_row( tv, rec, &row );
2847             if (r == ERROR_SUCCESS)
2848             {
2849                 if (!mask)
2850                 {
2851                     TRACE("deleting row [%d]:\n", row);
2852                     r = TABLE_delete_row( &tv->view, row );
2853                     if (r != ERROR_SUCCESS)
2854                         WARN("failed to delete row %u\n", r);
2855                 }
2856                 else if (mask & 1)
2857                 {
2858                     TRACE("modifying full row [%d]:\n", row);
2859                     r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2860                     if (r != ERROR_SUCCESS)
2861                         WARN("failed to modify row %u\n", r);
2862                 }
2863                 else
2864                 {
2865                     TRACE("modifying masked row [%d]:\n", row);
2866                     r = TABLE_set_row( &tv->view, row, rec, mask );
2867                     if (r != ERROR_SUCCESS)
2868                         WARN("failed to modify row %u\n", r);
2869                 }
2870             }
2871             else
2872             {
2873                 TRACE("inserting row\n");
2874                 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2875                 if (r != ERROR_SUCCESS)
2876                     WARN("failed to insert row %u\n", r);
2877             }
2878
2879             if (number != MSI_NULL_INTEGER && !strcmpW( name, szColumns ))
2880                 msi_update_table_columns( db, table );
2881
2882             msiobj_release( &rec->hdr );
2883         }
2884
2885         n += sz;
2886     }
2887
2888 err:
2889     /* no need to free the table, it's associated with the database */
2890     msi_free( rawdata );
2891     if( tv )
2892         tv->view.ops->delete( &tv->view );
2893
2894     return ERROR_SUCCESS;
2895 }
2896
2897 /*
2898  * msi_table_apply_transform
2899  *
2900  * Enumerate the table transforms in a transform storage and apply each one.
2901  */
2902 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2903 {
2904     struct list transforms;
2905     IEnumSTATSTG *stgenum = NULL;
2906     TRANSFORMDATA *transform;
2907     TRANSFORMDATA *tables = NULL, *columns = NULL;
2908     HRESULT r;
2909     STATSTG stat;
2910     string_table *strings;
2911     UINT ret = ERROR_FUNCTION_FAILED;
2912     UINT bytes_per_strref;
2913
2914     TRACE("%p %p\n", db, stg );
2915
2916     strings = msi_load_string_table( stg, &bytes_per_strref );
2917     if( !strings )
2918         goto end;
2919
2920     r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2921     if( FAILED( r ) )
2922         goto end;
2923
2924     list_init(&transforms);
2925
2926     while ( TRUE )
2927     {
2928         MSITABLEVIEW *tv = NULL;
2929         WCHAR name[0x40];
2930         ULONG count = 0;
2931
2932         r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2933         if ( FAILED( r ) || !count )
2934             break;
2935
2936         decode_streamname( stat.pwcsName, name );
2937         CoTaskMemFree( stat.pwcsName );
2938         if ( name[0] != 0x4840 )
2939             continue;
2940
2941         if ( !strcmpW( name+1, szStringPool ) ||
2942              !strcmpW( name+1, szStringData ) )
2943             continue;
2944
2945         transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2946         if ( !transform )
2947             break;
2948
2949         list_add_tail( &transforms, &transform->entry );
2950
2951         transform->name = strdupW( name + 1 );
2952
2953         if ( !strcmpW( transform->name, szTables ) )
2954             tables = transform;
2955         else if (!strcmpW( transform->name, szColumns ) )
2956             columns = transform;
2957
2958         TRACE("transform contains stream %s\n", debugstr_w(name));
2959
2960         /* load the table */
2961         r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2962         if( r != ERROR_SUCCESS )
2963             continue;
2964
2965         r = tv->view.ops->execute( &tv->view, NULL );
2966         if( r != ERROR_SUCCESS )
2967         {
2968             tv->view.ops->delete( &tv->view );
2969             continue;
2970         }
2971
2972         tv->view.ops->delete( &tv->view );
2973     }
2974
2975     /*
2976      * Apply _Tables and _Columns transforms first so that
2977      * the table metadata is correct, and empty tables exist.
2978      */
2979     ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2980     if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2981         goto end;
2982
2983     ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2984     if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2985         goto end;
2986
2987     ret = ERROR_SUCCESS;
2988
2989     while ( !list_empty( &transforms ) )
2990     {
2991         transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2992
2993         if ( strcmpW( transform->name, szColumns ) &&
2994              strcmpW( transform->name, szTables ) &&
2995              ret == ERROR_SUCCESS )
2996         {
2997             ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2998         }
2999
3000         list_remove( &transform->entry );
3001         msi_free( transform->name );
3002         msi_free( transform );
3003     }
3004
3005     if ( ret == ERROR_SUCCESS )
3006         append_storage_to_db( db, stg );
3007
3008 end:
3009     if ( stgenum )
3010         IEnumSTATSTG_Release( stgenum );
3011     if ( strings )
3012         msi_destroy_stringtable( strings );
3013
3014     return ret;
3015 }