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