msi: Correctly order transposed column values in the INSERT query.
[wine/multimedia.git] / dlls / msi / table.c
blob1d822e27f08289c24b6ac083c4b386f4e35e3696
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 MSICOLUMNHASHENTRY **hash_table;
63 } MSICOLUMNINFO;
65 typedef struct tagMSIORDERINFO
67 UINT *reorder;
68 UINT num_cols;
69 UINT cols[1];
70 } MSIORDERINFO;
72 struct tagMSITABLE
74 BYTE **data;
75 UINT row_count;
76 BYTE **nonpersistent_data;
77 UINT nonpersistent_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, NULL },
106 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, NULL },
107 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, NULL },
108 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, NULL },
111 static const MSICOLUMNINFO _Tables_cols[1] = {
112 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 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 for( i=0; i<table->nonpersistent_row_count; i++ )
479 msi_free( table->nonpersistent_data[i] );
480 msi_free( table->nonpersistent_data );
481 msi_free_colinfo( table->colinfo, table->col_count );
482 msi_free( table->colinfo );
483 msi_free( table );
486 static UINT msi_table_get_row_size( MSIDATABASE *db,const MSICOLUMNINFO *cols,
487 UINT count )
489 const MSICOLUMNINFO *last_col = &cols[count-1];
490 if (!count)
491 return 0;
492 return last_col->offset + bytes_per_column( db, last_col );
495 /* add this table to the list of cached tables in the database */
496 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
498 BYTE *rawdata = NULL;
499 UINT rawsize = 0, i, j, row_size = 0;
501 TRACE("%s\n",debugstr_w(t->name));
503 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
505 /* if we can't read the table, just assume that it's empty */
506 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
507 if( !rawdata )
508 return ERROR_SUCCESS;
510 TRACE("Read %d bytes\n", rawsize );
512 if( rawsize % row_size )
514 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
515 goto err;
518 t->row_count = rawsize / row_size;
519 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
520 if( !t->data )
521 goto err;
523 /* transpose all the data */
524 TRACE("Transposing data from %d rows\n", t->row_count );
525 for( i=0; i<t->row_count; i++ )
527 t->data[i] = msi_alloc( row_size );
528 if( !t->data[i] )
529 goto err;
531 for( j=0; j<t->col_count; j++ )
533 UINT ofs = t->colinfo[j].offset;
534 UINT n = bytes_per_column( db, &t->colinfo[j] );
535 UINT k;
537 if ( n != 2 && n != 3 && n != 4 )
539 ERR("oops - unknown column width %d\n", n);
540 goto err;
543 for ( k = 0; k < n; k++ )
544 t->data[i][ofs + k] = rawdata[ofs*t->row_count + i * n + k];
548 msi_free( rawdata );
549 return ERROR_SUCCESS;
550 err:
551 msi_free( rawdata );
552 return ERROR_FUNCTION_FAILED;
555 void free_cached_tables( MSIDATABASE *db )
557 while( !list_empty( &db->tables ) )
559 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
561 list_remove( &t->entry );
562 free_table( t );
566 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
568 MSITABLE *t;
570 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
571 if( !lstrcmpW( name, t->name ) )
572 return t;
574 return NULL;
577 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
579 UINT r, column_count = 0;
580 MSICOLUMNINFO *columns;
582 /* get the number of columns in this table */
583 column_count = 0;
584 r = get_tablecolumns( db, name, NULL, &column_count );
585 if( r != ERROR_SUCCESS )
586 return r;
588 *pcount = column_count;
590 /* if there's no columns, there's no table */
591 if( column_count == 0 )
592 return ERROR_INVALID_PARAMETER;
594 TRACE("Table %s found\n", debugstr_w(name) );
596 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
597 if( !columns )
598 return ERROR_FUNCTION_FAILED;
600 r = get_tablecolumns( db, name, columns, &column_count );
601 if( r != ERROR_SUCCESS )
603 msi_free( columns );
604 return ERROR_FUNCTION_FAILED;
607 *pcols = columns;
609 return r;
612 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
613 MSICONDITION 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->ref_count = 1;
634 table->row_count = 0;
635 table->data = NULL;
636 table->nonpersistent_row_count = 0;
637 table->nonpersistent_data = NULL;
638 table->colinfo = NULL;
639 table->col_count = 0;
640 table->persistent = persistent;
641 lstrcpyW( table->name, name );
643 for( col = col_info; col; col = col->next )
644 table->col_count++;
646 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
647 if (!table->colinfo)
649 free_table( table );
650 return ERROR_FUNCTION_FAILED;
653 for( i = 0, col = col_info; col; i++, col = col->next )
655 table->colinfo[ i ].tablename = strdupW( col->table );
656 table->colinfo[ i ].number = i + 1;
657 table->colinfo[ i ].colname = strdupW( col->column );
658 table->colinfo[ i ].type = col->type;
659 table->colinfo[ i ].offset = 0;
660 table->colinfo[ i ].ref_count = 0;
661 table->colinfo[ i ].hash_table = NULL;
663 table_calc_column_offsets( db, table->colinfo, table->col_count);
665 r = TABLE_CreateView( db, szTables, &tv );
666 TRACE("CreateView returned %x\n", r);
667 if( r )
669 free_table( table );
670 return r;
673 r = tv->ops->execute( tv, 0 );
674 TRACE("tv execute returned %x\n", r);
675 if( r )
676 goto err;
678 rec = MSI_CreateRecord( 1 );
679 if( !rec )
680 goto err;
682 r = MSI_RecordSetStringW( rec, 1, name );
683 if( r )
684 goto err;
686 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
687 TRACE("insert_row returned %x\n", r);
688 if( r )
689 goto err;
691 tv->ops->delete( tv );
692 tv = NULL;
694 msiobj_release( &rec->hdr );
695 rec = NULL;
697 if( persistent != MSICONDITION_FALSE )
699 /* add each column to the _Columns table */
700 r = TABLE_CreateView( db, szColumns, &tv );
701 if( r )
702 return r;
704 r = tv->ops->execute( tv, 0 );
705 TRACE("tv execute returned %x\n", r);
706 if( r )
707 goto err;
709 rec = MSI_CreateRecord( 4 );
710 if( !rec )
711 goto err;
713 r = MSI_RecordSetStringW( rec, 1, name );
714 if( r )
715 goto err;
718 * need to set the table, column number, col name and type
719 * for each column we enter in the table
721 nField = 1;
722 for( col = col_info; col; col = col->next )
724 r = MSI_RecordSetInteger( rec, 2, nField );
725 if( r )
726 goto err;
728 r = MSI_RecordSetStringW( rec, 3, col->column );
729 if( r )
730 goto err;
732 r = MSI_RecordSetInteger( rec, 4, col->type );
733 if( r )
734 goto err;
736 r = tv->ops->insert_row( tv, rec, -1, FALSE );
737 if( r )
738 goto err;
740 nField++;
742 if( !col )
743 r = ERROR_SUCCESS;
746 err:
747 if (rec)
748 msiobj_release( &rec->hdr );
749 /* FIXME: remove values from the string table on error */
750 if( tv )
751 tv->ops->delete( tv );
753 if (r == ERROR_SUCCESS)
755 list_add_head( &db->tables, &table->entry );
756 *table_ret = table;
758 else
759 free_table( table );
761 return r;
764 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
766 MSITABLE *table;
767 UINT r;
769 /* first, see if the table is cached */
770 table = find_cached_table( db, name );
771 if( table )
773 *table_ret = table;
774 return ERROR_SUCCESS;
777 /* nonexistent tables should be interpreted as empty tables */
778 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
779 if( !table )
780 return ERROR_FUNCTION_FAILED;
782 table->row_count = 0;
783 table->data = NULL;
784 table->nonpersistent_row_count = 0;
785 table->nonpersistent_data = NULL;
786 table->colinfo = NULL;
787 table->col_count = 0;
788 table->persistent = MSICONDITION_TRUE;
789 lstrcpyW( table->name, name );
791 if ( !lstrcmpW(name, szTables) || !lstrcmpW(name, szColumns) )
792 table->persistent = MSICONDITION_NONE;
794 r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
795 if (r != ERROR_SUCCESS)
797 free_table ( table );
798 return r;
801 r = read_table_from_storage( db, table, db->storage );
802 if( r != ERROR_SUCCESS )
804 free_table( table );
805 return r;
808 list_add_head( &db->tables, &table->entry );
809 *table_ret = table;
810 return ERROR_SUCCESS;
813 static UINT save_table( MSIDATABASE *db, const MSITABLE *t )
815 BYTE *rawdata = NULL, *p;
816 UINT rawsize, r, i, j, row_size;
818 /* Nothing to do for non-persistent tables */
819 if( t->persistent == MSICONDITION_FALSE )
820 return ERROR_SUCCESS;
822 TRACE("Saving %s\n", debugstr_w( t->name ) );
824 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
826 rawsize = t->row_count * row_size;
827 rawdata = msi_alloc_zero( rawsize );
828 if( !rawdata )
830 r = ERROR_NOT_ENOUGH_MEMORY;
831 goto err;
834 p = rawdata;
835 for( i=0; i<t->col_count; i++ )
837 for( j=0; j<t->row_count; j++ )
839 UINT offset = t->colinfo[i].offset;
841 *p++ = t->data[j][offset];
842 *p++ = t->data[j][offset + 1];
843 if( 4 == bytes_per_column( db, &t->colinfo[i] ) )
845 *p++ = t->data[j][offset + 2];
846 *p++ = t->data[j][offset + 3];
851 TRACE("writing %d bytes\n", rawsize);
852 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
854 err:
855 msi_free( rawdata );
857 return r;
860 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
861 DWORD count )
863 DWORD i;
865 for( i=0; colinfo && (i<count); i++ )
867 assert( (i+1) == colinfo[ i ].number );
868 if (i)
869 colinfo[i].offset = colinfo[ i - 1 ].offset
870 + bytes_per_column( db, &colinfo[ i - 1 ] );
871 else
872 colinfo[i].offset = 0;
873 TRACE("column %d is [%s] with type %08x ofs %d\n",
874 colinfo[i].number, debugstr_w(colinfo[i].colname),
875 colinfo[i].type, colinfo[i].offset);
879 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
880 MSICOLUMNINFO *colinfo, UINT *sz)
882 const MSICOLUMNINFO *p;
883 DWORD i, n;
885 TRACE("%s\n", debugstr_w(name));
887 if (!lstrcmpW( name, szTables ))
889 p = _Tables_cols;
890 n = 1;
892 else if (!lstrcmpW( name, szColumns ))
894 p = _Columns_cols;
895 n = 4;
897 else
898 return ERROR_FUNCTION_FAILED;
900 /* duplicate the string data so we can free it in msi_free_colinfo */
901 for (i=0; i<n; i++)
903 if (colinfo && (i < *sz) )
905 colinfo[i] = p[i];
906 colinfo[i].tablename = strdupW( p[i].tablename );
907 colinfo[i].colname = strdupW( p[i].colname );
909 if( colinfo && (i >= *sz) )
910 break;
912 table_calc_column_offsets( db, colinfo, n );
913 *sz = n;
914 return ERROR_SUCCESS;
917 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
919 UINT i;
921 for( i=0; i<count; i++ )
923 msi_free( colinfo[i].tablename );
924 msi_free( colinfo[i].colname );
925 msi_free( colinfo[i].hash_table );
929 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
931 return strdupW(msi_string_lookup_id( db->strings, stringid ));
934 static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
936 UINT ret = 0, i;
938 for (i = 0; i < bytes; i++)
939 ret += (data[row][col + i] << i * 8);
941 return ret;
944 static UINT get_tablecolumns( MSIDATABASE *db,
945 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
947 UINT r, i, n=0, table_id, count, maxcount = *sz;
948 MSITABLE *table = NULL;
950 TRACE("%s\n", debugstr_w(szTableName));
952 /* first check if there is a default table with that name */
953 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
954 if( ( r == ERROR_SUCCESS ) && *sz )
955 return r;
957 r = get_table( db, szColumns, &table );
958 if( r != ERROR_SUCCESS )
960 ERR("couldn't load _Columns table\n");
961 return ERROR_FUNCTION_FAILED;
964 /* convert table and column names to IDs from the string table */
965 r = msi_string2idW( db->strings, szTableName, &table_id );
966 if( r != ERROR_SUCCESS )
968 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
969 return r;
972 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
974 /* Note: _Columns table doesn't have non-persistent data */
976 /* if maxcount is non-zero, assume it's exactly right for this table */
977 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
978 count = table->row_count;
979 for( i=0; i<count; i++ )
981 if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
982 continue;
983 if( colinfo )
985 UINT id = read_table_int(table->data, i, table->colinfo[2].offset, db->bytes_per_strref);
986 UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
988 /* check the column number is in range */
989 if (col<1 || col>maxcount)
991 ERR("column %d out of range\n", col);
992 continue;
995 /* check if this column was already set */
996 if (colinfo[ col - 1 ].number)
998 ERR("duplicate column %d\n", col);
999 continue;
1002 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
1003 colinfo[ col - 1 ].number = col;
1004 colinfo[ col - 1 ].colname = msi_makestring( db, id );
1005 colinfo[ col - 1 ].type = read_table_int(table->data, i,
1006 table->colinfo[3].offset,
1007 sizeof(USHORT)) - (1<<15);
1008 colinfo[ col - 1 ].offset = 0;
1009 colinfo[ col - 1 ].ref_count = 0;
1010 colinfo[ col - 1 ].hash_table = NULL;
1012 n++;
1015 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
1017 if (colinfo && n != maxcount)
1019 ERR("missing column in table %s\n", debugstr_w(szTableName));
1020 msi_free_colinfo(colinfo, maxcount );
1021 return ERROR_FUNCTION_FAILED;
1024 table_calc_column_offsets( db, colinfo, n );
1025 *sz = n;
1027 return ERROR_SUCCESS;
1030 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
1032 MSITABLE *table;
1033 UINT size, offset, old_count;
1034 UINT n;
1036 table = find_cached_table( db, name );
1037 old_count = table->col_count;
1038 msi_free( table->colinfo );
1039 table_get_column_info( db, name, &table->colinfo, &table->col_count );
1041 if (!table->col_count)
1042 return;
1044 size = msi_table_get_row_size( db, table->colinfo, table->col_count );
1045 offset = table->colinfo[table->col_count - 1].offset;
1047 for ( n = 0; n < table->row_count; n++ )
1049 table->data[n] = msi_realloc( table->data[n], size );
1050 if (old_count < table->col_count)
1051 memset( &table->data[n][offset], 0, size - offset );
1055 /* try to find the table name in the _Tables table */
1056 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1058 UINT r, table_id = 0, i, count;
1059 MSITABLE *table = NULL;
1061 if( !lstrcmpW( name, szTables ) )
1062 return TRUE;
1063 if( !lstrcmpW( name, szColumns ) )
1064 return TRUE;
1066 r = msi_string2idW( db->strings, name, &table_id );
1067 if( r != ERROR_SUCCESS )
1069 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1070 return FALSE;
1073 r = get_table( db, szTables, &table );
1074 if( r != ERROR_SUCCESS )
1076 ERR("table %s not available\n", debugstr_w(szTables));
1077 return FALSE;
1080 count = table->row_count;
1081 for( i=0; i<count; i++ )
1082 if( table->data[ i ][ 0 ] == table_id )
1083 return TRUE;
1085 count = table->nonpersistent_row_count;
1086 for( i=0; i<count; i++ )
1087 if( table->nonpersistent_data[ i ][ 0 ] == table_id )
1088 return TRUE;
1090 return FALSE;
1093 /* below is the query interface to a table */
1095 typedef struct tagMSITABLEVIEW
1097 MSIVIEW view;
1098 MSIDATABASE *db;
1099 MSITABLE *table;
1100 MSICOLUMNINFO *columns;
1101 MSIORDERINFO *order;
1102 UINT num_cols;
1103 UINT row_size;
1104 WCHAR name[1];
1105 } MSITABLEVIEW;
1107 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1109 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1110 UINT offset, n;
1111 BYTE **data;
1113 if( !tv->table )
1114 return ERROR_INVALID_PARAMETER;
1116 if( (col==0) || (col>tv->num_cols) )
1117 return ERROR_INVALID_PARAMETER;
1119 /* how many rows are there ? */
1120 if( row >= tv->table->row_count + tv->table->nonpersistent_row_count )
1121 return ERROR_NO_MORE_ITEMS;
1123 if( tv->columns[col-1].offset >= tv->row_size )
1125 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1126 ERR("%p %p\n", tv, tv->columns );
1127 return ERROR_FUNCTION_FAILED;
1130 if (tv->order)
1131 row = tv->order->reorder[row];
1133 if (row >= tv->table->row_count)
1135 row -= tv->table->row_count;
1136 data = tv->table->nonpersistent_data;
1138 else
1139 data = tv->table->data;
1141 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1142 if (n != 2 && n != 3 && n != 4)
1144 ERR("oops! what is %d bytes per column?\n", n );
1145 return ERROR_FUNCTION_FAILED;
1148 offset = tv->columns[col-1].offset;
1149 *val = read_table_int(data, row, offset, n);
1151 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1153 return ERROR_SUCCESS;
1157 * We need a special case for streams, as we need to reference column with
1158 * the name of the stream in the same table, and the table name
1159 * which may not be available at higher levels of the query
1161 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1163 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1164 UINT ival = 0, refcol = 0, r;
1165 LPCWSTR sval;
1166 LPWSTR full_name;
1167 DWORD len;
1168 static const WCHAR szDot[] = { '.', 0 };
1169 WCHAR number[0x20];
1171 if( !view->ops->fetch_int )
1172 return ERROR_INVALID_PARAMETER;
1175 * The column marked with the type stream data seems to have a single number
1176 * which references the column containing the name of the stream data
1178 * Fetch the column to reference first.
1180 r = view->ops->fetch_int( view, row, col, &ival );
1181 if( r != ERROR_SUCCESS )
1182 return r;
1184 /* check the column value is in range */
1185 if (ival > tv->num_cols || ival == col)
1187 ERR("bad column ref (%u) for stream\n", ival);
1188 return ERROR_FUNCTION_FAILED;
1191 if ( tv->columns[ival - 1].type & MSITYPE_STRING )
1193 /* now get the column with the name of the stream */
1194 r = view->ops->fetch_int( view, row, ival, &refcol );
1195 if ( r != ERROR_SUCCESS )
1196 return r;
1198 /* lookup the string value from the string table */
1199 sval = msi_string_lookup_id( tv->db->strings, refcol );
1200 if ( !sval )
1201 return ERROR_INVALID_PARAMETER;
1203 else
1205 static const WCHAR fmt[] = { '%','d',0 };
1206 sprintfW( number, fmt, ival );
1207 sval = number;
1210 len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1211 full_name = msi_alloc( len*sizeof(WCHAR) );
1212 lstrcpyW( full_name, tv->name );
1213 lstrcatW( full_name, szDot );
1214 lstrcatW( full_name, sval );
1216 r = db_get_raw_stream( tv->db, full_name, stm );
1217 if( r )
1218 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1219 msi_free( full_name );
1221 return r;
1224 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1226 UINT offset, n, i;
1227 BYTE **data;
1229 if( !tv->table )
1230 return ERROR_INVALID_PARAMETER;
1232 if( (col==0) || (col>tv->num_cols) )
1233 return ERROR_INVALID_PARAMETER;
1235 if( row >= tv->table->row_count + tv->table->nonpersistent_row_count )
1236 return ERROR_INVALID_PARAMETER;
1238 if( tv->columns[col-1].offset >= tv->row_size )
1240 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1241 ERR("%p %p\n", tv, tv->columns );
1242 return ERROR_FUNCTION_FAILED;
1245 msi_free( tv->columns[col-1].hash_table );
1246 tv->columns[col-1].hash_table = NULL;
1248 if (row >= tv->table->row_count)
1250 row -= tv->table->row_count;
1251 data = tv->table->nonpersistent_data;
1253 else
1254 data = tv->table->data;
1256 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1257 if ( n != 2 && n != 3 && n != 4 )
1259 ERR("oops! what is %d bytes per column?\n", n );
1260 return ERROR_FUNCTION_FAILED;
1263 offset = tv->columns[col-1].offset;
1264 for ( i = 0; i < n; i++ )
1265 data[row][offset + i] = (val >> i * 8) & 0xff;
1267 return ERROR_SUCCESS;
1270 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1272 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1274 if (!tv->table)
1275 return ERROR_INVALID_PARAMETER;
1277 if (tv->order)
1278 row = tv->order->reorder[row];
1280 return msi_view_get_row(tv->db, view, row, rec);
1283 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1285 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1286 UINT i, val, r = ERROR_SUCCESS;
1288 if ( !tv->table )
1289 return ERROR_INVALID_PARAMETER;
1291 /* test if any of the mask bits are invalid */
1292 if ( mask >= (1<<tv->num_cols) )
1293 return ERROR_INVALID_PARAMETER;
1295 for ( i = 0; i < tv->num_cols; i++ )
1297 BOOL persistent;
1299 /* only update the fields specified in the mask */
1300 if ( !(mask&(1<<i)) )
1301 continue;
1303 /* if row >= tv->table->row_count then it is a non-persistent row */
1304 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1305 (row < tv->table->row_count);
1306 /* FIXME: should we allow updating keys? */
1308 val = 0;
1309 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1311 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1313 val = 1; /* refers to the first key column */
1315 else if ( tv->columns[i].type & MSITYPE_STRING )
1317 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1318 UINT ival, x;
1320 r = msi_string2idW(tv->db->strings, sval, &ival);
1321 if (r == ERROR_SUCCESS)
1323 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1324 if (ival == x)
1325 continue;
1328 val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
1329 persistent ? StringPersistent : StringNonPersistent );
1331 else if ( 2 == bytes_per_column( tv->db, &tv->columns[ i ] ) )
1333 val = 0x8000 + MSI_RecordGetInteger( rec, i + 1 );
1334 if ( val & 0xffff0000 )
1336 ERR("field %u value %d out of range\n", i+1, val - 0x8000 );
1337 return ERROR_FUNCTION_FAILED;
1340 else
1342 INT ival = MSI_RecordGetInteger( rec, i + 1 );
1343 val = ival ^ 0x80000000;
1347 r = TABLE_set_int( tv, row, i+1, val );
1348 if ( r != ERROR_SUCCESS )
1349 break;
1351 return r;
1354 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1356 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1357 BYTE **p, *row;
1358 UINT sz;
1359 BYTE ***data_ptr;
1360 UINT *row_count;
1362 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1364 if( !tv->table )
1365 return ERROR_INVALID_PARAMETER;
1367 row = msi_alloc_zero( tv->row_size );
1368 if( !row )
1369 return ERROR_NOT_ENOUGH_MEMORY;
1371 if( temporary )
1373 row_count = &tv->table->nonpersistent_row_count;
1374 data_ptr = &tv->table->nonpersistent_data;
1375 if (*num == -1)
1376 *num = tv->table->row_count + tv->table->nonpersistent_row_count;
1378 else
1380 row_count = &tv->table->row_count;
1381 data_ptr = &tv->table->data;
1382 if (*num == -1)
1383 *num = tv->table->row_count;
1386 sz = (*row_count + 1) * sizeof (BYTE*);
1387 if( *data_ptr )
1388 p = msi_realloc( *data_ptr, sz );
1389 else
1390 p = msi_alloc( sz );
1391 if( !p )
1393 msi_free( row );
1394 return ERROR_NOT_ENOUGH_MEMORY;
1397 *data_ptr = p;
1398 (*data_ptr)[*row_count] = row;
1399 (*row_count)++;
1401 return ERROR_SUCCESS;
1404 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1406 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1408 TRACE("%p %p\n", tv, record);
1410 TRACE("There are %d columns\n", tv->num_cols );
1412 return ERROR_SUCCESS;
1415 static UINT TABLE_close( struct tagMSIVIEW *view )
1417 TRACE("%p\n", view );
1419 return ERROR_SUCCESS;
1422 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1424 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1426 TRACE("%p %p %p\n", view, rows, cols );
1428 if( cols )
1429 *cols = tv->num_cols;
1430 if( rows )
1432 if( !tv->table )
1433 return ERROR_INVALID_PARAMETER;
1434 *rows = tv->table->row_count + tv->table->nonpersistent_row_count;
1437 return ERROR_SUCCESS;
1440 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1441 UINT n, LPWSTR *name, UINT *type )
1443 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1445 TRACE("%p %d %p %p\n", tv, n, name, type );
1447 if( ( n == 0 ) || ( n > tv->num_cols ) )
1448 return ERROR_INVALID_PARAMETER;
1450 if( name )
1452 *name = strdupW( tv->columns[n-1].colname );
1453 if( !*name )
1454 return ERROR_FUNCTION_FAILED;
1456 if( type )
1457 *type = tv->columns[n-1].type;
1459 return ERROR_SUCCESS;
1462 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1464 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1466 UINT r, row, i;
1468 /* check there's no null values where they're not allowed */
1469 for( i = 0; i < tv->num_cols; i++ )
1471 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1472 continue;
1474 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1475 TRACE("skipping binary column\n");
1476 else if ( tv->columns[i].type & MSITYPE_STRING )
1478 LPCWSTR str;
1480 str = MSI_RecordGetString( rec, i+1 );
1481 if (str == NULL || str[0] == 0)
1482 return ERROR_INVALID_DATA;
1484 else
1486 UINT n;
1488 n = MSI_RecordGetInteger( rec, i+1 );
1489 if (n == MSI_NULL_INTEGER)
1490 return ERROR_INVALID_DATA;
1494 /* check there's no duplicate keys */
1495 r = msi_table_find_row( tv, rec, &row );
1496 if (r == ERROR_SUCCESS)
1497 return ERROR_FUNCTION_FAILED;
1499 return ERROR_SUCCESS;
1502 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1504 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1505 UINT i, r, idx, size;
1506 BYTE **data;
1508 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1510 /* check that the key is unique - can we find a matching row? */
1511 r = table_validate_new( tv, rec );
1512 if( r != ERROR_SUCCESS )
1513 return ERROR_FUNCTION_FAILED;
1515 r = table_create_new_row( view, &row, temporary );
1516 TRACE("insert_row returned %08x\n", r);
1517 if( r != ERROR_SUCCESS )
1518 return r;
1520 idx = row;
1521 if( temporary )
1523 data = tv->table->nonpersistent_data;
1524 size = tv->table->nonpersistent_row_count;
1525 idx -= tv->table->row_count;
1527 else
1529 data = tv->table->data;
1530 size = tv->table->row_count;
1533 /* shift the rows to make room for the new row */
1534 if( idx != size - 1 )
1536 for (i = 1; i < size - idx; i++)
1537 memmove(&(data[size - i][0]),
1538 &(data[size - i - 1][0]), tv->row_size);
1541 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1544 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1546 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1547 UINT r, num_rows, num_cols, i;
1548 BYTE **data;
1550 TRACE("%p %d\n", tv, row);
1552 if ( !tv->table )
1553 return ERROR_INVALID_PARAMETER;
1555 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1556 if ( r != ERROR_SUCCESS )
1557 return r;
1559 if ( row >= num_rows )
1560 return ERROR_FUNCTION_FAILED;
1562 if ( row < tv->table->row_count )
1564 num_rows = tv->table->row_count;
1565 tv->table->row_count--;
1566 data = tv->table->data;
1568 else
1570 num_rows = tv->table->nonpersistent_row_count;
1571 row -= tv->table->row_count;
1572 tv->table->nonpersistent_row_count--;
1573 data = tv->table->nonpersistent_data;
1576 /* reset the hash tables */
1577 for (i = 0; i < tv->num_cols; i++)
1579 msi_free( tv->columns[i].hash_table );
1580 tv->columns[i].hash_table = NULL;
1583 if ( row == num_rows - 1 )
1584 return ERROR_SUCCESS;
1586 for (i = row + 1; i < num_rows; i++)
1587 memcpy(data[i - 1], data[i], tv->row_size);
1589 return ERROR_SUCCESS;
1592 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1594 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1595 UINT r, new_row;
1597 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1598 * sets the fetched record apart from other records
1601 if (!tv->table)
1602 return ERROR_INVALID_PARAMETER;
1604 r = msi_table_find_row(tv, rec, &new_row);
1605 if (r != ERROR_SUCCESS)
1607 ERR("can't find row to modify\n");
1608 return ERROR_FUNCTION_FAILED;
1611 /* the row cannot be changed */
1612 if (row != new_row + 1)
1613 return ERROR_FUNCTION_FAILED;
1615 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1618 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1620 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1621 UINT row, r;
1623 r = msi_table_find_row(tv, rec, &row);
1624 if (r != ERROR_SUCCESS)
1625 return r;
1627 return TABLE_delete_row(view, row);
1630 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1632 MSIRECORD *curr;
1633 UINT r, i, count;
1635 r = TABLE_get_row(view, row - 1, &curr);
1636 if (r != ERROR_SUCCESS)
1637 return r;
1639 count = MSI_RecordGetFieldCount(rec);
1640 for (i = 0; i < count; i++)
1641 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1643 msiobj_release(&curr->hdr);
1644 return ERROR_SUCCESS;
1647 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1648 MSIRECORD *rec, UINT row)
1650 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1651 UINT r;
1653 TRACE("%p %d %p\n", view, eModifyMode, rec );
1655 switch (eModifyMode)
1657 case MSIMODIFY_DELETE:
1658 r = modify_delete_row( view, rec );
1659 break;
1660 case MSIMODIFY_VALIDATE_NEW:
1661 r = table_validate_new( tv, rec );
1662 break;
1664 case MSIMODIFY_INSERT:
1665 r = table_validate_new( tv, rec );
1666 if (r != ERROR_SUCCESS)
1667 break;
1668 r = TABLE_insert_row( view, rec, -1, FALSE );
1669 break;
1671 case MSIMODIFY_INSERT_TEMPORARY:
1672 r = table_validate_new( tv, rec );
1673 if (r != ERROR_SUCCESS)
1674 break;
1675 r = TABLE_insert_row( view, rec, -1, TRUE );
1676 break;
1678 case MSIMODIFY_REFRESH:
1679 r = msi_refresh_record( view, rec, row );
1680 break;
1682 case MSIMODIFY_UPDATE:
1683 r = msi_table_update( view, rec, row );
1684 break;
1686 case MSIMODIFY_ASSIGN:
1687 case MSIMODIFY_REPLACE:
1688 case MSIMODIFY_MERGE:
1689 case MSIMODIFY_VALIDATE:
1690 case MSIMODIFY_VALIDATE_FIELD:
1691 case MSIMODIFY_VALIDATE_DELETE:
1692 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1693 r = ERROR_CALL_NOT_IMPLEMENTED;
1694 break;
1696 default:
1697 r = ERROR_INVALID_DATA;
1700 return r;
1703 static UINT TABLE_delete( struct tagMSIVIEW *view )
1705 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1707 TRACE("%p\n", view );
1709 tv->table = NULL;
1710 tv->columns = NULL;
1712 if (tv->order)
1714 msi_free( tv->order->reorder );
1715 msi_free( tv->order );
1716 tv->order = NULL;
1719 msi_free( tv );
1721 return ERROR_SUCCESS;
1724 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1725 UINT val, UINT *row, MSIITERHANDLE *handle )
1727 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1728 const MSICOLUMNHASHENTRY *entry;
1730 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1732 if( !tv->table )
1733 return ERROR_INVALID_PARAMETER;
1735 if( (col==0) || (col > tv->num_cols) )
1736 return ERROR_INVALID_PARAMETER;
1738 if( !tv->columns[col-1].hash_table )
1740 UINT i;
1741 UINT num_rows = tv->table->row_count + tv->table->nonpersistent_row_count;
1742 MSICOLUMNHASHENTRY **hash_table;
1743 MSICOLUMNHASHENTRY *new_entry;
1745 if( tv->columns[col-1].offset >= tv->row_size )
1747 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1748 ERR("%p %p\n", tv, tv->columns );
1749 return ERROR_FUNCTION_FAILED;
1752 /* allocate contiguous memory for the table and its entries so we
1753 * don't have to do an expensive cleanup */
1754 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1755 num_rows * sizeof(MSICOLUMNHASHENTRY));
1756 if (!hash_table)
1757 return ERROR_OUTOFMEMORY;
1759 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1760 tv->columns[col-1].hash_table = hash_table;
1762 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1764 for (i = 0; i < num_rows; i++, new_entry++)
1766 UINT row_value;
1768 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1769 continue;
1771 new_entry->next = NULL;
1772 new_entry->value = row_value;
1773 new_entry->row = i;
1774 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1776 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1777 while (prev_entry->next)
1778 prev_entry = prev_entry->next;
1779 prev_entry->next = new_entry;
1781 else
1782 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1786 if( !*handle )
1787 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1788 else
1789 entry = (*handle)->next;
1791 while (entry && entry->value != val)
1792 entry = entry->next;
1794 *handle = entry;
1795 if (!entry)
1796 return ERROR_NO_MORE_ITEMS;
1798 *row = entry->row;
1800 return ERROR_SUCCESS;
1803 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1805 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1806 UINT i;
1808 TRACE("%p %d\n", view, tv->table->ref_count);
1810 for (i = 0; i < tv->table->col_count; i++)
1812 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1813 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1816 return InterlockedIncrement(&tv->table->ref_count);
1819 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1821 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1822 MSIRECORD *rec = NULL;
1823 MSIVIEW *columns = NULL;
1824 UINT row, r;
1826 rec = MSI_CreateRecord(2);
1827 if (!rec)
1828 return ERROR_OUTOFMEMORY;
1830 MSI_RecordSetStringW(rec, 1, table);
1831 MSI_RecordSetInteger(rec, 2, number);
1833 r = TABLE_CreateView(tv->db, szColumns, &columns);
1834 if (r != ERROR_SUCCESS)
1835 return r;
1837 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
1838 if (r != ERROR_SUCCESS)
1839 goto done;
1841 r = TABLE_delete_row(columns, row);
1842 if (r != ERROR_SUCCESS)
1843 goto done;
1845 msi_update_table_columns(tv->db, table);
1847 done:
1848 msiobj_release(&rec->hdr);
1849 columns->ops->delete(columns);
1850 return r;
1853 static UINT TABLE_release(struct tagMSIVIEW *view)
1855 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1856 INT ref = tv->table->ref_count;
1857 UINT i, r;
1859 TRACE("%p %d\n", view, ref);
1861 for (i = 0; i < tv->table->col_count; i++)
1863 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1865 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1866 if (ref == 0)
1868 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1869 tv->table->colinfo[i].number);
1870 if (r != ERROR_SUCCESS)
1871 break;
1876 ref = InterlockedDecrement(&tv->table->ref_count);
1877 if (ref == 0)
1879 if (!tv->table->row_count)
1881 list_remove(&tv->table->entry);
1882 free_table(tv->table);
1883 TABLE_delete(view);
1887 return ref;
1890 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
1891 LPCWSTR column, UINT type, BOOL hold)
1893 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1894 MSITABLE *msitable;
1895 MSIRECORD *rec;
1896 UINT r, i;
1898 rec = MSI_CreateRecord(4);
1899 if (!rec)
1900 return ERROR_OUTOFMEMORY;
1902 MSI_RecordSetStringW(rec, 1, table);
1903 MSI_RecordSetInteger(rec, 2, number);
1904 MSI_RecordSetStringW(rec, 3, column);
1905 MSI_RecordSetInteger(rec, 4, type);
1907 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
1908 if (r != ERROR_SUCCESS)
1909 goto done;
1911 msi_update_table_columns(tv->db, table);
1913 if (!hold)
1914 goto done;
1916 msitable = find_cached_table(tv->db, table);
1917 for (i = 0; i < msitable->col_count; i++)
1919 if (!lstrcmpW(msitable->colinfo[i].colname, column))
1921 InterlockedIncrement(&msitable->colinfo[i].ref_count);
1922 break;
1926 done:
1927 msiobj_release(&rec->hdr);
1928 return r;
1931 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
1933 UINT n, r, count;
1935 r = TABLE_get_dimensions(view, NULL, &count);
1936 if (r != ERROR_SUCCESS)
1937 return r;
1939 if (order->num_cols >= count)
1940 return ERROR_FUNCTION_FAILED;
1942 r = VIEW_find_column(view, name, &n);
1943 if (r != ERROR_SUCCESS)
1944 return r;
1946 order->cols[order->num_cols] = n;
1947 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
1949 order->num_cols++;
1951 return ERROR_SUCCESS;
1954 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
1955 UINT a, UINT b, UINT *swap)
1957 UINT r, i, a_val = 0, b_val = 0;
1959 *swap = 0;
1960 for (i = 0; i < order->num_cols; i++)
1962 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
1963 if (r != ERROR_SUCCESS)
1964 return r;
1966 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
1967 if (r != ERROR_SUCCESS)
1968 return r;
1970 if (a_val != b_val)
1972 if (a_val > b_val)
1973 *swap = 1;
1974 break;
1978 return ERROR_SUCCESS;
1981 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
1982 UINT left, UINT right)
1984 UINT r, i, j, temp;
1985 UINT swap = 0, center = (left + right) / 2;
1986 UINT *array = order->reorder;
1988 if (left == right)
1989 return ERROR_SUCCESS;
1991 /* sort the left half */
1992 r = order_mergesort(view, order, left, center);
1993 if (r != ERROR_SUCCESS)
1994 return r;
1996 /* sort the right half */
1997 r = order_mergesort(view, order, center + 1, right);
1998 if (r != ERROR_SUCCESS)
1999 return r;
2001 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2003 r = order_compare(view, order, array[i], array[j], &swap);
2004 if (r != ERROR_SUCCESS)
2005 return r;
2007 if (swap)
2009 temp = array[j];
2010 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2011 array[i] = temp;
2012 j++;
2013 center++;
2017 return ERROR_SUCCESS;
2020 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2022 UINT i, swap, r;
2024 for (i = 1; i < num_rows; i++)
2026 r = order_compare(view, order, order->reorder[i - 1],
2027 order->reorder[i], &swap);
2028 if (r != ERROR_SUCCESS)
2029 return r;
2031 if (!swap)
2032 continue;
2034 ERR("Bad order! %d\n", i);
2035 return ERROR_FUNCTION_FAILED;
2038 return ERROR_SUCCESS;
2041 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2043 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2044 MSIORDERINFO *order;
2045 column_info *ptr;
2046 UINT r, i;
2047 UINT rows, cols;
2049 TRACE("sorting table %s\n", debugstr_w(tv->name));
2051 r = TABLE_get_dimensions(view, &rows, &cols);
2052 if (r != ERROR_SUCCESS)
2053 return r;
2055 if (rows == 0)
2056 return ERROR_SUCCESS;
2058 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2059 if (!order)
2060 return ERROR_OUTOFMEMORY;
2062 for (ptr = columns; ptr; ptr = ptr->next)
2063 order_add_column(view, order, ptr->column);
2065 order->reorder = msi_alloc(rows * sizeof(UINT));
2066 if (!order->reorder)
2067 return ERROR_OUTOFMEMORY;
2069 for (i = 0; i < rows; i++)
2070 order->reorder[i] = i;
2072 r = order_mergesort(view, order, 0, rows - 1);
2073 if (r != ERROR_SUCCESS)
2074 return r;
2076 r = order_verify(view, order, rows);
2077 if (r != ERROR_SUCCESS)
2078 return r;
2080 tv->order = order;
2082 return ERROR_SUCCESS;
2085 static UINT TABLE_drop(struct tagMSIVIEW *view)
2087 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2088 MSIVIEW *tables = NULL;
2089 MSIRECORD *rec = NULL;
2090 UINT r, row;
2091 INT i;
2093 TRACE("dropping table %s\n", debugstr_w(tv->name));
2095 for (i = tv->table->col_count - 1; i >= 0; i--)
2097 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2098 tv->table->colinfo[i].number);
2099 if (r != ERROR_SUCCESS)
2100 return r;
2103 rec = MSI_CreateRecord(1);
2104 if (!rec)
2105 return ERROR_OUTOFMEMORY;
2107 MSI_RecordSetStringW(rec, 1, tv->name);
2109 r = TABLE_CreateView(tv->db, szTables, &tables);
2110 if (r != ERROR_SUCCESS)
2111 return r;
2113 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
2114 if (r != ERROR_SUCCESS)
2115 goto done;
2117 r = TABLE_delete_row(tables, row);
2118 if (r != ERROR_SUCCESS)
2119 goto done;
2121 list_remove(&tv->table->entry);
2122 free_table(tv->table);
2123 TABLE_delete(view);
2125 done:
2126 msiobj_release(&rec->hdr);
2127 tables->ops->delete(tables);
2129 return r;
2132 static const MSIVIEWOPS table_ops =
2134 TABLE_fetch_int,
2135 TABLE_fetch_stream,
2136 TABLE_get_row,
2137 TABLE_set_row,
2138 TABLE_insert_row,
2139 TABLE_delete_row,
2140 TABLE_execute,
2141 TABLE_close,
2142 TABLE_get_dimensions,
2143 TABLE_get_column_info,
2144 TABLE_modify,
2145 TABLE_delete,
2146 TABLE_find_matching_rows,
2147 TABLE_add_ref,
2148 TABLE_release,
2149 TABLE_add_column,
2150 TABLE_remove_column,
2151 TABLE_sort,
2152 TABLE_drop,
2155 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2157 MSITABLEVIEW *tv ;
2158 UINT r, sz;
2160 static const WCHAR Streams[] = {'_','S','t','r','e','a','m','s',0};
2161 static const WCHAR Storages[] = {'_','S','t','o','r','a','g','e','s',0};
2163 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2165 if ( !lstrcmpW( name, Streams ) )
2166 return STREAMS_CreateView( db, view );
2167 else if ( !lstrcmpW( name, Storages ) )
2168 return STORAGES_CreateView( db, view );
2170 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2171 tv = msi_alloc_zero( sz );
2172 if( !tv )
2173 return ERROR_FUNCTION_FAILED;
2175 r = get_table( db, name, &tv->table );
2176 if( r != ERROR_SUCCESS )
2178 msi_free( tv );
2179 WARN("table not found\n");
2180 return r;
2183 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2185 /* fill the structure */
2186 tv->view.ops = &table_ops;
2187 tv->db = db;
2188 tv->columns = tv->table->colinfo;
2189 tv->num_cols = tv->table->col_count;
2190 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count );
2192 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2194 *view = (MSIVIEW*) tv;
2195 lstrcpyW( tv->name, name );
2197 return ERROR_SUCCESS;
2200 UINT MSI_CommitTables( MSIDATABASE *db )
2202 UINT r;
2203 MSITABLE *table = NULL;
2205 TRACE("%p\n",db);
2207 r = msi_save_string_table( db->strings, db->storage );
2208 if( r != ERROR_SUCCESS )
2210 WARN("failed to save string table r=%08x\n",r);
2211 return r;
2214 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2216 r = save_table( db, table );
2217 if( r != ERROR_SUCCESS )
2219 WARN("failed to save table %s (r=%08x)\n",
2220 debugstr_w(table->name), r);
2221 return r;
2225 /* force everything to reload next time */
2226 free_cached_tables( db );
2228 return ERROR_SUCCESS;
2231 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2233 MSITABLE *t;
2234 UINT r;
2236 TRACE("%p %s\n", db, debugstr_w(table));
2238 if (!table)
2239 return MSICONDITION_ERROR;
2241 r = get_table( db, table, &t );
2242 if (r != ERROR_SUCCESS)
2243 return MSICONDITION_NONE;
2245 return t->persistent;
2248 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2250 UINT ret = 0, i;
2252 for (i = 0; i < bytes; i++)
2253 ret += (data[col + i] << i * 8);
2255 return ret;
2258 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2259 const BYTE *rawdata, UINT bytes_per_strref )
2261 UINT i, val, ofs = 0;
2262 USHORT mask;
2263 MSICOLUMNINFO *columns = tv->columns;
2264 MSIRECORD *rec;
2266 mask = rawdata[0] | (rawdata[1] << 8);
2267 rawdata += 2;
2269 rec = MSI_CreateRecord( tv->num_cols );
2270 if( !rec )
2271 return rec;
2273 TRACE("row ->\n");
2274 for( i=0; i<tv->num_cols; i++ )
2276 if ( (mask&1) && (i>=(mask>>8)) )
2277 break;
2278 /* all keys must be present */
2279 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2280 continue;
2282 if( (columns[i].type & MSITYPE_STRING) &&
2283 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2285 LPCWSTR sval;
2287 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2288 sval = msi_string_lookup_id( st, val );
2289 MSI_RecordSetStringW( rec, i+1, sval );
2290 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2291 ofs += bytes_per_strref;
2293 else
2295 UINT n = bytes_per_column( tv->db, &columns[i] );
2296 switch( n )
2298 case 2:
2299 val = read_raw_int(rawdata, ofs, n);
2300 if (val)
2301 MSI_RecordSetInteger( rec, i+1, val^0x8000 );
2302 TRACE(" field %d [0x%04x]\n", i+1, val );
2303 break;
2304 case 4:
2305 val = read_raw_int(rawdata, ofs, n);
2306 if (val)
2307 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2308 TRACE(" field %d [0x%08x]\n", i+1, val );
2309 break;
2310 default:
2311 ERR("oops - unknown column width %d\n", n);
2312 break;
2314 ofs += n;
2317 return rec;
2320 static void dump_record( MSIRECORD *rec )
2322 UINT i, n;
2324 n = MSI_RecordGetFieldCount( rec );
2325 for( i=1; i<=n; i++ )
2327 LPCWSTR sval = MSI_RecordGetString( rec, i );
2329 if( MSI_RecordIsNull( rec, i ) )
2330 TRACE("row -> []\n");
2331 else if( (sval = MSI_RecordGetString( rec, i )) )
2332 TRACE("row -> [%s]\n", debugstr_w(sval));
2333 else
2334 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2338 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2340 LPCWSTR sval;
2341 UINT i;
2343 for( i=0; i<(rawsize/2); i++ )
2345 sval = msi_string_lookup_id( st, rawdata[i] );
2346 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2350 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2352 LPCWSTR str;
2353 UINT i, r, *data;
2355 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2356 for( i=0; i<tv->num_cols; i++ )
2358 data[i] = 0;
2360 if ( ~tv->columns[i].type & MSITYPE_KEY )
2361 continue;
2363 /* turn the transform column value into a row value */
2364 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2365 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2367 str = MSI_RecordGetString( rec, i+1 );
2368 r = msi_string2idW( tv->db->strings, str, &data[i] );
2370 /* if there's no matching string in the string table,
2371 these keys can't match any record, so fail now. */
2372 if( ERROR_SUCCESS != r )
2374 msi_free( data );
2375 return NULL;
2378 else
2380 data[i] = MSI_RecordGetInteger( rec, i+1 );
2382 if (data[i] == MSI_NULL_INTEGER)
2383 data[i] = 0;
2384 else if ((tv->columns[i].type&0xff) == 2)
2385 data[i] += 0x8000;
2386 else
2387 data[i] += 0x80000000;
2390 return data;
2393 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2395 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2397 for( i=0; i<tv->num_cols; i++ )
2399 if ( ~tv->columns[i].type & MSITYPE_KEY )
2400 continue;
2402 /* turn the transform column value into a row value */
2403 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2404 if ( r != ERROR_SUCCESS )
2406 ERR("TABLE_fetch_int shouldn't fail here\n");
2407 break;
2410 /* if this key matches, move to the next column */
2411 if ( x != data[i] )
2413 ret = ERROR_FUNCTION_FAILED;
2414 break;
2417 ret = ERROR_SUCCESS;
2420 return ret;
2423 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
2425 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2427 data = msi_record_to_row( tv, rec );
2428 if( !data )
2429 return r;
2430 for( i = 0; i < tv->table->row_count + tv->table->nonpersistent_row_count; i++ )
2432 r = msi_row_matches( tv, i, data );
2433 if( r == ERROR_SUCCESS )
2435 *row = i;
2436 break;
2439 msi_free( data );
2440 return r;
2443 typedef struct
2445 struct list entry;
2446 LPWSTR name;
2447 } TRANSFORMDATA;
2449 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2450 string_table *st, TRANSFORMDATA *transform,
2451 UINT bytes_per_strref )
2453 UINT rawsize = 0;
2454 BYTE *rawdata = NULL;
2455 MSITABLEVIEW *tv = NULL;
2456 UINT r, n, sz, i, mask;
2457 MSIRECORD *rec = NULL;
2458 UINT colcol = 0;
2459 WCHAR coltable[32];
2460 LPWSTR name;
2462 if (!transform)
2463 return ERROR_SUCCESS;
2465 name = transform->name;
2467 coltable[0] = 0;
2468 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2470 /* read the transform data */
2471 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2472 if ( !rawdata )
2474 TRACE("table %s empty\n", debugstr_w(name) );
2475 return ERROR_INVALID_TABLE;
2478 /* create a table view */
2479 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2480 if( r != ERROR_SUCCESS )
2481 goto err;
2483 r = tv->view.ops->execute( &tv->view, NULL );
2484 if( r != ERROR_SUCCESS )
2485 goto err;
2487 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2488 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2490 /* interpret the data */
2491 r = ERROR_SUCCESS;
2492 for( n=0; n < rawsize; )
2494 mask = rawdata[n] | (rawdata[n+1] << 8);
2496 if (mask&1)
2499 * if the low bit is set, columns are continuous and
2500 * the number of columns is specified in the high byte
2502 sz = 2;
2503 for( i=0; i<tv->num_cols; i++ )
2505 if( (tv->columns[i].type & MSITYPE_STRING) &&
2506 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2507 sz += bytes_per_strref;
2508 else
2509 sz += bytes_per_column( tv->db, &tv->columns[i] );
2512 else
2515 * If the low bit is not set, mask is a bitmask.
2516 * Excepting for key fields, which are always present,
2517 * each bit indicates that a field is present in the transform record.
2519 * mask == 0 is a special case ... only the keys will be present
2520 * and it means that this row should be deleted.
2522 sz = 2;
2523 for( i=0; i<tv->num_cols; i++ )
2525 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2527 if( (tv->columns[i].type & MSITYPE_STRING) &&
2528 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2529 sz += bytes_per_strref;
2530 else
2531 sz += bytes_per_column( tv->db, &tv->columns[i] );
2536 /* check we didn't run of the end of the table */
2537 if ( (n+sz) > rawsize )
2539 ERR("borked.\n");
2540 dump_table( st, (USHORT *)rawdata, rawsize );
2541 break;
2544 rec = msi_get_transform_record( tv, st, &rawdata[n], bytes_per_strref );
2545 if (rec)
2547 if ( mask & 1 )
2549 WCHAR table[32];
2550 DWORD sz = 32;
2551 UINT number = MSI_NULL_INTEGER;
2553 TRACE("inserting record\n");
2555 if (!lstrcmpW(name, szColumns))
2557 MSI_RecordGetStringW( rec, 1, table, &sz );
2558 number = MSI_RecordGetInteger( rec, 2 );
2561 * Native msi seems writes nul into the Number (2nd) column of
2562 * the _Columns table, only when the columns are from a new table
2564 if ( number == MSI_NULL_INTEGER )
2566 /* reset the column number on a new table */
2567 if ( lstrcmpW(coltable, table) )
2569 colcol = 0;
2570 lstrcpyW( coltable, table );
2573 /* fix nul column numbers */
2574 MSI_RecordSetInteger( rec, 2, ++colcol );
2578 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2579 if (r != ERROR_SUCCESS)
2580 ERR("insert row failed\n");
2582 if ( number != MSI_NULL_INTEGER && !lstrcmpW(name, szColumns) )
2583 msi_update_table_columns( db, table );
2585 else
2587 UINT row = 0;
2589 r = msi_table_find_row( tv, rec, &row );
2590 if (r != ERROR_SUCCESS)
2591 ERR("no matching row to transform\n");
2592 else if ( mask )
2594 TRACE("modifying row [%d]:\n", row);
2595 TABLE_set_row( &tv->view, row, rec, mask );
2597 else
2599 TRACE("deleting row [%d]:\n", row);
2600 TABLE_delete_row( &tv->view, row );
2603 if( TRACE_ON(msidb) ) dump_record( rec );
2604 msiobj_release( &rec->hdr );
2607 n += sz;
2610 err:
2611 /* no need to free the table, it's associated with the database */
2612 msi_free( rawdata );
2613 if( tv )
2614 tv->view.ops->delete( &tv->view );
2616 return ERROR_SUCCESS;
2620 * msi_table_apply_transform
2622 * Enumerate the table transforms in a transform storage and apply each one.
2624 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2626 struct list transforms;
2627 IEnumSTATSTG *stgenum = NULL;
2628 TRANSFORMDATA *transform;
2629 TRANSFORMDATA *tables = NULL, *columns = NULL;
2630 HRESULT r;
2631 STATSTG stat;
2632 string_table *strings;
2633 UINT ret = ERROR_FUNCTION_FAILED;
2634 UINT bytes_per_strref;
2636 TRACE("%p %p\n", db, stg );
2638 strings = msi_load_string_table( stg, &bytes_per_strref );
2639 if( !strings )
2640 goto end;
2642 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2643 if( FAILED( r ) )
2644 goto end;
2646 list_init(&transforms);
2648 while ( TRUE )
2650 MSITABLEVIEW *tv = NULL;
2651 WCHAR name[0x40];
2652 ULONG count = 0;
2654 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2655 if ( FAILED( r ) || !count )
2656 break;
2658 decode_streamname( stat.pwcsName, name );
2659 CoTaskMemFree( stat.pwcsName );
2660 if ( name[0] != 0x4840 )
2661 continue;
2663 if ( !lstrcmpW( name+1, szStringPool ) ||
2664 !lstrcmpW( name+1, szStringData ) )
2665 continue;
2667 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2668 if ( !transform )
2669 break;
2671 list_add_tail( &transforms, &transform->entry );
2673 transform->name = strdupW( name + 1 );
2675 if ( !lstrcmpW( transform->name, szTables ) )
2676 tables = transform;
2677 else if (!lstrcmpW( transform->name, szColumns ) )
2678 columns = transform;
2680 TRACE("transform contains stream %s\n", debugstr_w(name));
2682 /* load the table */
2683 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2684 if( r != ERROR_SUCCESS )
2685 continue;
2687 r = tv->view.ops->execute( &tv->view, NULL );
2688 if( r != ERROR_SUCCESS )
2690 tv->view.ops->delete( &tv->view );
2691 continue;
2694 tv->view.ops->delete( &tv->view );
2698 * Apply _Tables and _Columns transforms first so that
2699 * the table metadata is correct, and empty tables exist.
2701 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2702 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2703 goto end;
2705 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2706 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2707 goto end;
2709 ret = ERROR_SUCCESS;
2711 while ( !list_empty( &transforms ) )
2713 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2715 if ( lstrcmpW( transform->name, szColumns ) &&
2716 lstrcmpW( transform->name, szTables ) &&
2717 ret == ERROR_SUCCESS )
2719 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2722 list_remove( &transform->entry );
2723 msi_free( transform->name );
2724 msi_free( transform );
2727 if ( ret == ERROR_SUCCESS )
2728 append_storage_to_db( db, stg );
2730 end:
2731 if ( stgenum )
2732 IEnumSTATSTG_Release( stgenum );
2733 if ( strings )
2734 msi_destroy_stringtable( strings );
2736 return ret;
2739 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
2741 MSITRANSFORM *t;
2743 t = msi_alloc( sizeof *t );
2744 t->stg = stg;
2745 IStorage_AddRef( stg );
2746 list_add_tail( &db->transforms, &t->entry );
2749 void msi_free_transforms( MSIDATABASE *db )
2751 while( !list_empty( &db->transforms ) )
2753 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
2754 MSITRANSFORM, entry );
2755 list_remove( &t->entry );
2756 IStorage_Release( t->stg );
2757 msi_free( t );