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