push ac694015ba9a1d7cf8fc6346c6e51d4c35a62962
[wine/hacks.git] / dlls / msi / table.c
blob0b5b99164b9b691da06f75a877dd37e09c88b296
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 LPWSTR tablename;
57 UINT number;
58 LPWSTR colname;
59 UINT type;
60 UINT offset;
61 INT ref_count;
62 BOOL temporary;
63 MSICOLUMNHASHENTRY **hash_table;
64 } MSICOLUMNINFO;
66 typedef struct tagMSIORDERINFO
68 UINT *reorder;
69 UINT num_cols;
70 UINT cols[1];
71 } MSIORDERINFO;
73 struct tagMSITABLE
75 BYTE **data;
76 BOOL *data_persistent;
77 UINT row_count;
78 struct list entry;
79 MSICOLUMNINFO *colinfo;
80 UINT col_count;
81 MSICONDITION persistent;
82 INT ref_count;
83 WCHAR name[1];
86 typedef struct tagMSITRANSFORM {
87 struct list entry;
88 IStorage *stg;
89 } MSITRANSFORM;
91 static const WCHAR szStringData[] = {
92 '_','S','t','r','i','n','g','D','a','t','a',0 };
93 static const WCHAR szStringPool[] = {
94 '_','S','t','r','i','n','g','P','o','o','l',0 };
96 /* information for default tables */
97 static WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
98 static WCHAR szTable[] = { 'T','a','b','l','e',0 };
99 static WCHAR szName[] = { 'N','a','m','e',0 };
100 static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
101 static WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
102 static WCHAR szType[] = { 'T','y','p','e',0 };
104 static const MSICOLUMNINFO _Columns_cols[4] = {
105 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
106 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
107 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
108 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
111 static const MSICOLUMNINFO _Tables_cols[1] = {
112 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
115 #define MAX_STREAM_NAME 0x1f
117 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
118 MSICOLUMNINFO **pcols, UINT *pcount );
119 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
120 DWORD count );
121 static UINT get_tablecolumns( MSIDATABASE *db,
122 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
123 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
125 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col )
127 if( MSITYPE_IS_BINARY(col->type) )
128 return 2;
129 if( col->type & MSITYPE_STRING )
130 return db->bytes_per_strref;
131 if( (col->type & 0xff) > 4 )
132 ERR("Invalid column size!\n");
133 return col->type & 0xff;
136 static int utf2mime(int x)
138 if( (x>='0') && (x<='9') )
139 return x-'0';
140 if( (x>='A') && (x<='Z') )
141 return x-'A'+10;
142 if( (x>='a') && (x<='z') )
143 return x-'a'+10+26;
144 if( x=='.' )
145 return 10+26+26;
146 if( x=='_' )
147 return 10+26+26+1;
148 return -1;
151 static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
153 DWORD count = MAX_STREAM_NAME;
154 DWORD ch, next;
155 LPWSTR out, p;
157 if( !bTable )
158 count = lstrlenW( in )+2;
159 out = msi_alloc( count*sizeof(WCHAR) );
160 p = out;
162 if( bTable )
164 *p++ = 0x4840;
165 count --;
167 while( count -- )
169 ch = *in++;
170 if( !ch )
172 *p = ch;
173 return out;
175 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
177 ch = utf2mime(ch) + 0x4800;
178 next = *in;
179 if( next && (next<0x80) )
181 next = utf2mime(next);
182 if( next != -1 )
184 next += 0x3ffffc0;
185 ch += (next<<6);
186 in++;
190 *p++ = ch;
192 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
193 msi_free( out );
194 return NULL;
197 static int mime2utf(int x)
199 if( x<10 )
200 return x + '0';
201 if( x<(10+26))
202 return x - 10 + 'A';
203 if( x<(10+26+26))
204 return x - 10 - 26 + 'a';
205 if( x == (10+26+26) )
206 return '.';
207 return '_';
210 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
212 WCHAR ch;
213 DWORD count = 0;
215 while ( (ch = *in++) )
217 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
219 if( ch >= 0x4800 )
220 ch = mime2utf(ch-0x4800);
221 else
223 ch -= 0x3800;
224 *out++ = mime2utf(ch&0x3f);
225 count++;
226 ch = mime2utf((ch>>6)&0x3f);
229 *out++ = ch;
230 count++;
232 *out = 0;
233 return count;
236 void enum_stream_names( IStorage *stg )
238 IEnumSTATSTG *stgenum = NULL;
239 HRESULT r;
240 STATSTG stat;
241 ULONG n, count;
242 WCHAR name[0x40];
244 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
245 if( FAILED( r ) )
246 return;
248 n = 0;
249 while( 1 )
251 count = 0;
252 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
253 if( FAILED( r ) || !count )
254 break;
255 decode_streamname( stat.pwcsName, name );
256 TRACE("stream %2d -> %s %s\n", n,
257 debugstr_w(stat.pwcsName), debugstr_w(name) );
258 CoTaskMemFree( stat.pwcsName );
259 n++;
262 IEnumSTATSTG_Release( stgenum );
265 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
266 BYTE **pdata, UINT *psz )
268 HRESULT r;
269 UINT ret = ERROR_FUNCTION_FAILED;
270 VOID *data;
271 ULONG sz, count;
272 IStream *stm = NULL;
273 STATSTG stat;
274 LPWSTR encname;
276 encname = encode_streamname(table, stname);
278 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
280 r = IStorage_OpenStream(stg, encname, NULL,
281 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
282 msi_free( encname );
283 if( FAILED( r ) )
285 WARN("open stream failed r = %08x - empty table?\n", r);
286 return ret;
289 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
290 if( FAILED( r ) )
292 WARN("open stream failed r = %08x!\n", r);
293 goto end;
296 if( stat.cbSize.QuadPart >> 32 )
298 WARN("Too big!\n");
299 goto end;
302 sz = stat.cbSize.QuadPart;
303 data = msi_alloc( sz );
304 if( !data )
306 WARN("couldn't allocate memory r=%08x!\n", r);
307 ret = ERROR_NOT_ENOUGH_MEMORY;
308 goto end;
311 r = IStream_Read(stm, data, sz, &count );
312 if( FAILED( r ) || ( count != sz ) )
314 msi_free( data );
315 WARN("read stream failed r = %08x!\n", r);
316 goto end;
319 *pdata = data;
320 *psz = sz;
321 ret = ERROR_SUCCESS;
323 end:
324 IStream_Release( stm );
326 return ret;
329 static UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
331 LPWSTR encname;
332 HRESULT r;
334 encname = encode_streamname(FALSE, stname);
336 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
338 r = IStorage_OpenStream(db->storage, encname, NULL,
339 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
340 if( FAILED( r ) )
342 MSITRANSFORM *transform;
344 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
346 TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
347 r = IStorage_OpenStream( transform->stg, encname, NULL,
348 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
349 if (SUCCEEDED(r))
350 break;
354 msi_free( encname );
356 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
359 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
360 USHORT **pdata, UINT *psz )
362 HRESULT r;
363 UINT ret = ERROR_FUNCTION_FAILED;
364 VOID *data;
365 ULONG sz, count;
366 IStream *stm = NULL;
367 STATSTG stat;
369 r = db_get_raw_stream( db, stname, &stm );
370 if( r != ERROR_SUCCESS)
371 return ret;
372 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
373 if( FAILED( r ) )
375 WARN("open stream failed r = %08x!\n", r);
376 goto end;
379 if( stat.cbSize.QuadPart >> 32 )
381 WARN("Too big!\n");
382 goto end;
385 sz = stat.cbSize.QuadPart;
386 data = msi_alloc( sz );
387 if( !data )
389 WARN("couldn't allocate memory r=%08x!\n", r);
390 ret = ERROR_NOT_ENOUGH_MEMORY;
391 goto end;
394 r = IStream_Read(stm, data, sz, &count );
395 if( FAILED( r ) || ( count != sz ) )
397 msi_free( data );
398 WARN("read stream failed r = %08x!\n", r);
399 goto end;
402 *pdata = data;
403 *psz = sz;
404 ret = ERROR_SUCCESS;
406 end:
407 IStream_Release( stm );
409 return ret;
412 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
413 LPCVOID data, UINT sz, BOOL bTable )
415 HRESULT r;
416 UINT ret = ERROR_FUNCTION_FAILED;
417 ULONG count;
418 IStream *stm = NULL;
419 ULARGE_INTEGER size;
420 LARGE_INTEGER pos;
421 LPWSTR encname;
423 encname = encode_streamname(bTable, stname );
424 r = IStorage_OpenStream( stg, encname, NULL,
425 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
426 if( FAILED(r) )
428 r = IStorage_CreateStream( stg, encname,
429 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
431 msi_free( encname );
432 if( FAILED( r ) )
434 WARN("open stream failed r = %08x\n", r);
435 return ret;
438 size.QuadPart = sz;
439 r = IStream_SetSize( stm, size );
440 if( FAILED( r ) )
442 WARN("Failed to SetSize\n");
443 goto end;
446 pos.QuadPart = 0;
447 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
448 if( FAILED( r ) )
450 WARN("Failed to Seek\n");
451 goto end;
454 if (sz)
456 r = IStream_Write(stm, data, sz, &count );
457 if( FAILED( r ) || ( count != sz ) )
459 WARN("Failed to Write\n");
460 goto end;
464 ret = ERROR_SUCCESS;
466 end:
467 IStream_Release( stm );
469 return ret;
472 static void free_table( MSITABLE *table )
474 UINT i;
475 for( i=0; i<table->row_count; i++ )
476 msi_free( table->data[i] );
477 msi_free( table->data );
478 msi_free( table->data_persistent );
479 msi_free_colinfo( table->colinfo, table->col_count );
480 msi_free( table->colinfo );
481 msi_free( table );
484 static UINT msi_table_get_row_size( MSIDATABASE *db,const MSICOLUMNINFO *cols,
485 UINT count )
487 const MSICOLUMNINFO *last_col = &cols[count-1];
488 if (!count)
489 return 0;
490 return last_col->offset + bytes_per_column( db, last_col );
493 /* add this table to the list of cached tables in the database */
494 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
496 BYTE *rawdata = NULL;
497 UINT rawsize = 0, i, j, row_size = 0;
499 TRACE("%s\n",debugstr_w(t->name));
501 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
503 /* if we can't read the table, just assume that it's empty */
504 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
505 if( !rawdata )
506 return ERROR_SUCCESS;
508 TRACE("Read %d bytes\n", rawsize );
510 if( rawsize % row_size )
512 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
513 goto err;
516 t->row_count = rawsize / row_size;
517 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
518 if( !t->data )
519 goto err;
520 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
521 if ( !t->data_persistent )
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;
531 t->data_persistent[i] = TRUE;
533 for( j=0; j<t->col_count; j++ )
535 UINT ofs = t->colinfo[j].offset;
536 UINT n = bytes_per_column( db, &t->colinfo[j] );
537 UINT k;
539 if ( n != 2 && n != 3 && n != 4 )
541 ERR("oops - unknown column width %d\n", n);
542 goto err;
545 for ( k = 0; k < n; k++ )
546 t->data[i][ofs + k] = rawdata[ofs*t->row_count + i * n + k];
550 msi_free( rawdata );
551 return ERROR_SUCCESS;
552 err:
553 msi_free( rawdata );
554 return ERROR_FUNCTION_FAILED;
557 void free_cached_tables( MSIDATABASE *db )
559 while( !list_empty( &db->tables ) )
561 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
563 list_remove( &t->entry );
564 free_table( t );
568 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
570 MSITABLE *t;
572 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
573 if( !lstrcmpW( name, t->name ) )
574 return t;
576 return NULL;
579 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
581 UINT r, column_count = 0;
582 MSICOLUMNINFO *columns;
584 /* get the number of columns in this table */
585 column_count = 0;
586 r = get_tablecolumns( db, name, NULL, &column_count );
587 if( r != ERROR_SUCCESS )
588 return r;
590 *pcount = column_count;
592 /* if there's no columns, there's no table */
593 if( column_count == 0 )
594 return ERROR_INVALID_PARAMETER;
596 TRACE("Table %s found\n", debugstr_w(name) );
598 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
599 if( !columns )
600 return ERROR_FUNCTION_FAILED;
602 r = get_tablecolumns( db, name, columns, &column_count );
603 if( r != ERROR_SUCCESS )
605 msi_free( columns );
606 return ERROR_FUNCTION_FAILED;
609 *pcols = columns;
611 return r;
614 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
615 MSICONDITION persistent, MSITABLE **table_ret)
617 UINT r, nField;
618 MSIVIEW *tv = NULL;
619 MSIRECORD *rec = NULL;
620 column_info *col;
621 MSITABLE *table;
622 UINT i;
624 /* only add tables that don't exist already */
625 if( TABLE_Exists(db, name ) )
627 WARN("table %s exists\n", debugstr_w(name));
628 return ERROR_BAD_QUERY_SYNTAX;
631 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
632 if( !table )
633 return ERROR_FUNCTION_FAILED;
635 table->ref_count = 1;
636 table->row_count = 0;
637 table->data = NULL;
638 table->data_persistent = NULL;
639 table->colinfo = NULL;
640 table->col_count = 0;
641 table->persistent = persistent;
642 lstrcpyW( table->name, name );
644 for( col = col_info; col; col = col->next )
645 table->col_count++;
647 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
648 if (!table->colinfo)
650 free_table( table );
651 return ERROR_FUNCTION_FAILED;
654 for( i = 0, col = col_info; col; i++, col = col->next )
656 table->colinfo[ i ].tablename = strdupW( col->table );
657 table->colinfo[ i ].number = i + 1;
658 table->colinfo[ i ].colname = strdupW( col->column );
659 table->colinfo[ i ].type = col->type;
660 table->colinfo[ i ].offset = 0;
661 table->colinfo[ i ].ref_count = 0;
662 table->colinfo[ i ].hash_table = NULL;
663 table->colinfo[ i ].temporary = col->temporary;
665 table_calc_column_offsets( db, table->colinfo, table->col_count);
667 r = TABLE_CreateView( db, szTables, &tv );
668 TRACE("CreateView returned %x\n", r);
669 if( r )
671 free_table( table );
672 return r;
675 r = tv->ops->execute( tv, 0 );
676 TRACE("tv execute returned %x\n", r);
677 if( r )
678 goto err;
680 rec = MSI_CreateRecord( 1 );
681 if( !rec )
682 goto err;
684 r = MSI_RecordSetStringW( rec, 1, name );
685 if( r )
686 goto err;
688 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
689 TRACE("insert_row returned %x\n", r);
690 if( r )
691 goto err;
693 tv->ops->delete( tv );
694 tv = NULL;
696 msiobj_release( &rec->hdr );
697 rec = NULL;
699 if( persistent != MSICONDITION_FALSE )
701 /* add each column to the _Columns table */
702 r = TABLE_CreateView( db, szColumns, &tv );
703 if( r )
704 return r;
706 r = tv->ops->execute( tv, 0 );
707 TRACE("tv execute returned %x\n", r);
708 if( r )
709 goto err;
711 rec = MSI_CreateRecord( 4 );
712 if( !rec )
713 goto err;
715 r = MSI_RecordSetStringW( rec, 1, name );
716 if( r )
717 goto err;
720 * need to set the table, column number, col name and type
721 * for each column we enter in the table
723 nField = 1;
724 for( col = col_info; col; col = col->next )
726 r = MSI_RecordSetInteger( rec, 2, nField );
727 if( r )
728 goto err;
730 r = MSI_RecordSetStringW( rec, 3, col->column );
731 if( r )
732 goto err;
734 r = MSI_RecordSetInteger( rec, 4, col->type );
735 if( r )
736 goto err;
738 r = tv->ops->insert_row( tv, rec, -1, FALSE );
739 if( r )
740 goto err;
742 nField++;
744 if( !col )
745 r = ERROR_SUCCESS;
748 err:
749 if (rec)
750 msiobj_release( &rec->hdr );
751 /* FIXME: remove values from the string table on error */
752 if( tv )
753 tv->ops->delete( tv );
755 if (r == ERROR_SUCCESS)
757 list_add_head( &db->tables, &table->entry );
758 *table_ret = table;
760 else
761 free_table( table );
763 return r;
766 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
768 MSITABLE *table;
769 UINT r;
771 /* first, see if the table is cached */
772 table = find_cached_table( db, name );
773 if( table )
775 *table_ret = table;
776 return ERROR_SUCCESS;
779 /* nonexistent tables should be interpreted as empty tables */
780 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
781 if( !table )
782 return ERROR_FUNCTION_FAILED;
784 table->row_count = 0;
785 table->data = NULL;
786 table->data_persistent = NULL;
787 table->colinfo = NULL;
788 table->col_count = 0;
789 table->persistent = MSICONDITION_TRUE;
790 lstrcpyW( table->name, name );
792 if ( !lstrcmpW(name, szTables) || !lstrcmpW(name, szColumns) )
793 table->persistent = MSICONDITION_NONE;
795 r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
796 if (r != ERROR_SUCCESS)
798 free_table ( table );
799 return r;
802 r = read_table_from_storage( db, table, db->storage );
803 if( r != ERROR_SUCCESS )
805 free_table( table );
806 return r;
809 list_add_head( &db->tables, &table->entry );
810 *table_ret = table;
811 return ERROR_SUCCESS;
814 static UINT save_table( MSIDATABASE *db, const MSITABLE *t )
816 BYTE *rawdata = NULL, *p;
817 UINT rawsize, r, i, j, row_size;
819 /* Nothing to do for non-persistent tables */
820 if( t->persistent == MSICONDITION_FALSE )
821 return ERROR_SUCCESS;
823 TRACE("Saving %s\n", debugstr_w( t->name ) );
825 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
827 rawsize = t->row_count * row_size;
828 rawdata = msi_alloc_zero( rawsize );
829 if( !rawdata )
831 r = ERROR_NOT_ENOUGH_MEMORY;
832 goto err;
835 rawsize = 0;
836 p = rawdata;
837 for( i=0; i<t->col_count; i++ )
839 for( j=0; j<t->row_count; j++ )
841 UINT offset = t->colinfo[i].offset;
843 if (!t->data_persistent[j]) continue;
844 if (i == 0)
845 rawsize += row_size;
847 *p++ = t->data[j][offset];
848 *p++ = t->data[j][offset + 1];
849 if( 4 == bytes_per_column( db, &t->colinfo[i] ) )
851 *p++ = t->data[j][offset + 2];
852 *p++ = t->data[j][offset + 3];
857 TRACE("writing %d bytes\n", rawsize);
858 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
860 err:
861 msi_free( rawdata );
863 return r;
866 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
867 DWORD count )
869 DWORD i;
871 for( i=0; colinfo && (i<count); i++ )
873 assert( (i+1) == colinfo[ i ].number );
874 if (i)
875 colinfo[i].offset = colinfo[ i - 1 ].offset
876 + bytes_per_column( db, &colinfo[ i - 1 ] );
877 else
878 colinfo[i].offset = 0;
879 TRACE("column %d is [%s] with type %08x ofs %d\n",
880 colinfo[i].number, debugstr_w(colinfo[i].colname),
881 colinfo[i].type, colinfo[i].offset);
885 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
886 MSICOLUMNINFO *colinfo, UINT *sz)
888 const MSICOLUMNINFO *p;
889 DWORD i, n;
891 TRACE("%s\n", debugstr_w(name));
893 if (!lstrcmpW( name, szTables ))
895 p = _Tables_cols;
896 n = 1;
898 else if (!lstrcmpW( name, szColumns ))
900 p = _Columns_cols;
901 n = 4;
903 else
904 return ERROR_FUNCTION_FAILED;
906 /* duplicate the string data so we can free it in msi_free_colinfo */
907 for (i=0; i<n; i++)
909 if (colinfo && (i < *sz) )
911 colinfo[i] = p[i];
912 colinfo[i].tablename = strdupW( p[i].tablename );
913 colinfo[i].colname = strdupW( p[i].colname );
915 if( colinfo && (i >= *sz) )
916 break;
918 table_calc_column_offsets( db, colinfo, n );
919 *sz = n;
920 return ERROR_SUCCESS;
923 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
925 UINT i;
927 for( i=0; i<count; i++ )
929 msi_free( colinfo[i].tablename );
930 msi_free( colinfo[i].colname );
931 msi_free( colinfo[i].hash_table );
935 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
937 return strdupW(msi_string_lookup_id( db->strings, stringid ));
940 static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
942 UINT ret = 0, i;
944 for (i = 0; i < bytes; i++)
945 ret += (data[row][col + i] << i * 8);
947 return ret;
950 static UINT get_tablecolumns( MSIDATABASE *db,
951 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
953 UINT r, i, n=0, table_id, count, maxcount = *sz;
954 MSITABLE *table = NULL;
956 TRACE("%s\n", debugstr_w(szTableName));
958 /* first check if there is a default table with that name */
959 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
960 if( ( r == ERROR_SUCCESS ) && *sz )
961 return r;
963 r = get_table( db, szColumns, &table );
964 if( r != ERROR_SUCCESS )
966 ERR("couldn't load _Columns table\n");
967 return ERROR_FUNCTION_FAILED;
970 /* convert table and column names to IDs from the string table */
971 r = msi_string2idW( db->strings, szTableName, &table_id );
972 if( r != ERROR_SUCCESS )
974 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
975 return r;
978 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
980 /* Note: _Columns table doesn't have non-persistent data */
982 /* if maxcount is non-zero, assume it's exactly right for this table */
983 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
984 count = table->row_count;
985 for( i=0; i<count; i++ )
987 if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
988 continue;
989 if( colinfo )
991 UINT id = read_table_int(table->data, i, table->colinfo[2].offset, db->bytes_per_strref);
992 UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
994 /* check the column number is in range */
995 if (col<1 || col>maxcount)
997 ERR("column %d out of range\n", col);
998 continue;
1001 /* check if this column was already set */
1002 if (colinfo[ col - 1 ].number)
1004 ERR("duplicate column %d\n", col);
1005 continue;
1008 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
1009 colinfo[ col - 1 ].number = col;
1010 colinfo[ col - 1 ].colname = msi_makestring( db, id );
1011 colinfo[ col - 1 ].type = read_table_int(table->data, i,
1012 table->colinfo[3].offset,
1013 sizeof(USHORT)) - (1<<15);
1014 colinfo[ col - 1 ].offset = 0;
1015 colinfo[ col - 1 ].ref_count = 0;
1016 colinfo[ col - 1 ].hash_table = NULL;
1018 n++;
1021 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
1023 if (colinfo && n != maxcount)
1025 ERR("missing column in table %s\n", debugstr_w(szTableName));
1026 msi_free_colinfo(colinfo, maxcount );
1027 return ERROR_FUNCTION_FAILED;
1030 table_calc_column_offsets( db, colinfo, n );
1031 *sz = n;
1033 return ERROR_SUCCESS;
1036 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
1038 MSITABLE *table;
1039 UINT size, offset, old_count;
1040 UINT n;
1042 table = find_cached_table( db, name );
1043 old_count = table->col_count;
1044 msi_free( table->colinfo );
1045 table->colinfo = NULL;
1047 table_get_column_info( db, name, &table->colinfo, &table->col_count );
1048 if (!table->col_count)
1049 return;
1051 size = msi_table_get_row_size( db, table->colinfo, table->col_count );
1052 offset = table->colinfo[table->col_count - 1].offset;
1054 for ( n = 0; n < table->row_count; n++ )
1056 table->data[n] = msi_realloc( table->data[n], size );
1057 if (old_count < table->col_count)
1058 memset( &table->data[n][offset], 0, size - offset );
1062 /* try to find the table name in the _Tables table */
1063 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1065 UINT r, table_id = 0, i, count;
1066 MSITABLE *table = NULL;
1068 static const WCHAR szStreams[] = {'_','S','t','r','e','a','m','s',0};
1069 static const WCHAR szStorages[] = {'_','S','t','o','r','a','g','e','s',0};
1071 if( !lstrcmpW( name, szTables ) || !lstrcmpW( name, szColumns ) ||
1072 !lstrcmpW( name, szStreams ) || !lstrcmpW( name, szStorages ) )
1073 return TRUE;
1075 r = msi_string2idW( db->strings, name, &table_id );
1076 if( r != ERROR_SUCCESS )
1078 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1079 return FALSE;
1082 r = get_table( db, szTables, &table );
1083 if( r != ERROR_SUCCESS )
1085 ERR("table %s not available\n", debugstr_w(szTables));
1086 return FALSE;
1089 count = table->row_count;
1090 for( i=0; i<count; i++ )
1091 if( table->data[ i ][ 0 ] == table_id )
1092 return TRUE;
1094 return FALSE;
1097 /* below is the query interface to a table */
1099 typedef struct tagMSITABLEVIEW
1101 MSIVIEW view;
1102 MSIDATABASE *db;
1103 MSITABLE *table;
1104 MSICOLUMNINFO *columns;
1105 MSIORDERINFO *order;
1106 UINT num_cols;
1107 UINT row_size;
1108 WCHAR name[1];
1109 } MSITABLEVIEW;
1111 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1113 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1114 UINT offset, n;
1116 if( !tv->table )
1117 return ERROR_INVALID_PARAMETER;
1119 if( (col==0) || (col>tv->num_cols) )
1120 return ERROR_INVALID_PARAMETER;
1122 /* how many rows are there ? */
1123 if( row >= tv->table->row_count )
1124 return ERROR_NO_MORE_ITEMS;
1126 if( tv->columns[col-1].offset >= tv->row_size )
1128 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1129 ERR("%p %p\n", tv, tv->columns );
1130 return ERROR_FUNCTION_FAILED;
1133 if (tv->order)
1134 row = tv->order->reorder[row];
1136 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1137 if (n != 2 && n != 3 && n != 4)
1139 ERR("oops! what is %d bytes per column?\n", n );
1140 return ERROR_FUNCTION_FAILED;
1143 offset = tv->columns[col-1].offset;
1144 *val = read_table_int(tv->table->data, row, offset, n);
1146 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1148 return ERROR_SUCCESS;
1151 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1153 LPWSTR p, stname = NULL;
1154 UINT i, r, type, ival;
1155 DWORD len;
1156 LPCWSTR sval;
1157 MSIVIEW *view = (MSIVIEW *) tv;
1159 TRACE("%p %d\n", tv, row);
1161 len = lstrlenW( tv->name ) + 1;
1162 stname = msi_alloc( len*sizeof(WCHAR) );
1163 if ( !stname )
1165 r = ERROR_OUTOFMEMORY;
1166 goto err;
1169 lstrcpyW( stname, tv->name );
1171 for ( i = 0; i < tv->num_cols; i++ )
1173 type = tv->columns[i].type;
1174 if ( type & MSITYPE_KEY )
1176 static const WCHAR szDot[] = { '.', 0 };
1178 r = TABLE_fetch_int( view, row, i+1, &ival );
1179 if ( r != ERROR_SUCCESS )
1180 goto err;
1182 if ( tv->columns[i].type & MSITYPE_STRING )
1184 sval = msi_string_lookup_id( tv->db->strings, ival );
1185 if ( !sval )
1187 r = ERROR_INVALID_PARAMETER;
1188 goto err;
1191 else
1193 static const WCHAR fmt[] = { '%','d',0 };
1194 WCHAR number[0x20];
1195 UINT n = bytes_per_column( tv->db, &tv->columns[i] );
1197 switch( n )
1199 case 2:
1200 sprintfW( number, fmt, ival^0x8000 );
1201 break;
1202 case 4:
1203 sprintfW( number, fmt, ival^0x80000000 );
1204 break;
1205 default:
1206 ERR( "oops - unknown column width %d\n", n );
1207 r = ERROR_FUNCTION_FAILED;
1208 goto err;
1210 sval = number;
1213 len += lstrlenW( szDot ) + lstrlenW( sval );
1214 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1215 if ( !p )
1217 r = ERROR_OUTOFMEMORY;
1218 goto err;
1220 stname = p;
1222 lstrcatW( stname, szDot );
1223 lstrcatW( stname, sval );
1225 else
1226 continue;
1229 *pstname = stname;
1230 return ERROR_SUCCESS;
1232 err:
1233 msi_free( stname );
1234 *pstname = NULL;
1235 return r;
1239 * We need a special case for streams, as we need to reference column with
1240 * the name of the stream in the same table, and the table name
1241 * which may not be available at higher levels of the query
1243 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1245 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1246 UINT r;
1247 LPWSTR full_name = NULL;
1249 if( !view->ops->fetch_int )
1250 return ERROR_INVALID_PARAMETER;
1252 r = msi_stream_name( tv, row, &full_name );
1253 if ( r != ERROR_SUCCESS )
1255 ERR("fetching stream, error = %d\n", r);
1256 return r;
1259 r = db_get_raw_stream( tv->db, full_name, stm );
1260 if( r )
1261 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1262 msi_free( full_name );
1264 return r;
1267 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1269 UINT offset, n, i;
1271 if( !tv->table )
1272 return ERROR_INVALID_PARAMETER;
1274 if( (col==0) || (col>tv->num_cols) )
1275 return ERROR_INVALID_PARAMETER;
1277 if( row >= tv->table->row_count )
1278 return ERROR_INVALID_PARAMETER;
1280 if( tv->columns[col-1].offset >= tv->row_size )
1282 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1283 ERR("%p %p\n", tv, tv->columns );
1284 return ERROR_FUNCTION_FAILED;
1287 msi_free( tv->columns[col-1].hash_table );
1288 tv->columns[col-1].hash_table = NULL;
1290 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1291 if ( n != 2 && n != 3 && n != 4 )
1293 ERR("oops! what is %d bytes per column?\n", n );
1294 return ERROR_FUNCTION_FAILED;
1297 offset = tv->columns[col-1].offset;
1298 for ( i = 0; i < n; i++ )
1299 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1301 return ERROR_SUCCESS;
1304 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1306 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1308 if (!tv->table)
1309 return ERROR_INVALID_PARAMETER;
1311 if (tv->order)
1312 row = tv->order->reorder[row];
1314 return msi_view_get_row(tv->db, view, row, rec);
1317 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1319 UINT r;
1320 MSIQUERY *query = NULL;
1321 MSIRECORD *rec = NULL;
1323 static const WCHAR insert[] = {
1324 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1325 '`','_','S','t','r','e','a','m','s','`',' ',
1326 '(','`','N','a','m','e','`',',',
1327 '`','D','a','t','a','`',')',' ',
1328 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1330 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1332 rec = MSI_CreateRecord( 2 );
1333 if ( !rec )
1334 return ERROR_OUTOFMEMORY;
1336 r = MSI_RecordSetStringW( rec, 1, name );
1337 if ( r != ERROR_SUCCESS )
1338 goto err;
1340 r = MSI_RecordSetIStream( rec, 2, data );
1341 if ( r != ERROR_SUCCESS )
1342 goto err;
1344 r = MSI_DatabaseOpenViewW( db, insert, &query );
1345 if ( r != ERROR_SUCCESS )
1346 goto err;
1348 r = MSI_ViewExecute( query, rec );
1350 err:
1351 msiobj_release( &query->hdr );
1352 msiobj_release( &rec->hdr );
1354 return r;
1357 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1359 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1360 UINT i, val, r = ERROR_SUCCESS;
1362 if ( !tv->table )
1363 return ERROR_INVALID_PARAMETER;
1365 /* test if any of the mask bits are invalid */
1366 if ( mask >= (1<<tv->num_cols) )
1367 return ERROR_INVALID_PARAMETER;
1369 for ( i = 0; i < tv->num_cols; i++ )
1371 BOOL persistent;
1373 /* only update the fields specified in the mask */
1374 if ( !(mask&(1<<i)) )
1375 continue;
1377 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1378 (tv->table->data_persistent[row]);
1379 /* FIXME: should we allow updating keys? */
1381 val = 0;
1382 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1384 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1386 IStream *stm;
1387 LPWSTR stname;
1389 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1390 if ( r != ERROR_SUCCESS )
1391 return r;
1393 r = msi_stream_name( tv, row, &stname );
1394 if ( r != ERROR_SUCCESS )
1396 IStream_Release( stm );
1397 return r;
1400 r = msi_addstreamW( tv->db, stname, stm );
1401 IStream_Release( stm );
1402 msi_free ( stname );
1404 if ( r != ERROR_SUCCESS )
1405 return r;
1407 val = 1; /* refers to the first key column */
1409 else if ( tv->columns[i].type & MSITYPE_STRING )
1411 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1412 UINT ival, x;
1414 r = msi_string2idW(tv->db->strings, sval, &ival);
1415 if (r == ERROR_SUCCESS)
1417 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1418 if (ival == x)
1419 continue;
1422 val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
1423 persistent ? StringPersistent : StringNonPersistent );
1425 else if ( 2 == bytes_per_column( tv->db, &tv->columns[ i ] ) )
1427 val = 0x8000 + MSI_RecordGetInteger( rec, i + 1 );
1428 if ( val & 0xffff0000 )
1430 ERR("field %u value %d out of range\n", i+1, val - 0x8000 );
1431 return ERROR_FUNCTION_FAILED;
1434 else
1436 INT ival = MSI_RecordGetInteger( rec, i + 1 );
1437 val = ival ^ 0x80000000;
1441 r = TABLE_set_int( tv, row, i+1, val );
1442 if ( r != ERROR_SUCCESS )
1443 break;
1445 return r;
1448 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1450 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1451 BYTE **p, *row;
1452 BOOL *b;
1453 UINT sz;
1454 BYTE ***data_ptr;
1455 BOOL **data_persist_ptr;
1456 UINT *row_count;
1458 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1460 if( !tv->table )
1461 return ERROR_INVALID_PARAMETER;
1463 row = msi_alloc_zero( tv->row_size );
1464 if( !row )
1465 return ERROR_NOT_ENOUGH_MEMORY;
1467 row_count = &tv->table->row_count;
1468 data_ptr = &tv->table->data;
1469 data_persist_ptr = &tv->table->data_persistent;
1470 if (*num == -1)
1471 *num = tv->table->row_count;
1473 sz = (*row_count + 1) * sizeof (BYTE*);
1474 if( *data_ptr )
1475 p = msi_realloc( *data_ptr, sz );
1476 else
1477 p = msi_alloc( sz );
1478 if( !p )
1480 msi_free( row );
1481 return ERROR_NOT_ENOUGH_MEMORY;
1484 sz = (*row_count + 1) * sizeof (BOOL);
1485 if( *data_persist_ptr )
1486 b = msi_realloc( *data_persist_ptr, sz );
1487 else
1488 b = msi_alloc( sz );
1489 if( !b )
1491 msi_free( row );
1492 msi_free( p );
1493 return ERROR_NOT_ENOUGH_MEMORY;
1496 *data_ptr = p;
1497 (*data_ptr)[*row_count] = row;
1499 *data_persist_ptr = b;
1500 (*data_persist_ptr)[*row_count] = !temporary;
1502 (*row_count)++;
1504 return ERROR_SUCCESS;
1507 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1509 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1511 TRACE("%p %p\n", tv, record);
1513 TRACE("There are %d columns\n", tv->num_cols );
1515 return ERROR_SUCCESS;
1518 static UINT TABLE_close( struct tagMSIVIEW *view )
1520 TRACE("%p\n", view );
1522 return ERROR_SUCCESS;
1525 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1527 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1529 TRACE("%p %p %p\n", view, rows, cols );
1531 if( cols )
1532 *cols = tv->num_cols;
1533 if( rows )
1535 if( !tv->table )
1536 return ERROR_INVALID_PARAMETER;
1537 *rows = tv->table->row_count;
1540 return ERROR_SUCCESS;
1543 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1544 UINT n, LPWSTR *name, UINT *type, BOOL *temporary )
1546 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1548 TRACE("%p %d %p %p\n", tv, n, name, type );
1550 if( ( n == 0 ) || ( n > tv->num_cols ) )
1551 return ERROR_INVALID_PARAMETER;
1553 if( name )
1555 *name = strdupW( tv->columns[n-1].colname );
1556 if( !*name )
1557 return ERROR_FUNCTION_FAILED;
1560 if( type )
1561 *type = tv->columns[n-1].type;
1563 if( temporary )
1564 *temporary = tv->columns[n-1].temporary;
1566 return ERROR_SUCCESS;
1569 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1571 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1573 UINT r, row, i;
1575 /* check there's no null values where they're not allowed */
1576 for( i = 0; i < tv->num_cols; i++ )
1578 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1579 continue;
1581 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1582 TRACE("skipping binary column\n");
1583 else if ( tv->columns[i].type & MSITYPE_STRING )
1585 LPCWSTR str;
1587 str = MSI_RecordGetString( rec, i+1 );
1588 if (str == NULL || str[0] == 0)
1589 return ERROR_INVALID_DATA;
1591 else
1593 UINT n;
1595 n = MSI_RecordGetInteger( rec, i+1 );
1596 if (n == MSI_NULL_INTEGER)
1597 return ERROR_INVALID_DATA;
1601 /* check there's no duplicate keys */
1602 r = msi_table_find_row( tv, rec, &row );
1603 if (r == ERROR_SUCCESS)
1604 return ERROR_FUNCTION_FAILED;
1606 return ERROR_SUCCESS;
1609 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1611 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1612 UINT i, r;
1614 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1616 /* check that the key is unique - can we find a matching row? */
1617 r = table_validate_new( tv, rec );
1618 if( r != ERROR_SUCCESS )
1619 return ERROR_FUNCTION_FAILED;
1621 r = table_create_new_row( view, &row, temporary );
1622 TRACE("insert_row returned %08x\n", r);
1623 if( r != ERROR_SUCCESS )
1624 return r;
1626 /* shift the rows to make room for the new row */
1627 for (i = tv->table->row_count - 1; i > row; i--)
1629 memmove(&(tv->table->data[i][0]),
1630 &(tv->table->data[i - 1][0]), tv->row_size);
1631 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1634 /* Re-set the persistence flag */
1635 tv->table->data_persistent[row] = !temporary;
1636 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1639 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1641 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1642 UINT r, num_rows, num_cols, i;
1644 TRACE("%p %d\n", tv, row);
1646 if ( !tv->table )
1647 return ERROR_INVALID_PARAMETER;
1649 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1650 if ( r != ERROR_SUCCESS )
1651 return r;
1653 if ( row >= num_rows )
1654 return ERROR_FUNCTION_FAILED;
1656 num_rows = tv->table->row_count;
1657 tv->table->row_count--;
1659 /* reset the hash tables */
1660 for (i = 0; i < tv->num_cols; i++)
1662 msi_free( tv->columns[i].hash_table );
1663 tv->columns[i].hash_table = NULL;
1666 if ( row == num_rows - 1 )
1667 return ERROR_SUCCESS;
1669 for (i = row + 1; i < num_rows; i++)
1671 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1672 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1675 return ERROR_SUCCESS;
1678 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1680 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1681 UINT r, new_row;
1683 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1684 * sets the fetched record apart from other records
1687 if (!tv->table)
1688 return ERROR_INVALID_PARAMETER;
1690 r = msi_table_find_row(tv, rec, &new_row);
1691 if (r != ERROR_SUCCESS)
1693 ERR("can't find row to modify\n");
1694 return ERROR_FUNCTION_FAILED;
1697 /* the row cannot be changed */
1698 if (row != new_row + 1)
1699 return ERROR_FUNCTION_FAILED;
1701 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1704 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1706 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1707 UINT row, r;
1709 r = msi_table_find_row(tv, rec, &row);
1710 if (r != ERROR_SUCCESS)
1711 return r;
1713 return TABLE_delete_row(view, row);
1716 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1718 MSIRECORD *curr;
1719 UINT r, i, count;
1721 r = TABLE_get_row(view, row - 1, &curr);
1722 if (r != ERROR_SUCCESS)
1723 return r;
1725 count = MSI_RecordGetFieldCount(rec);
1726 for (i = 0; i < count; i++)
1727 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1729 msiobj_release(&curr->hdr);
1730 return ERROR_SUCCESS;
1733 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1734 MSIRECORD *rec, UINT row)
1736 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1737 UINT r;
1739 TRACE("%p %d %p\n", view, eModifyMode, rec );
1741 switch (eModifyMode)
1743 case MSIMODIFY_DELETE:
1744 r = modify_delete_row( view, rec );
1745 break;
1746 case MSIMODIFY_VALIDATE_NEW:
1747 r = table_validate_new( tv, rec );
1748 break;
1750 case MSIMODIFY_INSERT:
1751 r = table_validate_new( tv, rec );
1752 if (r != ERROR_SUCCESS)
1753 break;
1754 r = TABLE_insert_row( view, rec, -1, FALSE );
1755 break;
1757 case MSIMODIFY_INSERT_TEMPORARY:
1758 r = table_validate_new( tv, rec );
1759 if (r != ERROR_SUCCESS)
1760 break;
1761 r = TABLE_insert_row( view, rec, -1, TRUE );
1762 break;
1764 case MSIMODIFY_REFRESH:
1765 r = msi_refresh_record( view, rec, row );
1766 break;
1768 case MSIMODIFY_UPDATE:
1769 r = msi_table_update( view, rec, row );
1770 break;
1772 case MSIMODIFY_ASSIGN:
1773 case MSIMODIFY_REPLACE:
1774 case MSIMODIFY_MERGE:
1775 case MSIMODIFY_VALIDATE:
1776 case MSIMODIFY_VALIDATE_FIELD:
1777 case MSIMODIFY_VALIDATE_DELETE:
1778 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1779 r = ERROR_CALL_NOT_IMPLEMENTED;
1780 break;
1782 default:
1783 r = ERROR_INVALID_DATA;
1786 return r;
1789 static UINT TABLE_delete( struct tagMSIVIEW *view )
1791 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1793 TRACE("%p\n", view );
1795 tv->table = NULL;
1796 tv->columns = NULL;
1798 if (tv->order)
1800 msi_free( tv->order->reorder );
1801 msi_free( tv->order );
1802 tv->order = NULL;
1805 msi_free( tv );
1807 return ERROR_SUCCESS;
1810 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1811 UINT val, UINT *row, MSIITERHANDLE *handle )
1813 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1814 const MSICOLUMNHASHENTRY *entry;
1816 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1818 if( !tv->table )
1819 return ERROR_INVALID_PARAMETER;
1821 if( (col==0) || (col > tv->num_cols) )
1822 return ERROR_INVALID_PARAMETER;
1824 if( !tv->columns[col-1].hash_table )
1826 UINT i;
1827 UINT num_rows = tv->table->row_count;
1828 MSICOLUMNHASHENTRY **hash_table;
1829 MSICOLUMNHASHENTRY *new_entry;
1831 if( tv->columns[col-1].offset >= tv->row_size )
1833 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1834 ERR("%p %p\n", tv, tv->columns );
1835 return ERROR_FUNCTION_FAILED;
1838 /* allocate contiguous memory for the table and its entries so we
1839 * don't have to do an expensive cleanup */
1840 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1841 num_rows * sizeof(MSICOLUMNHASHENTRY));
1842 if (!hash_table)
1843 return ERROR_OUTOFMEMORY;
1845 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1846 tv->columns[col-1].hash_table = hash_table;
1848 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1850 for (i = 0; i < num_rows; i++, new_entry++)
1852 UINT row_value;
1854 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1855 continue;
1857 new_entry->next = NULL;
1858 new_entry->value = row_value;
1859 new_entry->row = i;
1860 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1862 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1863 while (prev_entry->next)
1864 prev_entry = prev_entry->next;
1865 prev_entry->next = new_entry;
1867 else
1868 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1872 if( !*handle )
1873 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1874 else
1875 entry = (*handle)->next;
1877 while (entry && entry->value != val)
1878 entry = entry->next;
1880 *handle = entry;
1881 if (!entry)
1882 return ERROR_NO_MORE_ITEMS;
1884 *row = entry->row;
1886 return ERROR_SUCCESS;
1889 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1891 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1892 UINT i;
1894 TRACE("%p %d\n", view, tv->table->ref_count);
1896 for (i = 0; i < tv->table->col_count; i++)
1898 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1899 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1902 return InterlockedIncrement(&tv->table->ref_count);
1905 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1907 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1908 MSIRECORD *rec = NULL;
1909 MSIVIEW *columns = NULL;
1910 UINT row, r;
1912 rec = MSI_CreateRecord(2);
1913 if (!rec)
1914 return ERROR_OUTOFMEMORY;
1916 MSI_RecordSetStringW(rec, 1, table);
1917 MSI_RecordSetInteger(rec, 2, number);
1919 r = TABLE_CreateView(tv->db, szColumns, &columns);
1920 if (r != ERROR_SUCCESS)
1921 return r;
1923 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
1924 if (r != ERROR_SUCCESS)
1925 goto done;
1927 r = TABLE_delete_row(columns, row);
1928 if (r != ERROR_SUCCESS)
1929 goto done;
1931 msi_update_table_columns(tv->db, table);
1933 done:
1934 msiobj_release(&rec->hdr);
1935 columns->ops->delete(columns);
1936 return r;
1939 static UINT TABLE_release(struct tagMSIVIEW *view)
1941 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1942 INT ref = tv->table->ref_count;
1943 UINT i, r;
1945 TRACE("%p %d\n", view, ref);
1947 for (i = 0; i < tv->table->col_count; i++)
1949 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1951 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1952 if (ref == 0)
1954 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1955 tv->table->colinfo[i].number);
1956 if (r != ERROR_SUCCESS)
1957 break;
1962 ref = InterlockedDecrement(&tv->table->ref_count);
1963 if (ref == 0)
1965 if (!tv->table->row_count)
1967 list_remove(&tv->table->entry);
1968 free_table(tv->table);
1969 TABLE_delete(view);
1973 return ref;
1976 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
1977 LPCWSTR column, UINT type, BOOL hold)
1979 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1980 MSITABLE *msitable;
1981 MSIRECORD *rec;
1982 UINT r, i;
1984 rec = MSI_CreateRecord(4);
1985 if (!rec)
1986 return ERROR_OUTOFMEMORY;
1988 MSI_RecordSetStringW(rec, 1, table);
1989 MSI_RecordSetInteger(rec, 2, number);
1990 MSI_RecordSetStringW(rec, 3, column);
1991 MSI_RecordSetInteger(rec, 4, type);
1993 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
1994 if (r != ERROR_SUCCESS)
1995 goto done;
1997 msi_update_table_columns(tv->db, table);
1999 if (!hold)
2000 goto done;
2002 msitable = find_cached_table(tv->db, table);
2003 for (i = 0; i < msitable->col_count; i++)
2005 if (!lstrcmpW(msitable->colinfo[i].colname, column))
2007 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2008 break;
2012 done:
2013 msiobj_release(&rec->hdr);
2014 return r;
2017 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2019 UINT n, r, count;
2021 r = TABLE_get_dimensions(view, NULL, &count);
2022 if (r != ERROR_SUCCESS)
2023 return r;
2025 if (order->num_cols >= count)
2026 return ERROR_FUNCTION_FAILED;
2028 r = VIEW_find_column(view, name, &n);
2029 if (r != ERROR_SUCCESS)
2030 return r;
2032 order->cols[order->num_cols] = n;
2033 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2035 order->num_cols++;
2037 return ERROR_SUCCESS;
2040 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2041 UINT a, UINT b, UINT *swap)
2043 UINT r, i, a_val = 0, b_val = 0;
2045 *swap = 0;
2046 for (i = 0; i < order->num_cols; i++)
2048 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2049 if (r != ERROR_SUCCESS)
2050 return r;
2052 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2053 if (r != ERROR_SUCCESS)
2054 return r;
2056 if (a_val != b_val)
2058 if (a_val > b_val)
2059 *swap = 1;
2060 break;
2064 return ERROR_SUCCESS;
2067 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2068 UINT left, UINT right)
2070 UINT r, i, j, temp;
2071 UINT swap = 0, center = (left + right) / 2;
2072 UINT *array = order->reorder;
2074 if (left == right)
2075 return ERROR_SUCCESS;
2077 /* sort the left half */
2078 r = order_mergesort(view, order, left, center);
2079 if (r != ERROR_SUCCESS)
2080 return r;
2082 /* sort the right half */
2083 r = order_mergesort(view, order, center + 1, right);
2084 if (r != ERROR_SUCCESS)
2085 return r;
2087 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2089 r = order_compare(view, order, array[i], array[j], &swap);
2090 if (r != ERROR_SUCCESS)
2091 return r;
2093 if (swap)
2095 temp = array[j];
2096 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2097 array[i] = temp;
2098 j++;
2099 center++;
2103 return ERROR_SUCCESS;
2106 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2108 UINT i, swap, r;
2110 for (i = 1; i < num_rows; i++)
2112 r = order_compare(view, order, order->reorder[i - 1],
2113 order->reorder[i], &swap);
2114 if (r != ERROR_SUCCESS)
2115 return r;
2117 if (!swap)
2118 continue;
2120 ERR("Bad order! %d\n", i);
2121 return ERROR_FUNCTION_FAILED;
2124 return ERROR_SUCCESS;
2127 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2129 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2130 MSIORDERINFO *order;
2131 column_info *ptr;
2132 UINT r, i;
2133 UINT rows, cols;
2135 TRACE("sorting table %s\n", debugstr_w(tv->name));
2137 r = TABLE_get_dimensions(view, &rows, &cols);
2138 if (r != ERROR_SUCCESS)
2139 return r;
2141 if (rows == 0)
2142 return ERROR_SUCCESS;
2144 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2145 if (!order)
2146 return ERROR_OUTOFMEMORY;
2148 for (ptr = columns; ptr; ptr = ptr->next)
2149 order_add_column(view, order, ptr->column);
2151 order->reorder = msi_alloc(rows * sizeof(UINT));
2152 if (!order->reorder)
2153 return ERROR_OUTOFMEMORY;
2155 for (i = 0; i < rows; i++)
2156 order->reorder[i] = i;
2158 r = order_mergesort(view, order, 0, rows - 1);
2159 if (r != ERROR_SUCCESS)
2160 return r;
2162 r = order_verify(view, order, rows);
2163 if (r != ERROR_SUCCESS)
2164 return r;
2166 tv->order = order;
2168 return ERROR_SUCCESS;
2171 static UINT TABLE_drop(struct tagMSIVIEW *view)
2173 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2174 MSIVIEW *tables = NULL;
2175 MSIRECORD *rec = NULL;
2176 UINT r, row;
2177 INT i;
2179 TRACE("dropping table %s\n", debugstr_w(tv->name));
2181 for (i = tv->table->col_count - 1; i >= 0; i--)
2183 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2184 tv->table->colinfo[i].number);
2185 if (r != ERROR_SUCCESS)
2186 return r;
2189 rec = MSI_CreateRecord(1);
2190 if (!rec)
2191 return ERROR_OUTOFMEMORY;
2193 MSI_RecordSetStringW(rec, 1, tv->name);
2195 r = TABLE_CreateView(tv->db, szTables, &tables);
2196 if (r != ERROR_SUCCESS)
2197 return r;
2199 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
2200 if (r != ERROR_SUCCESS)
2201 goto done;
2203 r = TABLE_delete_row(tables, row);
2204 if (r != ERROR_SUCCESS)
2205 goto done;
2207 list_remove(&tv->table->entry);
2208 free_table(tv->table);
2209 TABLE_delete(view);
2211 done:
2212 msiobj_release(&rec->hdr);
2213 tables->ops->delete(tables);
2215 return r;
2218 static const MSIVIEWOPS table_ops =
2220 TABLE_fetch_int,
2221 TABLE_fetch_stream,
2222 TABLE_get_row,
2223 TABLE_set_row,
2224 TABLE_insert_row,
2225 TABLE_delete_row,
2226 TABLE_execute,
2227 TABLE_close,
2228 TABLE_get_dimensions,
2229 TABLE_get_column_info,
2230 TABLE_modify,
2231 TABLE_delete,
2232 TABLE_find_matching_rows,
2233 TABLE_add_ref,
2234 TABLE_release,
2235 TABLE_add_column,
2236 TABLE_remove_column,
2237 TABLE_sort,
2238 TABLE_drop,
2241 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2243 MSITABLEVIEW *tv ;
2244 UINT r, sz;
2246 static const WCHAR Streams[] = {'_','S','t','r','e','a','m','s',0};
2247 static const WCHAR Storages[] = {'_','S','t','o','r','a','g','e','s',0};
2249 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2251 if ( !lstrcmpW( name, Streams ) )
2252 return STREAMS_CreateView( db, view );
2253 else if ( !lstrcmpW( name, Storages ) )
2254 return STORAGES_CreateView( db, view );
2256 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2257 tv = msi_alloc_zero( sz );
2258 if( !tv )
2259 return ERROR_FUNCTION_FAILED;
2261 r = get_table( db, name, &tv->table );
2262 if( r != ERROR_SUCCESS )
2264 msi_free( tv );
2265 WARN("table not found\n");
2266 return r;
2269 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2271 /* fill the structure */
2272 tv->view.ops = &table_ops;
2273 tv->db = db;
2274 tv->columns = tv->table->colinfo;
2275 tv->num_cols = tv->table->col_count;
2276 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count );
2278 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2280 *view = (MSIVIEW*) tv;
2281 lstrcpyW( tv->name, name );
2283 return ERROR_SUCCESS;
2286 UINT MSI_CommitTables( MSIDATABASE *db )
2288 UINT r;
2289 MSITABLE *table = NULL;
2291 TRACE("%p\n",db);
2293 r = msi_save_string_table( db->strings, db->storage );
2294 if( r != ERROR_SUCCESS )
2296 WARN("failed to save string table r=%08x\n",r);
2297 return r;
2300 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2302 r = save_table( db, table );
2303 if( r != ERROR_SUCCESS )
2305 WARN("failed to save table %s (r=%08x)\n",
2306 debugstr_w(table->name), r);
2307 return r;
2311 /* force everything to reload next time */
2312 free_cached_tables( db );
2314 return ERROR_SUCCESS;
2317 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2319 MSITABLE *t;
2320 UINT r;
2322 TRACE("%p %s\n", db, debugstr_w(table));
2324 if (!table)
2325 return MSICONDITION_ERROR;
2327 r = get_table( db, table, &t );
2328 if (r != ERROR_SUCCESS)
2329 return MSICONDITION_NONE;
2331 return t->persistent;
2334 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2336 UINT ret = 0, i;
2338 for (i = 0; i < bytes; i++)
2339 ret += (data[col + i] << i * 8);
2341 return ret;
2344 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2346 static const WCHAR szDot[] = { '.', 0 };
2347 LPWSTR stname = NULL, sval, p;
2348 DWORD len;
2349 UINT i, r;
2351 TRACE("%p %p\n", tv, rec);
2353 len = lstrlenW( tv->name ) + 1;
2354 stname = msi_alloc( len*sizeof(WCHAR) );
2355 if ( !stname )
2357 r = ERROR_OUTOFMEMORY;
2358 goto err;
2361 lstrcpyW( stname, tv->name );
2363 for ( i = 0; i < tv->num_cols; i++ )
2365 if ( tv->columns[i].type & MSITYPE_KEY )
2367 sval = msi_dup_record_field( rec, i + 1 );
2368 if ( !sval )
2370 r = ERROR_OUTOFMEMORY;
2371 goto err;
2374 len += lstrlenW( szDot ) + lstrlenW ( sval );
2375 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2376 if ( !p )
2378 r = ERROR_OUTOFMEMORY;
2379 goto err;
2381 stname = p;
2383 lstrcatW( stname, szDot );
2384 lstrcatW( stname, sval );
2386 msi_free( sval );
2388 else
2389 continue;
2392 *pstname = encode_streamname( FALSE, stname );
2393 msi_free( stname );
2395 return ERROR_SUCCESS;
2397 err:
2398 msi_free ( stname );
2399 *pstname = NULL;
2400 return r;
2403 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2404 IStorage *stg,
2405 const BYTE *rawdata, UINT bytes_per_strref )
2407 UINT i, val, ofs = 0;
2408 USHORT mask;
2409 MSICOLUMNINFO *columns = tv->columns;
2410 MSIRECORD *rec;
2412 mask = rawdata[0] | (rawdata[1] << 8);
2413 rawdata += 2;
2415 rec = MSI_CreateRecord( tv->num_cols );
2416 if( !rec )
2417 return rec;
2419 TRACE("row ->\n");
2420 for( i=0; i<tv->num_cols; i++ )
2422 if ( (mask&1) && (i>=(mask>>8)) )
2423 break;
2424 /* all keys must be present */
2425 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2426 continue;
2428 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2430 LPWSTR encname;
2431 IStream *stm = NULL;
2432 UINT r;
2434 ofs += bytes_per_column( tv->db, &columns[i] );
2436 r = msi_record_encoded_stream_name( tv, rec, &encname );
2437 if ( r != ERROR_SUCCESS )
2438 return NULL;
2440 r = IStorage_OpenStream( stg, encname, NULL,
2441 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2442 msi_free( encname );
2443 if ( r != ERROR_SUCCESS )
2444 return NULL;
2446 MSI_RecordSetStream( rec, i+1, stm );
2447 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2449 else if( columns[i].type & MSITYPE_STRING )
2451 LPCWSTR sval;
2453 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2454 sval = msi_string_lookup_id( st, val );
2455 MSI_RecordSetStringW( rec, i+1, sval );
2456 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2457 ofs += bytes_per_strref;
2459 else
2461 UINT n = bytes_per_column( tv->db, &columns[i] );
2462 switch( n )
2464 case 2:
2465 val = read_raw_int(rawdata, ofs, n);
2466 if (val)
2467 MSI_RecordSetInteger( rec, i+1, val^0x8000 );
2468 TRACE(" field %d [0x%04x]\n", i+1, val );
2469 break;
2470 case 4:
2471 val = read_raw_int(rawdata, ofs, n);
2472 if (val)
2473 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2474 TRACE(" field %d [0x%08x]\n", i+1, val );
2475 break;
2476 default:
2477 ERR("oops - unknown column width %d\n", n);
2478 break;
2480 ofs += n;
2483 return rec;
2486 static void dump_record( MSIRECORD *rec )
2488 UINT i, n;
2490 n = MSI_RecordGetFieldCount( rec );
2491 for( i=1; i<=n; i++ )
2493 LPCWSTR sval = MSI_RecordGetString( rec, i );
2495 if( MSI_RecordIsNull( rec, i ) )
2496 TRACE("row -> []\n");
2497 else if( (sval = MSI_RecordGetString( rec, i )) )
2498 TRACE("row -> [%s]\n", debugstr_w(sval));
2499 else
2500 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2504 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2506 LPCWSTR sval;
2507 UINT i;
2509 for( i=0; i<(rawsize/2); i++ )
2511 sval = msi_string_lookup_id( st, rawdata[i] );
2512 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2516 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2518 LPCWSTR str;
2519 UINT i, r, *data;
2521 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2522 for( i=0; i<tv->num_cols; i++ )
2524 data[i] = 0;
2526 if ( ~tv->columns[i].type & MSITYPE_KEY )
2527 continue;
2529 /* turn the transform column value into a row value */
2530 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2531 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2533 str = MSI_RecordGetString( rec, i+1 );
2534 r = msi_string2idW( tv->db->strings, str, &data[i] );
2536 /* if there's no matching string in the string table,
2537 these keys can't match any record, so fail now. */
2538 if( ERROR_SUCCESS != r )
2540 msi_free( data );
2541 return NULL;
2544 else
2546 data[i] = MSI_RecordGetInteger( rec, i+1 );
2548 if (data[i] == MSI_NULL_INTEGER)
2549 data[i] = 0;
2550 else if ((tv->columns[i].type&0xff) == 2)
2551 data[i] += 0x8000;
2552 else
2553 data[i] += 0x80000000;
2556 return data;
2559 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2561 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2563 for( i=0; i<tv->num_cols; i++ )
2565 if ( ~tv->columns[i].type & MSITYPE_KEY )
2566 continue;
2568 /* turn the transform column value into a row value */
2569 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2570 if ( r != ERROR_SUCCESS )
2572 ERR("TABLE_fetch_int shouldn't fail here\n");
2573 break;
2576 /* if this key matches, move to the next column */
2577 if ( x != data[i] )
2579 ret = ERROR_FUNCTION_FAILED;
2580 break;
2583 ret = ERROR_SUCCESS;
2586 return ret;
2589 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
2591 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2593 data = msi_record_to_row( tv, rec );
2594 if( !data )
2595 return r;
2596 for( i = 0; i < tv->table->row_count; i++ )
2598 r = msi_row_matches( tv, i, data );
2599 if( r == ERROR_SUCCESS )
2601 *row = i;
2602 break;
2605 msi_free( data );
2606 return r;
2609 typedef struct
2611 struct list entry;
2612 LPWSTR name;
2613 } TRANSFORMDATA;
2615 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2616 string_table *st, TRANSFORMDATA *transform,
2617 UINT bytes_per_strref )
2619 UINT rawsize = 0;
2620 BYTE *rawdata = NULL;
2621 MSITABLEVIEW *tv = NULL;
2622 UINT r, n, sz, i, mask;
2623 MSIRECORD *rec = NULL;
2624 UINT colcol = 0;
2625 WCHAR coltable[32];
2626 LPWSTR name;
2628 if (!transform)
2629 return ERROR_SUCCESS;
2631 name = transform->name;
2633 coltable[0] = 0;
2634 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2636 /* read the transform data */
2637 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2638 if ( !rawdata )
2640 TRACE("table %s empty\n", debugstr_w(name) );
2641 return ERROR_INVALID_TABLE;
2644 /* create a table view */
2645 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2646 if( r != ERROR_SUCCESS )
2647 goto err;
2649 r = tv->view.ops->execute( &tv->view, NULL );
2650 if( r != ERROR_SUCCESS )
2651 goto err;
2653 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2654 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2656 /* interpret the data */
2657 r = ERROR_SUCCESS;
2658 for( n=0; n < rawsize; )
2660 mask = rawdata[n] | (rawdata[n+1] << 8);
2662 if (mask&1)
2665 * if the low bit is set, columns are continuous and
2666 * the number of columns is specified in the high byte
2668 sz = 2;
2669 for( i=0; i<tv->num_cols; i++ )
2671 if( (tv->columns[i].type & MSITYPE_STRING) &&
2672 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2673 sz += bytes_per_strref;
2674 else
2675 sz += bytes_per_column( tv->db, &tv->columns[i] );
2678 else
2681 * If the low bit is not set, mask is a bitmask.
2682 * Excepting for key fields, which are always present,
2683 * each bit indicates that a field is present in the transform record.
2685 * mask == 0 is a special case ... only the keys will be present
2686 * and it means that this row should be deleted.
2688 sz = 2;
2689 for( i=0; i<tv->num_cols; i++ )
2691 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2693 if( (tv->columns[i].type & MSITYPE_STRING) &&
2694 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2695 sz += bytes_per_strref;
2696 else
2697 sz += bytes_per_column( tv->db, &tv->columns[i] );
2702 /* check we didn't run of the end of the table */
2703 if ( (n+sz) > rawsize )
2705 ERR("borked.\n");
2706 dump_table( st, (USHORT *)rawdata, rawsize );
2707 break;
2710 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2711 if (rec)
2713 if ( mask & 1 )
2715 WCHAR table[32];
2716 DWORD sz = 32;
2717 UINT number = MSI_NULL_INTEGER;
2719 TRACE("inserting record\n");
2721 if (!lstrcmpW(name, szColumns))
2723 MSI_RecordGetStringW( rec, 1, table, &sz );
2724 number = MSI_RecordGetInteger( rec, 2 );
2727 * Native msi seems writes nul into the Number (2nd) column of
2728 * the _Columns table, only when the columns are from a new table
2730 if ( number == MSI_NULL_INTEGER )
2732 /* reset the column number on a new table */
2733 if ( lstrcmpW(coltable, table) )
2735 colcol = 0;
2736 lstrcpyW( coltable, table );
2739 /* fix nul column numbers */
2740 MSI_RecordSetInteger( rec, 2, ++colcol );
2744 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2745 if (r != ERROR_SUCCESS)
2746 ERR("insert row failed\n");
2748 if ( number != MSI_NULL_INTEGER && !lstrcmpW(name, szColumns) )
2749 msi_update_table_columns( db, table );
2751 else
2753 UINT row = 0;
2755 r = msi_table_find_row( tv, rec, &row );
2756 if (r != ERROR_SUCCESS)
2757 ERR("no matching row to transform\n");
2758 else if ( mask )
2760 TRACE("modifying row [%d]:\n", row);
2761 TABLE_set_row( &tv->view, row, rec, mask );
2763 else
2765 TRACE("deleting row [%d]:\n", row);
2766 TABLE_delete_row( &tv->view, row );
2769 if( TRACE_ON(msidb) ) dump_record( rec );
2770 msiobj_release( &rec->hdr );
2773 n += sz;
2776 err:
2777 /* no need to free the table, it's associated with the database */
2778 msi_free( rawdata );
2779 if( tv )
2780 tv->view.ops->delete( &tv->view );
2782 return ERROR_SUCCESS;
2786 * msi_table_apply_transform
2788 * Enumerate the table transforms in a transform storage and apply each one.
2790 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2792 struct list transforms;
2793 IEnumSTATSTG *stgenum = NULL;
2794 TRANSFORMDATA *transform;
2795 TRANSFORMDATA *tables = NULL, *columns = NULL;
2796 HRESULT r;
2797 STATSTG stat;
2798 string_table *strings;
2799 UINT ret = ERROR_FUNCTION_FAILED;
2800 UINT bytes_per_strref;
2802 TRACE("%p %p\n", db, stg );
2804 strings = msi_load_string_table( stg, &bytes_per_strref );
2805 if( !strings )
2806 goto end;
2808 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2809 if( FAILED( r ) )
2810 goto end;
2812 list_init(&transforms);
2814 while ( TRUE )
2816 MSITABLEVIEW *tv = NULL;
2817 WCHAR name[0x40];
2818 ULONG count = 0;
2820 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2821 if ( FAILED( r ) || !count )
2822 break;
2824 decode_streamname( stat.pwcsName, name );
2825 CoTaskMemFree( stat.pwcsName );
2826 if ( name[0] != 0x4840 )
2827 continue;
2829 if ( !lstrcmpW( name+1, szStringPool ) ||
2830 !lstrcmpW( name+1, szStringData ) )
2831 continue;
2833 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2834 if ( !transform )
2835 break;
2837 list_add_tail( &transforms, &transform->entry );
2839 transform->name = strdupW( name + 1 );
2841 if ( !lstrcmpW( transform->name, szTables ) )
2842 tables = transform;
2843 else if (!lstrcmpW( transform->name, szColumns ) )
2844 columns = transform;
2846 TRACE("transform contains stream %s\n", debugstr_w(name));
2848 /* load the table */
2849 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2850 if( r != ERROR_SUCCESS )
2851 continue;
2853 r = tv->view.ops->execute( &tv->view, NULL );
2854 if( r != ERROR_SUCCESS )
2856 tv->view.ops->delete( &tv->view );
2857 continue;
2860 tv->view.ops->delete( &tv->view );
2864 * Apply _Tables and _Columns transforms first so that
2865 * the table metadata is correct, and empty tables exist.
2867 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2868 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2869 goto end;
2871 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2872 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2873 goto end;
2875 ret = ERROR_SUCCESS;
2877 while ( !list_empty( &transforms ) )
2879 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2881 if ( lstrcmpW( transform->name, szColumns ) &&
2882 lstrcmpW( transform->name, szTables ) &&
2883 ret == ERROR_SUCCESS )
2885 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2888 list_remove( &transform->entry );
2889 msi_free( transform->name );
2890 msi_free( transform );
2893 if ( ret == ERROR_SUCCESS )
2894 append_storage_to_db( db, stg );
2896 end:
2897 if ( stgenum )
2898 IEnumSTATSTG_Release( stgenum );
2899 if ( strings )
2900 msi_destroy_stringtable( strings );
2902 return ret;
2905 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
2907 MSITRANSFORM *t;
2909 t = msi_alloc( sizeof *t );
2910 t->stg = stg;
2911 IStorage_AddRef( stg );
2912 list_add_tail( &db->transforms, &t->entry );
2915 void msi_free_transforms( MSIDATABASE *db )
2917 while( !list_empty( &db->transforms ) )
2919 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
2920 MSITRANSFORM, entry );
2921 list_remove( &t->entry );
2922 IStorage_Release( t->stg );
2923 msi_free( t );