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