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