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