d3d8: Hold the lock in IDirect3DIndexBuffer8 methods.
[wine.git] / dlls / msi / table.c
blob9c78743ca2402ab0e2588c705ee1805eccb28aaf
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
45 #define LONG_STR_BYTES 3
47 typedef struct tagMSICOLUMNHASHENTRY
49 struct tagMSICOLUMNHASHENTRY *next;
50 UINT value;
51 UINT row;
52 } MSICOLUMNHASHENTRY;
54 typedef struct tagMSICOLUMNINFO
56 LPCWSTR tablename;
57 UINT number;
58 LPCWSTR colname;
59 UINT type;
60 UINT offset;
61 MSICOLUMNHASHENTRY **hash_table;
62 } MSICOLUMNINFO;
64 struct tagMSITABLE
66 BYTE **data;
67 UINT row_count;
68 BYTE **nonpersistent_data;
69 UINT nonpersistent_row_count;
70 struct list entry;
71 MSICOLUMNINFO *colinfo;
72 UINT col_count;
73 BOOL persistent;
74 WCHAR name[1];
77 typedef struct tagMSITRANSFORM {
78 struct list entry;
79 IStorage *stg;
80 } MSITRANSFORM;
82 static const WCHAR szStringData[] = {
83 '_','S','t','r','i','n','g','D','a','t','a',0 };
84 static const WCHAR szStringPool[] = {
85 '_','S','t','r','i','n','g','P','o','o','l',0 };
87 /* information for default tables */
88 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
89 static const WCHAR szTable[] = { 'T','a','b','l','e',0 };
90 static const WCHAR szName[] = { 'N','a','m','e',0 };
91 static const WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
92 static const WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
93 static const WCHAR szType[] = { 'T','y','p','e',0 };
95 /* These tables are written into (the .hash_table part).
96 * Do not mark them const.
98 static MSICOLUMNINFO _Columns_cols[4] = {
99 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
100 { szColumns, 2, szNumber, MSITYPE_VALID | 2, 2 },
101 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4 },
102 { szColumns, 4, szType, MSITYPE_VALID | 2, 6 },
104 static MSICOLUMNINFO _Tables_cols[1] = {
105 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
108 #define MAX_STREAM_NAME 0x1f
110 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
111 MSICOLUMNINFO **pcols, UINT *pcount );
112 static void table_calc_column_offsets( MSICOLUMNINFO *colinfo, DWORD count );
113 static UINT get_tablecolumns( MSIDATABASE *db,
114 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
115 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
118 void msi_table_set_strref(UINT bytes_per_strref)
120 _Columns_cols[0].offset = 0;
121 _Columns_cols[1].offset = bytes_per_strref;
122 _Columns_cols[2].offset = _Columns_cols[1].offset + sizeof(USHORT);
123 _Columns_cols[3].offset = _Columns_cols[2].offset + bytes_per_strref;
126 static inline UINT bytes_per_column( const MSICOLUMNINFO *col )
128 if( col->type & MSITYPE_STRING )
129 return _Columns_cols[1].offset;
130 if( (col->type & 0xff) > 4 )
131 ERR("Invalid column size!\n");
132 return col->type & 0xff;
135 static int utf2mime(int x)
137 if( (x>='0') && (x<='9') )
138 return x-'0';
139 if( (x>='A') && (x<='Z') )
140 return x-'A'+10;
141 if( (x>='a') && (x<='z') )
142 return x-'a'+10+26;
143 if( x=='.' )
144 return 10+26+26;
145 if( x=='_' )
146 return 10+26+26+1;
147 return -1;
150 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
152 DWORD count = MAX_STREAM_NAME;
153 DWORD ch, next;
154 LPWSTR out, p;
156 if( !bTable )
157 count = lstrlenW( in )+2;
158 out = msi_alloc( count*sizeof(WCHAR) );
159 p = out;
161 if( bTable )
163 *p++ = 0x4840;
164 count --;
166 while( count -- )
168 ch = *in++;
169 if( !ch )
171 *p = ch;
172 return out;
174 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
176 ch = utf2mime(ch) + 0x4800;
177 next = *in;
178 if( next && (next<0x80) )
180 next = utf2mime(next);
181 if( next >= 0 )
183 next += 0x3ffffc0;
184 ch += (next<<6);
185 in++;
189 *p++ = ch;
191 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
192 msi_free( out );
193 return NULL;
196 static int mime2utf(int x)
198 if( x<10 )
199 return x + '0';
200 if( x<(10+26))
201 return x - 10 + 'A';
202 if( x<(10+26+26))
203 return x - 10 - 26 + 'a';
204 if( x == (10+26+26) )
205 return '.';
206 return '_';
209 BOOL decode_streamname(LPWSTR in, LPWSTR out)
211 WCHAR ch;
212 DWORD count = 0;
214 while ( (ch = *in++) )
216 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
218 if( ch >= 0x4800 )
219 ch = mime2utf(ch-0x4800);
220 else
222 ch -= 0x3800;
223 *out++ = mime2utf(ch&0x3f);
224 count++;
225 ch = mime2utf((ch>>6)&0x3f);
228 *out++ = ch;
229 count++;
231 *out = 0;
232 return count;
235 void enum_stream_names( IStorage *stg )
237 IEnumSTATSTG *stgenum = NULL;
238 HRESULT r;
239 STATSTG stat;
240 ULONG n, count;
241 WCHAR name[0x40];
243 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
244 if( FAILED( r ) )
245 return;
247 n = 0;
248 while( 1 )
250 count = 0;
251 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
252 if( FAILED( r ) || !count )
253 break;
254 decode_streamname( stat.pwcsName, name );
255 TRACE("stream %2d -> %s %s\n", n,
256 debugstr_w(stat.pwcsName), debugstr_w(name) );
257 n++;
260 IEnumSTATSTG_Release( stgenum );
263 UINT read_stream_data( IStorage *stg, LPCWSTR stname,
264 USHORT **pdata, UINT *psz )
266 HRESULT r;
267 UINT ret = ERROR_FUNCTION_FAILED;
268 VOID *data;
269 ULONG sz, count;
270 IStream *stm = NULL;
271 STATSTG stat;
272 LPWSTR encname;
274 encname = encode_streamname(TRUE, stname);
276 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
278 r = IStorage_OpenStream(stg, encname, NULL,
279 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
280 msi_free( encname );
281 if( FAILED( r ) )
283 WARN("open stream failed r = %08x - empty table?\n", r);
284 return ret;
287 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
288 if( FAILED( r ) )
290 WARN("open stream failed r = %08x!\n", r);
291 goto end;
294 if( stat.cbSize.QuadPart >> 32 )
296 WARN("Too big!\n");
297 goto end;
300 sz = stat.cbSize.QuadPart;
301 data = msi_alloc( sz );
302 if( !data )
304 WARN("couldn't allocate memory r=%08x!\n", r);
305 ret = ERROR_NOT_ENOUGH_MEMORY;
306 goto end;
309 r = IStream_Read(stm, data, sz, &count );
310 if( FAILED( r ) || ( count != sz ) )
312 msi_free( data );
313 WARN("read stream failed r = %08x!\n", r);
314 goto end;
317 *pdata = data;
318 *psz = sz;
319 ret = ERROR_SUCCESS;
321 end:
322 IStream_Release( stm );
324 return ret;
327 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
329 LPWSTR encname;
330 HRESULT r;
332 encname = encode_streamname(FALSE, stname);
334 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
336 r = IStorage_OpenStream(db->storage, encname, NULL,
337 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
338 if( FAILED( r ) )
340 MSITRANSFORM *transform;
342 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
344 TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
345 r = IStorage_OpenStream( transform->stg, encname, NULL,
346 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
347 if (SUCCEEDED(r))
348 break;
352 msi_free( encname );
354 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
357 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
358 USHORT **pdata, UINT *psz )
360 HRESULT r;
361 UINT ret = ERROR_FUNCTION_FAILED;
362 VOID *data;
363 ULONG sz, count;
364 IStream *stm = NULL;
365 STATSTG stat;
367 r = db_get_raw_stream( db, stname, &stm );
368 if( r != ERROR_SUCCESS)
369 return ret;
370 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
371 if( FAILED( r ) )
373 WARN("open stream failed r = %08x!\n", r);
374 goto end;
377 if( stat.cbSize.QuadPart >> 32 )
379 WARN("Too big!\n");
380 goto end;
383 sz = stat.cbSize.QuadPart;
384 data = msi_alloc( sz );
385 if( !data )
387 WARN("couldn't allocate memory r=%08x!\n", r);
388 ret = ERROR_NOT_ENOUGH_MEMORY;
389 goto end;
392 r = IStream_Read(stm, data, sz, &count );
393 if( FAILED( r ) || ( count != sz ) )
395 msi_free( data );
396 WARN("read stream failed r = %08x!\n", r);
397 goto end;
400 *pdata = data;
401 *psz = sz;
402 ret = ERROR_SUCCESS;
404 end:
405 IStream_Release( stm );
407 return ret;
410 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
411 LPVOID data, UINT sz, BOOL bTable )
413 HRESULT r;
414 UINT ret = ERROR_FUNCTION_FAILED;
415 ULONG count;
416 IStream *stm = NULL;
417 ULARGE_INTEGER size;
418 LARGE_INTEGER pos;
419 LPWSTR encname;
421 encname = encode_streamname(bTable, stname );
422 r = IStorage_OpenStream( stg, encname, NULL,
423 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
424 if( FAILED(r) )
426 r = IStorage_CreateStream( stg, encname,
427 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
429 msi_free( encname );
430 if( FAILED( r ) )
432 WARN("open stream failed r = %08x\n", r);
433 return ret;
436 size.QuadPart = sz;
437 r = IStream_SetSize( stm, size );
438 if( FAILED( r ) )
440 WARN("Failed to SetSize\n");
441 goto end;
444 pos.QuadPart = 0;
445 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
446 if( FAILED( r ) )
448 WARN("Failed to Seek\n");
449 goto end;
452 if (sz)
454 r = IStream_Write(stm, data, sz, &count );
455 if( FAILED( r ) || ( count != sz ) )
457 WARN("Failed to Write\n");
458 goto end;
462 ret = ERROR_SUCCESS;
464 end:
465 IStream_Release( stm );
467 return ret;
470 static void free_table( MSITABLE *table )
472 int i;
473 for( i=0; i<table->row_count; i++ )
474 msi_free( table->data[i] );
475 msi_free( table->data );
476 for( i=0; i<table->nonpersistent_row_count; i++ )
477 msi_free( table->nonpersistent_data[i] );
478 msi_free( table->nonpersistent_data );
479 if( (table->colinfo != _Tables_cols) &&
480 (table->colinfo != _Columns_cols) )
482 msi_free_colinfo( table->colinfo, table->col_count );
483 msi_free( table->colinfo );
485 msi_free( table );
488 static UINT msi_table_get_row_size( const MSICOLUMNINFO *cols, UINT count )
490 const MSICOLUMNINFO *last_col = &cols[count-1];
491 if (!count)
492 return 0;
493 return last_col->offset + bytes_per_column( last_col );
496 /* add this table to the list of cached tables in the database */
497 static UINT read_table_from_storage( MSITABLE *t, IStorage *stg )
499 BYTE *rawdata = NULL;
500 UINT rawsize = 0, i, j, row_size = 0;
502 TRACE("%s\n",debugstr_w(t->name));
504 row_size = msi_table_get_row_size( t->colinfo, t->col_count );
506 /* if we can't read the table, just assume that it's empty */
507 read_stream_data( stg, t->name, (USHORT **)&rawdata, &rawsize );
508 if( !rawdata )
509 return ERROR_SUCCESS;
511 TRACE("Read %d bytes\n", rawsize );
513 if( rawsize % row_size )
515 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
516 goto err;
519 t->row_count = rawsize / row_size;
520 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
521 if( !t->data )
522 goto err;
524 /* transpose all the data */
525 TRACE("Transposing data from %d rows\n", t->row_count );
526 for( i=0; i<t->row_count; i++ )
528 t->data[i] = msi_alloc( row_size );
529 if( !t->data[i] )
530 goto err;
532 for( j=0; j<t->col_count; j++ )
534 UINT ofs = t->colinfo[j].offset;
535 UINT n = bytes_per_column( &t->colinfo[j] );
536 UINT k;
538 if ( n != 2 && n != 3 && n != 4 )
540 ERR("oops - unknown column width %d\n", n);
541 goto err;
544 for ( k = 0; k < n; k++ )
545 t->data[i][ofs + k] = rawdata[ofs*t->row_count + i * n + k];
549 msi_free( rawdata );
550 return ERROR_SUCCESS;
551 err:
552 msi_free( rawdata );
553 return ERROR_FUNCTION_FAILED;
556 void free_cached_tables( MSIDATABASE *db )
558 while( !list_empty( &db->tables ) )
560 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
562 list_remove( &t->entry );
563 free_table( t );
567 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
569 MSITABLE *t;
571 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
572 if( !lstrcmpW( name, t->name ) )
573 return t;
575 return NULL;
578 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
580 UINT r, column_count = 0;
581 MSICOLUMNINFO *columns;
583 /* get the number of columns in this table */
584 column_count = 0;
585 r = get_tablecolumns( db, name, NULL, &column_count );
586 if( r != ERROR_SUCCESS )
587 return r;
589 /* if there's no columns, there's no table */
590 if( column_count == 0 )
591 return ERROR_INVALID_PARAMETER;
593 TRACE("Table %s found\n", debugstr_w(name) );
595 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
596 if( !columns )
597 return ERROR_FUNCTION_FAILED;
599 r = get_tablecolumns( db, name, columns, &column_count );
600 if( r != ERROR_SUCCESS )
602 msi_free( columns );
603 return ERROR_FUNCTION_FAILED;
606 *pcols = columns;
607 *pcount = column_count;
609 return r;
612 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
613 BOOL persistent, MSITABLE **table_ret)
615 UINT r, nField;
616 MSIVIEW *tv = NULL;
617 MSIRECORD *rec = NULL;
618 column_info *col;
619 MSITABLE *table;
620 UINT i;
622 /* only add tables that don't exist already */
623 if( TABLE_Exists(db, name ) )
625 WARN("table %s exists\n", debugstr_w(name));
626 return ERROR_BAD_QUERY_SYNTAX;
629 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
630 if( !table )
631 return ERROR_FUNCTION_FAILED;
633 table->row_count = 0;
634 table->data = NULL;
635 table->nonpersistent_row_count = 0;
636 table->nonpersistent_data = NULL;
637 table->colinfo = NULL;
638 table->col_count = 0;
639 table->persistent = persistent;
640 lstrcpyW( table->name, name );
642 for( col = col_info; col; col = col->next )
643 table->col_count++;
645 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
646 if (!table->colinfo)
648 free_table( table );
649 return ERROR_FUNCTION_FAILED;
652 for( i = 0, col = col_info; col; i++, col = col->next )
654 table->colinfo[ i ].tablename = strdupW( col->table );
655 table->colinfo[ i ].number = i + 1;
656 table->colinfo[ i ].colname = strdupW( col->column );
657 table->colinfo[ i ].type = col->type;
658 table->colinfo[ i ].offset = 0;
659 table->colinfo[ i ].hash_table = NULL;
661 table_calc_column_offsets( table->colinfo, table->col_count);
663 r = TABLE_CreateView( db, szTables, &tv );
664 TRACE("CreateView returned %x\n", r);
665 if( r )
667 free_table( table );
668 return r;
671 r = tv->ops->execute( tv, 0 );
672 TRACE("tv execute returned %x\n", r);
673 if( r )
674 goto err;
676 rec = MSI_CreateRecord( 1 );
677 if( !rec )
678 goto err;
680 r = MSI_RecordSetStringW( rec, 1, name );
681 if( r )
682 goto err;
684 r = tv->ops->insert_row( tv, rec, !persistent );
685 TRACE("insert_row returned %x\n", r);
686 if( r )
687 goto err;
689 tv->ops->delete( tv );
690 tv = NULL;
692 msiobj_release( &rec->hdr );
693 rec = NULL;
695 if( persistent )
697 /* add each column to the _Columns table */
698 r = TABLE_CreateView( db, szColumns, &tv );
699 if( r )
700 return r;
702 r = tv->ops->execute( tv, 0 );
703 TRACE("tv execute returned %x\n", r);
704 if( r )
705 goto err;
707 rec = MSI_CreateRecord( 4 );
708 if( !rec )
709 goto err;
711 r = MSI_RecordSetStringW( rec, 1, name );
712 if( r )
713 goto err;
716 * need to set the table, column number, col name and type
717 * for each column we enter in the table
719 nField = 1;
720 for( col = col_info; col; col = col->next )
722 r = MSI_RecordSetInteger( rec, 2, nField );
723 if( r )
724 goto err;
726 r = MSI_RecordSetStringW( rec, 3, col->column );
727 if( r )
728 goto err;
730 r = MSI_RecordSetInteger( rec, 4, col->type );
731 if( r )
732 goto err;
734 r = tv->ops->insert_row( tv, rec, FALSE );
735 if( r )
736 goto err;
738 nField++;
740 if( !col )
741 r = ERROR_SUCCESS;
744 err:
745 if (rec)
746 msiobj_release( &rec->hdr );
747 /* FIXME: remove values from the string table on error */
748 if( tv )
749 tv->ops->delete( tv );
751 if (r == ERROR_SUCCESS)
753 list_add_head( &db->tables, &table->entry );
754 *table_ret = table;
756 else
757 free_table( table );
759 return r;
762 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
764 MSITABLE *table;
765 UINT r;
767 /* first, see if the table is cached */
768 table = find_cached_table( db, name );
769 if( table )
771 *table_ret = table;
772 return ERROR_SUCCESS;
775 /* nonexistent tables should be interpreted as empty tables */
776 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
777 if( !table )
778 return ERROR_FUNCTION_FAILED;
780 table->row_count = 0;
781 table->data = NULL;
782 table->nonpersistent_row_count = 0;
783 table->nonpersistent_data = NULL;
784 table->colinfo = NULL;
785 table->col_count = 0;
786 table->persistent = TRUE;
787 lstrcpyW( table->name, name );
789 /* these two tables are special - we know the column types already */
790 if( !lstrcmpW( name, szColumns ) )
792 table->colinfo = _Columns_cols;
793 table->col_count = sizeof(_Columns_cols)/sizeof(_Columns_cols[0]);
795 else if( !lstrcmpW( name, szTables ) )
797 table->colinfo = _Tables_cols;
798 table->col_count = sizeof(_Tables_cols)/sizeof(_Tables_cols[0]);
800 else
802 r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
803 if (r != ERROR_SUCCESS)
805 free_table ( table );
806 return r;
810 r = read_table_from_storage( table, db->storage );
811 if( r != ERROR_SUCCESS )
813 free_table( table );
814 return r;
817 list_add_head( &db->tables, &table->entry );
818 *table_ret = table;
819 return ERROR_SUCCESS;
822 static UINT save_table( MSIDATABASE *db, MSITABLE *t )
824 BYTE *rawdata = NULL, *p;
825 UINT rawsize, r, i, j, row_size;
827 /* Nothing to do for non-persistent tables */
828 if( !t->persistent )
829 return ERROR_SUCCESS;
831 TRACE("Saving %s\n", debugstr_w( t->name ) );
833 row_size = msi_table_get_row_size( t->colinfo, t->col_count );
835 rawsize = t->row_count * row_size;
836 rawdata = msi_alloc_zero( rawsize );
837 if( !rawdata )
839 r = ERROR_NOT_ENOUGH_MEMORY;
840 goto err;
843 p = rawdata;
844 for( i=0; i<t->col_count; i++ )
846 for( j=0; j<t->row_count; j++ )
848 UINT offset = t->colinfo[i].offset;
850 *p++ = t->data[j][offset];
851 *p++ = t->data[j][offset + 1];
852 if( 4 == bytes_per_column( &t->colinfo[i] ) )
854 *p++ = t->data[j][offset + 2];
855 *p++ = t->data[j][offset + 3];
860 TRACE("writing %d bytes\n", rawsize);
861 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
863 err:
864 msi_free( rawdata );
866 return r;
869 static void table_calc_column_offsets( MSICOLUMNINFO *colinfo, DWORD count )
871 DWORD i;
873 for( i=0; colinfo && (i<count); i++ )
875 assert( (i+1) == colinfo[ i ].number );
876 if (i)
877 colinfo[i].offset = colinfo[ i - 1 ].offset
878 + bytes_per_column( &colinfo[ i - 1 ] );
879 else
880 colinfo[i].offset = 0;
881 TRACE("column %d is [%s] with type %08x ofs %d\n",
882 colinfo[i].number, debugstr_w(colinfo[i].colname),
883 colinfo[i].type, colinfo[i].offset);
887 static UINT get_defaulttablecolumns( LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz)
889 const MSICOLUMNINFO *p;
890 DWORD i, n;
892 TRACE("%s\n", debugstr_w(name));
894 if (!lstrcmpW( name, szTables ))
896 p = _Tables_cols;
897 n = 1;
899 else if (!lstrcmpW( name, szColumns ))
901 p = _Columns_cols;
902 n = 4;
904 else
905 return ERROR_FUNCTION_FAILED;
907 /* duplicate the string data so we can free it in msi_free_colinfo */
908 for (i=0; i<n; i++)
910 if (colinfo && (i < *sz) )
912 memcpy( &colinfo[i], &p[i], sizeof(MSICOLUMNINFO) );
913 colinfo[i].tablename = strdupW( p[i].tablename );
914 colinfo[i].colname = strdupW( p[i].colname );
916 if( colinfo && (i >= *sz) )
917 break;
919 table_calc_column_offsets( colinfo, n );
920 *sz = n;
921 return ERROR_SUCCESS;
924 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
926 UINT i;
928 for( i=0; i<count; i++ )
930 msi_free( (LPWSTR) colinfo[i].tablename );
931 msi_free( (LPWSTR) colinfo[i].colname );
932 msi_free( colinfo[i].hash_table );
936 static LPWSTR msi_makestring( MSIDATABASE *db, UINT stringid)
938 return strdupW(msi_string_lookup_id( db->strings, stringid ));
941 static UINT read_table_int(BYTE **data, UINT row, UINT col, UINT bytes)
943 UINT ret = 0, i;
945 for (i = 0; i < bytes; i++)
946 ret += (data[row][col + i] << i * 8);
948 return ret;
951 static UINT get_tablecolumns( MSIDATABASE *db,
952 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
954 UINT r, i, n=0, table_id, count, maxcount = *sz;
955 MSITABLE *table = NULL;
957 TRACE("%s\n", debugstr_w(szTableName));
959 /* first check if there is a default table with that name */
960 r = get_defaulttablecolumns( szTableName, colinfo, sz );
961 if( ( r == ERROR_SUCCESS ) && *sz )
962 return r;
964 r = get_table( db, szColumns, &table );
965 if( r != ERROR_SUCCESS )
967 ERR("couldn't load _Columns table\n");
968 return ERROR_FUNCTION_FAILED;
971 /* convert table and column names to IDs from the string table */
972 r = msi_string2idW( db->strings, szTableName, &table_id );
973 if( r != ERROR_SUCCESS )
975 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
976 return r;
979 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
981 /* Note: _Columns table doesn't have non-persistent data */
983 /* if maxcount is non-zero, assume it's exactly right for this table */
984 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
985 count = table->row_count;
986 for( i=0; i<count; i++ )
988 if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
989 continue;
990 if( colinfo )
992 UINT id = read_table_int(table->data, i, _Columns_cols[2].offset, db->bytes_per_strref);
993 UINT col = read_table_int(table->data, i, _Columns_cols[1].offset, sizeof(USHORT)) - (1<<15);
995 /* check the column number is in range */
996 if (col<1 || col>maxcount)
998 ERR("column %d out of range\n", col);
999 continue;
1002 /* check if this column was already set */
1003 if (colinfo[ col - 1 ].number)
1005 ERR("duplicate column %d\n", col);
1006 continue;
1009 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
1010 colinfo[ col - 1 ].number = col;
1011 colinfo[ col - 1 ].colname = msi_makestring( db, id );
1012 colinfo[ col - 1 ].type = read_table_int(table->data, i, _Columns_cols[3].offset, sizeof(USHORT)) - (1<<15);
1013 colinfo[ col - 1 ].offset = 0;
1014 colinfo[ col - 1 ].hash_table = NULL;
1016 n++;
1019 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
1021 if (colinfo && n != maxcount)
1023 ERR("missing column in table %s\n", debugstr_w(szTableName));
1024 msi_free_colinfo(colinfo, maxcount );
1025 return ERROR_FUNCTION_FAILED;
1028 table_calc_column_offsets( colinfo, n );
1029 *sz = n;
1031 return ERROR_SUCCESS;
1034 /* try to find the table name in the _Tables table */
1035 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1037 UINT r, table_id = 0, i, count;
1038 MSITABLE *table = NULL;
1040 if( !lstrcmpW( name, szTables ) )
1041 return TRUE;
1042 if( !lstrcmpW( name, szColumns ) )
1043 return TRUE;
1045 r = msi_string2idW( db->strings, name, &table_id );
1046 if( r != ERROR_SUCCESS )
1048 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1049 return FALSE;
1052 r = get_table( db, szTables, &table );
1053 if( r != ERROR_SUCCESS )
1055 ERR("table %s not available\n", debugstr_w(szTables));
1056 return FALSE;
1059 count = table->row_count;
1060 for( i=0; i<count; i++ )
1061 if( table->data[ i ][ 0 ] == table_id )
1062 break;
1064 if (i!=count)
1065 return TRUE;
1067 count = table->nonpersistent_row_count;
1068 for( i=0; i<count; i++ )
1069 if( table->nonpersistent_data[ i ][ 0 ] == table_id )
1070 break;
1072 if (i!=count)
1073 return TRUE;
1075 TRACE("Searched %d tables, but %d was not found\n", count, table_id );
1077 return FALSE;
1080 /* below is the query interface to a table */
1082 typedef struct tagMSITABLEVIEW
1084 MSIVIEW view;
1085 MSIDATABASE *db;
1086 MSITABLE *table;
1087 MSICOLUMNINFO *columns;
1088 UINT num_cols;
1089 UINT row_size;
1090 WCHAR name[1];
1091 } MSITABLEVIEW;
1093 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1095 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1096 UINT offset, n;
1097 BYTE **data;
1099 if( !tv->table )
1100 return ERROR_INVALID_PARAMETER;
1102 if( (col==0) || (col>tv->num_cols) )
1103 return ERROR_INVALID_PARAMETER;
1105 /* how many rows are there ? */
1106 if( row >= tv->table->row_count + tv->table->nonpersistent_row_count )
1107 return ERROR_NO_MORE_ITEMS;
1109 if( tv->columns[col-1].offset >= tv->row_size )
1111 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1112 ERR("%p %p\n", tv, tv->columns );
1113 return ERROR_FUNCTION_FAILED;
1116 if (row >= tv->table->row_count)
1118 row -= tv->table->row_count;
1119 data = tv->table->nonpersistent_data;
1121 else
1122 data = tv->table->data;
1124 n = bytes_per_column( &tv->columns[col-1] );
1125 if (n != 2 && n != 3 && n != 4)
1127 ERR("oops! what is %d bytes per column?\n", n );
1128 return ERROR_FUNCTION_FAILED;
1131 offset = tv->columns[col-1].offset;
1132 *val = read_table_int(data, row, offset, n);
1134 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1136 return ERROR_SUCCESS;
1140 * We need a special case for streams, as we need to reference column with
1141 * the name of the stream in the same table, and the table name
1142 * which may not be available at higher levels of the query
1144 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1146 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1147 UINT ival = 0, refcol = 0, r;
1148 LPCWSTR sval;
1149 LPWSTR full_name;
1150 DWORD len;
1151 static const WCHAR szDot[] = { '.', 0 };
1152 WCHAR number[0x20];
1154 if( !view->ops->fetch_int )
1155 return ERROR_INVALID_PARAMETER;
1158 * The column marked with the type stream data seems to have a single number
1159 * which references the column containing the name of the stream data
1161 * Fetch the column to reference first.
1163 r = view->ops->fetch_int( view, row, col, &ival );
1164 if( r != ERROR_SUCCESS )
1165 return r;
1167 /* check the column value is in range */
1168 if (ival < 0 || ival > tv->num_cols || ival == col)
1170 ERR("bad column ref (%u) for stream\n", ival);
1171 return ERROR_FUNCTION_FAILED;
1174 if ( tv->columns[ival - 1].type & MSITYPE_STRING )
1176 /* now get the column with the name of the stream */
1177 r = view->ops->fetch_int( view, row, ival, &refcol );
1178 if ( r != ERROR_SUCCESS )
1179 return r;
1181 /* lookup the string value from the string table */
1182 sval = msi_string_lookup_id( tv->db->strings, refcol );
1183 if ( !sval )
1184 return ERROR_INVALID_PARAMETER;
1186 else
1188 static const WCHAR fmt[] = { '%','d',0 };
1189 sprintfW( number, fmt, ival );
1190 sval = number;
1193 len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1194 full_name = msi_alloc( len*sizeof(WCHAR) );
1195 lstrcpyW( full_name, tv->name );
1196 lstrcatW( full_name, szDot );
1197 lstrcatW( full_name, sval );
1199 r = db_get_raw_stream( tv->db, full_name, stm );
1200 if( r )
1201 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1202 msi_free( full_name );
1204 return r;
1207 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1209 UINT offset, n, i;
1210 BYTE **data;
1212 if( !tv->table )
1213 return ERROR_INVALID_PARAMETER;
1215 if( (col==0) || (col>tv->num_cols) )
1216 return ERROR_INVALID_PARAMETER;
1218 if( row >= tv->table->row_count + tv->table->nonpersistent_row_count )
1219 return ERROR_INVALID_PARAMETER;
1221 if( tv->columns[col-1].offset >= tv->row_size )
1223 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1224 ERR("%p %p\n", tv, tv->columns );
1225 return ERROR_FUNCTION_FAILED;
1228 msi_free( tv->columns[col-1].hash_table );
1229 tv->columns[col-1].hash_table = NULL;
1231 if (row >= tv->table->row_count)
1233 row -= tv->table->row_count;
1234 data = tv->table->nonpersistent_data;
1236 else
1237 data = tv->table->data;
1239 n = bytes_per_column( &tv->columns[col-1] );
1240 if ( n != 2 && n != 3 && n != 4 )
1242 ERR("oops! what is %d bytes per column?\n", n );
1243 return ERROR_FUNCTION_FAILED;
1246 offset = tv->columns[col-1].offset;
1247 for ( i = 0; i < n; i++ )
1248 data[row][offset + i] = (val >> i * 8) & 0xff;
1250 return ERROR_SUCCESS;
1253 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1255 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1256 UINT i, val, r = ERROR_SUCCESS;
1258 if ( !tv->table )
1259 return ERROR_INVALID_PARAMETER;
1261 /* test if any of the mask bits are invalid */
1262 if ( mask >= (1<<tv->num_cols) )
1263 return ERROR_INVALID_PARAMETER;
1265 for ( i = 0; i < tv->num_cols; i++ )
1267 BOOL persistent;
1269 /* only update the fields specified in the mask */
1270 if ( !(mask&(1<<i)) )
1271 continue;
1273 /* if row >= tv->table->row_count then it is a non-persistent row */
1274 persistent = tv->table->persistent && (row < tv->table->row_count);
1275 /* FIXME: should we allow updating keys? */
1277 val = 0;
1278 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1280 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1282 val = 1; /* refers to the first key column */
1284 else if ( tv->columns[i].type & MSITYPE_STRING )
1286 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1287 val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
1288 persistent ? StringPersistent : StringNonPersistent );
1290 else if ( 2 == bytes_per_column( &tv->columns[ i ] ) )
1292 val = 0x8000 + MSI_RecordGetInteger( rec, i + 1 );
1293 if ( val & 0xffff0000 )
1295 ERR("field %u value %d out of range\n", i+1, val - 0x8000 );
1296 return ERROR_FUNCTION_FAILED;
1299 else
1301 INT ival = MSI_RecordGetInteger( rec, i + 1 );
1302 val = ival ^ 0x80000000;
1306 r = TABLE_set_int( tv, row, i+1, val );
1307 if ( r != ERROR_SUCCESS )
1308 break;
1310 return r;
1313 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1315 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1316 BYTE **p, *row;
1317 UINT sz;
1318 BYTE ***data_ptr;
1319 UINT *row_count;
1321 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1323 if( !tv->table )
1324 return ERROR_INVALID_PARAMETER;
1326 row = msi_alloc_zero( tv->row_size );
1327 if( !row )
1328 return ERROR_NOT_ENOUGH_MEMORY;
1330 if( temporary )
1332 row_count = &tv->table->nonpersistent_row_count;
1333 data_ptr = &tv->table->nonpersistent_data;
1334 *num = tv->table->row_count + tv->table->nonpersistent_row_count;
1336 else
1338 row_count = &tv->table->row_count;
1339 data_ptr = &tv->table->data;
1340 *num = tv->table->row_count;
1343 sz = (*row_count + 1) * sizeof (BYTE*);
1344 if( *data_ptr )
1345 p = msi_realloc( *data_ptr, sz );
1346 else
1347 p = msi_alloc( sz );
1348 if( !p )
1350 msi_free( row );
1351 return ERROR_NOT_ENOUGH_MEMORY;
1354 *data_ptr = p;
1355 (*data_ptr)[*row_count] = row;
1356 (*row_count)++;
1358 return ERROR_SUCCESS;
1361 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1363 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1365 TRACE("%p %p\n", tv, record);
1367 TRACE("There are %d columns\n", tv->num_cols );
1369 return ERROR_SUCCESS;
1372 static UINT TABLE_close( struct tagMSIVIEW *view )
1374 TRACE("%p\n", view );
1376 return ERROR_SUCCESS;
1379 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1381 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1383 TRACE("%p %p %p\n", view, rows, cols );
1385 if( cols )
1386 *cols = tv->num_cols;
1387 if( rows )
1389 if( !tv->table )
1390 return ERROR_INVALID_PARAMETER;
1391 *rows = tv->table->row_count + tv->table->nonpersistent_row_count;
1394 return ERROR_SUCCESS;
1397 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1398 UINT n, LPWSTR *name, UINT *type )
1400 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1402 TRACE("%p %d %p %p\n", tv, n, name, type );
1404 if( ( n == 0 ) || ( n > tv->num_cols ) )
1405 return ERROR_INVALID_PARAMETER;
1407 if( name )
1409 *name = strdupW( tv->columns[n-1].colname );
1410 if( !*name )
1411 return ERROR_FUNCTION_FAILED;
1413 if( type )
1414 *type = tv->columns[n-1].type;
1416 return ERROR_SUCCESS;
1419 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1421 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1423 UINT r, row, i;
1425 /* check there's no null values where they're not allowed */
1426 for( i = 0; i < tv->num_cols; i++ )
1428 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1429 continue;
1431 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1432 TRACE("skipping binary column\n");
1433 else if ( tv->columns[i].type & MSITYPE_STRING )
1435 LPCWSTR str;
1437 str = MSI_RecordGetString( rec, i+1 );
1438 if (str == NULL || str[0] == 0)
1439 return ERROR_INVALID_DATA;
1441 else
1443 UINT n;
1445 n = MSI_RecordGetInteger( rec, i+1 );
1446 if (n == MSI_NULL_INTEGER)
1447 return ERROR_INVALID_DATA;
1451 /* check there's no duplicate keys */
1452 r = msi_table_find_row( tv, rec, &row );
1453 if (r == ERROR_SUCCESS)
1454 return ERROR_INVALID_DATA;
1456 return ERROR_SUCCESS;
1459 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, BOOL temporary )
1461 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1462 UINT r, row = -1;
1464 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1466 /* check that the key is unique - can we find a matching row? */
1467 r = table_validate_new( tv, rec );
1468 if( r != ERROR_SUCCESS )
1469 return ERROR_FUNCTION_FAILED;
1471 r = table_create_new_row( view, &row, temporary );
1472 TRACE("insert_row returned %08x\n", r);
1473 if( r != ERROR_SUCCESS )
1474 return r;
1476 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1479 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1480 MSIRECORD *rec)
1482 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1483 UINT r;
1485 TRACE("%p %d %p\n", view, eModifyMode, rec );
1487 switch (eModifyMode)
1489 case MSIMODIFY_VALIDATE_NEW:
1490 r = table_validate_new( tv, rec );
1491 break;
1493 case MSIMODIFY_INSERT_TEMPORARY:
1494 r = table_validate_new( tv, rec );
1495 if (r != ERROR_SUCCESS)
1496 break;
1497 r = TABLE_insert_row( view, rec, TRUE );
1498 break;
1500 case MSIMODIFY_REFRESH:
1501 case MSIMODIFY_INSERT:
1502 case MSIMODIFY_UPDATE:
1503 case MSIMODIFY_ASSIGN:
1504 case MSIMODIFY_REPLACE:
1505 case MSIMODIFY_MERGE:
1506 case MSIMODIFY_DELETE:
1507 case MSIMODIFY_VALIDATE:
1508 case MSIMODIFY_VALIDATE_FIELD:
1509 case MSIMODIFY_VALIDATE_DELETE:
1510 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1511 r = ERROR_CALL_NOT_IMPLEMENTED;
1512 break;
1514 default:
1515 r = ERROR_INVALID_DATA;
1518 return r;
1521 static UINT TABLE_delete( struct tagMSIVIEW *view )
1523 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1525 TRACE("%p\n", view );
1527 tv->table = NULL;
1529 tv->columns = NULL;
1531 msi_free( tv );
1533 return ERROR_SUCCESS;
1536 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1537 UINT val, UINT *row, MSIITERHANDLE *handle )
1539 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1540 const MSICOLUMNHASHENTRY *entry;
1542 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1544 if( !tv->table )
1545 return ERROR_INVALID_PARAMETER;
1547 if( (col==0) || (col > tv->num_cols) )
1548 return ERROR_INVALID_PARAMETER;
1550 if( !tv->columns[col-1].hash_table )
1552 UINT i;
1553 UINT num_rows = tv->table->row_count + tv->table->nonpersistent_row_count;
1554 MSICOLUMNHASHENTRY **hash_table;
1555 MSICOLUMNHASHENTRY *new_entry;
1557 if( tv->columns[col-1].offset >= tv->row_size )
1559 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1560 ERR("%p %p\n", tv, tv->columns );
1561 return ERROR_FUNCTION_FAILED;
1564 /* allocate contiguous memory for the table and its entries so we
1565 * don't have to do an expensive cleanup */
1566 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1567 num_rows * sizeof(MSICOLUMNHASHENTRY));
1568 if (!hash_table)
1569 return ERROR_OUTOFMEMORY;
1571 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1572 tv->columns[col-1].hash_table = hash_table;
1574 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1576 for (i = 0; i < num_rows; i++, new_entry++)
1578 UINT row_value;
1580 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1581 continue;
1583 new_entry->next = NULL;
1584 new_entry->value = row_value;
1585 new_entry->row = i;
1586 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1588 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1589 while (prev_entry->next)
1590 prev_entry = prev_entry->next;
1591 prev_entry->next = new_entry;
1593 else
1594 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1598 if( !*handle )
1599 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1600 else
1601 entry = (*handle)->next;
1603 while (entry && entry->value != val)
1604 entry = entry->next;
1606 *handle = entry;
1607 if (!entry)
1608 return ERROR_NO_MORE_ITEMS;
1610 *row = entry->row;
1611 return ERROR_SUCCESS;
1615 static const MSIVIEWOPS table_ops =
1617 TABLE_fetch_int,
1618 TABLE_fetch_stream,
1619 TABLE_set_row,
1620 TABLE_insert_row,
1621 TABLE_execute,
1622 TABLE_close,
1623 TABLE_get_dimensions,
1624 TABLE_get_column_info,
1625 TABLE_modify,
1626 TABLE_delete,
1627 TABLE_find_matching_rows
1630 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
1632 MSITABLEVIEW *tv ;
1633 UINT r, sz;
1635 static const WCHAR Streams[] = {'_','S','t','r','e','a','m','s',0};
1637 TRACE("%p %s %p\n", db, debugstr_w(name), view );
1639 if ( !lstrcmpW( name, Streams ) )
1640 return STREAMS_CreateView( db, view );
1642 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
1643 tv = msi_alloc_zero( sz );
1644 if( !tv )
1645 return ERROR_FUNCTION_FAILED;
1647 r = get_table( db, name, &tv->table );
1648 if( r != ERROR_SUCCESS )
1650 msi_free( tv );
1651 WARN("table not found\n");
1652 return r;
1655 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
1657 /* fill the structure */
1658 tv->view.ops = &table_ops;
1659 tv->db = db;
1660 tv->columns = tv->table->colinfo;
1661 tv->num_cols = tv->table->col_count;
1662 tv->row_size = msi_table_get_row_size( tv->table->colinfo, tv->table->col_count );
1664 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
1666 *view = (MSIVIEW*) tv;
1667 lstrcpyW( tv->name, name );
1669 return ERROR_SUCCESS;
1672 UINT MSI_CommitTables( MSIDATABASE *db )
1674 UINT r;
1675 MSITABLE *table = NULL;
1677 TRACE("%p\n",db);
1679 r = msi_save_string_table( db->strings, db->storage );
1680 if( r != ERROR_SUCCESS )
1682 WARN("failed to save string table r=%08x\n",r);
1683 return r;
1686 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
1688 r = save_table( db, table );
1689 if( r != ERROR_SUCCESS )
1691 WARN("failed to save table %s (r=%08x)\n",
1692 debugstr_w(table->name), r);
1693 return r;
1697 /* force everything to reload next time */
1698 free_cached_tables( db );
1700 return ERROR_SUCCESS;
1703 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
1705 MSITABLE *t;
1706 UINT r;
1708 TRACE("%p %s\n", db, debugstr_w(table));
1710 if (!table)
1711 return MSICONDITION_ERROR;
1713 r = get_table( db, table, &t );
1714 if (r != ERROR_SUCCESS)
1715 return MSICONDITION_NONE;
1717 if (t->persistent)
1718 return MSICONDITION_TRUE;
1719 else
1720 return MSICONDITION_FALSE;
1723 static MSIRECORD *msi_get_transform_record( MSITABLEVIEW *tv, string_table *st, USHORT *rawdata )
1725 UINT i, val, ofs = 0;
1726 USHORT mask = *rawdata++;
1727 MSICOLUMNINFO *columns = tv->columns;
1728 MSIRECORD *rec;
1730 rec = MSI_CreateRecord( tv->num_cols );
1731 if( !rec )
1732 return rec;
1734 TRACE("row ->\n");
1735 for( i=0; i<tv->num_cols; i++ )
1737 UINT n = bytes_per_column( &columns[i] );
1739 if ( (mask&1) && (i>=(mask>>8)) )
1740 break;
1741 /* all keys must be present */
1742 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
1743 continue;
1745 switch( n )
1747 case 2:
1748 val = rawdata[ofs];
1749 if( (columns[i].type & MSITYPE_STRING) &&
1750 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1752 LPCWSTR sval = msi_string_lookup_id( st, val );
1753 MSI_RecordSetStringW( rec, i+1, sval );
1754 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
1756 else
1758 if (val)
1759 MSI_RecordSetInteger( rec, i+1, val^0x8000 );
1760 TRACE(" field %d [0x%04x]\n", i+1, val );
1762 break;
1763 case 4:
1764 val = (rawdata[ofs] + (rawdata[ofs + 1]<<16));
1765 if (val)
1766 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
1767 TRACE(" field %d [0x%08x]\n", i+1, val );
1768 break;
1769 default:
1770 ERR("oops - unknown column width %d\n", n);
1771 break;
1773 ofs += n/2;
1775 return rec;
1778 static void dump_record( MSIRECORD *rec )
1780 UINT i, n;
1782 n = MSI_RecordGetFieldCount( rec );
1783 for( i=1; i<=n; i++ )
1785 LPCWSTR sval = MSI_RecordGetString( rec, i );
1787 if( MSI_RecordIsNull( rec, i ) )
1788 TRACE("row -> []\n");
1789 else if( (sval = MSI_RecordGetString( rec, i )) )
1790 TRACE("row -> [%s]\n", debugstr_w(sval));
1791 else
1792 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
1796 static void dump_table( string_table *st, USHORT *rawdata, UINT rawsize )
1798 LPCWSTR sval;
1799 UINT i;
1801 for( i=0; i<(rawsize/2); i++ )
1803 sval = msi_string_lookup_id( st, rawdata[i] );
1804 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
1808 static UINT* msi_record_to_row( MSITABLEVIEW *tv, MSIRECORD *rec )
1810 LPCWSTR str;
1811 UINT i, r, *data;
1813 data = msi_alloc( tv->num_cols *sizeof (UINT) );
1814 for( i=0; i<tv->num_cols; i++ )
1816 data[i] = 0;
1818 if ( ~tv->columns[i].type & MSITYPE_KEY )
1819 continue;
1821 /* turn the transform column value into a row value */
1822 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
1823 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1825 str = MSI_RecordGetString( rec, i+1 );
1826 r = msi_string2idW( tv->db->strings, str, &data[i] );
1828 /* if there's no matching string in the string table,
1829 these keys can't match any record, so fail now. */
1830 if( ERROR_SUCCESS != r )
1832 msi_free( data );
1833 return NULL;
1836 else
1838 data[i] = MSI_RecordGetInteger( rec, i+1 );
1839 if ((tv->columns[i].type&0xff) == 2)
1840 data[i] += 0x8000;
1841 else
1842 data[i] += 0x80000000;
1845 return data;
1848 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, UINT *data )
1850 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
1852 for( i=0; i<tv->num_cols; i++ )
1854 if ( ~tv->columns[i].type & MSITYPE_KEY )
1855 continue;
1857 /* turn the transform column value into a row value */
1858 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
1859 if ( r != ERROR_SUCCESS )
1861 ERR("TABLE_fetch_int shouldn't fail here\n");
1862 break;
1865 /* if this key matches, move to the next column */
1866 if ( x != data[i] )
1868 ret = ERROR_FUNCTION_FAILED;
1869 break;
1872 ret = ERROR_SUCCESS;
1875 return ret;
1878 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
1880 UINT i, r = ERROR_FUNCTION_FAILED, *data;
1882 data = msi_record_to_row( tv, rec );
1883 if( !data )
1884 return r;
1885 for( i = 0; i < tv->table->row_count + tv->table->nonpersistent_row_count; i++ )
1887 r = msi_row_matches( tv, i, data );
1888 if( r == ERROR_SUCCESS )
1890 *row = i;
1891 break;
1894 msi_free( data );
1895 return r;
1898 static UINT msi_delete_row( MSITABLEVIEW *tv, UINT row )
1900 UINT i;
1902 for( i=1; i<=tv->num_cols; i++ )
1903 TABLE_set_int( tv, row, i, 0 );
1904 return ERROR_SUCCESS;
1907 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
1908 string_table *st, LPCWSTR name )
1910 UINT rawsize = 0;
1911 USHORT *rawdata = NULL;
1912 MSITABLEVIEW *tv = NULL;
1913 UINT r, n, sz, i, mask;
1914 MSIRECORD *rec = NULL;
1915 UINT colcol = 0;
1916 WCHAR coltable[32];
1918 coltable[0] = 0;
1919 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
1921 /* read the transform data */
1922 read_stream_data( stg, name, &rawdata, &rawsize );
1923 if ( !rawdata )
1925 TRACE("table %s empty\n", debugstr_w(name) );
1926 return ERROR_INVALID_TABLE;
1929 /* create a table view */
1930 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
1931 if( r != ERROR_SUCCESS )
1932 goto err;
1934 r = tv->view.ops->execute( &tv->view, NULL );
1935 if( r != ERROR_SUCCESS )
1936 goto err;
1938 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
1939 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
1941 /* interpret the data */
1942 r = ERROR_SUCCESS;
1943 for( n=0; n < (rawsize/2); )
1945 mask = rawdata[n];
1947 if (mask&1)
1950 * if the low bit is set, columns are continuous and
1951 * the number of columns is specified in the high byte
1953 sz = 2 + tv->row_size;
1955 else
1958 * If the low bit is not set, rowdata[n] is a bitmask.
1959 * Excepting for key fields, which are always present,
1960 * each bit indicates that a field is present in the transform record.
1962 * rawdata[n] == 0 is a special case ... only the keys will be present
1963 * and it means that this row should be deleted.
1965 sz = 2;
1966 for( i=0; i<tv->num_cols; i++ )
1968 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
1969 sz += bytes_per_column( &tv->columns[i] );
1973 /* check we didn't run of the end of the table */
1974 if ( (n+sz) > rawsize )
1976 ERR("borked.\n");
1977 dump_table( st, rawdata, rawsize );
1978 break;
1981 rec = msi_get_transform_record( tv, st, &rawdata[n] );
1982 if (rec)
1984 if ( mask & 1 )
1986 TRACE("inserting record\n");
1989 * Native msi seems writes nul into the
1990 * Number (2nd) column of the _Columns table.
1991 * Not sure that it's deliberate...
1993 if (!lstrcmpW(name, szColumns))
1995 WCHAR table[32];
1996 DWORD sz = 32;
1998 MSI_RecordGetStringW( rec, 1, table, &sz );
2000 /* reset the column number on a new table */
2001 if ( lstrcmpW(coltable, table) )
2003 colcol = 0;
2004 lstrcpyW( coltable, table );
2007 /* fix nul column numbers */
2008 MSI_RecordSetInteger( rec, 2, ++colcol );
2011 r = TABLE_insert_row( &tv->view, rec, FALSE );
2012 if (r != ERROR_SUCCESS)
2013 ERR("insert row failed\n");
2015 else
2017 UINT row = 0;
2019 r = msi_table_find_row( tv, rec, &row );
2020 if (r != ERROR_SUCCESS)
2021 ERR("no matching row to transform\n");
2022 else if ( mask )
2024 TRACE("modifying row [%d]:\n", row);
2025 TABLE_set_row( &tv->view, row, rec, mask );
2027 else
2029 TRACE("deleting row [%d]:\n", row);
2030 msi_delete_row( tv, row );
2033 if( TRACE_ON(msidb) ) dump_record( rec );
2034 msiobj_release( &rec->hdr );
2037 n += sz/2;
2040 err:
2041 /* no need to free the table, it's associated with the database */
2042 msi_free( rawdata );
2043 if( tv )
2044 tv->view.ops->delete( &tv->view );
2046 return ERROR_SUCCESS;
2050 * msi_table_apply_transform
2052 * Enumerate the table transforms in a transform storage and apply each one.
2054 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2056 IEnumSTATSTG *stgenum = NULL;
2057 HRESULT r;
2058 STATSTG stat;
2059 ULONG count;
2060 WCHAR name[0x40];
2061 string_table *strings;
2062 UINT ret = ERROR_FUNCTION_FAILED;
2064 TRACE("%p %p\n", db, stg );
2066 strings = msi_load_string_table( stg, &db->bytes_per_strref );
2067 if( !strings )
2068 goto end;
2070 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2071 if( FAILED( r ) )
2072 goto end;
2075 * Apply _Tables and _Columns transforms first so that
2076 * the table metadata is correct, and empty tables exist.
2078 ret = msi_table_load_transform( db, stg, strings, szTables );
2079 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2080 goto end;
2082 ret = msi_table_load_transform( db, stg, strings, szColumns );
2083 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2084 goto end;
2086 ret = ERROR_SUCCESS;
2088 while( r == ERROR_SUCCESS )
2090 count = 0;
2091 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2092 if( FAILED( r ) || !count )
2093 break;
2095 decode_streamname( stat.pwcsName, name );
2096 if ( name[0] != 0x4840 )
2097 continue;
2099 TRACE("transform contains stream %s\n", debugstr_w(name));
2101 if ( !lstrcmpW( name+1, szStringPool ) ||
2102 !lstrcmpW( name+1, szStringData ) ||
2103 !lstrcmpW( name+1, szColumns ) ||
2104 !lstrcmpW( name+1, szTables ) )
2105 continue;
2107 ret = msi_table_load_transform( db, stg, strings, name+1 );
2110 if ( ret == ERROR_SUCCESS )
2111 append_storage_to_db( db, stg );
2113 end:
2114 if ( stgenum )
2115 IEnumSTATSTG_Release( stgenum );
2116 if ( strings )
2117 msi_destroy_stringtable( strings );
2119 return ret;
2122 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
2124 MSITRANSFORM *t;
2126 t = msi_alloc( sizeof *t );
2127 t->stg = stg;
2128 IStorage_AddRef( stg );
2129 list_add_tail( &db->transforms, &t->entry );
2132 void msi_free_transforms( MSIDATABASE *db )
2134 while( !list_empty( &db->transforms ) )
2136 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
2137 MSITRANSFORM, entry );
2138 list_remove( &t->entry );
2139 IStorage_Release( t->stg );
2140 msi_free( t );