msi/tests: Write-strings warnings fix.
[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
23 #define COBJMACROS
24 #define NONAMELESSUNION
25 #define NONAMELESSSTRUCT
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "wine/debug.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "msipriv.h"
36 #include "winnls.h"
37
38 #include "query.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
41
42 #define MSITABLE_HASH_TABLE_SIZE 37
43
44 typedef struct tagMSICOLUMNHASHENTRY
45 {
46     struct tagMSICOLUMNHASHENTRY *next;
47     UINT value;
48     UINT row;
49 } MSICOLUMNHASHENTRY;
50
51 typedef struct tagMSICOLUMNINFO
52 {
53     LPCWSTR tablename;
54     UINT   number;
55     LPCWSTR colname;
56     UINT   type;
57     UINT   offset;
58     MSICOLUMNHASHENTRY **hash_table;
59 } MSICOLUMNINFO;
60
61 struct tagMSITABLE
62 {
63     USHORT **data;
64     UINT row_count;
65     struct list entry;
66     WCHAR name[1];
67 };
68
69 typedef struct tagMSITRANSFORM {
70     struct list entry;
71     IStorage *stg;
72 } MSITRANSFORM;
73
74 #define MAX_STREAM_NAME 0x1f
75
76 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
77        MSICOLUMNINFO **pcols, UINT *pcount );
78 static UINT get_tablecolumns( MSIDATABASE *db, 
79        LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
80 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
81
82 static inline UINT bytes_per_column( const MSICOLUMNINFO *col )
83 {
84     if( col->type & MSITYPE_STRING )
85         return 2;
86     if( (col->type & 0xff) > 4 )
87         ERR("Invalid column size!\n");
88     return col->type & 0xff;
89 }
90
91 static int utf2mime(int x)
92 {
93     if( (x>='0') && (x<='9') )
94         return x-'0';
95     if( (x>='A') && (x<='Z') )
96         return x-'A'+10;
97     if( (x>='a') && (x<='z') )
98         return x-'a'+10+26;
99     if( x=='.' )
100         return 10+26+26;
101     if( x=='_' )
102         return 10+26+26+1;
103     return -1;
104 }
105
106 static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
107 {
108     DWORD count = MAX_STREAM_NAME;
109     DWORD ch, next;
110     LPWSTR out, p;
111
112     if( !bTable )
113         count = lstrlenW( in )+2;
114     out = msi_alloc( count*sizeof(WCHAR) );
115     p = out;
116
117     if( bTable )
118     {
119          *p++ = 0x4840;
120          count --;
121     }
122     while( count -- ) 
123     {
124         ch = *in++;
125         if( !ch )
126         {
127             *p = ch;
128             return out;
129         }
130         if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
131         {
132             ch = utf2mime(ch) + 0x4800;
133             next = *in;
134             if( next && (next<0x80) )
135             {
136                 next = utf2mime(next);
137                 if( next >= 0  )
138                 {
139                      next += 0x3ffffc0;
140                      ch += (next<<6);
141                      in++;
142                 }
143             }
144         }
145         *p++ = ch;
146     }
147     ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
148     msi_free( out );
149     return NULL;
150 }
151
152 static int mime2utf(int x)
153 {
154     if( x<10 )
155         return x + '0';
156     if( x<(10+26))
157         return x - 10 + 'A';
158     if( x<(10+26+26))
159         return x - 10 - 26 + 'a';
160     if( x == (10+26+26) )
161         return '.';
162     return '_';
163 }
164
165 static BOOL decode_streamname(LPWSTR in, LPWSTR out)
166 {
167     WCHAR ch;
168     DWORD count = 0;
169
170     while ( (ch = *in++) )
171     {
172         if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
173         {
174             if( ch >= 0x4800 )
175                 ch = mime2utf(ch-0x4800);
176             else
177             {
178                 ch -= 0x3800;
179                 *out++ = mime2utf(ch&0x3f);
180                 count++;
181                 ch = mime2utf((ch>>6)&0x3f);
182             }
183         }
184         *out++ = ch;
185         count++;
186     }
187     *out = 0;
188     return count;
189 }
190
191 void enum_stream_names( IStorage *stg )
192 {
193     IEnumSTATSTG *stgenum = NULL;
194     HRESULT r;
195     STATSTG stat;
196     ULONG n, count;
197     WCHAR name[0x40];
198
199     r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
200     if( FAILED( r ) )
201         return;
202
203     n = 0;
204     while( 1 )
205     {
206         count = 0;
207         r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
208         if( FAILED( r ) || !count )
209             break;
210         decode_streamname( stat.pwcsName, name );
211         TRACE("stream %2ld -> %s %s\n", n, 
212               debugstr_w(stat.pwcsName), debugstr_w(name) );
213         n++;
214     }
215
216     IEnumSTATSTG_Release( stgenum );
217 }
218
219 static UINT read_stream_data( IStorage *stg, LPCWSTR stname,
220                               USHORT **pdata, UINT *psz )
221 {
222     HRESULT r;
223     UINT ret = ERROR_FUNCTION_FAILED;
224     VOID *data;
225     ULONG sz, count;
226     IStream *stm = NULL;
227     STATSTG stat;
228     LPWSTR encname;
229
230     encname = encode_streamname(TRUE, stname);
231
232     TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
233
234     r = IStorage_OpenStream(stg, encname, NULL, 
235             STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
236     msi_free( encname );
237     if( FAILED( r ) )
238     {
239         WARN("open stream failed r = %08lx - empty table?\n",r);
240         return ret;
241     }
242
243     r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
244     if( FAILED( r ) )
245     {
246         WARN("open stream failed r = %08lx!\n",r);
247         goto end;
248     }
249
250     if( stat.cbSize.QuadPart >> 32 )
251     {
252         WARN("Too big!\n");
253         goto end;
254     }
255         
256     sz = stat.cbSize.QuadPart;
257     data = msi_alloc( sz );
258     if( !data )
259     {
260         WARN("couldn't allocate memory r=%08lx!\n",r);
261         ret = ERROR_NOT_ENOUGH_MEMORY;
262         goto end;
263     }
264         
265     r = IStream_Read(stm, data, sz, &count );
266     if( FAILED( r ) || ( count != sz ) )
267     {
268         msi_free( data );
269         WARN("read stream failed r = %08lx!\n",r);
270         goto end;
271     }
272
273     *pdata = data;
274     *psz = sz;
275     ret = ERROR_SUCCESS;
276
277 end:
278     IStream_Release( stm );
279
280     return ret;
281 }
282
283 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
284 {
285     LPWSTR encname;
286     HRESULT r;
287
288     encname = encode_streamname(FALSE, stname);
289
290     TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
291
292     r = IStorage_OpenStream(db->storage, encname, NULL, 
293             STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
294     if( FAILED( r ) )
295     {
296         MSITRANSFORM *transform;
297
298         LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
299         {
300             TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
301             r = IStorage_OpenStream( transform->stg, encname, NULL, 
302                     STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
303             if (SUCCEEDED(r))
304                 break;
305         }
306     }
307
308     msi_free( encname );
309
310     return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
311 }
312
313 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
314                               USHORT **pdata, UINT *psz )
315 {
316     HRESULT r;
317     UINT ret = ERROR_FUNCTION_FAILED;
318     VOID *data;
319     ULONG sz, count;
320     IStream *stm = NULL;
321     STATSTG stat;
322
323     r = db_get_raw_stream( db, stname, &stm );
324     if( r != ERROR_SUCCESS)
325         return ret;
326     r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
327     if( FAILED( r ) )
328     {
329         WARN("open stream failed r = %08lx!\n",r);
330         goto end;
331     }
332
333     if( stat.cbSize.QuadPart >> 32 )
334     {
335         WARN("Too big!\n");
336         goto end;
337     }
338         
339     sz = stat.cbSize.QuadPart;
340     data = msi_alloc( sz );
341     if( !data )
342     {
343         WARN("couldn't allocate memory r=%08lx!\n",r);
344         ret = ERROR_NOT_ENOUGH_MEMORY;
345         goto end;
346     }
347         
348     r = IStream_Read(stm, data, sz, &count );
349     if( FAILED( r ) || ( count != sz ) )
350     {
351         msi_free( data );
352         WARN("read stream failed r = %08lx!\n",r);
353         goto end;
354     }
355
356     *pdata = data;
357     *psz = sz;
358     ret = ERROR_SUCCESS;
359
360 end:
361     IStream_Release( stm );
362
363     return ret;
364 }
365
366 static UINT write_stream_data( IStorage *stg, LPCWSTR stname,
367                                LPVOID data, UINT sz )
368 {
369     HRESULT r;
370     UINT ret = ERROR_FUNCTION_FAILED;
371     ULONG count;
372     IStream *stm = NULL;
373     ULARGE_INTEGER size;
374     LARGE_INTEGER pos;
375     LPWSTR encname;
376
377     encname = encode_streamname(TRUE, stname );
378     r = IStorage_OpenStream( stg, encname, NULL, 
379             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
380     if( FAILED(r) )
381     {
382         r = IStorage_CreateStream( stg, encname,
383                 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
384     }
385     msi_free( encname );
386     if( FAILED( r ) )
387     {
388         WARN("open stream failed r = %08lx\n",r);
389         return ret;
390     }
391
392     size.QuadPart = sz;
393     r = IStream_SetSize( stm, size );
394     if( FAILED( r ) )
395     {
396         WARN("Failed to SetSize\n");
397         goto end;
398     }
399
400     pos.QuadPart = 0;
401     r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
402     if( FAILED( r ) )
403     {
404         WARN("Failed to Seek\n");
405         goto end;
406     }
407
408     r = IStream_Write(stm, data, sz, &count );
409     if( FAILED( r ) || ( count != sz ) )
410     {
411         WARN("Failed to Write\n");
412         goto end;
413     }
414
415     ret = ERROR_SUCCESS;
416
417 end:
418     IStream_Release( stm );
419
420     return ret;
421 }
422
423 static void free_table( MSITABLE *table )
424 {
425     int i;
426     for( i=0; i<table->row_count; i++ )
427         msi_free( table->data[i] );
428     msi_free( table->data );
429     msi_free( table );
430 }
431
432 static UINT msi_table_get_row_size( const MSICOLUMNINFO *cols, UINT count )
433 {
434     const MSICOLUMNINFO *last_col = &cols[count-1];
435     if (!count)
436         return 0;
437     return last_col->offset + bytes_per_column( last_col );
438 }
439
440 /* add this table to the list of cached tables in the database */
441 static MSITABLE *read_table_from_storage( IStorage *stg, LPCWSTR name,
442                                     const MSICOLUMNINFO *cols, UINT num_cols )
443 {
444     MSITABLE *t;
445     USHORT *rawdata = NULL;
446     UINT rawsize = 0, i, j, row_size = 0;
447
448     TRACE("%s\n",debugstr_w(name));
449
450     /* nonexistent tables should be interpreted as empty tables */
451     t = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
452     if( !t )
453         return t;
454
455     row_size = msi_table_get_row_size( cols, num_cols );
456
457     t->row_count = 0;
458     t->data = NULL;
459     lstrcpyW( t->name, name );
460
461     /* if we can't read the table, just assume that it's empty */
462     read_stream_data( stg, name, &rawdata, &rawsize );
463     if( !rawdata )
464         return t;
465
466     TRACE("Read %d bytes\n", rawsize );
467
468     if( rawsize % row_size )
469     {
470         WARN("Table size is invalid %d/%d\n", rawsize, row_size );
471         goto err;
472     }
473
474     t->row_count = rawsize / row_size;
475     t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
476     if( !t->data )
477         goto err;
478
479     /* transpose all the data */
480     TRACE("Transposing data from %d rows\n", t->row_count );
481     for( i=0; i<t->row_count; i++ )
482     {
483         t->data[i] = msi_alloc( row_size );
484         if( !t->data[i] )
485             goto err;
486
487         for( j=0; j<num_cols; j++ )
488         {
489             UINT ofs = cols[j].offset/2;
490             UINT n = bytes_per_column( &cols[j] );
491
492             switch( n )
493             {
494             case 2:
495                 t->data[i][ofs] = rawdata[ofs*t->row_count + i ];
496                 break;
497             case 4:
498                 t->data[i][ofs] = rawdata[ofs*t->row_count + i*2 ];
499                 t->data[i][ofs+1] = rawdata[ofs*t->row_count + i*2 + 1];
500                 break;
501             default:
502                 ERR("oops - unknown column width %d\n", n);
503                 goto err;
504             }
505         }
506     }
507
508     msi_free( rawdata );
509     return t;
510 err:
511     msi_free( rawdata );
512     free_table( t );
513     return NULL;
514 }
515
516 void free_cached_tables( MSIDATABASE *db )
517 {
518     while( !list_empty( &db->tables ) )
519     {
520         MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
521
522         list_remove( &t->entry );
523         free_table( t );
524     }
525 }
526
527 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
528 {
529     MSITABLE *t;
530
531     LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
532         if( !lstrcmpW( name, t->name ) )
533             return t;
534
535     return NULL;
536 }
537
538 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
539 {
540     UINT r, column_count = 0;
541     MSICOLUMNINFO *columns;
542
543     /* get the number of columns in this table */
544     column_count = 0;
545     r = get_tablecolumns( db, name, NULL, &column_count );
546     if( r != ERROR_SUCCESS )
547         return r;
548
549     /* if there's no columns, there's no table */
550     if( column_count == 0 )
551         return ERROR_INVALID_PARAMETER;
552
553     TRACE("Table %s found\n", debugstr_w(name) );
554
555     columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
556     if( !columns )
557         return ERROR_FUNCTION_FAILED;
558
559     r = get_tablecolumns( db, name, columns, &column_count );
560     if( r != ERROR_SUCCESS )
561     {
562         msi_free( columns );
563         return ERROR_FUNCTION_FAILED;
564     }
565
566     *pcols = columns;
567     *pcount = column_count;
568
569     return r;
570 }
571
572 static MSITABLE *get_table( MSIDATABASE *db, LPCWSTR name,
573                             const MSICOLUMNINFO *cols, UINT num_cols )
574 {
575     MSITABLE *table;
576
577     /* first, see if the table is cached */
578     table = find_cached_table( db, name );
579     if( table )
580         return table;
581
582     table = read_table_from_storage( db->storage, name, cols, num_cols );
583     if( table )
584         list_add_head( &db->tables, &table->entry );
585
586     return table;
587 }
588
589 static UINT save_table( MSIDATABASE *db, MSITABLE *t )
590 {
591     USHORT *rawdata = NULL, *p;
592     UINT rawsize, r, i, j, row_size, num_cols = 0;
593     MSICOLUMNINFO *cols = NULL;
594
595     TRACE("Saving %s\n", debugstr_w( t->name ) );
596
597     r = table_get_column_info( db, t->name, &cols, &num_cols );
598     if( r != ERROR_SUCCESS )
599         return r;
600     
601     row_size = msi_table_get_row_size( cols, num_cols );
602
603     rawsize = t->row_count * row_size;
604     rawdata = msi_alloc_zero( rawsize );
605     if( !rawdata )
606     {
607         r = ERROR_NOT_ENOUGH_MEMORY;
608         goto err;
609     }
610
611     p = rawdata;
612     for( i=0; i<num_cols; i++ )
613     {
614         for( j=0; j<t->row_count; j++ )
615         {
616             UINT offset = cols[i].offset;
617
618             *p++ = t->data[j][offset/2];
619             if( 4 == bytes_per_column( &cols[i] ) )
620                 *p++ = t->data[j][offset/2+1];
621         }
622     }
623
624     TRACE("writing %d bytes\n", rawsize);
625     r = write_stream_data( db->storage, t->name, rawdata, rawsize );
626
627 err:
628     msi_free_colinfo( cols, num_cols );
629     msi_free( cols );
630     msi_free( rawdata );
631
632     return r;
633 }
634
635 HRESULT init_string_table( IStorage *stg )
636 {
637     HRESULT r;
638     static const WCHAR szStringData[] = {
639         '_','S','t','r','i','n','g','D','a','t','a',0 };
640     static const WCHAR szStringPool[] = {
641         '_','S','t','r','i','n','g','P','o','o','l',0 };
642     USHORT zero[2] = { 0, 0 };
643     ULONG count = 0;
644     IStream *stm = NULL;
645     LPWSTR encname;
646
647     encname = encode_streamname(TRUE, szStringPool );
648
649     /* create the StringPool stream... add the zero string to it*/
650     r = IStorage_CreateStream( stg, encname,
651             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
652     msi_free( encname );
653     if( r ) 
654     {
655         TRACE("Failed\n");
656         return r;
657     }
658
659     r = IStream_Write(stm, zero, sizeof zero, &count );
660     IStream_Release( stm );
661
662     if( FAILED( r ) || ( count != sizeof zero ) )
663     {
664         TRACE("Failed\n");
665         return E_FAIL;
666     }
667
668     /* create the StringData stream... make it zero length */
669     encname = encode_streamname(TRUE, szStringData );
670     r = IStorage_CreateStream( stg, encname,
671             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
672     msi_free( encname );
673     if( r ) 
674     {
675         TRACE("Failed\n");
676         return E_FAIL;
677     }
678     IStream_Release( stm );
679
680     return r;
681 }
682
683 string_table *load_string_table( IStorage *stg )
684 {
685     string_table *st = NULL;
686     CHAR *data = NULL;
687     USHORT *pool = NULL;
688     UINT r, datasize = 0, poolsize = 0, codepage;
689     DWORD i, count, offset, len, n;
690     static const WCHAR szStringData[] = {
691         '_','S','t','r','i','n','g','D','a','t','a',0 };
692     static const WCHAR szStringPool[] = {
693         '_','S','t','r','i','n','g','P','o','o','l',0 };
694
695     r = read_stream_data( stg, szStringPool, &pool, &poolsize );
696     if( r != ERROR_SUCCESS)
697         goto end;
698     r = read_stream_data( stg, szStringData, (USHORT**)&data, &datasize );
699     if( r != ERROR_SUCCESS)
700         goto end;
701
702     count = poolsize/4;
703     if( poolsize > 4 )
704         codepage = pool[0] | ( pool[1] << 16 );
705     else
706         codepage = CP_ACP;
707     st = msi_init_stringtable( count, codepage );
708
709     offset = 0;
710     n = 1;
711     for( i=1; i<count; i++ )
712     {
713         len = pool[i*2];
714
715         /*
716          * If a string is over 64k, the previous string entry is made null
717          * and its the high word of the length is inserted in the null string's
718          * reference count field.
719          */
720         if( pool[i*2-2] == 0 && pool[i*2-1] )
721             len += pool[i*2+1] * 0x10000;
722
723         if( (offset + len) > datasize )
724         {
725             ERR("string table corrupt?\n");
726             break;
727         }
728
729         /* don't add the high word of a string's length as a string */
730         if ( len || !pool[i*2+1] )
731         {
732             r = msi_addstring( st, n, data+offset, len, pool[i*2+1] );
733             if( r != n )
734                 ERR("Failed to add string %ld\n", n );
735             n++;
736         }
737
738         offset += len;
739     }
740
741     if ( datasize != offset )
742         ERR("string table load failed! (%08x != %08lx)\n", datasize, offset );
743
744     TRACE("Loaded %ld strings\n", count);
745
746 end:
747     msi_free( pool );
748     msi_free( data );
749
750     return st;
751 }
752
753 static UINT save_string_table( MSIDATABASE *db )
754 {
755     UINT i, count, datasize, poolsize, sz, used, r, codepage;
756     UINT ret = ERROR_FUNCTION_FAILED;
757     static const WCHAR szStringData[] = {
758         '_','S','t','r','i','n','g','D','a','t','a',0 };
759     static const WCHAR szStringPool[] = {
760         '_','S','t','r','i','n','g','P','o','o','l',0 };
761     CHAR *data = NULL;
762     USHORT *pool = NULL;
763
764     TRACE("\n");
765
766     /* construct the new table in memory first */
767     datasize = msi_string_totalsize( db->strings, &count );
768     poolsize = (count + 1)*2*sizeof(USHORT);
769
770     pool = msi_alloc( poolsize );
771     if( ! pool )
772     {
773         WARN("Failed to alloc pool %d bytes\n", poolsize );
774         goto err;
775     }
776     data = msi_alloc( datasize );
777     if( ! data )
778     {
779         WARN("Failed to alloc data %d bytes\n", poolsize );
780         goto err;
781     }
782
783     used = 0;
784     codepage = msi_string_get_codepage( db->strings );
785     pool[0]=codepage&0xffff;
786     pool[1]=(codepage>>16);
787     for( i=1; i<count; i++ )
788     {
789         sz = datasize - used;
790         r = msi_id2stringA( db->strings, i, data+used, &sz );
791         if( r != ERROR_SUCCESS )
792         {
793             ERR("failed to fetch string\n");
794             sz = 0;
795         }
796         if( sz && (sz < (datasize - used ) ) )
797             sz--;
798         TRACE("adding %u bytes %s\n", sz, debugstr_a(data+used) );
799         pool[ i*2 ] = sz;
800         pool[ i*2 + 1 ] = msi_id_refcount( db->strings, i );
801         used += sz;
802         if( used > datasize  )
803         {
804             ERR("oops overran %d >= %d\n", used, datasize);
805             goto err;
806         }
807     }
808
809     if( used != datasize )
810     {
811         ERR("oops used %d != datasize %d\n", used, datasize);
812         goto err;
813     }
814
815     /* write the streams */
816     r = write_stream_data( db->storage, szStringData, data, datasize );
817     TRACE("Wrote StringData r=%08x\n", r);
818     if( r )
819         goto err;
820     r = write_stream_data( db->storage, szStringPool, pool, poolsize );
821     TRACE("Wrote StringPool r=%08x\n", r);
822     if( r )
823         goto err;
824
825     ret = ERROR_SUCCESS;
826
827 err:
828     msi_free( data );
829     msi_free( pool );
830
831     return ret;
832 }
833
834 /* information for default tables */
835 static const WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
836 static const WCHAR szTable[]  = { 'T','a','b','l','e',0 };
837 static const WCHAR szName[]    = { 'N','a','m','e',0 };
838 static const WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
839 static const WCHAR szColumn[]  = { 'C','o','l','u','m','n',0 };
840 static const WCHAR szNumber[]  = { 'N','u','m','b','e','r',0 };
841 static const WCHAR szType[]    = { 'T','y','p','e',0 };
842
843 static const MSICOLUMNINFO _Columns_cols[4] = {
844     { szColumns, 1, szTable,  MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
845     { szColumns, 2, szNumber, MSITYPE_VALID | 2,                   2 },
846     { szColumns, 3, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 4 },
847     { szColumns, 4, szType,   MSITYPE_VALID | 2,                   6 },
848 };
849 static const MSICOLUMNINFO _Tables_cols[1] = {
850     { szTables,  1, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
851 };
852
853 static UINT get_defaulttablecolumns( LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz)
854 {
855     const MSICOLUMNINFO *p;
856     DWORD i, n;
857
858     TRACE("%s\n", debugstr_w(name));
859
860     if (!lstrcmpW( name, szTables ))
861     {
862         p = _Tables_cols;
863         n = 1;
864     }
865     else if (!lstrcmpW( name, szColumns ))
866     {
867         p = _Columns_cols;
868         n = 4;
869     }
870     else
871         return ERROR_FUNCTION_FAILED;
872
873     /* duplicate the string data so we can free it in msi_free_colinfo */
874     for (i=0; i<n; i++)
875     {
876         if (colinfo && (i < *sz) )
877         {
878             memcpy( &colinfo[i], &p[i], sizeof(MSICOLUMNINFO) );
879             colinfo[i].tablename = strdupW( p[i].tablename );
880             colinfo[i].colname = strdupW( p[i].colname );
881         }
882         if( colinfo && (i >= *sz) )
883             break;
884     }
885     *sz = n;
886     return ERROR_SUCCESS;
887 }
888
889 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
890 {
891     UINT i;
892
893     for( i=0; i<count; i++ )
894     {
895         msi_free( (LPWSTR) colinfo[i].tablename );
896         msi_free( (LPWSTR) colinfo[i].colname );
897         msi_free( colinfo[i].hash_table );
898     }
899 }
900
901 LPWSTR MSI_makestring( MSIDATABASE *db, UINT stringid)
902 {
903     UINT sz=0, r;
904     LPWSTR str;
905
906     r = msi_id2stringW( db->strings, stringid, NULL, &sz );
907     if( r != ERROR_SUCCESS )
908         return NULL;
909     str = msi_alloc( sz*sizeof (WCHAR) );
910     if( !str )
911         return str;
912     r = msi_id2stringW( db->strings, stringid, str, &sz );
913     if( r == ERROR_SUCCESS )
914         return str;
915     msi_free( str );
916     return NULL;
917 }
918
919 static UINT get_tablecolumns( MSIDATABASE *db, 
920        LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
921 {
922     UINT r, i, n=0, table_id, count, maxcount = *sz;
923     MSITABLE *table = NULL;
924
925     /* first check if there is a default table with that name */
926     r = get_defaulttablecolumns( szTableName, colinfo, sz );
927     if( ( r == ERROR_SUCCESS ) && *sz )
928         return r;
929
930     table = get_table( db, szColumns, _Columns_cols, 4 );
931     if( !table )
932     {
933         ERR("couldn't load _Columns table\n");
934         return ERROR_FUNCTION_FAILED;
935     }
936
937     /* convert table and column names to IDs from the string table */
938     r = msi_string2idW( db->strings, szTableName, &table_id );
939     if( r != ERROR_SUCCESS )
940     {
941         WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
942         return r;
943     }
944
945     TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
946
947     count = table->row_count;
948     for( i=0; i<count; i++ )
949     {
950         if( table->data[ i ][ 0 ] != table_id )
951             continue;
952         if( colinfo )
953         {
954             UINT id = table->data[ i ] [ 2 ];
955             colinfo[n].tablename = MSI_makestring( db, table_id );
956             colinfo[n].number = table->data[ i ][ 1 ] - (1<<15);
957             colinfo[n].colname = MSI_makestring( db, id );
958             colinfo[n].type = table->data[ i ] [ 3 ] ^ 0x8000;
959             colinfo[n].hash_table = NULL;
960             /* this assumes that columns are in order in the table */
961             if( n )
962                 colinfo[n].offset = colinfo[n-1].offset
963                                   + bytes_per_column( &colinfo[n-1] );
964             else
965                 colinfo[n].offset = 0;
966             TRACE("table %s column %d is [%s] (%d) with type %08x "
967                   "offset %d at row %d\n", debugstr_w(szTableName),
968                    colinfo[n].number, debugstr_w(colinfo[n].colname),
969                    id, colinfo[n].type, colinfo[n].offset, i);
970             if( n != (colinfo[n].number-1) )
971             {
972                 ERR("oops. data in the _Columns table isn't in the right "
973                     "order for table %s\n", debugstr_w(szTableName));
974                 return ERROR_FUNCTION_FAILED;
975             }
976         }
977         n++;
978         if( colinfo && ( n >= maxcount ) )
979             break;
980     }
981     *sz = n;
982
983     return ERROR_SUCCESS;
984 }
985
986 /* try to find the table name in the _Tables table */
987 BOOL TABLE_Exists( MSIDATABASE *db, LPWSTR name )
988 {
989     UINT r, table_id = 0, i, count;
990     MSITABLE *table = NULL;
991
992     if( !lstrcmpW( name, szTables ) )
993         return TRUE;
994     if( !lstrcmpW( name, szColumns ) )
995         return TRUE;
996
997     r = msi_string2idW( db->strings, name, &table_id );
998     if( r != ERROR_SUCCESS )
999     {
1000         TRACE("Couldn't find id for %s\n", debugstr_w(name));
1001         return FALSE;
1002     }
1003
1004     table = get_table( db, szTables, _Tables_cols, 1 );
1005     if( !table )
1006     {
1007         TRACE("table %s not available\n", debugstr_w(szTables));
1008         return FALSE;
1009     }
1010
1011     /* count = table->size/2; */
1012     count = table->row_count;
1013     for( i=0; i<count; i++ )
1014         if( table->data[ i ][ 0 ] == table_id )
1015             break;
1016
1017     if (i!=count)
1018         return TRUE;
1019
1020     TRACE("Searched %d tables, but %d was not found\n", count, table_id );
1021
1022     return FALSE;
1023 }
1024
1025 /* below is the query interface to a table */
1026
1027 typedef struct tagMSITABLEVIEW
1028 {
1029     MSIVIEW        view;
1030     MSIDATABASE   *db;
1031     MSITABLE      *table;
1032     MSICOLUMNINFO *columns;
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, num_rows, 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     num_rows = tv->table->row_count;
1051     if( row >= num_rows )
1052         return ERROR_NO_MORE_ITEMS;
1053
1054     if( tv->columns[col-1].offset >= tv->row_size )
1055     {
1056         ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1057         ERR("%p %p\n", tv, tv->columns );
1058         return ERROR_FUNCTION_FAILED;
1059     }
1060
1061     offset = row + (tv->columns[col-1].offset/2) * num_rows;
1062     n = bytes_per_column( &tv->columns[col-1] );
1063     switch( n )
1064     {
1065     case 4:
1066         offset = tv->columns[col-1].offset/2;
1067         *val = tv->table->data[row][offset] + 
1068                (tv->table->data[row][offset + 1] << 16);
1069         break;
1070     case 2:
1071         offset = tv->columns[col-1].offset/2;
1072         *val = tv->table->data[row][offset];
1073         break;
1074     default:
1075         ERR("oops! what is %d bytes per column?\n", n );
1076         return ERROR_FUNCTION_FAILED;
1077     }
1078
1079     /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1080
1081     return ERROR_SUCCESS;
1082 }
1083
1084 /*
1085  * We need a special case for streams, as we need to reference column with
1086  * the name of the stream in the same table, and the table name
1087  * which may not be available at higher levels of the query
1088  */
1089 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1090 {
1091     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1092     UINT ival = 0, refcol = 0, r;
1093     LPWSTR sval;
1094     LPWSTR full_name;
1095     DWORD len;
1096     static const WCHAR szDot[] = { '.', 0 };
1097
1098     if( !view->ops->fetch_int )
1099         return ERROR_INVALID_PARAMETER;
1100
1101     /*
1102      * The column marked with the type stream data seems to have a single number
1103      * which references the column containing the name of the stream data
1104      *
1105      * Fetch the column to reference first.
1106      */
1107     r = view->ops->fetch_int( view, row, col, &ival );
1108     if( r != ERROR_SUCCESS )
1109         return r;
1110
1111     /* now get the column with the name of the stream */
1112     r = view->ops->fetch_int( view, row, ival, &refcol );
1113     if( r != ERROR_SUCCESS )
1114         return r;
1115
1116     /* lookup the string value from the string table */
1117     sval = MSI_makestring( tv->db, refcol );
1118     if( !sval )
1119         return ERROR_INVALID_PARAMETER;
1120
1121     len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1122     full_name = msi_alloc( len*sizeof(WCHAR) );
1123     lstrcpyW( full_name, tv->name );
1124     lstrcatW( full_name, szDot );
1125     lstrcatW( full_name, sval );
1126
1127     r = db_get_raw_stream( tv->db, full_name, stm );
1128     if( r )
1129         ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1130     msi_free( full_name );
1131     msi_free( sval );
1132
1133     return r;
1134 }
1135
1136 static UINT TABLE_set_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT val )
1137 {
1138     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1139     UINT offset, n;
1140
1141     if( !tv->table )
1142         return ERROR_INVALID_PARAMETER;
1143
1144     if( (col==0) || (col>tv->num_cols) )
1145         return ERROR_INVALID_PARAMETER;
1146
1147     if( tv->columns[col-1].offset >= tv->row_size )
1148     {
1149         ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1150         ERR("%p %p\n", tv, tv->columns );
1151         return ERROR_FUNCTION_FAILED;
1152     }
1153
1154     n = bytes_per_column( &tv->columns[col-1] );
1155     switch( n )
1156     {
1157     case 4:
1158         offset = tv->columns[col-1].offset/2;
1159         tv->table->data[row][offset]     = val & 0xffff;
1160         tv->table->data[row][offset + 1] = (val>>16)&0xffff;
1161         break;
1162     case 2:
1163         offset = tv->columns[col-1].offset/2;
1164         tv->table->data[row][offset] = val;
1165         break;
1166     default:
1167         ERR("oops! what is %d bytes per column?\n", n );
1168         return ERROR_FUNCTION_FAILED;
1169     }
1170     return ERROR_SUCCESS;
1171 }
1172
1173 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num )
1174 {
1175     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1176     USHORT **p, *row;
1177     UINT sz;
1178
1179     TRACE("%p\n", view);
1180
1181     if( !tv->table )
1182         return ERROR_INVALID_PARAMETER;
1183
1184     row = msi_alloc_zero( tv->row_size );
1185     if( !row )
1186         return ERROR_NOT_ENOUGH_MEMORY;
1187
1188     sz = (tv->table->row_count + 1) * sizeof (UINT*);
1189     if( tv->table->data )
1190         p = msi_realloc( tv->table->data, sz );
1191     else
1192         p = msi_alloc( sz );
1193     if( !p )
1194     {
1195         msi_free( row );
1196         return ERROR_NOT_ENOUGH_MEMORY;
1197     }
1198
1199     tv->table->data = p;
1200     tv->table->data[tv->table->row_count] = row;
1201     *num = tv->table->row_count;
1202     tv->table->row_count++;
1203
1204     return ERROR_SUCCESS;
1205 }
1206
1207 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1208 {
1209     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1210
1211     TRACE("%p %p\n", tv, record);
1212
1213     TRACE("There are %d columns\n", tv->num_cols );
1214     tv->table = get_table( tv->db, tv->name, tv->columns, tv->num_cols );
1215     if( !tv->table )
1216         return ERROR_FUNCTION_FAILED;
1217
1218     return ERROR_SUCCESS;
1219 }
1220
1221 static UINT TABLE_close( struct tagMSIVIEW *view )
1222 {
1223     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1224
1225     TRACE("%p\n", view );
1226
1227     if( !tv->table )
1228         return ERROR_FUNCTION_FAILED;
1229
1230     tv->table = NULL;
1231     
1232     return ERROR_SUCCESS;
1233 }
1234
1235 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1236 {
1237     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1238
1239     TRACE("%p %p %p\n", view, rows, cols );
1240
1241     if( cols )
1242         *cols = tv->num_cols;
1243     if( rows )
1244     {
1245         if( !tv->table )
1246             return ERROR_INVALID_PARAMETER;
1247         *rows = tv->table->row_count;
1248     }
1249
1250     return ERROR_SUCCESS;
1251 }
1252
1253 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1254                 UINT n, LPWSTR *name, UINT *type )
1255 {
1256     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1257
1258     TRACE("%p %d %p %p\n", tv, n, name, type );
1259
1260     if( ( n == 0 ) || ( n > tv->num_cols ) )
1261         return ERROR_INVALID_PARAMETER;
1262
1263     if( name )
1264     {
1265         *name = strdupW( tv->columns[n-1].colname );
1266         if( !*name )
1267             return ERROR_FUNCTION_FAILED;
1268     }
1269     if( type )
1270         *type = tv->columns[n-1].type;
1271
1272     return ERROR_SUCCESS;
1273 }
1274
1275 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1276
1277 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1278 {
1279     UINT r, row;
1280
1281     r = msi_table_find_row( tv, rec, &row );
1282     if (r != ERROR_SUCCESS)
1283         return ERROR_SUCCESS;
1284     return ERROR_INVALID_DATA;
1285 }
1286
1287 static UINT msi_table_modify_row( MSITABLEVIEW *tv, MSIRECORD *rec,
1288                                   UINT row, UINT mask )
1289 {
1290     UINT i, val, r = ERROR_SUCCESS;
1291
1292     TRACE("%p %p %u %08x\n", tv, rec, row, mask );
1293
1294     for( i = 0; i < tv->num_cols; i++ )
1295     {
1296         /* set keys or values specified in the mask */
1297         if( (~tv->columns[i].type & MSITYPE_KEY) && (~mask & (1<<i)) )
1298             continue;
1299
1300         if( (tv->columns[i].type & MSITYPE_STRING) &&
1301             ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1302         {
1303             const WCHAR *str = MSI_RecordGetString( rec, i+1 );
1304             val = msi_addstringW( tv->db->strings, 0, str, -1, 1 );
1305         }
1306         else
1307         {
1308             val = MSI_RecordGetInteger( rec, i+1 );
1309             if ( 2 == bytes_per_column( &tv->columns[i] ) )
1310                 val ^= 0x8000;
1311             else
1312                 val ^= 0x80000000;
1313         }
1314         r = TABLE_set_int( &tv->view, row, i+1, val );
1315         if( r )
1316             break;
1317     }
1318
1319     return r;
1320 }
1321
1322 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1323 {
1324     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1325     UINT r, row = -1;
1326
1327     TRACE("%p %p\n", tv, rec );
1328
1329     r = table_create_new_row( view, &row );
1330     TRACE("insert_row returned %08x\n", r);
1331     if( r != ERROR_SUCCESS )
1332         return r;
1333
1334     return msi_table_modify_row( tv, rec, row, ~0 );
1335 }
1336
1337 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1338                 MSIRECORD *rec)
1339 {
1340     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1341     UINT r;
1342
1343     TRACE("%p %d %p\n", view, eModifyMode, rec );
1344
1345     if (!tv->table)
1346     {
1347         r = TABLE_execute( view, NULL );
1348         if( r )
1349             return r;
1350     }
1351
1352     switch (eModifyMode)
1353     {
1354     case MSIMODIFY_VALIDATE_NEW:
1355         r = table_validate_new( tv, rec );
1356         break;
1357
1358     case MSIMODIFY_INSERT_TEMPORARY:
1359         r = table_validate_new( tv, rec );
1360         if (r != ERROR_SUCCESS)
1361             break;
1362         r = TABLE_insert_row( view, rec );
1363         break;
1364
1365     case MSIMODIFY_REFRESH:
1366     case MSIMODIFY_INSERT:
1367     case MSIMODIFY_UPDATE:
1368     case MSIMODIFY_ASSIGN:
1369     case MSIMODIFY_REPLACE:
1370     case MSIMODIFY_MERGE:
1371     case MSIMODIFY_DELETE:
1372     case MSIMODIFY_VALIDATE:
1373     case MSIMODIFY_VALIDATE_FIELD:
1374     case MSIMODIFY_VALIDATE_DELETE:
1375         FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1376         r = ERROR_CALL_NOT_IMPLEMENTED;
1377         break;
1378
1379     default:
1380         r = ERROR_INVALID_DATA;
1381     }
1382
1383     return r;
1384 }
1385
1386 static UINT TABLE_delete( struct tagMSIVIEW *view )
1387 {
1388     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1389
1390     TRACE("%p\n", view );
1391
1392     tv->table = NULL;
1393
1394     if( tv->columns )
1395     {
1396         msi_free_colinfo( tv->columns, tv->num_cols );
1397         msi_free( tv->columns );
1398     }
1399     tv->columns = NULL;
1400
1401     msi_free( tv );
1402
1403     return ERROR_SUCCESS;
1404 }
1405
1406 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1407     UINT val, UINT *row, MSIITERHANDLE *handle )
1408 {
1409     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1410     const MSICOLUMNHASHENTRY *entry;
1411
1412     TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1413
1414     if( !tv->table )
1415         return ERROR_INVALID_PARAMETER;
1416
1417     if( (col==0) || (col > tv->num_cols) )
1418         return ERROR_INVALID_PARAMETER;
1419
1420     if( !tv->columns[col-1].hash_table )
1421     {
1422         UINT i;
1423         UINT num_rows = tv->table->row_count;
1424         MSICOLUMNHASHENTRY **hash_table;
1425         MSICOLUMNHASHENTRY *new_entry;
1426
1427         if( tv->columns[col-1].offset >= tv->row_size )
1428         {
1429             ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1430             ERR("%p %p\n", tv, tv->columns );
1431             return ERROR_FUNCTION_FAILED;
1432         }
1433
1434         /* allocate contiguous memory for the table and its entries so we
1435          * don't have to do an expensive cleanup */
1436         hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1437             num_rows * sizeof(MSICOLUMNHASHENTRY));
1438         if (!hash_table)
1439             return ERROR_OUTOFMEMORY;
1440
1441         memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1442         tv->columns[col-1].hash_table = hash_table;
1443
1444         new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1445
1446         for (i = 0; i < num_rows; i++, new_entry++)
1447         {
1448             UINT row_value, n;
1449             UINT offset = i + (tv->columns[col-1].offset/2) * num_rows;
1450             n = bytes_per_column( &tv->columns[col-1] );
1451             switch( n )
1452             {
1453             case 4:
1454                 offset = tv->columns[col-1].offset/2;
1455                 row_value = tv->table->data[i][offset] + 
1456                     (tv->table->data[i][offset + 1] << 16);
1457                 break;
1458             case 2:
1459                 offset = tv->columns[col-1].offset/2;
1460                 row_value = tv->table->data[i][offset];
1461                 break;
1462             default:
1463                 ERR("oops! what is %d bytes per column?\n", n );
1464                 continue;
1465             }
1466
1467             new_entry->next = NULL;
1468             new_entry->value = row_value;
1469             new_entry->row = i;
1470             if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1471             {
1472                 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1473                 while (prev_entry->next)
1474                     prev_entry = prev_entry->next;
1475                 prev_entry->next = new_entry;
1476             }
1477             else
1478                 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1479         }
1480     }
1481
1482     if( !*handle )
1483         entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1484     else
1485         entry = ((const MSICOLUMNHASHENTRY *)*handle)->next;
1486
1487     while (entry && entry->value != val)
1488         entry = entry->next;
1489
1490     *handle = (MSIITERHANDLE)entry;
1491     if (!entry)
1492         return ERROR_NO_MORE_ITEMS;
1493
1494     *row = entry->row;
1495     return ERROR_SUCCESS;
1496 }
1497
1498
1499 static const MSIVIEWOPS table_ops =
1500 {
1501     TABLE_fetch_int,
1502     TABLE_fetch_stream,
1503     TABLE_set_int,
1504     TABLE_insert_row,
1505     TABLE_execute,
1506     TABLE_close,
1507     TABLE_get_dimensions,
1508     TABLE_get_column_info,
1509     TABLE_modify,
1510     TABLE_delete,
1511     TABLE_find_matching_rows
1512 };
1513
1514 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
1515 {
1516     MSITABLEVIEW *tv ;
1517     UINT r, sz, column_count;
1518     MSICOLUMNINFO *columns;
1519
1520     TRACE("%p %s %p\n", db, debugstr_w(name), view );
1521
1522     /* get the number of columns in this table */
1523     column_count = 0;
1524     r = get_tablecolumns( db, name, NULL, &column_count );
1525     if( r != ERROR_SUCCESS )
1526         return r;
1527
1528     /* if there's no columns, there's no table */
1529     if( column_count == 0 )
1530         return ERROR_INVALID_PARAMETER;
1531
1532     TRACE("Table found\n");
1533
1534     sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
1535     tv = msi_alloc_zero( sz );
1536     if( !tv )
1537         return ERROR_FUNCTION_FAILED;
1538     
1539     columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO));
1540     if( !columns )
1541     {
1542         msi_free( tv );
1543         return ERROR_FUNCTION_FAILED;
1544     }
1545
1546     r = get_tablecolumns( db, name, columns, &column_count );
1547     if( r != ERROR_SUCCESS )
1548     {
1549         msi_free( columns );
1550         msi_free( tv );
1551         return ERROR_FUNCTION_FAILED;
1552     }
1553
1554     TRACE("Table has %d columns\n", column_count);
1555
1556     /* fill the structure */
1557     tv->view.ops = &table_ops;
1558     tv->db = db;
1559     tv->columns = columns;
1560     tv->num_cols = column_count;
1561     tv->table = NULL;
1562     tv->row_size = msi_table_get_row_size( columns, column_count );
1563
1564     TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
1565
1566     *view = (MSIVIEW*) tv;
1567     lstrcpyW( tv->name, name );
1568
1569     return ERROR_SUCCESS;
1570 }
1571
1572 UINT MSI_CommitTables( MSIDATABASE *db )
1573 {
1574     UINT r;
1575     MSITABLE *table = NULL;
1576
1577     TRACE("%p\n",db);
1578
1579     r = save_string_table( db );
1580     if( r != ERROR_SUCCESS )
1581     {
1582         WARN("failed to save string table r=%08x\n",r);
1583         return r;
1584     }
1585
1586     LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
1587     {
1588         r = save_table( db, table );
1589         if( r != ERROR_SUCCESS )
1590         {
1591             WARN("failed to save table %s (r=%08x)\n",
1592                   debugstr_w(table->name), r);
1593             return r;
1594         }
1595     }
1596
1597     /* force everything to reload next time */
1598     free_cached_tables( db );
1599
1600     return ERROR_SUCCESS;
1601 }
1602
1603 static MSIRECORD *msi_get_transform_record( MSITABLEVIEW *tv, string_table *st, USHORT *rawdata )
1604 {
1605     UINT i, val, ofs = 0;
1606     USHORT mask = *rawdata++;
1607     MSICOLUMNINFO *columns = tv->columns;
1608     MSIRECORD *rec;
1609
1610     rec = MSI_CreateRecord( tv->num_cols );
1611     if( !rec )
1612         return rec;
1613
1614     TRACE("row -> ");
1615     for( i=0; i<tv->num_cols; i++ )
1616     {
1617         UINT n = bytes_per_column( &columns[i] );
1618
1619         if ( (mask&1) && (i>=(mask>>8)) )
1620             break;
1621         /* all keys must be present */
1622         if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
1623             continue;
1624
1625         switch( n )
1626         {
1627         case 2:
1628             val = rawdata[ofs];
1629             if( (columns[i].type & MSITYPE_STRING) &&
1630                 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1631             {
1632                 LPCWSTR sval = msi_string_lookup_id( st, val );
1633                 MSI_RecordSetStringW( rec, i+1, sval );
1634                 TRACE("[%s]", debugstr_w(sval));
1635             }
1636             else
1637             {
1638                 val ^= 0x8000;
1639                 MSI_RecordSetInteger( rec, i+1, val );
1640                 TRACE("[0x%04x]", val );
1641             }
1642             break;
1643         case 4:
1644             val = rawdata[ofs] + (rawdata[ofs + 1]<<16);
1645             /* val ^= 0x80000000; */
1646             MSI_RecordSetInteger( rec, i+1, val );
1647             TRACE("[0x%08x]", val );
1648             break;
1649         default:
1650             ERR("oops - unknown column width %d\n", n);
1651             break;
1652         }
1653         ofs += n/2;
1654     }
1655     TRACE("\n");
1656     return rec;
1657 }
1658
1659 static void dump_record( MSIRECORD *rec )
1660 {
1661     UINT i, n;
1662
1663     n = MSI_RecordGetFieldCount( rec );
1664     for( i=1; i<=n; i++ )
1665     {
1666         LPCWSTR sval = MSI_RecordGetString( rec, i );
1667
1668         if( MSI_RecordIsNull( rec, i ) )
1669             TRACE("row -> []\n");
1670         else if( (sval = MSI_RecordGetString( rec, i )) )
1671             TRACE("row -> [%s]\n", debugstr_w(sval));
1672         else
1673             TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
1674     }
1675 }
1676
1677 static void dump_table( string_table *st, USHORT *rawdata, UINT rawsize )
1678 {
1679     LPCWSTR sval;
1680     UINT i;
1681
1682     for( i=0; i<(rawsize/2); i++ )
1683     {
1684         sval = msi_string_lookup_id( st, rawdata[i] );
1685         MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
1686     }
1687 }
1688
1689 static UINT* msi_record_to_row( MSITABLEVIEW *tv, MSIRECORD *rec )
1690 {
1691     LPCWSTR str;
1692     UINT i, r, *data;
1693
1694     data = msi_alloc( tv->num_cols *sizeof (UINT) );
1695     for( i=0; i<tv->num_cols; i++ )
1696     {
1697         data[i] = 0;
1698
1699         if ( ~tv->columns[i].type & MSITYPE_KEY )
1700             continue;
1701
1702         /* turn the transform column value into a row value */
1703         if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
1704              ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1705         {
1706             str = MSI_RecordGetString( rec, i+1 );
1707             r = msi_string2idW( tv->db->strings, str, &data[i] );
1708
1709             /* if there's no matching string in the string table,
1710                these keys can't match any record, so fail now. */
1711             if( ERROR_SUCCESS != r )
1712             {
1713                 msi_free( data );
1714                 return NULL;
1715             }
1716         }
1717         else
1718             data[i] = MSI_RecordGetInteger( rec, i+1 );
1719     }
1720     return data;
1721 }
1722
1723 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, UINT *data )
1724 {
1725     UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
1726
1727     for( i=0; i<tv->num_cols; i++ )
1728     {
1729         if ( ~tv->columns[i].type & MSITYPE_KEY )
1730             continue;
1731
1732         /* turn the transform column value into a row value */
1733         r = TABLE_fetch_int( &tv->view, row, i+1, &x );
1734         if ( r != ERROR_SUCCESS )
1735         {
1736             ERR("TABLE_fetch_int shouldn't fail here\n");
1737             break;
1738         }
1739
1740         /* if this key matches, move to the next column */
1741         if ( x != data[i] )
1742         {
1743             ret = ERROR_FUNCTION_FAILED;
1744             break;
1745         }
1746
1747         ret = ERROR_SUCCESS;
1748     }
1749
1750     return ret;
1751 }
1752
1753 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
1754 {
1755     UINT i, r = ERROR_FUNCTION_FAILED, *data;
1756
1757     data = msi_record_to_row( tv, rec );
1758     if( !data )
1759         return r;
1760     for( i=0; i<tv->table->row_count; i++ )
1761     {
1762         r = msi_row_matches( tv, i, data );
1763         if( r == ERROR_SUCCESS )
1764         {
1765             *row = i;
1766             break;
1767         }
1768     }
1769     msi_free( data );
1770     return r;
1771 }
1772
1773 static UINT msi_delete_row( MSITABLEVIEW *tv, UINT row )
1774 {
1775     UINT i;
1776     for( i=1; i<=tv->num_cols; i++ )
1777         tv->view.ops->set_int( &tv->view, row, i, 0 );
1778     return ERROR_SUCCESS;
1779 }
1780
1781 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
1782                                       string_table *st, LPCWSTR name )
1783 {
1784     UINT rawsize = 0;
1785     USHORT *rawdata = NULL;
1786     MSITABLEVIEW *tv = NULL;
1787     UINT r, n, sz, i, mask;
1788     MSIRECORD *rec = NULL;
1789
1790     TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
1791
1792     /* create a table view */
1793     r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
1794     if( r != ERROR_SUCCESS )
1795         goto err;
1796
1797     r = tv->view.ops->execute( &tv->view, NULL );
1798     if( r != ERROR_SUCCESS )
1799         goto err;
1800
1801     /* read the transform data */
1802     r = ERROR_FUNCTION_FAILED;
1803     read_stream_data( stg, name, &rawdata, &rawsize );
1804     if( !rawdata || (rawsize < 2) )
1805     {
1806         ERR("odd sized transform for table %s\n", debugstr_w(name));
1807         goto err;
1808     }
1809
1810     TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
1811           debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
1812
1813     /* interpret the data */
1814     r = ERROR_SUCCESS;
1815     for( n=0; n < (rawsize/2);  )
1816     {
1817         mask = rawdata[n];
1818
1819         if (mask&1)
1820         {
1821             /*
1822              * if the low bit is set, columns are continuous and
1823              * the number of columns is specified in the high byte
1824              */
1825             sz = 2 + tv->row_size;
1826         }
1827         else
1828         {
1829             /*
1830              * If the low bit is not set, rowdata[n] is a bitmask.
1831              * Excepting for key fields, which are always present,
1832              *  each bit indicates that a field is present in the transform record.
1833              *
1834              * rawdata[n] == 0 is a special case ... only the keys will be present
1835              * and it means that this row should be deleted.
1836              */
1837             sz = 2;
1838             for( i=0; i<tv->num_cols; i++ )
1839             {
1840                 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
1841                     sz += bytes_per_column( &tv->columns[i] );
1842             }
1843         }
1844
1845         /* check we didn't run of the end of the table */
1846         if ( (n+sz) > rawsize )
1847         {
1848             ERR("borked.\n");
1849             dump_table( st, rawdata, rawsize );
1850             break;
1851         }
1852
1853         rec = msi_get_transform_record( tv, st, &rawdata[n] );
1854         if (rec)
1855         {
1856             UINT row = 0;
1857
1858             r = msi_table_find_row( tv, rec, &row );
1859
1860             if( rawdata[n] & 1)
1861             {
1862                 TRACE("insert [%d]: ", row);
1863                 TABLE_insert_row( &tv->view, rec );
1864             }
1865             else if( mask & 0xff )
1866             {
1867                 TRACE("modify [%d]: ", row);
1868                 msi_table_modify_row( tv, rec, row, mask );
1869             }
1870             else
1871             {
1872                 TRACE("delete [%d]: ", row);
1873                 msi_delete_row( tv, row );
1874             }
1875             if( TRACE_ON(msidb) ) dump_record( rec );
1876             msiobj_release( &rec->hdr );
1877         }
1878
1879         n += sz/2;
1880         
1881     }
1882
1883 err:
1884     /* no need to free the table, it's associated with the database */
1885     msi_free( rawdata );
1886     if( tv )
1887         tv->view.ops->delete( &tv->view );
1888
1889     return ERROR_SUCCESS;
1890 }
1891
1892 /*
1893  * msi_table_apply_transform
1894  *
1895  * Enumerate the table transforms in a transform storage and apply each one.
1896  */
1897 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
1898 {
1899     IEnumSTATSTG *stgenum = NULL;
1900     HRESULT r;
1901     STATSTG stat;
1902     ULONG n, count;
1903     WCHAR name[0x40];
1904     string_table *strings;
1905     UINT ret = ERROR_FUNCTION_FAILED;
1906
1907     TRACE("%p %p\n", db, stg );
1908
1909     strings = load_string_table( stg );
1910     if( !strings )
1911         goto end;
1912
1913     r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
1914     if( FAILED( r ) )
1915         goto end;
1916
1917     n = 0;
1918     ret = ERROR_SUCCESS;
1919
1920     while( r == ERROR_SUCCESS )
1921     {
1922         count = 0;
1923         r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
1924         if( FAILED( r ) || !count )
1925             break;
1926         decode_streamname( stat.pwcsName, name );
1927         if( ( name[0] == 0x4840 ) && ( name[1] != '_' ) )
1928             ret = msi_table_load_transform( db, stg, strings, name+1 );
1929         else
1930             TRACE("transform contains stream %s\n", debugstr_w(name));
1931         n++;
1932     }
1933
1934     if ( ret == ERROR_SUCCESS )
1935     {
1936         MSITRANSFORM *t;
1937
1938         t = msi_alloc( sizeof *t );
1939         t->stg = stg;
1940         IStorage_AddRef( stg );
1941         list_add_tail( &db->transforms, &t->entry );
1942     }
1943
1944 end:
1945     if ( stgenum )
1946         IEnumSTATSTG_Release( stgenum );
1947     if ( strings )
1948         msi_destroy_stringtable( strings );
1949
1950     return ret;
1951 }
1952
1953 void msi_free_transforms( MSIDATABASE *db )
1954 {
1955     while( !list_empty( &db->transforms ) )
1956     {
1957         MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
1958                                       MSITRANSFORM, entry );
1959         list_remove( &t->entry );
1960         IStorage_Release( t->stg );
1961         msi_free( t );
1962     }
1963 }