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