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