msi: assert.h is not a local header (spotted by winapi_check).
[wine/multimedia.git] / dlls / msi / table.c
blob014c453938dcebf35a795ea706f296bb4da34c8d
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002-2005 Mike McCormack for CodeWeavers
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.
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.
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
21 #include <stdarg.h>
22 #include <assert.h>
24 #define COBJMACROS
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
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"
39 #include "wine/debug.h"
40 #include "wine/unicode.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
44 #define MSITABLE_HASH_TABLE_SIZE 37
46 typedef struct tagMSICOLUMNHASHENTRY
48 struct tagMSICOLUMNHASHENTRY *next;
49 UINT value;
50 UINT row;
51 } MSICOLUMNHASHENTRY;
53 typedef struct tagMSICOLUMNINFO
55 LPCWSTR tablename;
56 UINT number;
57 LPCWSTR colname;
58 UINT type;
59 UINT offset;
60 MSICOLUMNHASHENTRY **hash_table;
61 } MSICOLUMNINFO;
63 struct tagMSITABLE
65 USHORT **data;
66 UINT row_count;
67 struct list entry;
68 WCHAR name[1];
71 typedef struct tagMSITRANSFORM {
72 struct list entry;
73 IStorage *stg;
74 } MSITRANSFORM;
76 static const WCHAR szStringData[] = {
77 '_','S','t','r','i','n','g','D','a','t','a',0 };
78 static const WCHAR szStringPool[] = {
79 '_','S','t','r','i','n','g','P','o','o','l',0 };
81 #define MAX_STREAM_NAME 0x1f
83 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
84 MSICOLUMNINFO **pcols, UINT *pcount );
85 static UINT get_tablecolumns( MSIDATABASE *db,
86 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
87 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
89 static inline UINT bytes_per_column( const MSICOLUMNINFO *col )
91 if( col->type & MSITYPE_STRING )
92 return 2;
93 if( (col->type & 0xff) > 4 )
94 ERR("Invalid column size!\n");
95 return col->type & 0xff;
98 static int utf2mime(int x)
100 if( (x>='0') && (x<='9') )
101 return x-'0';
102 if( (x>='A') && (x<='Z') )
103 return x-'A'+10;
104 if( (x>='a') && (x<='z') )
105 return x-'a'+10+26;
106 if( x=='.' )
107 return 10+26+26;
108 if( x=='_' )
109 return 10+26+26+1;
110 return -1;
113 static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
115 DWORD count = MAX_STREAM_NAME;
116 DWORD ch, next;
117 LPWSTR out, p;
119 if( !bTable )
120 count = lstrlenW( in )+2;
121 out = msi_alloc( count*sizeof(WCHAR) );
122 p = out;
124 if( bTable )
126 *p++ = 0x4840;
127 count --;
129 while( count -- )
131 ch = *in++;
132 if( !ch )
134 *p = ch;
135 return out;
137 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
139 ch = utf2mime(ch) + 0x4800;
140 next = *in;
141 if( next && (next<0x80) )
143 next = utf2mime(next);
144 if( next >= 0 )
146 next += 0x3ffffc0;
147 ch += (next<<6);
148 in++;
152 *p++ = ch;
154 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
155 msi_free( out );
156 return NULL;
159 static int mime2utf(int x)
161 if( x<10 )
162 return x + '0';
163 if( x<(10+26))
164 return x - 10 + 'A';
165 if( x<(10+26+26))
166 return x - 10 - 26 + 'a';
167 if( x == (10+26+26) )
168 return '.';
169 return '_';
172 static BOOL decode_streamname(LPWSTR in, LPWSTR out)
174 WCHAR ch;
175 DWORD count = 0;
177 while ( (ch = *in++) )
179 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
181 if( ch >= 0x4800 )
182 ch = mime2utf(ch-0x4800);
183 else
185 ch -= 0x3800;
186 *out++ = mime2utf(ch&0x3f);
187 count++;
188 ch = mime2utf((ch>>6)&0x3f);
191 *out++ = ch;
192 count++;
194 *out = 0;
195 return count;
198 void enum_stream_names( IStorage *stg )
200 IEnumSTATSTG *stgenum = NULL;
201 HRESULT r;
202 STATSTG stat;
203 ULONG n, count;
204 WCHAR name[0x40];
206 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
207 if( FAILED( r ) )
208 return;
210 n = 0;
211 while( 1 )
213 count = 0;
214 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
215 if( FAILED( r ) || !count )
216 break;
217 decode_streamname( stat.pwcsName, name );
218 TRACE("stream %2d -> %s %s\n", n,
219 debugstr_w(stat.pwcsName), debugstr_w(name) );
220 n++;
223 IEnumSTATSTG_Release( stgenum );
226 static UINT read_stream_data( IStorage *stg, LPCWSTR stname,
227 USHORT **pdata, UINT *psz )
229 HRESULT r;
230 UINT ret = ERROR_FUNCTION_FAILED;
231 VOID *data;
232 ULONG sz, count;
233 IStream *stm = NULL;
234 STATSTG stat;
235 LPWSTR encname;
237 encname = encode_streamname(TRUE, stname);
239 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
241 r = IStorage_OpenStream(stg, encname, NULL,
242 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
243 msi_free( encname );
244 if( FAILED( r ) )
246 WARN("open stream failed r = %08x - empty table?\n", r);
247 return ret;
250 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
251 if( FAILED( r ) )
253 WARN("open stream failed r = %08x!\n", r);
254 goto end;
257 if( stat.cbSize.QuadPart >> 32 )
259 WARN("Too big!\n");
260 goto end;
263 sz = stat.cbSize.QuadPart;
264 data = msi_alloc( sz );
265 if( !data )
267 WARN("couldn't allocate memory r=%08x!\n", r);
268 ret = ERROR_NOT_ENOUGH_MEMORY;
269 goto end;
272 r = IStream_Read(stm, data, sz, &count );
273 if( FAILED( r ) || ( count != sz ) )
275 msi_free( data );
276 WARN("read stream failed r = %08x!\n", r);
277 goto end;
280 *pdata = data;
281 *psz = sz;
282 ret = ERROR_SUCCESS;
284 end:
285 IStream_Release( stm );
287 return ret;
290 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
292 LPWSTR encname;
293 HRESULT r;
295 encname = encode_streamname(FALSE, stname);
297 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
299 r = IStorage_OpenStream(db->storage, encname, NULL,
300 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
301 if( FAILED( r ) )
303 MSITRANSFORM *transform;
305 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
307 TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
308 r = IStorage_OpenStream( transform->stg, encname, NULL,
309 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
310 if (SUCCEEDED(r))
311 break;
315 msi_free( encname );
317 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
320 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
321 USHORT **pdata, UINT *psz )
323 HRESULT r;
324 UINT ret = ERROR_FUNCTION_FAILED;
325 VOID *data;
326 ULONG sz, count;
327 IStream *stm = NULL;
328 STATSTG stat;
330 r = db_get_raw_stream( db, stname, &stm );
331 if( r != ERROR_SUCCESS)
332 return ret;
333 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
334 if( FAILED( r ) )
336 WARN("open stream failed r = %08x!\n", r);
337 goto end;
340 if( stat.cbSize.QuadPart >> 32 )
342 WARN("Too big!\n");
343 goto end;
346 sz = stat.cbSize.QuadPart;
347 data = msi_alloc( sz );
348 if( !data )
350 WARN("couldn't allocate memory r=%08x!\n", r);
351 ret = ERROR_NOT_ENOUGH_MEMORY;
352 goto end;
355 r = IStream_Read(stm, data, sz, &count );
356 if( FAILED( r ) || ( count != sz ) )
358 msi_free( data );
359 WARN("read stream failed r = %08x!\n", r);
360 goto end;
363 *pdata = data;
364 *psz = sz;
365 ret = ERROR_SUCCESS;
367 end:
368 IStream_Release( stm );
370 return ret;
373 static UINT write_stream_data( IStorage *stg, LPCWSTR stname,
374 LPVOID data, UINT sz )
376 HRESULT r;
377 UINT ret = ERROR_FUNCTION_FAILED;
378 ULONG count;
379 IStream *stm = NULL;
380 ULARGE_INTEGER size;
381 LARGE_INTEGER pos;
382 LPWSTR encname;
384 encname = encode_streamname(TRUE, stname );
385 r = IStorage_OpenStream( stg, encname, NULL,
386 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
387 if( FAILED(r) )
389 r = IStorage_CreateStream( stg, encname,
390 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
392 msi_free( encname );
393 if( FAILED( r ) )
395 WARN("open stream failed r = %08x\n", r);
396 return ret;
399 size.QuadPart = sz;
400 r = IStream_SetSize( stm, size );
401 if( FAILED( r ) )
403 WARN("Failed to SetSize\n");
404 goto end;
407 pos.QuadPart = 0;
408 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
409 if( FAILED( r ) )
411 WARN("Failed to Seek\n");
412 goto end;
415 r = IStream_Write(stm, data, sz, &count );
416 if( FAILED( r ) || ( count != sz ) )
418 WARN("Failed to Write\n");
419 goto end;
422 ret = ERROR_SUCCESS;
424 end:
425 IStream_Release( stm );
427 return ret;
430 static void free_table( MSITABLE *table )
432 int i;
433 for( i=0; i<table->row_count; i++ )
434 msi_free( table->data[i] );
435 msi_free( table->data );
436 msi_free( table );
439 static UINT msi_table_get_row_size( const MSICOLUMNINFO *cols, UINT count )
441 const MSICOLUMNINFO *last_col = &cols[count-1];
442 if (!count)
443 return 0;
444 return last_col->offset + bytes_per_column( last_col );
447 /* add this table to the list of cached tables in the database */
448 static MSITABLE *read_table_from_storage( IStorage *stg, LPCWSTR name,
449 const MSICOLUMNINFO *cols, UINT num_cols )
451 MSITABLE *t;
452 USHORT *rawdata = NULL;
453 UINT rawsize = 0, i, j, row_size = 0;
455 TRACE("%s\n",debugstr_w(name));
457 /* nonexistent tables should be interpreted as empty tables */
458 t = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
459 if( !t )
460 return t;
462 row_size = msi_table_get_row_size( cols, num_cols );
464 t->row_count = 0;
465 t->data = NULL;
466 lstrcpyW( t->name, name );
468 /* if we can't read the table, just assume that it's empty */
469 read_stream_data( stg, name, &rawdata, &rawsize );
470 if( !rawdata )
471 return t;
473 TRACE("Read %d bytes\n", rawsize );
475 if( rawsize % row_size )
477 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
478 goto err;
481 t->row_count = rawsize / row_size;
482 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
483 if( !t->data )
484 goto err;
486 /* transpose all the data */
487 TRACE("Transposing data from %d rows\n", t->row_count );
488 for( i=0; i<t->row_count; i++ )
490 t->data[i] = msi_alloc( row_size );
491 if( !t->data[i] )
492 goto err;
494 for( j=0; j<num_cols; j++ )
496 UINT ofs = cols[j].offset/2;
497 UINT n = bytes_per_column( &cols[j] );
499 switch( n )
501 case 2:
502 t->data[i][ofs] = rawdata[ofs*t->row_count + i ];
503 break;
504 case 4:
505 t->data[i][ofs] = rawdata[ofs*t->row_count + i*2 ];
506 t->data[i][ofs+1] = rawdata[ofs*t->row_count + i*2 + 1];
507 break;
508 default:
509 ERR("oops - unknown column width %d\n", n);
510 goto err;
515 msi_free( rawdata );
516 return t;
517 err:
518 msi_free( rawdata );
519 free_table( t );
520 return NULL;
523 void free_cached_tables( MSIDATABASE *db )
525 while( !list_empty( &db->tables ) )
527 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
529 list_remove( &t->entry );
530 free_table( t );
534 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
536 MSITABLE *t;
538 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
539 if( !lstrcmpW( name, t->name ) )
540 return t;
542 return NULL;
545 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
547 UINT r, column_count = 0;
548 MSICOLUMNINFO *columns;
550 /* get the number of columns in this table */
551 column_count = 0;
552 r = get_tablecolumns( db, name, NULL, &column_count );
553 if( r != ERROR_SUCCESS )
554 return r;
556 /* if there's no columns, there's no table */
557 if( column_count == 0 )
558 return ERROR_INVALID_PARAMETER;
560 TRACE("Table %s found\n", debugstr_w(name) );
562 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
563 if( !columns )
564 return ERROR_FUNCTION_FAILED;
566 r = get_tablecolumns( db, name, columns, &column_count );
567 if( r != ERROR_SUCCESS )
569 msi_free( columns );
570 return ERROR_FUNCTION_FAILED;
573 *pcols = columns;
574 *pcount = column_count;
576 return r;
579 static MSITABLE *get_table( MSIDATABASE *db, LPCWSTR name,
580 const MSICOLUMNINFO *cols, UINT num_cols )
582 MSITABLE *table;
584 /* first, see if the table is cached */
585 table = find_cached_table( db, name );
586 if( table )
587 return table;
589 table = read_table_from_storage( db->storage, name, cols, num_cols );
590 if( table )
591 list_add_head( &db->tables, &table->entry );
593 return table;
596 static UINT save_table( MSIDATABASE *db, MSITABLE *t )
598 USHORT *rawdata = NULL, *p;
599 UINT rawsize, r, i, j, row_size, num_cols = 0;
600 MSICOLUMNINFO *cols = NULL;
602 TRACE("Saving %s\n", debugstr_w( t->name ) );
604 r = table_get_column_info( db, t->name, &cols, &num_cols );
605 if( r != ERROR_SUCCESS )
606 return r;
608 row_size = msi_table_get_row_size( cols, num_cols );
610 rawsize = t->row_count * row_size;
611 rawdata = msi_alloc_zero( rawsize );
612 if( !rawdata )
614 r = ERROR_NOT_ENOUGH_MEMORY;
615 goto err;
618 p = rawdata;
619 for( i=0; i<num_cols; i++ )
621 for( j=0; j<t->row_count; j++ )
623 UINT offset = cols[i].offset;
625 *p++ = t->data[j][offset/2];
626 if( 4 == bytes_per_column( &cols[i] ) )
627 *p++ = t->data[j][offset/2+1];
631 TRACE("writing %d bytes\n", rawsize);
632 r = write_stream_data( db->storage, t->name, rawdata, rawsize );
634 err:
635 msi_free_colinfo( cols, num_cols );
636 msi_free( cols );
637 msi_free( rawdata );
639 return r;
642 HRESULT init_string_table( IStorage *stg )
644 HRESULT r;
645 USHORT zero[2] = { 0, 0 };
646 ULONG count = 0;
647 IStream *stm = NULL;
648 LPWSTR encname;
650 encname = encode_streamname(TRUE, szStringPool );
652 /* create the StringPool stream... add the zero string to it*/
653 r = IStorage_CreateStream( stg, encname,
654 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
655 msi_free( encname );
656 if( r )
658 TRACE("Failed\n");
659 return r;
662 r = IStream_Write(stm, zero, sizeof zero, &count );
663 IStream_Release( stm );
665 if( FAILED( r ) || ( count != sizeof zero ) )
667 TRACE("Failed\n");
668 return E_FAIL;
671 /* create the StringData stream... make it zero length */
672 encname = encode_streamname(TRUE, szStringData );
673 r = IStorage_CreateStream( stg, encname,
674 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
675 msi_free( encname );
676 if( r )
678 TRACE("Failed\n");
679 return E_FAIL;
681 IStream_Release( stm );
683 return r;
686 string_table *load_string_table( IStorage *stg )
688 string_table *st = NULL;
689 CHAR *data = NULL;
690 USHORT *pool = NULL;
691 UINT r, datasize = 0, poolsize = 0, codepage;
692 DWORD i, count, offset, len, n, refs;
694 r = read_stream_data( stg, szStringPool, &pool, &poolsize );
695 if( r != ERROR_SUCCESS)
696 goto end;
697 r = read_stream_data( stg, szStringData, (USHORT**)&data, &datasize );
698 if( r != ERROR_SUCCESS)
699 goto end;
701 count = poolsize/4;
702 if( poolsize > 4 )
703 codepage = pool[0] | ( pool[1] << 16 );
704 else
705 codepage = CP_ACP;
706 st = msi_init_stringtable( count, codepage );
708 offset = 0;
709 n = 1;
710 i = 1;
711 while( i<count )
713 /* the string reference count is always the second word */
714 refs = pool[i*2+1];
716 /* empty entries have two zeros, still have a string id */
717 if (pool[i*2] == 0 && refs == 0)
719 i++;
720 n++;
721 continue;
725 * If a string is over 64k, the previous string entry is made null
726 * and its the high word of the length is inserted in the null string's
727 * reference count field.
729 if( pool[i*2] == 0)
731 len = (pool[i*2+3] << 16) + pool[i*2+2];
732 i += 2;
734 else
736 len = pool[i*2];
737 i += 1;
740 if ( (offset + len) > datasize )
742 ERR("string table corrupt?\n");
743 break;
746 r = msi_addstring( st, n, data+offset, len, refs );
747 if( r != n )
748 ERR("Failed to add string %d\n", n );
749 n++;
750 offset += len;
753 if ( datasize != offset )
754 ERR("string table load failed! (%08x != %08x), please report\n", datasize, offset );
756 TRACE("Loaded %d strings\n", count);
758 end:
759 msi_free( pool );
760 msi_free( data );
762 return st;
765 static UINT save_string_table( MSIDATABASE *db )
767 UINT i, count, datasize = 0, poolsize = 0, sz, used, r, codepage, n;
768 UINT ret = ERROR_FUNCTION_FAILED;
769 CHAR *data = NULL;
770 USHORT *pool = NULL;
772 TRACE("\n");
774 /* construct the new table in memory first */
775 count = msi_string_totalsize( db->strings, &datasize, &poolsize );
777 TRACE("%u %u %u\n", count, datasize, poolsize );
779 pool = msi_alloc( poolsize );
780 if( ! pool )
782 WARN("Failed to alloc pool %d bytes\n", poolsize );
783 goto err;
785 data = msi_alloc( datasize );
786 if( ! data )
788 WARN("Failed to alloc data %d bytes\n", poolsize );
789 goto err;
792 used = 0;
793 codepage = msi_string_get_codepage( db->strings );
794 pool[0]=codepage&0xffff;
795 pool[1]=(codepage>>16);
796 n = 1;
797 for( i=1; i<count; i++ )
799 sz = datasize - used;
800 r = msi_id2stringA( db->strings, i, data+used, &sz );
801 if( r != ERROR_SUCCESS )
803 ERR("failed to fetch string\n");
804 sz = 0;
806 if( sz && (sz < (datasize - used ) ) )
807 sz--;
809 if (sz)
810 pool[ n*2 + 1 ] = msi_id_refcount( db->strings, i );
811 else
812 pool[ n*2 + 1 ] = 0;
813 if (sz < 0x10000)
815 pool[ n*2 ] = sz;
816 n++;
818 else
820 pool[ n*2 ] = 0;
821 pool[ n*2 + 2 ] = sz&0xffff;
822 pool[ n*2 + 3 ] = (sz>>16);
823 n += 2;
825 used += sz;
826 if( used > datasize )
828 ERR("oops overran %d >= %d\n", used, datasize);
829 goto err;
833 if( used != datasize )
835 ERR("oops used %d != datasize %d\n", used, datasize);
836 goto err;
839 /* write the streams */
840 r = write_stream_data( db->storage, szStringData, data, datasize );
841 TRACE("Wrote StringData r=%08x\n", r);
842 if( r )
843 goto err;
844 r = write_stream_data( db->storage, szStringPool, pool, poolsize );
845 TRACE("Wrote StringPool r=%08x\n", r);
846 if( r )
847 goto err;
849 ret = ERROR_SUCCESS;
851 err:
852 msi_free( data );
853 msi_free( pool );
855 return ret;
858 /* information for default tables */
859 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
860 static const WCHAR szTable[] = { 'T','a','b','l','e',0 };
861 static const WCHAR szName[] = { 'N','a','m','e',0 };
862 static const WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
863 static const WCHAR szColumn[] = { 'C','o','l','u','m','n',0 };
864 static const WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
865 static const WCHAR szType[] = { 'T','y','p','e',0 };
867 static const MSICOLUMNINFO _Columns_cols[4] = {
868 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
869 { szColumns, 2, szNumber, MSITYPE_VALID | 2, 2 },
870 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4 },
871 { szColumns, 4, szType, MSITYPE_VALID | 2, 6 },
873 static const MSICOLUMNINFO _Tables_cols[1] = {
874 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
877 static UINT get_defaulttablecolumns( LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz)
879 const MSICOLUMNINFO *p;
880 DWORD i, n;
882 TRACE("%s\n", debugstr_w(name));
884 if (!lstrcmpW( name, szTables ))
886 p = _Tables_cols;
887 n = 1;
889 else if (!lstrcmpW( name, szColumns ))
891 p = _Columns_cols;
892 n = 4;
894 else
895 return ERROR_FUNCTION_FAILED;
897 /* duplicate the string data so we can free it in msi_free_colinfo */
898 for (i=0; i<n; i++)
900 if (colinfo && (i < *sz) )
902 memcpy( &colinfo[i], &p[i], sizeof(MSICOLUMNINFO) );
903 colinfo[i].tablename = strdupW( p[i].tablename );
904 colinfo[i].colname = strdupW( p[i].colname );
906 if( colinfo && (i >= *sz) )
907 break;
909 *sz = n;
910 return ERROR_SUCCESS;
913 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
915 UINT i;
917 for( i=0; i<count; i++ )
919 msi_free( (LPWSTR) colinfo[i].tablename );
920 msi_free( (LPWSTR) colinfo[i].colname );
921 msi_free( colinfo[i].hash_table );
925 static LPWSTR msi_makestring( MSIDATABASE *db, UINT stringid)
927 return strdupW(msi_string_lookup_id( db->strings, stringid ));
930 static UINT get_tablecolumns( MSIDATABASE *db,
931 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
933 UINT r, i, n=0, table_id, count, maxcount = *sz;
934 MSITABLE *table = NULL;
936 TRACE("%s\n", debugstr_w(szTableName));
938 /* first check if there is a default table with that name */
939 r = get_defaulttablecolumns( szTableName, colinfo, sz );
940 if( ( r == ERROR_SUCCESS ) && *sz )
941 return r;
943 table = get_table( db, szColumns, _Columns_cols, 4 );
944 if( !table )
946 ERR("couldn't load _Columns table\n");
947 return ERROR_FUNCTION_FAILED;
950 /* convert table and column names to IDs from the string table */
951 r = msi_string2idW( db->strings, szTableName, &table_id );
952 if( r != ERROR_SUCCESS )
954 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
955 return r;
958 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
960 /* if maxcount is non-zero, assume it's exactly right for this table */
961 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
962 count = table->row_count;
963 for( i=0; i<count; i++ )
965 if( table->data[ i ][ 0 ] != table_id )
966 continue;
967 if( colinfo )
969 UINT id = table->data[ i ] [ 2 ];
970 UINT col = table->data[ i ][ 1 ] - (1<<15);
972 /* check the column number is in range */
973 if (col<1 || col>maxcount)
975 ERR("column %d out of range\n", col);
976 continue;
979 /* check if this column was already set */
980 if (colinfo[ col - 1 ].number)
982 ERR("duplicate column %d\n", col);
983 continue;
986 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
987 colinfo[ col - 1 ].number = col;
988 colinfo[ col - 1 ].colname = msi_makestring( db, id );
989 colinfo[ col - 1 ].type = table->data[ i ] [ 3 ] - (1<<15);
990 colinfo[ col - 1 ].offset = 0;
991 colinfo[ col - 1 ].hash_table = NULL;
993 n++;
996 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
998 if (maxcount && n != maxcount)
1000 ERR("missing column in table %s\n", debugstr_w(szTableName));
1001 msi_free_colinfo(colinfo, maxcount );
1002 return ERROR_FUNCTION_FAILED;
1005 /* calculate the offsets */
1006 for( i=0; maxcount && (i<maxcount); i++ )
1008 assert( (i+1) == colinfo[ i ].number );
1009 if (i)
1010 colinfo[i].offset = colinfo[ i - 1 ].offset
1011 + bytes_per_column( &colinfo[ i - 1 ] );
1012 else
1013 colinfo[i].offset = 0;
1014 TRACE("column %d is [%s] with type %08x ofs %d\n",
1015 colinfo[i].number, debugstr_w(colinfo[i].colname),
1016 colinfo[i].type, colinfo[i].offset);
1018 *sz = n;
1020 return ERROR_SUCCESS;
1023 /* try to find the table name in the _Tables table */
1024 BOOL TABLE_Exists( MSIDATABASE *db, LPWSTR name )
1026 UINT r, table_id = 0, i, count;
1027 MSITABLE *table = NULL;
1029 if( !lstrcmpW( name, szTables ) )
1030 return TRUE;
1031 if( !lstrcmpW( name, szColumns ) )
1032 return TRUE;
1034 r = msi_string2idW( db->strings, name, &table_id );
1035 if( r != ERROR_SUCCESS )
1037 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1038 return FALSE;
1041 table = get_table( db, szTables, _Tables_cols, 1 );
1042 if( !table )
1044 TRACE("table %s not available\n", debugstr_w(szTables));
1045 return FALSE;
1048 /* count = table->size/2; */
1049 count = table->row_count;
1050 for( i=0; i<count; i++ )
1051 if( table->data[ i ][ 0 ] == table_id )
1052 break;
1054 if (i!=count)
1055 return TRUE;
1057 TRACE("Searched %d tables, but %d was not found\n", count, table_id );
1059 return FALSE;
1062 /* below is the query interface to a table */
1064 typedef struct tagMSITABLEVIEW
1066 MSIVIEW view;
1067 MSIDATABASE *db;
1068 MSITABLE *table;
1069 MSICOLUMNINFO *columns;
1070 UINT num_cols;
1071 UINT row_size;
1072 WCHAR name[1];
1073 } MSITABLEVIEW;
1075 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1077 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1078 UINT offset, num_rows, n;
1080 if( !tv->table )
1081 return ERROR_INVALID_PARAMETER;
1083 if( (col==0) || (col>tv->num_cols) )
1084 return ERROR_INVALID_PARAMETER;
1086 /* how many rows are there ? */
1087 num_rows = tv->table->row_count;
1088 if( row >= num_rows )
1089 return ERROR_NO_MORE_ITEMS;
1091 if( tv->columns[col-1].offset >= tv->row_size )
1093 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1094 ERR("%p %p\n", tv, tv->columns );
1095 return ERROR_FUNCTION_FAILED;
1098 offset = row + (tv->columns[col-1].offset/2) * num_rows;
1099 n = bytes_per_column( &tv->columns[col-1] );
1100 switch( n )
1102 case 4:
1103 offset = tv->columns[col-1].offset/2;
1104 *val = tv->table->data[row][offset] +
1105 (tv->table->data[row][offset + 1] << 16);
1106 break;
1107 case 2:
1108 offset = tv->columns[col-1].offset/2;
1109 *val = tv->table->data[row][offset];
1110 break;
1111 default:
1112 ERR("oops! what is %d bytes per column?\n", n );
1113 return ERROR_FUNCTION_FAILED;
1116 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1118 return ERROR_SUCCESS;
1122 * We need a special case for streams, as we need to reference column with
1123 * the name of the stream in the same table, and the table name
1124 * which may not be available at higher levels of the query
1126 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1128 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1129 UINT ival = 0, refcol = 0, r;
1130 LPCWSTR sval;
1131 LPWSTR full_name;
1132 DWORD len;
1133 static const WCHAR szDot[] = { '.', 0 };
1134 WCHAR number[0x20];
1136 if( !view->ops->fetch_int )
1137 return ERROR_INVALID_PARAMETER;
1140 * The column marked with the type stream data seems to have a single number
1141 * which references the column containing the name of the stream data
1143 * Fetch the column to reference first.
1145 r = view->ops->fetch_int( view, row, col, &ival );
1146 if( r != ERROR_SUCCESS )
1147 return r;
1149 /* check the column value is in range */
1150 if (ival < 0 || ival > tv->num_cols || ival == col)
1152 ERR("bad column ref (%u) for stream\n", ival);
1153 return ERROR_FUNCTION_FAILED;
1156 if ( tv->columns[ival - 1].type & MSITYPE_STRING )
1158 /* now get the column with the name of the stream */
1159 r = view->ops->fetch_int( view, row, ival, &refcol );
1160 if ( r != ERROR_SUCCESS )
1161 return r;
1163 /* lookup the string value from the string table */
1164 sval = msi_string_lookup_id( tv->db->strings, refcol );
1165 if ( !sval )
1166 return ERROR_INVALID_PARAMETER;
1168 else
1170 static const WCHAR fmt[] = { '%','d',0 };
1171 sprintfW( number, fmt, ival );
1172 sval = number;
1175 len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1176 full_name = msi_alloc( len*sizeof(WCHAR) );
1177 lstrcpyW( full_name, tv->name );
1178 lstrcatW( full_name, szDot );
1179 lstrcatW( full_name, sval );
1181 r = db_get_raw_stream( tv->db, full_name, stm );
1182 if( r )
1183 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1184 msi_free( full_name );
1186 return r;
1189 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1191 UINT offset, n;
1193 if( !tv->table )
1194 return ERROR_INVALID_PARAMETER;
1196 if( (col==0) || (col>tv->num_cols) )
1197 return ERROR_INVALID_PARAMETER;
1199 if( tv->columns[col-1].offset >= tv->row_size )
1201 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1202 ERR("%p %p\n", tv, tv->columns );
1203 return ERROR_FUNCTION_FAILED;
1206 n = bytes_per_column( &tv->columns[col-1] );
1207 switch( n )
1209 case 4:
1210 offset = tv->columns[col-1].offset/2;
1211 tv->table->data[row][offset] = val & 0xffff;
1212 tv->table->data[row][offset + 1] = (val>>16)&0xffff;
1213 break;
1214 case 2:
1215 offset = tv->columns[col-1].offset/2;
1216 tv->table->data[row][offset] = val;
1217 break;
1218 default:
1219 ERR("oops! what is %d bytes per column?\n", n );
1220 return ERROR_FUNCTION_FAILED;
1222 return ERROR_SUCCESS;
1225 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1227 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1228 UINT i, val, r = ERROR_SUCCESS;
1230 if ( !tv->table )
1231 return ERROR_INVALID_PARAMETER;
1233 /* test if any of the mask bits are invalid */
1234 if ( mask >= (1<<tv->num_cols) )
1235 return ERROR_INVALID_PARAMETER;
1237 for ( i = 0; i < tv->num_cols; i++ )
1239 /* only update the fields specified in the mask */
1240 if ( !(mask&(1<<i)) )
1241 continue;
1243 /* FIXME: should we allow updating keys? */
1245 val = 0;
1246 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1248 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1250 val = 1; /* refers to the first key column */
1252 else if ( tv->columns[i].type & MSITYPE_STRING )
1254 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1255 val = msi_addstringW( tv->db->strings, 0, sval, -1, 1 );
1257 else if ( 2 == bytes_per_column( &tv->columns[ i ] ) )
1259 val = 0x8000 + MSI_RecordGetInteger( rec, i + 1 );
1260 if ( val & 0xffff0000 )
1262 ERR("field %u value %d out of range\n", i+1, val - 0x8000 );
1263 return ERROR_FUNCTION_FAILED;
1266 else
1268 INT ival = MSI_RecordGetInteger( rec, i + 1 );
1269 val = ival ^ 0x80000000;
1273 r = TABLE_set_int( tv, row, i+1, val );
1274 if ( r != ERROR_SUCCESS )
1275 break;
1277 return r;
1280 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num )
1282 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1283 USHORT **p, *row;
1284 UINT sz;
1286 TRACE("%p\n", view);
1288 if( !tv->table )
1289 return ERROR_INVALID_PARAMETER;
1291 row = msi_alloc_zero( tv->row_size );
1292 if( !row )
1293 return ERROR_NOT_ENOUGH_MEMORY;
1295 sz = (tv->table->row_count + 1) * sizeof (UINT*);
1296 if( tv->table->data )
1297 p = msi_realloc( tv->table->data, sz );
1298 else
1299 p = msi_alloc( sz );
1300 if( !p )
1302 msi_free( row );
1303 return ERROR_NOT_ENOUGH_MEMORY;
1306 tv->table->data = p;
1307 tv->table->data[tv->table->row_count] = row;
1308 *num = tv->table->row_count;
1309 tv->table->row_count++;
1311 return ERROR_SUCCESS;
1314 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1316 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1318 TRACE("%p %p\n", tv, record);
1320 TRACE("There are %d columns\n", tv->num_cols );
1321 tv->table = get_table( tv->db, tv->name, tv->columns, tv->num_cols );
1322 if( !tv->table )
1323 return ERROR_FUNCTION_FAILED;
1325 return ERROR_SUCCESS;
1328 static UINT TABLE_close( struct tagMSIVIEW *view )
1330 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1332 TRACE("%p\n", view );
1334 if( !tv->table )
1335 return ERROR_FUNCTION_FAILED;
1337 tv->table = NULL;
1339 return ERROR_SUCCESS;
1342 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1344 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1346 TRACE("%p %p %p\n", view, rows, cols );
1348 if( cols )
1349 *cols = tv->num_cols;
1350 if( rows )
1352 if( !tv->table )
1353 return ERROR_INVALID_PARAMETER;
1354 *rows = tv->table->row_count;
1357 return ERROR_SUCCESS;
1360 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1361 UINT n, LPWSTR *name, UINT *type )
1363 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1365 TRACE("%p %d %p %p\n", tv, n, name, type );
1367 if( ( n == 0 ) || ( n > tv->num_cols ) )
1368 return ERROR_INVALID_PARAMETER;
1370 if( name )
1372 *name = strdupW( tv->columns[n-1].colname );
1373 if( !*name )
1374 return ERROR_FUNCTION_FAILED;
1376 if( type )
1377 *type = tv->columns[n-1].type;
1379 return ERROR_SUCCESS;
1382 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1384 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1386 UINT r, row, i;
1388 /* check there's no null values where they're not allowed */
1389 for( i = 0; i < tv->num_cols; i++ )
1391 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1392 continue;
1394 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1395 TRACE("skipping binary column\n");
1396 else if ( tv->columns[i].type & MSITYPE_STRING )
1398 LPCWSTR str;
1400 str = MSI_RecordGetString( rec, i+1 );
1401 if (str == NULL || str[0] == 0)
1402 return ERROR_INVALID_DATA;
1404 else
1406 UINT n;
1408 n = MSI_RecordGetInteger( rec, i+1 );
1409 if (n == MSI_NULL_INTEGER)
1410 return ERROR_INVALID_DATA;
1414 /* check there's no duplicate keys */
1415 r = msi_table_find_row( tv, rec, &row );
1416 if (r == ERROR_SUCCESS)
1417 return ERROR_INVALID_DATA;
1419 return ERROR_SUCCESS;
1422 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1424 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1425 UINT r, row = -1;
1427 TRACE("%p %p\n", tv, rec );
1429 /* check that the key is unique - can we find a matching row? */
1430 r = table_validate_new( tv, rec );
1431 if( r != ERROR_SUCCESS )
1432 return ERROR_FUNCTION_FAILED;
1434 r = table_create_new_row( view, &row );
1435 TRACE("insert_row returned %08x\n", r);
1436 if( r != ERROR_SUCCESS )
1437 return r;
1439 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1442 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1443 MSIRECORD *rec)
1445 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1446 UINT r;
1448 TRACE("%p %d %p\n", view, eModifyMode, rec );
1450 if (!tv->table)
1452 r = TABLE_execute( view, NULL );
1453 if( r )
1454 return r;
1457 switch (eModifyMode)
1459 case MSIMODIFY_VALIDATE_NEW:
1460 r = table_validate_new( tv, rec );
1461 break;
1463 case MSIMODIFY_INSERT_TEMPORARY:
1464 r = table_validate_new( tv, rec );
1465 if (r != ERROR_SUCCESS)
1466 break;
1467 r = TABLE_insert_row( view, rec );
1468 break;
1470 case MSIMODIFY_REFRESH:
1471 case MSIMODIFY_INSERT:
1472 case MSIMODIFY_UPDATE:
1473 case MSIMODIFY_ASSIGN:
1474 case MSIMODIFY_REPLACE:
1475 case MSIMODIFY_MERGE:
1476 case MSIMODIFY_DELETE:
1477 case MSIMODIFY_VALIDATE:
1478 case MSIMODIFY_VALIDATE_FIELD:
1479 case MSIMODIFY_VALIDATE_DELETE:
1480 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1481 r = ERROR_CALL_NOT_IMPLEMENTED;
1482 break;
1484 default:
1485 r = ERROR_INVALID_DATA;
1488 return r;
1491 static UINT TABLE_delete( struct tagMSIVIEW *view )
1493 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1495 TRACE("%p\n", view );
1497 tv->table = NULL;
1499 if( tv->columns )
1501 msi_free_colinfo( tv->columns, tv->num_cols );
1502 msi_free( tv->columns );
1504 tv->columns = NULL;
1506 msi_free( tv );
1508 return ERROR_SUCCESS;
1511 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1512 UINT val, UINT *row, MSIITERHANDLE *handle )
1514 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1515 const MSICOLUMNHASHENTRY *entry;
1517 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1519 if( !tv->table )
1520 return ERROR_INVALID_PARAMETER;
1522 if( (col==0) || (col > tv->num_cols) )
1523 return ERROR_INVALID_PARAMETER;
1525 if( !tv->columns[col-1].hash_table )
1527 UINT i;
1528 UINT num_rows = tv->table->row_count;
1529 MSICOLUMNHASHENTRY **hash_table;
1530 MSICOLUMNHASHENTRY *new_entry;
1532 if( tv->columns[col-1].offset >= tv->row_size )
1534 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1535 ERR("%p %p\n", tv, tv->columns );
1536 return ERROR_FUNCTION_FAILED;
1539 /* allocate contiguous memory for the table and its entries so we
1540 * don't have to do an expensive cleanup */
1541 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1542 num_rows * sizeof(MSICOLUMNHASHENTRY));
1543 if (!hash_table)
1544 return ERROR_OUTOFMEMORY;
1546 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1547 tv->columns[col-1].hash_table = hash_table;
1549 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1551 for (i = 0; i < num_rows; i++, new_entry++)
1553 UINT row_value, n;
1554 UINT offset = i + (tv->columns[col-1].offset/2) * num_rows;
1555 n = bytes_per_column( &tv->columns[col-1] );
1556 switch( n )
1558 case 4:
1559 offset = tv->columns[col-1].offset/2;
1560 row_value = tv->table->data[i][offset] +
1561 (tv->table->data[i][offset + 1] << 16);
1562 break;
1563 case 2:
1564 offset = tv->columns[col-1].offset/2;
1565 row_value = tv->table->data[i][offset];
1566 break;
1567 default:
1568 ERR("oops! what is %d bytes per column?\n", n );
1569 continue;
1572 new_entry->next = NULL;
1573 new_entry->value = row_value;
1574 new_entry->row = i;
1575 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1577 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1578 while (prev_entry->next)
1579 prev_entry = prev_entry->next;
1580 prev_entry->next = new_entry;
1582 else
1583 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1587 if( !*handle )
1588 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1589 else
1590 entry = (*handle)->next;
1592 while (entry && entry->value != val)
1593 entry = entry->next;
1595 *handle = entry;
1596 if (!entry)
1597 return ERROR_NO_MORE_ITEMS;
1599 *row = entry->row;
1600 return ERROR_SUCCESS;
1604 static const MSIVIEWOPS table_ops =
1606 TABLE_fetch_int,
1607 TABLE_fetch_stream,
1608 TABLE_set_row,
1609 TABLE_insert_row,
1610 TABLE_execute,
1611 TABLE_close,
1612 TABLE_get_dimensions,
1613 TABLE_get_column_info,
1614 TABLE_modify,
1615 TABLE_delete,
1616 TABLE_find_matching_rows
1619 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
1621 MSITABLEVIEW *tv ;
1622 UINT r, sz, column_count;
1623 MSICOLUMNINFO *columns;
1625 TRACE("%p %s %p\n", db, debugstr_w(name), view );
1627 /* get the number of columns in this table */
1628 column_count = 0;
1629 r = get_tablecolumns( db, name, NULL, &column_count );
1630 if( r != ERROR_SUCCESS )
1631 return r;
1633 /* if there's no columns, there's no table */
1634 if( column_count == 0 )
1635 return ERROR_INVALID_PARAMETER;
1637 TRACE("Table found\n");
1639 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
1640 tv = msi_alloc_zero( sz );
1641 if( !tv )
1642 return ERROR_FUNCTION_FAILED;
1644 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO));
1645 if( !columns )
1647 msi_free( tv );
1648 return ERROR_FUNCTION_FAILED;
1651 r = get_tablecolumns( db, name, columns, &column_count );
1652 if( r != ERROR_SUCCESS )
1654 msi_free( columns );
1655 msi_free( tv );
1656 return ERROR_FUNCTION_FAILED;
1659 TRACE("Table has %d columns\n", column_count);
1661 /* fill the structure */
1662 tv->view.ops = &table_ops;
1663 tv->db = db;
1664 tv->columns = columns;
1665 tv->num_cols = column_count;
1666 tv->table = NULL;
1667 tv->row_size = msi_table_get_row_size( columns, column_count );
1669 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
1671 *view = (MSIVIEW*) tv;
1672 lstrcpyW( tv->name, name );
1674 return ERROR_SUCCESS;
1677 UINT MSI_CommitTables( MSIDATABASE *db )
1679 UINT r;
1680 MSITABLE *table = NULL;
1682 TRACE("%p\n",db);
1684 r = save_string_table( db );
1685 if( r != ERROR_SUCCESS )
1687 WARN("failed to save string table r=%08x\n",r);
1688 return r;
1691 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
1693 r = save_table( db, table );
1694 if( r != ERROR_SUCCESS )
1696 WARN("failed to save table %s (r=%08x)\n",
1697 debugstr_w(table->name), r);
1698 return r;
1702 /* force everything to reload next time */
1703 free_cached_tables( db );
1705 return ERROR_SUCCESS;
1708 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
1710 if (!table)
1711 return MSICONDITION_ERROR;
1713 return MSICONDITION_FALSE;
1716 static MSIRECORD *msi_get_transform_record( MSITABLEVIEW *tv, string_table *st, USHORT *rawdata )
1718 UINT i, val, ofs = 0;
1719 USHORT mask = *rawdata++;
1720 MSICOLUMNINFO *columns = tv->columns;
1721 MSIRECORD *rec;
1723 rec = MSI_CreateRecord( tv->num_cols );
1724 if( !rec )
1725 return rec;
1727 TRACE("row ->\n");
1728 for( i=0; i<tv->num_cols; i++ )
1730 UINT n = bytes_per_column( &columns[i] );
1732 if ( (mask&1) && (i>=(mask>>8)) )
1733 break;
1734 /* all keys must be present */
1735 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
1736 continue;
1738 switch( n )
1740 case 2:
1741 val = rawdata[ofs];
1742 if( (columns[i].type & MSITYPE_STRING) &&
1743 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1745 LPCWSTR sval = msi_string_lookup_id( st, val );
1746 MSI_RecordSetStringW( rec, i+1, sval );
1747 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
1749 else
1751 if (val)
1752 MSI_RecordSetInteger( rec, i+1, val^0x8000 );
1753 TRACE(" field %d [0x%04x]\n", i+1, val );
1755 break;
1756 case 4:
1757 val = (rawdata[ofs] + (rawdata[ofs + 1]<<16));
1758 if (val)
1759 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
1760 TRACE(" field %d [0x%08x]\n", i+1, val );
1761 break;
1762 default:
1763 ERR("oops - unknown column width %d\n", n);
1764 break;
1766 ofs += n/2;
1768 return rec;
1771 static void dump_record( MSIRECORD *rec )
1773 UINT i, n;
1775 n = MSI_RecordGetFieldCount( rec );
1776 for( i=1; i<=n; i++ )
1778 LPCWSTR sval = MSI_RecordGetString( rec, i );
1780 if( MSI_RecordIsNull( rec, i ) )
1781 TRACE("row -> []\n");
1782 else if( (sval = MSI_RecordGetString( rec, i )) )
1783 TRACE("row -> [%s]\n", debugstr_w(sval));
1784 else
1785 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
1789 static void dump_table( string_table *st, USHORT *rawdata, UINT rawsize )
1791 LPCWSTR sval;
1792 UINT i;
1794 for( i=0; i<(rawsize/2); i++ )
1796 sval = msi_string_lookup_id( st, rawdata[i] );
1797 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
1801 static UINT* msi_record_to_row( MSITABLEVIEW *tv, MSIRECORD *rec )
1803 LPCWSTR str;
1804 UINT i, r, *data;
1806 data = msi_alloc( tv->num_cols *sizeof (UINT) );
1807 for( i=0; i<tv->num_cols; i++ )
1809 data[i] = 0;
1811 if ( ~tv->columns[i].type & MSITYPE_KEY )
1812 continue;
1814 /* turn the transform column value into a row value */
1815 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
1816 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1818 str = MSI_RecordGetString( rec, i+1 );
1819 r = msi_string2idW( tv->db->strings, str, &data[i] );
1821 /* if there's no matching string in the string table,
1822 these keys can't match any record, so fail now. */
1823 if( ERROR_SUCCESS != r )
1825 msi_free( data );
1826 return NULL;
1829 else
1831 data[i] = MSI_RecordGetInteger( rec, i+1 );
1832 if ((tv->columns[i].type&0xff) == 2)
1833 data[i] += 0x8000;
1834 else
1835 data[i] += 0x80000000;
1838 return data;
1841 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, UINT *data )
1843 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
1845 for( i=0; i<tv->num_cols; i++ )
1847 if ( ~tv->columns[i].type & MSITYPE_KEY )
1848 continue;
1850 /* turn the transform column value into a row value */
1851 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
1852 if ( r != ERROR_SUCCESS )
1854 ERR("TABLE_fetch_int shouldn't fail here\n");
1855 break;
1858 /* if this key matches, move to the next column */
1859 if ( x != data[i] )
1861 ret = ERROR_FUNCTION_FAILED;
1862 break;
1865 ret = ERROR_SUCCESS;
1868 return ret;
1871 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
1873 UINT i, r = ERROR_FUNCTION_FAILED, *data;
1875 data = msi_record_to_row( tv, rec );
1876 if( !data )
1877 return r;
1878 for( i=0; i<tv->table->row_count; i++ )
1880 r = msi_row_matches( tv, i, data );
1881 if( r == ERROR_SUCCESS )
1883 *row = i;
1884 break;
1887 msi_free( data );
1888 return r;
1891 static UINT msi_delete_row( MSITABLEVIEW *tv, UINT row )
1893 UINT i;
1895 for( i=1; i<=tv->num_cols; i++ )
1896 TABLE_set_int( tv, row, i, 0 );
1897 return ERROR_SUCCESS;
1900 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
1901 string_table *st, LPCWSTR name )
1903 UINT rawsize = 0;
1904 USHORT *rawdata = NULL;
1905 MSITABLEVIEW *tv = NULL;
1906 UINT r, n, sz, i, mask;
1907 MSIRECORD *rec = NULL;
1908 UINT colcol = 0;
1909 WCHAR coltable[32];
1911 coltable[0] = 0;
1912 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
1914 /* read the transform data */
1915 read_stream_data( stg, name, &rawdata, &rawsize );
1916 if ( !rawdata )
1918 TRACE("table %s empty\n", debugstr_w(name) );
1919 return ERROR_INVALID_TABLE;
1922 /* create a table view */
1923 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
1924 if( r != ERROR_SUCCESS )
1925 goto err;
1927 r = tv->view.ops->execute( &tv->view, NULL );
1928 if( r != ERROR_SUCCESS )
1929 goto err;
1931 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
1932 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
1934 /* interpret the data */
1935 r = ERROR_SUCCESS;
1936 for( n=0; n < (rawsize/2); )
1938 mask = rawdata[n];
1940 if (mask&1)
1943 * if the low bit is set, columns are continuous and
1944 * the number of columns is specified in the high byte
1946 sz = 2 + tv->row_size;
1948 else
1951 * If the low bit is not set, rowdata[n] is a bitmask.
1952 * Excepting for key fields, which are always present,
1953 * each bit indicates that a field is present in the transform record.
1955 * rawdata[n] == 0 is a special case ... only the keys will be present
1956 * and it means that this row should be deleted.
1958 sz = 2;
1959 for( i=0; i<tv->num_cols; i++ )
1961 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
1962 sz += bytes_per_column( &tv->columns[i] );
1966 /* check we didn't run of the end of the table */
1967 if ( (n+sz) > rawsize )
1969 ERR("borked.\n");
1970 dump_table( st, rawdata, rawsize );
1971 break;
1974 rec = msi_get_transform_record( tv, st, &rawdata[n] );
1975 if (rec)
1977 if ( mask & 1 )
1979 TRACE("inserting record\n");
1982 * Native msi seems writes nul into the
1983 * Number (2nd) column of the _Columns table.
1984 * Not sure that it's deliberate...
1986 if (!lstrcmpW(name, szColumns))
1988 WCHAR table[32];
1989 DWORD sz = 32;
1991 MSI_RecordGetStringW( rec, 1, table, &sz );
1993 /* reset the column number on a new table */
1994 if ( lstrcmpW(coltable, table) )
1996 colcol = 0;
1997 lstrcpyW( coltable, table );
2000 /* fix nul column numbers */
2001 MSI_RecordSetInteger( rec, 2, ++colcol );
2004 r = TABLE_insert_row( &tv->view, rec );
2005 if (r != ERROR_SUCCESS)
2006 ERR("insert row failed\n");
2008 else
2010 UINT row = 0;
2012 r = msi_table_find_row( tv, rec, &row );
2013 if (r != ERROR_SUCCESS)
2014 ERR("no matching row to transform\n");
2015 else if ( mask )
2017 TRACE("modifying row [%d]:\n", row);
2018 TABLE_set_row( &tv->view, row, rec, mask );
2020 else
2022 TRACE("deleting row [%d]:\n", row);
2023 msi_delete_row( tv, row );
2026 if( TRACE_ON(msidb) ) dump_record( rec );
2027 msiobj_release( &rec->hdr );
2030 n += sz/2;
2033 err:
2034 /* no need to free the table, it's associated with the database */
2035 msi_free( rawdata );
2036 if( tv )
2037 tv->view.ops->delete( &tv->view );
2039 return ERROR_SUCCESS;
2043 * msi_table_apply_transform
2045 * Enumerate the table transforms in a transform storage and apply each one.
2047 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2049 IEnumSTATSTG *stgenum = NULL;
2050 HRESULT r;
2051 STATSTG stat;
2052 ULONG count;
2053 WCHAR name[0x40];
2054 string_table *strings;
2055 UINT ret = ERROR_FUNCTION_FAILED;
2057 TRACE("%p %p\n", db, stg );
2059 strings = load_string_table( stg );
2060 if( !strings )
2061 goto end;
2063 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2064 if( FAILED( r ) )
2065 goto end;
2068 * Apply _Tables and _Columns transforms first so that
2069 * the table metadata is correct, and empty tables exist.
2071 ret = msi_table_load_transform( db, stg, strings, szTables );
2072 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2073 goto end;
2075 ret = msi_table_load_transform( db, stg, strings, szColumns );
2076 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2077 goto end;
2079 ret = ERROR_SUCCESS;
2081 while( r == ERROR_SUCCESS )
2083 count = 0;
2084 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2085 if( FAILED( r ) || !count )
2086 break;
2088 decode_streamname( stat.pwcsName, name );
2089 if ( name[0] != 0x4840 )
2090 continue;
2092 TRACE("transform contains stream %s\n", debugstr_w(name));
2094 if ( !lstrcmpW( name+1, szStringPool ) ||
2095 !lstrcmpW( name+1, szStringData ) ||
2096 !lstrcmpW( name+1, szColumns ) ||
2097 !lstrcmpW( name+1, szTables ) )
2098 continue;
2100 ret = msi_table_load_transform( db, stg, strings, name+1 );
2103 if ( ret == ERROR_SUCCESS )
2104 append_storage_to_db( db, stg );
2106 end:
2107 if ( stgenum )
2108 IEnumSTATSTG_Release( stgenum );
2109 if ( strings )
2110 msi_destroy_stringtable( strings );
2112 return ret;
2115 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
2117 MSITRANSFORM *t;
2119 t = msi_alloc( sizeof *t );
2120 t->stg = stg;
2121 IStorage_AddRef( stg );
2122 list_add_tail( &db->transforms, &t->entry );
2125 void msi_free_transforms( MSIDATABASE *db )
2127 while( !list_empty( &db->transforms ) )
2129 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
2130 MSITRANSFORM, entry );
2131 list_remove( &t->entry );
2132 IStorage_Release( t->stg );
2133 msi_free( t );