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