- do not pass private data to the application but a copy of it
[wine/multimedia.git] / dlls / msi / table.c
blobb3b110ae989178ae3e4483607c64d8ee80154157
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include <stdarg.h>
23 #define COBJMACROS
24 #define NONAMELESSUNION
25 #define NONAMELESSSTRUCT
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "wine/debug.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "msipriv.h"
36 #include "winnls.h"
38 #include "query.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(msi);
42 typedef struct tagMSICOLUMNINFO
44 LPCWSTR tablename;
45 UINT number;
46 LPCWSTR colname;
47 UINT type;
48 UINT offset;
49 } MSICOLUMNINFO;
51 struct tagMSITABLE
53 USHORT **data;
54 UINT row_count;
55 struct list entry;
56 WCHAR name[1];
59 #define MAX_STREAM_NAME 0x1f
61 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
62 MSICOLUMNINFO **pcols, UINT *pcount );
63 static UINT get_tablecolumns( MSIDATABASE *db,
64 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
65 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
67 static inline UINT bytes_per_column( const MSICOLUMNINFO *col )
69 if( col->type & MSITYPE_STRING )
70 return 2;
71 if( (col->type & 0xff) > 4 )
72 ERR("Invalid column size!\n");
73 return col->type & 0xff;
76 static int utf2mime(int x)
78 if( (x>='0') && (x<='9') )
79 return x-'0';
80 if( (x>='A') && (x<='Z') )
81 return x-'A'+10;
82 if( (x>='a') && (x<='z') )
83 return x-'a'+10+26;
84 if( x=='.' )
85 return 10+26+26;
86 if( x=='_' )
87 return 10+26+26+1;
88 return -1;
91 static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
93 DWORD count = MAX_STREAM_NAME;
94 DWORD ch, next;
95 LPWSTR out, p;
97 if( !bTable )
98 count = lstrlenW( in )+2;
99 out = msi_alloc( count*sizeof(WCHAR) );
100 p = out;
102 if( bTable )
104 *p++ = 0x4840;
105 count --;
107 while( count -- )
109 ch = *in++;
110 if( !ch )
112 *p = ch;
113 return out;
115 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
117 ch = utf2mime(ch) + 0x4800;
118 next = *in;
119 if( next && (next<0x80) )
121 next = utf2mime(next);
122 if( next >= 0 )
124 next += 0x3ffffc0;
125 ch += (next<<6);
126 in++;
130 *p++ = ch;
132 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
133 msi_free( out );
134 return NULL;
137 static int mime2utf(int x)
139 if( x<10 )
140 return x + '0';
141 if( x<(10+26))
142 return x - 10 + 'A';
143 if( x<(10+26+26))
144 return x - 10 - 26 + 'a';
145 if( x == (10+26+26) )
146 return '.';
147 return '_';
150 static BOOL decode_streamname(LPWSTR in, LPWSTR out)
152 WCHAR ch;
153 DWORD count = 0;
155 while ( (ch = *in++) )
157 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
159 if( ch >= 0x4800 )
160 ch = mime2utf(ch-0x4800);
161 else
163 ch -= 0x3800;
164 *out++ = mime2utf(ch&0x3f);
165 count++;
166 ch = mime2utf((ch>>6)&0x3f);
169 *out++ = ch;
170 count++;
172 *out = 0;
173 return count;
176 void enum_stream_names( IStorage *stg )
178 IEnumSTATSTG *stgenum = NULL;
179 HRESULT r;
180 STATSTG stat;
181 ULONG n, count;
182 WCHAR name[0x40];
184 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
185 if( FAILED( r ) )
186 return;
188 n = 0;
189 while( 1 )
191 count = 0;
192 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
193 if( FAILED( r ) || !count )
194 break;
195 decode_streamname( stat.pwcsName, name );
196 TRACE("stream %2ld -> %s %s\n", n,
197 debugstr_w(stat.pwcsName), debugstr_w(name) );
198 n++;
201 IEnumSTATSTG_Release( stgenum );
204 static UINT read_stream_data( IStorage *stg, LPCWSTR stname,
205 USHORT **pdata, UINT *psz )
207 HRESULT r;
208 UINT ret = ERROR_FUNCTION_FAILED;
209 VOID *data;
210 ULONG sz, count;
211 IStream *stm = NULL;
212 STATSTG stat;
213 LPWSTR encname;
215 encname = encode_streamname(TRUE, stname);
217 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
219 r = IStorage_OpenStream(stg, encname, NULL,
220 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
221 msi_free( encname );
222 if( FAILED( r ) )
224 WARN("open stream failed r = %08lx - empty table?\n",r);
225 return ret;
228 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
229 if( FAILED( r ) )
231 WARN("open stream failed r = %08lx!\n",r);
232 goto end;
235 if( stat.cbSize.QuadPart >> 32 )
237 WARN("Too big!\n");
238 goto end;
241 sz = stat.cbSize.QuadPart;
242 data = msi_alloc( sz );
243 if( !data )
245 WARN("couldn't allocate memory r=%08lx!\n",r);
246 ret = ERROR_NOT_ENOUGH_MEMORY;
247 goto end;
250 r = IStream_Read(stm, data, sz, &count );
251 if( FAILED( r ) || ( count != sz ) )
253 msi_free( data );
254 WARN("read stream failed r = %08lx!\n",r);
255 goto end;
258 *pdata = data;
259 *psz = sz;
260 ret = ERROR_SUCCESS;
262 end:
263 IStream_Release( stm );
265 return ret;
268 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
270 LPWSTR encname;
271 HRESULT r;
273 encname = encode_streamname(FALSE, stname);
275 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
277 r = IStorage_OpenStream(db->storage, encname, NULL,
278 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
279 msi_free( encname );
280 if( FAILED( r ) )
282 WARN("open stream failed r = %08lx - empty table?\n",r);
283 return ERROR_FUNCTION_FAILED;
286 return ERROR_SUCCESS;
289 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
290 USHORT **pdata, UINT *psz )
292 HRESULT r;
293 UINT ret = ERROR_FUNCTION_FAILED;
294 VOID *data;
295 ULONG sz, count;
296 IStream *stm = NULL;
297 STATSTG stat;
299 r = db_get_raw_stream( db, stname, &stm );
300 if( r != ERROR_SUCCESS)
301 return ret;
302 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
303 if( FAILED( r ) )
305 WARN("open stream failed r = %08lx!\n",r);
306 goto end;
309 if( stat.cbSize.QuadPart >> 32 )
311 WARN("Too big!\n");
312 goto end;
315 sz = stat.cbSize.QuadPart;
316 data = msi_alloc( sz );
317 if( !data )
319 WARN("couldn't allocate memory r=%08lx!\n",r);
320 ret = ERROR_NOT_ENOUGH_MEMORY;
321 goto end;
324 r = IStream_Read(stm, data, sz, &count );
325 if( FAILED( r ) || ( count != sz ) )
327 msi_free( data );
328 WARN("read stream failed r = %08lx!\n",r);
329 goto end;
332 *pdata = data;
333 *psz = sz;
334 ret = ERROR_SUCCESS;
336 end:
337 IStream_Release( stm );
339 return ret;
342 static UINT write_stream_data( IStorage *stg, LPCWSTR stname,
343 LPVOID data, UINT sz )
345 HRESULT r;
346 UINT ret = ERROR_FUNCTION_FAILED;
347 ULONG count;
348 IStream *stm = NULL;
349 ULARGE_INTEGER size;
350 LARGE_INTEGER pos;
351 LPWSTR encname;
353 encname = encode_streamname(TRUE, stname );
354 r = IStorage_OpenStream( stg, encname, NULL,
355 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
356 if( FAILED(r) )
358 r = IStorage_CreateStream( stg, encname,
359 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
361 msi_free( encname );
362 if( FAILED( r ) )
364 WARN("open stream failed r = %08lx\n",r);
365 return ret;
368 size.QuadPart = sz;
369 r = IStream_SetSize( stm, size );
370 if( FAILED( r ) )
372 WARN("Failed to SetSize\n");
373 goto end;
376 pos.QuadPart = 0;
377 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
378 if( FAILED( r ) )
380 WARN("Failed to Seek\n");
381 goto end;
384 r = IStream_Write(stm, data, sz, &count );
385 if( FAILED( r ) || ( count != sz ) )
387 WARN("Failed to Write\n");
388 goto end;
391 ret = ERROR_SUCCESS;
393 end:
394 IStream_Release( stm );
396 return ret;
399 static void free_table( MSITABLE *table )
401 int i;
402 for( i=0; i<table->row_count; i++ )
403 msi_free( table->data[i] );
404 msi_free( table->data );
405 msi_free( table );
408 static UINT msi_table_get_row_size( const MSICOLUMNINFO *cols, UINT count )
410 const MSICOLUMNINFO *last_col = &cols[count-1];
411 if (!count)
412 return 0;
413 return last_col->offset + bytes_per_column( last_col );
416 /* add this table to the list of cached tables in the database */
417 static MSITABLE *read_table_from_storage( IStorage *stg, LPCWSTR name,
418 const MSICOLUMNINFO *cols, UINT num_cols )
420 MSITABLE *t;
421 USHORT *rawdata = NULL;
422 UINT rawsize = 0, i, j, row_size = 0;
424 TRACE("%s\n",debugstr_w(name));
426 /* nonexistent tables should be interpreted as empty tables */
427 t = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
428 if( !t )
429 return t;
431 row_size = msi_table_get_row_size( cols, num_cols );
433 t->row_count = 0;
434 t->data = NULL;
435 lstrcpyW( t->name, name );
437 /* if we can't read the table, just assume that it's empty */
438 read_stream_data( stg, name, &rawdata, &rawsize );
439 if( !rawdata )
440 return t;
442 TRACE("Read %d bytes\n", rawsize );
444 if( rawsize % row_size )
446 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
447 goto err;
450 t->row_count = rawsize / row_size;
451 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
452 if( !t->data )
453 goto err;
455 /* transpose all the data */
456 TRACE("Transposing data from %d columns\n", t->row_count );
457 for( i=0; i<t->row_count; i++ )
459 t->data[i] = msi_alloc( row_size );
460 if( !t->data[i] )
461 goto err;
463 for( j=0; j<num_cols; j++ )
465 UINT ofs = cols[j].offset/2;
466 UINT n = bytes_per_column( &cols[j] );
468 switch( n )
470 case 2:
471 t->data[i][ofs] = rawdata[ofs*t->row_count + i ];
472 break;
473 case 4:
474 t->data[i][ofs] = rawdata[ofs*t->row_count + i*2 ];
475 t->data[i][ofs+1] = rawdata[ofs*t->row_count + i*2 + 1];
476 break;
477 default:
478 ERR("oops - unknown column width %d\n", n);
479 goto err;
484 msi_free( rawdata );
485 return t;
486 err:
487 msi_free( rawdata );
488 free_table( t );
489 return NULL;
492 void free_cached_tables( MSIDATABASE *db )
494 while( !list_empty( &db->tables ) )
496 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
498 list_remove( &t->entry );
499 free_table( t );
503 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
505 MSITABLE *t;
507 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
508 if( !lstrcmpW( name, t->name ) )
509 return t;
511 return NULL;
514 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
516 UINT r, column_count = 0;
517 MSICOLUMNINFO *columns;
519 /* get the number of columns in this table */
520 column_count = 0;
521 r = get_tablecolumns( db, name, NULL, &column_count );
522 if( r != ERROR_SUCCESS )
523 return r;
525 /* if there's no columns, there's no table */
526 if( column_count == 0 )
527 return ERROR_INVALID_PARAMETER;
529 TRACE("Table %s found\n", debugstr_w(name) );
531 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
532 if( !columns )
533 return ERROR_FUNCTION_FAILED;
535 r = get_tablecolumns( db, name, columns, &column_count );
536 if( r != ERROR_SUCCESS )
538 msi_free( columns );
539 return ERROR_FUNCTION_FAILED;
542 *pcols = columns;
543 *pcount = column_count;
545 return r;
548 static MSITABLE *get_table( MSIDATABASE *db, LPCWSTR name,
549 const MSICOLUMNINFO *cols, UINT num_cols )
551 MSITABLE *table;
553 /* first, see if the table is cached */
554 table = find_cached_table( db, name );
555 if( table )
556 return table;
558 table = read_table_from_storage( db->storage, name, cols, num_cols );
559 if( table )
560 list_add_head( &db->tables, &table->entry );
562 return table;
565 static UINT save_table( MSIDATABASE *db, MSITABLE *t )
567 USHORT *rawdata = NULL, *p;
568 UINT rawsize, r, i, j, row_size, num_cols = 0;
569 MSICOLUMNINFO *cols = NULL;
571 TRACE("Saving %s\n", debugstr_w( t->name ) );
573 r = table_get_column_info( db, t->name, &cols, &num_cols );
574 if( r != ERROR_SUCCESS )
575 return r;
577 row_size = msi_table_get_row_size( cols, num_cols );
579 rawsize = t->row_count * row_size;
580 rawdata = msi_alloc_zero( rawsize );
581 if( !rawdata )
583 r = ERROR_NOT_ENOUGH_MEMORY;
584 goto err;
587 p = rawdata;
588 for( i=0; i<num_cols; i++ )
590 for( j=0; j<t->row_count; j++ )
592 UINT offset = cols[i].offset;
594 *p++ = t->data[j][offset/2];
595 if( 4 == bytes_per_column( &cols[i] ) )
596 *p++ = t->data[j][offset/2+1];
600 TRACE("writing %d bytes\n", rawsize);
601 r = write_stream_data( db->storage, t->name, rawdata, rawsize );
603 err:
604 msi_free_colinfo( cols, num_cols );
605 msi_free( cols );
606 msi_free( rawdata );
608 return r;
611 HRESULT init_string_table( IStorage *stg )
613 HRESULT r;
614 static const WCHAR szStringData[] = {
615 '_','S','t','r','i','n','g','D','a','t','a',0 };
616 static const WCHAR szStringPool[] = {
617 '_','S','t','r','i','n','g','P','o','o','l',0 };
618 USHORT zero[2] = { 0, 0 };
619 ULONG count = 0;
620 IStream *stm = NULL;
621 LPWSTR encname;
623 encname = encode_streamname(TRUE, szStringPool );
625 /* create the StringPool stream... add the zero string to it*/
626 r = IStorage_CreateStream( stg, encname,
627 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
628 msi_free( encname );
629 if( r )
631 TRACE("Failed\n");
632 return r;
635 r = IStream_Write(stm, zero, sizeof zero, &count );
636 IStream_Release( stm );
638 if( FAILED( r ) || ( count != sizeof zero ) )
640 TRACE("Failed\n");
641 return E_FAIL;
644 /* create the StringData stream... make it zero length */
645 encname = encode_streamname(TRUE, szStringData );
646 r = IStorage_CreateStream( stg, encname,
647 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
648 msi_free( encname );
649 if( r )
651 TRACE("Failed\n");
652 return E_FAIL;
654 IStream_Release( stm );
656 return r;
659 string_table *load_string_table( IStorage *stg )
661 string_table *st = NULL;
662 CHAR *data;
663 USHORT *pool;
664 UINT r, datasize = 0, poolsize = 0, codepage;
665 DWORD i, count, offset, len, n;
666 static const WCHAR szStringData[] = {
667 '_','S','t','r','i','n','g','D','a','t','a',0 };
668 static const WCHAR szStringPool[] = {
669 '_','S','t','r','i','n','g','P','o','o','l',0 };
671 r = read_stream_data( stg, szStringPool, &pool, &poolsize );
672 if( r != ERROR_SUCCESS)
673 goto end;
674 r = read_stream_data( stg, szStringData, (USHORT**)&data, &datasize );
675 if( r != ERROR_SUCCESS)
676 goto end;
678 count = poolsize/4;
679 if( poolsize > 4 )
680 codepage = pool[0] | ( pool[1] << 16 );
681 else
682 codepage = CP_ACP;
683 st = msi_init_stringtable( count, codepage );
685 offset = 0;
686 n = 1;
687 for( i=1; i<count; i++ )
689 len = pool[i*2];
692 * If a string is over 64k, the previous string entry is made null
693 * and its the high word of the length is inserted in the null string's
694 * reference count field.
696 if( pool[i*2-2] == 0 )
697 len += pool[i*2-1] * 0x10000;
699 if( (offset + len) > datasize )
701 ERR("string table corrupt?\n");
702 break;
705 /* don't add the high word of a string's length as a string */
706 if ( len || !pool[i*2+1] )
708 r = msi_addstring( st, n, data+offset, len, pool[i*2+1] );
709 if( r != n )
710 ERR("Failed to add string %ld\n", n );
711 n++;
714 offset += len;
717 if ( datasize != offset )
718 ERR("string table load failed! (%08x != %08lx)\n", datasize, offset );
720 TRACE("Loaded %ld strings\n", count);
722 end:
723 msi_free( pool );
724 msi_free( data );
726 return st;
729 static UINT save_string_table( MSIDATABASE *db )
731 UINT i, count, datasize, poolsize, sz, used, r, codepage;
732 UINT ret = ERROR_FUNCTION_FAILED;
733 static const WCHAR szStringData[] = {
734 '_','S','t','r','i','n','g','D','a','t','a',0 };
735 static const WCHAR szStringPool[] = {
736 '_','S','t','r','i','n','g','P','o','o','l',0 };
737 CHAR *data = NULL;
738 USHORT *pool = NULL;
740 TRACE("\n");
742 /* construct the new table in memory first */
743 datasize = msi_string_totalsize( db->strings, &count );
744 poolsize = count*2*sizeof(USHORT);
746 pool = msi_alloc( poolsize );
747 if( ! pool )
749 WARN("Failed to alloc pool %d bytes\n", poolsize );
750 goto err;
752 data = msi_alloc( datasize );
753 if( ! data )
755 WARN("Failed to alloc data %d bytes\n", poolsize );
756 goto err;
759 used = 0;
760 codepage = msi_string_get_codepage( db->strings );
761 pool[0]=codepage&0xffff;
762 pool[1]=(codepage>>16);
763 for( i=1; i<count; i++ )
765 sz = datasize - used;
766 r = msi_id2stringA( db->strings, i, data+used, &sz );
767 if( r != ERROR_SUCCESS )
769 ERR("failed to fetch string\n");
770 sz = 0;
772 if( sz && (sz < (datasize - used ) ) )
773 sz--;
774 TRACE("adding %u bytes %s\n", sz, debugstr_a(data+used) );
775 pool[ i*2 ] = sz;
776 pool[ i*2 + 1 ] = msi_id_refcount( db->strings, i );
777 used += sz;
778 if( used > datasize )
780 ERR("oops overran %d >= %d\n", used, datasize);
781 goto err;
785 if( used != datasize )
787 ERR("oops used %d != datasize %d\n", used, datasize);
788 goto err;
791 /* write the streams */
792 r = write_stream_data( db->storage, szStringData, data, datasize );
793 TRACE("Wrote StringData r=%08x\n", r);
794 if( r )
795 goto err;
796 r = write_stream_data( db->storage, szStringPool, pool, poolsize );
797 TRACE("Wrote StringPool r=%08x\n", r);
798 if( r )
799 goto err;
801 ret = ERROR_SUCCESS;
803 err:
804 msi_free( data );
805 msi_free( pool );
807 return ret;
810 /* information for default tables */
811 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
812 static const WCHAR szTable[] = { 'T','a','b','l','e',0 };
813 static const WCHAR szName[] = { 'N','a','m','e',0 };
814 static const WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
815 static const WCHAR szColumn[] = { 'C','o','l','u','m','n',0 };
816 static const WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
817 static const WCHAR szType[] = { 'T','y','p','e',0 };
819 static const MSICOLUMNINFO _Columns_cols[4] = {
820 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
821 { szColumns, 2, szNumber, MSITYPE_VALID | 2, 2 },
822 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4 },
823 { szColumns, 4, szType, MSITYPE_VALID | 2, 6 },
825 static const MSICOLUMNINFO _Tables_cols[1] = {
826 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
829 static UINT get_defaulttablecolumns( LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz)
831 const MSICOLUMNINFO *p;
832 DWORD i, n;
834 TRACE("%s\n", debugstr_w(name));
836 if (!lstrcmpW( name, szTables ))
838 p = _Tables_cols;
839 n = 1;
841 else if (!lstrcmpW( name, szColumns ))
843 p = _Columns_cols;
844 n = 4;
846 else
847 return ERROR_FUNCTION_FAILED;
849 /* duplicate the string data so we can free it in msi_free_colinfo */
850 for (i=0; i<n; i++)
852 if (colinfo && (i < *sz) )
854 memcpy( &colinfo[i], &p[i], sizeof(MSICOLUMNINFO) );
855 colinfo[i].tablename = strdupW( p[i].tablename );
856 colinfo[i].colname = strdupW( p[i].colname );
858 if( colinfo && (i >= *sz) )
859 break;
861 *sz = n;
862 return ERROR_SUCCESS;
865 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
867 UINT i;
869 for( i=0; i<count; i++ )
871 msi_free( (LPWSTR) colinfo[i].tablename );
872 msi_free( (LPWSTR) colinfo[i].colname );
876 LPWSTR MSI_makestring( MSIDATABASE *db, UINT stringid)
878 UINT sz=0, r;
879 LPWSTR str;
881 r = msi_id2stringW( db->strings, stringid, NULL, &sz );
882 if( r != ERROR_SUCCESS )
883 return NULL;
884 str = msi_alloc( sz*sizeof (WCHAR) );
885 if( !str )
886 return str;
887 r = msi_id2stringW( db->strings, stringid, str, &sz );
888 if( r == ERROR_SUCCESS )
889 return str;
890 msi_free( str );
891 return NULL;
894 static UINT get_tablecolumns( MSIDATABASE *db,
895 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
897 UINT r, i, n=0, table_id, count, maxcount = *sz;
898 MSITABLE *table = NULL;
900 /* first check if there is a default table with that name */
901 r = get_defaulttablecolumns( szTableName, colinfo, sz );
902 if( ( r == ERROR_SUCCESS ) && *sz )
903 return r;
905 table = get_table( db, szColumns, _Columns_cols, 4 );
906 if( !table )
908 ERR("couldn't load _Columns table\n");
909 return ERROR_FUNCTION_FAILED;
912 /* convert table and column names to IDs from the string table */
913 r = msi_string2idW( db->strings, szTableName, &table_id );
914 if( r != ERROR_SUCCESS )
916 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
917 return r;
920 TRACE("Table id is %d\n", table_id);
922 count = table->row_count;
923 for( i=0; i<count; i++ )
925 if( table->data[ i ][ 0 ] != table_id )
926 continue;
927 if( colinfo )
929 UINT id = table->data[ i ] [ 2 ];
930 colinfo[n].tablename = MSI_makestring( db, table_id );
931 colinfo[n].number = table->data[ i ][ 1 ] - (1<<15);
932 colinfo[n].colname = MSI_makestring( db, id );
933 colinfo[n].type = table->data[ i ] [ 3 ] ^ 0x8000;
934 /* this assumes that columns are in order in the table */
935 if( n )
936 colinfo[n].offset = colinfo[n-1].offset
937 + bytes_per_column( &colinfo[n-1] );
938 else
939 colinfo[n].offset = 0;
940 TRACE("table %s column %d is [%s] (%d) with type %08x "
941 "offset %d at row %d\n", debugstr_w(szTableName),
942 colinfo[n].number, debugstr_w(colinfo[n].colname),
943 id, colinfo[n].type, colinfo[n].offset, i);
944 if( n != (colinfo[n].number-1) )
946 ERR("oops. data in the _Columns table isn't in the right "
947 "order for table %s\n", debugstr_w(szTableName));
948 return ERROR_FUNCTION_FAILED;
951 n++;
952 if( colinfo && ( n >= maxcount ) )
953 break;
955 *sz = n;
957 return ERROR_SUCCESS;
960 /* try to find the table name in the _Tables table */
961 BOOL TABLE_Exists( MSIDATABASE *db, LPWSTR name )
963 UINT r, table_id = 0, i, count;
964 MSITABLE *table = NULL;
966 if( !lstrcmpW( name, szTables ) )
967 return TRUE;
968 if( !lstrcmpW( name, szColumns ) )
969 return TRUE;
971 r = msi_string2idW( db->strings, name, &table_id );
972 if( r != ERROR_SUCCESS )
974 TRACE("Couldn't find id for %s\n", debugstr_w(name));
975 return FALSE;
978 table = get_table( db, szTables, _Tables_cols, 1 );
979 if( !table )
981 TRACE("table %s not available\n", debugstr_w(szTables));
982 return FALSE;
985 /* count = table->size/2; */
986 count = table->row_count;
987 for( i=0; i<count; i++ )
988 if( table->data[ i ][ 0 ] == table_id )
989 break;
991 if (i!=count)
992 return TRUE;
994 TRACE("Searched %d tables, but %d was not found\n", count, table_id );
996 return FALSE;
999 /* below is the query interface to a table */
1001 typedef struct tagMSITABLEVIEW
1003 MSIVIEW view;
1004 MSIDATABASE *db;
1005 MSITABLE *table;
1006 MSICOLUMNINFO *columns;
1007 UINT num_cols;
1008 UINT row_size;
1009 WCHAR name[1];
1010 } MSITABLEVIEW;
1012 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1014 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1015 UINT offset, num_rows, n;
1017 if( !tv->table )
1018 return ERROR_INVALID_PARAMETER;
1020 if( (col==0) || (col>tv->num_cols) )
1021 return ERROR_INVALID_PARAMETER;
1023 /* how many rows are there ? */
1024 num_rows = tv->table->row_count;
1025 if( row >= num_rows )
1026 return ERROR_NO_MORE_ITEMS;
1028 if( tv->columns[col-1].offset >= tv->row_size )
1030 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1031 ERR("%p %p\n", tv, tv->columns );
1032 return ERROR_FUNCTION_FAILED;
1035 offset = row + (tv->columns[col-1].offset/2) * num_rows;
1036 n = bytes_per_column( &tv->columns[col-1] );
1037 switch( n )
1039 case 4:
1040 offset = tv->columns[col-1].offset/2;
1041 *val = tv->table->data[row][offset] +
1042 (tv->table->data[row][offset + 1] << 16);
1043 break;
1044 case 2:
1045 offset = tv->columns[col-1].offset/2;
1046 *val = tv->table->data[row][offset];
1047 break;
1048 default:
1049 ERR("oops! what is %d bytes per column?\n", n );
1050 return ERROR_FUNCTION_FAILED;
1053 /* TRACE("Data [%d][%d] = %d \n", row, col, *val ); */
1055 return ERROR_SUCCESS;
1059 * We need a special case for streams, as we need to reference column with
1060 * the name of the stream in the same table, and the table name
1061 * which may not be available at higher levels of the query
1063 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1065 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1066 UINT ival = 0, refcol = 0, r;
1067 LPWSTR sval;
1068 LPWSTR full_name;
1069 DWORD len;
1070 static const WCHAR szDot[] = { '.', 0 };
1072 if( !view->ops->fetch_int )
1073 return ERROR_INVALID_PARAMETER;
1076 * The column marked with the type stream data seems to have a single number
1077 * which references the column containing the name of the stream data
1079 * Fetch the column to reference first.
1081 r = view->ops->fetch_int( view, row, col, &ival );
1082 if( r != ERROR_SUCCESS )
1083 return r;
1085 /* now get the column with the name of the stream */
1086 r = view->ops->fetch_int( view, row, ival, &refcol );
1087 if( r != ERROR_SUCCESS )
1088 return r;
1090 /* lookup the string value from the string table */
1091 sval = MSI_makestring( tv->db, refcol );
1092 if( !sval )
1093 return ERROR_INVALID_PARAMETER;
1095 len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1096 full_name = msi_alloc( len*sizeof(WCHAR) );
1097 lstrcpyW( full_name, tv->name );
1098 lstrcatW( full_name, szDot );
1099 lstrcatW( full_name, sval );
1101 r = db_get_raw_stream( tv->db, full_name, stm );
1102 if( r )
1103 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1104 msi_free( full_name );
1105 msi_free( sval );
1107 return r;
1110 static UINT TABLE_set_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT val )
1112 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1113 UINT offset, n;
1115 if( !tv->table )
1116 return ERROR_INVALID_PARAMETER;
1118 if( (col==0) || (col>tv->num_cols) )
1119 return ERROR_INVALID_PARAMETER;
1121 if( tv->columns[col-1].offset >= tv->row_size )
1123 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1124 ERR("%p %p\n", tv, tv->columns );
1125 return ERROR_FUNCTION_FAILED;
1128 n = bytes_per_column( &tv->columns[col-1] );
1129 switch( n )
1131 case 4:
1132 offset = tv->columns[col-1].offset/2;
1133 tv->table->data[row][offset] = val & 0xffff;
1134 tv->table->data[row][offset + 1] = (val>>16)&0xffff;
1135 break;
1136 case 2:
1137 offset = tv->columns[col-1].offset/2;
1138 tv->table->data[row][offset] = val;
1139 break;
1140 default:
1141 ERR("oops! what is %d bytes per column?\n", n );
1142 return ERROR_FUNCTION_FAILED;
1144 return ERROR_SUCCESS;
1147 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num )
1149 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1150 USHORT **p, *row;
1151 UINT sz;
1153 TRACE("%p\n", view);
1155 if( !tv->table )
1156 return ERROR_INVALID_PARAMETER;
1158 row = msi_alloc_zero( tv->row_size );
1159 if( !row )
1160 return ERROR_NOT_ENOUGH_MEMORY;
1162 sz = (tv->table->row_count + 1) * sizeof (UINT*);
1163 if( tv->table->data )
1164 p = msi_realloc( tv->table->data, sz );
1165 else
1166 p = msi_alloc( sz );
1167 if( !p )
1169 msi_free( row );
1170 return ERROR_NOT_ENOUGH_MEMORY;
1173 tv->table->data = p;
1174 tv->table->data[tv->table->row_count] = row;
1175 *num = tv->table->row_count;
1176 tv->table->row_count++;
1178 return ERROR_SUCCESS;
1181 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1183 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1185 TRACE("%p %p\n", tv, record);
1187 TRACE("There are %d columns\n", tv->num_cols );
1188 tv->table = get_table( tv->db, tv->name, tv->columns, tv->num_cols );
1189 if( !tv->table )
1190 return ERROR_FUNCTION_FAILED;
1192 return ERROR_SUCCESS;
1195 static UINT TABLE_close( struct tagMSIVIEW *view )
1197 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1199 TRACE("%p\n", view );
1201 if( !tv->table )
1202 return ERROR_FUNCTION_FAILED;
1204 tv->table = NULL;
1206 return ERROR_SUCCESS;
1209 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1211 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1213 TRACE("%p %p %p\n", view, rows, cols );
1215 if( cols )
1216 *cols = tv->num_cols;
1217 if( rows )
1219 if( !tv->table )
1220 return ERROR_INVALID_PARAMETER;
1221 *rows = tv->table->row_count;
1224 return ERROR_SUCCESS;
1227 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1228 UINT n, LPWSTR *name, UINT *type )
1230 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1232 TRACE("%p %d %p %p\n", tv, n, name, type );
1234 if( ( n == 0 ) || ( n > tv->num_cols ) )
1235 return ERROR_INVALID_PARAMETER;
1237 if( name )
1239 *name = strdupW( tv->columns[n-1].colname );
1240 if( !*name )
1241 return ERROR_FUNCTION_FAILED;
1243 if( type )
1244 *type = tv->columns[n-1].type;
1246 return ERROR_SUCCESS;
1249 static UINT table_find_in_column( MSITABLEVIEW *tv, UINT col, UINT val, UINT *row )
1251 UINT i, r, x;
1253 for( i=0; i<tv->table->row_count; i++ )
1255 r = TABLE_fetch_int( (struct tagMSIVIEW*) tv, i, col, &x );
1256 if ( r != ERROR_SUCCESS )
1258 ERR("TABLE_fetch_int shouldn't fail here\n");
1259 break;
1261 if ( x == val )
1263 *row = i;
1264 return ERROR_SUCCESS;
1267 return ERROR_FUNCTION_FAILED;
1270 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1272 LPCWSTR str;
1273 UINT i, val, r, row;
1274 BOOL has_key = FALSE;
1276 /* FIXME: set the MsiViewGetError value */
1278 for( i = 0; i<tv->num_cols; i++ )
1280 /* check for duplicate keys */
1281 if( !( tv->columns[i].type & MSITYPE_KEY ) )
1282 continue;
1284 has_key = TRUE;
1286 TRACE("column %d (%s.%s)is a key\n", i,
1287 debugstr_w(tv->columns[i].tablename),
1288 debugstr_w(tv->columns[i].colname) );
1290 val = 0;
1291 if( tv->columns[i].type & MSITYPE_STRING )
1293 /* keys can't be null */
1294 str = MSI_RecordGetString( rec, i+1 );
1295 if( !str )
1296 return ERROR_INVALID_DATA;
1298 /* if the string doesn't exist in the string table yet, it's OK */
1299 r = msi_string2idW( tv->db->strings, str, &val );
1300 if( ERROR_SUCCESS != r )
1301 return ERROR_SUCCESS;
1303 else
1305 val = MSI_RecordGetInteger( rec, i+1 );
1306 val ^= 0x8000;
1309 /* if we find the same value in the table, it's a duplicate */
1310 row = 0;
1311 r = table_find_in_column( tv, i+1, val, &row );
1312 if( ERROR_SUCCESS != r )
1313 return ERROR_SUCCESS;
1315 TRACE("found in row %d\n", row );
1318 if (has_key)
1319 return ERROR_INVALID_DATA;
1321 return ERROR_SUCCESS;
1324 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1326 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1327 UINT n, type, val, r, row, col_count = 0;
1329 r = TABLE_get_dimensions( view, NULL, &col_count );
1330 if( r )
1331 return r;
1333 row = -1;
1334 r = table_create_new_row( view, &row );
1335 TRACE("insert_row returned %08x\n", r);
1336 if( r )
1337 return r;
1339 for( n = 1; n <= col_count; n++ )
1341 r = TABLE_get_column_info( view, n, NULL, &type );
1342 if( r )
1343 break;
1345 if( type & MSITYPE_STRING )
1347 const WCHAR *str = MSI_RecordGetString( rec, n );
1348 val = msi_addstringW( tv->db->strings, 0, str, -1, 1 );
1350 else
1352 val = MSI_RecordGetInteger( rec, n );
1353 val ^= 0x8000;
1355 r = TABLE_set_int( view, row, n, val );
1356 if( r )
1357 break;
1360 return r;
1363 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1364 MSIRECORD *rec)
1366 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1367 UINT r;
1369 TRACE("%p %d %p\n", view, eModifyMode, rec );
1371 if (!tv->table)
1373 r = TABLE_execute( view, NULL );
1374 if( r )
1375 return r;
1378 switch (eModifyMode)
1380 case MSIMODIFY_VALIDATE_NEW:
1381 r = table_validate_new( tv, rec );
1382 break;
1384 case MSIMODIFY_INSERT_TEMPORARY:
1385 r = table_validate_new( tv, rec );
1386 if (r != ERROR_SUCCESS)
1387 break;
1388 r = TABLE_insert_row( view, rec );
1389 break;
1391 case MSIMODIFY_REFRESH:
1392 case MSIMODIFY_INSERT:
1393 case MSIMODIFY_UPDATE:
1394 case MSIMODIFY_ASSIGN:
1395 case MSIMODIFY_REPLACE:
1396 case MSIMODIFY_MERGE:
1397 case MSIMODIFY_DELETE:
1398 case MSIMODIFY_VALIDATE:
1399 case MSIMODIFY_VALIDATE_FIELD:
1400 case MSIMODIFY_VALIDATE_DELETE:
1401 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1402 r = ERROR_CALL_NOT_IMPLEMENTED;
1403 break;
1405 default:
1406 r = ERROR_INVALID_DATA;
1409 return r;
1412 static UINT TABLE_delete( struct tagMSIVIEW *view )
1414 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1416 TRACE("%p\n", view );
1418 tv->table = NULL;
1420 if( tv->columns )
1422 msi_free_colinfo( tv->columns, tv->num_cols );
1423 msi_free( tv->columns );
1425 tv->columns = NULL;
1427 msi_free( tv );
1429 return ERROR_SUCCESS;
1433 MSIVIEWOPS table_ops =
1435 TABLE_fetch_int,
1436 TABLE_fetch_stream,
1437 TABLE_set_int,
1438 TABLE_insert_row,
1439 TABLE_execute,
1440 TABLE_close,
1441 TABLE_get_dimensions,
1442 TABLE_get_column_info,
1443 TABLE_modify,
1444 TABLE_delete
1447 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
1449 MSITABLEVIEW *tv ;
1450 UINT r, sz, column_count;
1451 MSICOLUMNINFO *columns;
1453 TRACE("%p %s %p\n", db, debugstr_w(name), view );
1455 /* get the number of columns in this table */
1456 column_count = 0;
1457 r = get_tablecolumns( db, name, NULL, &column_count );
1458 if( r != ERROR_SUCCESS )
1459 return r;
1461 /* if there's no columns, there's no table */
1462 if( column_count == 0 )
1463 return ERROR_INVALID_PARAMETER;
1465 TRACE("Table found\n");
1467 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
1468 tv = msi_alloc_zero( sz );
1469 if( !tv )
1470 return ERROR_FUNCTION_FAILED;
1472 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO));
1473 if( !columns )
1475 msi_free( tv );
1476 return ERROR_FUNCTION_FAILED;
1479 r = get_tablecolumns( db, name, columns, &column_count );
1480 if( r != ERROR_SUCCESS )
1482 msi_free( columns );
1483 msi_free( tv );
1484 return ERROR_FUNCTION_FAILED;
1487 TRACE("Table has %d columns\n", column_count);
1489 /* fill the structure */
1490 tv->view.ops = &table_ops;
1491 tv->db = db;
1492 tv->columns = columns;
1493 tv->num_cols = column_count;
1494 tv->table = NULL;
1495 tv->row_size = msi_table_get_row_size( columns, column_count );
1497 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
1499 *view = (MSIVIEW*) tv;
1500 lstrcpyW( tv->name, name );
1502 return ERROR_SUCCESS;
1505 UINT MSI_CommitTables( MSIDATABASE *db )
1507 UINT r;
1508 MSITABLE *table = NULL;
1510 TRACE("%p\n",db);
1512 r = save_string_table( db );
1513 if( r != ERROR_SUCCESS )
1515 WARN("failed to save string table r=%08x\n",r);
1516 return r;
1519 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
1521 r = save_table( db, table );
1522 if( r != ERROR_SUCCESS )
1524 WARN("failed to save table %s (r=%08x)\n",
1525 debugstr_w(table->name), r);
1526 return r;
1530 /* force everything to reload next time */
1531 free_cached_tables( db );
1533 return ERROR_SUCCESS;