msi: Use 0-indexed row numbers in the modify() view operation.
[wine.git] / dlls / msi / table.c
blobb507268eb7c8ec49e027b496c977f7278f1c9405
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
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winerror.h"
29 #include "msi.h"
30 #include "msiquery.h"
31 #include "objbase.h"
32 #include "objidl.h"
33 #include "winnls.h"
34 #include "msipriv.h"
35 #include "query.h"
37 #include "wine/debug.h"
38 #include "wine/unicode.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
42 #define MSITABLE_HASH_TABLE_SIZE 37
44 typedef struct tagMSICOLUMNHASHENTRY
46 struct tagMSICOLUMNHASHENTRY *next;
47 UINT value;
48 UINT row;
49 } MSICOLUMNHASHENTRY;
51 typedef struct tagMSICOLUMNINFO
53 LPCWSTR tablename;
54 UINT number;
55 LPCWSTR colname;
56 UINT type;
57 UINT offset;
58 INT ref_count;
59 BOOL temporary;
60 MSICOLUMNHASHENTRY **hash_table;
61 } MSICOLUMNINFO;
63 struct tagMSITABLE
65 BYTE **data;
66 BOOL *data_persistent;
67 UINT row_count;
68 struct list entry;
69 MSICOLUMNINFO *colinfo;
70 UINT col_count;
71 MSICONDITION persistent;
72 INT ref_count;
73 WCHAR name[1];
76 /* information for default tables */
77 static const WCHAR szTables[] = {'_','T','a','b','l','e','s',0};
78 static const WCHAR szTable[] = {'T','a','b','l','e',0};
79 static const WCHAR szColumns[] = {'_','C','o','l','u','m','n','s',0};
80 static const WCHAR szNumber[] = {'N','u','m','b','e','r',0};
81 static const WCHAR szType[] = {'T','y','p','e',0};
83 static const MSICOLUMNINFO _Columns_cols[4] = {
84 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
85 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
86 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
87 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
90 static const MSICOLUMNINFO _Tables_cols[1] = {
91 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
94 #define MAX_STREAM_NAME 0x1f
96 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
98 if( MSITYPE_IS_BINARY(col->type) )
99 return 2;
101 if( col->type & MSITYPE_STRING )
102 return bytes_per_strref;
104 if( (col->type & 0xff) <= 2)
105 return 2;
107 if( (col->type & 0xff) != 4 )
108 ERR("Invalid column size %u\n", col->type & 0xff);
110 return 4;
113 static int utf2mime(int x)
115 if( (x>='0') && (x<='9') )
116 return x-'0';
117 if( (x>='A') && (x<='Z') )
118 return x-'A'+10;
119 if( (x>='a') && (x<='z') )
120 return x-'a'+10+26;
121 if( x=='.' )
122 return 10+26+26;
123 if( x=='_' )
124 return 10+26+26+1;
125 return -1;
128 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
130 DWORD count = MAX_STREAM_NAME;
131 DWORD ch, next;
132 LPWSTR out, p;
134 if( !bTable )
135 count = lstrlenW( in )+2;
136 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
137 p = out;
139 if( bTable )
141 *p++ = 0x4840;
142 count --;
144 while( count -- )
146 ch = *in++;
147 if( !ch )
149 *p = ch;
150 return out;
152 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
154 ch = utf2mime(ch) + 0x4800;
155 next = *in;
156 if( next && (next<0x80) )
158 next = utf2mime(next);
159 if( next != -1 )
161 next += 0x3ffffc0;
162 ch += (next<<6);
163 in++;
167 *p++ = ch;
169 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
170 msi_free( out );
171 return NULL;
174 static int mime2utf(int x)
176 if( x<10 )
177 return x + '0';
178 if( x<(10+26))
179 return x - 10 + 'A';
180 if( x<(10+26+26))
181 return x - 10 - 26 + 'a';
182 if( x == (10+26+26) )
183 return '.';
184 return '_';
187 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
189 WCHAR ch;
190 DWORD count = 0;
192 while ( (ch = *in++) )
194 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
196 if( ch >= 0x4800 )
197 ch = mime2utf(ch-0x4800);
198 else
200 ch -= 0x3800;
201 *out++ = mime2utf(ch&0x3f);
202 count++;
203 ch = mime2utf((ch>>6)&0x3f);
206 *out++ = ch;
207 count++;
209 *out = 0;
210 return count;
213 void enum_stream_names( IStorage *stg )
215 IEnumSTATSTG *stgenum = NULL;
216 HRESULT r;
217 STATSTG stat;
218 ULONG n, count;
219 WCHAR name[0x40];
221 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
222 if( FAILED( r ) )
223 return;
225 n = 0;
226 while( 1 )
228 count = 0;
229 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
230 if( FAILED( r ) || !count )
231 break;
232 decode_streamname( stat.pwcsName, name );
233 TRACE("stream %2d -> %s %s\n", n,
234 debugstr_w(stat.pwcsName), debugstr_w(name) );
235 CoTaskMemFree( stat.pwcsName );
236 n++;
239 IEnumSTATSTG_Release( stgenum );
242 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
243 BYTE **pdata, UINT *psz )
245 HRESULT r;
246 UINT ret = ERROR_FUNCTION_FAILED;
247 VOID *data;
248 ULONG sz, count;
249 IStream *stm = NULL;
250 STATSTG stat;
251 LPWSTR encname;
253 encname = encode_streamname(table, stname);
255 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
257 r = IStorage_OpenStream(stg, encname, NULL,
258 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
259 msi_free( encname );
260 if( FAILED( r ) )
262 WARN("open stream failed r = %08x - empty table?\n", r);
263 return ret;
266 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
267 if( FAILED( r ) )
269 WARN("open stream failed r = %08x!\n", r);
270 goto end;
273 if( stat.cbSize.QuadPart >> 32 )
275 WARN("Too big!\n");
276 goto end;
279 sz = stat.cbSize.QuadPart;
280 data = msi_alloc( sz );
281 if( !data )
283 WARN("couldn't allocate memory r=%08x!\n", r);
284 ret = ERROR_NOT_ENOUGH_MEMORY;
285 goto end;
288 r = IStream_Read(stm, data, sz, &count );
289 if( FAILED( r ) || ( count != sz ) )
291 msi_free( data );
292 WARN("read stream failed r = %08x!\n", r);
293 goto end;
296 *pdata = data;
297 *psz = sz;
298 ret = ERROR_SUCCESS;
300 end:
301 IStream_Release( stm );
303 return ret;
306 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
307 LPCVOID data, UINT sz, BOOL bTable )
309 HRESULT r;
310 UINT ret = ERROR_FUNCTION_FAILED;
311 ULONG count;
312 IStream *stm = NULL;
313 ULARGE_INTEGER size;
314 LARGE_INTEGER pos;
315 LPWSTR encname;
317 encname = encode_streamname(bTable, stname );
318 r = IStorage_OpenStream( stg, encname, NULL,
319 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
320 if( FAILED(r) )
322 r = IStorage_CreateStream( stg, encname,
323 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
325 msi_free( encname );
326 if( FAILED( r ) )
328 WARN("open stream failed r = %08x\n", r);
329 return ret;
332 size.QuadPart = sz;
333 r = IStream_SetSize( stm, size );
334 if( FAILED( r ) )
336 WARN("Failed to SetSize\n");
337 goto end;
340 pos.QuadPart = 0;
341 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
342 if( FAILED( r ) )
344 WARN("Failed to Seek\n");
345 goto end;
348 if (sz)
350 r = IStream_Write(stm, data, sz, &count );
351 if( FAILED( r ) || ( count != sz ) )
353 WARN("Failed to Write\n");
354 goto end;
358 ret = ERROR_SUCCESS;
360 end:
361 IStream_Release( stm );
363 return ret;
366 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
368 UINT i;
369 for (i = 0; i < count; i++) msi_free( colinfo[i].hash_table );
372 static void free_table( MSITABLE *table )
374 UINT i;
375 for( i=0; i<table->row_count; i++ )
376 msi_free( table->data[i] );
377 msi_free( table->data );
378 msi_free( table->data_persistent );
379 msi_free_colinfo( table->colinfo, table->col_count );
380 msi_free( table->colinfo );
381 msi_free( table );
384 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
386 const MSICOLUMNINFO *last_col;
388 if (!count)
389 return 0;
391 if (bytes_per_strref != LONG_STR_BYTES)
393 UINT i, size = 0;
394 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
395 return size;
397 last_col = &cols[count - 1];
398 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
401 /* add this table to the list of cached tables in the database */
402 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
404 BYTE *rawdata = NULL;
405 UINT rawsize = 0, i, j, row_size, row_size_mem;
407 TRACE("%s\n",debugstr_w(t->name));
409 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
410 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
412 /* if we can't read the table, just assume that it's empty */
413 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
414 if( !rawdata )
415 return ERROR_SUCCESS;
417 TRACE("Read %d bytes\n", rawsize );
419 if( rawsize % row_size )
421 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
422 goto err;
425 if ((t->row_count = rawsize / row_size))
427 if (!(t->data = msi_alloc_zero( t->row_count * sizeof(USHORT *) ))) goto err;
428 if (!(t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL) ))) goto err;
431 /* transpose all the data */
432 TRACE("Transposing data from %d rows\n", t->row_count );
433 for (i = 0; i < t->row_count; i++)
435 UINT ofs = 0, ofs_mem = 0;
437 t->data[i] = msi_alloc( row_size_mem );
438 if( !t->data[i] )
439 goto err;
440 t->data_persistent[i] = TRUE;
442 for (j = 0; j < t->col_count; j++)
444 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
445 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
446 UINT k;
448 if ( n != 2 && n != 3 && n != 4 )
450 ERR("oops - unknown column width %d\n", n);
451 goto err;
453 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
455 for (k = 0; k < m; k++)
457 if (k < n)
458 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
459 else
460 t->data[i][ofs_mem + k] = 0;
463 else
465 for (k = 0; k < n; k++)
466 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
468 ofs_mem += m;
469 ofs += n;
473 msi_free( rawdata );
474 return ERROR_SUCCESS;
475 err:
476 msi_free( rawdata );
477 return ERROR_FUNCTION_FAILED;
480 void free_cached_tables( MSIDATABASE *db )
482 while( !list_empty( &db->tables ) )
484 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
486 list_remove( &t->entry );
487 free_table( t );
491 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
493 MSITABLE *t;
495 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
496 if( !strcmpW( name, t->name ) )
497 return t;
499 return NULL;
502 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
504 DWORD i;
506 for (i = 0; colinfo && i < count; i++)
508 assert( i + 1 == colinfo[i].number );
509 if (i) colinfo[i].offset = colinfo[i - 1].offset +
510 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
511 else colinfo[i].offset = 0;
513 TRACE("column %d is [%s] with type %08x ofs %d\n",
514 colinfo[i].number, debugstr_w(colinfo[i].colname),
515 colinfo[i].type, colinfo[i].offset);
519 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
521 const MSICOLUMNINFO *p;
522 DWORD i, n;
524 TRACE("%s\n", debugstr_w(name));
526 if (!strcmpW( name, szTables ))
528 p = _Tables_cols;
529 n = 1;
531 else if (!strcmpW( name, szColumns ))
533 p = _Columns_cols;
534 n = 4;
536 else return ERROR_FUNCTION_FAILED;
538 for (i = 0; i < n; i++)
540 if (colinfo && i < *sz) colinfo[i] = p[i];
541 if (colinfo && i >= *sz) break;
543 table_calc_column_offsets( db, colinfo, n );
544 *sz = n;
545 return ERROR_SUCCESS;
548 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
550 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
552 UINT r, column_count = 0;
553 MSICOLUMNINFO *columns;
555 /* get the number of columns in this table */
556 column_count = 0;
557 r = get_tablecolumns( db, name, NULL, &column_count );
558 if (r != ERROR_SUCCESS)
559 return r;
561 *pcount = column_count;
563 /* if there are no columns, there's no table */
564 if (!column_count)
565 return ERROR_INVALID_PARAMETER;
567 TRACE("table %s found\n", debugstr_w(name));
569 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
570 if (!columns)
571 return ERROR_FUNCTION_FAILED;
573 r = get_tablecolumns( db, name, columns, &column_count );
574 if (r != ERROR_SUCCESS)
576 msi_free( columns );
577 return ERROR_FUNCTION_FAILED;
579 *pcols = columns;
580 return r;
583 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
585 MSITABLE *table;
586 UINT r;
588 /* first, see if the table is cached */
589 table = find_cached_table( db, name );
590 if (table)
592 *table_ret = table;
593 return ERROR_SUCCESS;
596 /* nonexistent tables should be interpreted as empty tables */
597 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
598 if (!table)
599 return ERROR_FUNCTION_FAILED;
601 table->row_count = 0;
602 table->data = NULL;
603 table->data_persistent = NULL;
604 table->colinfo = NULL;
605 table->col_count = 0;
606 table->persistent = MSICONDITION_TRUE;
607 lstrcpyW( table->name, name );
609 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
610 table->persistent = MSICONDITION_NONE;
612 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
613 if (r != ERROR_SUCCESS)
615 free_table( table );
616 return r;
618 r = read_table_from_storage( db, table, db->storage );
619 if (r != ERROR_SUCCESS)
621 free_table( table );
622 return r;
624 list_add_head( &db->tables, &table->entry );
625 *table_ret = table;
626 return ERROR_SUCCESS;
629 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
631 UINT ret = 0, i;
633 for (i = 0; i < bytes; i++)
634 ret += data[row][col + i] << i * 8;
636 return ret;
639 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
641 UINT r, i, n = 0, table_id, count, maxcount = *sz;
642 MSITABLE *table = NULL;
644 TRACE("%s\n", debugstr_w(szTableName));
646 /* first check if there is a default table with that name */
647 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
648 if (r == ERROR_SUCCESS && *sz)
649 return r;
651 r = get_table( db, szColumns, &table );
652 if (r != ERROR_SUCCESS)
654 ERR("couldn't load _Columns table\n");
655 return ERROR_FUNCTION_FAILED;
658 /* convert table and column names to IDs from the string table */
659 r = msi_string2id( db->strings, szTableName, -1, &table_id );
660 if (r != ERROR_SUCCESS)
662 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
663 return r;
665 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
667 /* Note: _Columns table doesn't have non-persistent data */
669 /* if maxcount is non-zero, assume it's exactly right for this table */
670 if (colinfo) memset( colinfo, 0, maxcount * sizeof(*colinfo) );
671 count = table->row_count;
672 for (i = 0; i < count; i++)
674 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
675 if (colinfo)
677 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
678 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
680 /* check the column number is in range */
681 if (col < 1 || col > maxcount)
683 ERR("column %d out of range (maxcount: %d)\n", col, maxcount);
684 continue;
686 /* check if this column was already set */
687 if (colinfo[col - 1].number)
689 ERR("duplicate column %d\n", col);
690 continue;
692 colinfo[col - 1].tablename = msi_string_lookup( db->strings, table_id, NULL );
693 colinfo[col - 1].number = col;
694 colinfo[col - 1].colname = msi_string_lookup( db->strings, id, NULL );
695 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
696 sizeof(USHORT) ) - (1 << 15);
697 colinfo[col - 1].offset = 0;
698 colinfo[col - 1].ref_count = 0;
699 colinfo[col - 1].hash_table = NULL;
701 n++;
703 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
705 if (colinfo && n != maxcount)
707 ERR("missing column in table %s\n", debugstr_w(szTableName));
708 msi_free_colinfo( colinfo, maxcount );
709 return ERROR_FUNCTION_FAILED;
711 table_calc_column_offsets( db, colinfo, n );
712 *sz = n;
713 return ERROR_SUCCESS;
716 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
717 MSICONDITION persistent )
719 UINT r, nField;
720 MSIVIEW *tv = NULL;
721 MSIRECORD *rec = NULL;
722 column_info *col;
723 MSITABLE *table;
724 UINT i;
726 /* only add tables that don't exist already */
727 if( TABLE_Exists(db, name ) )
729 WARN("table %s exists\n", debugstr_w(name));
730 return ERROR_BAD_QUERY_SYNTAX;
733 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
734 if( !table )
735 return ERROR_FUNCTION_FAILED;
737 table->ref_count = 1;
738 table->row_count = 0;
739 table->data = NULL;
740 table->data_persistent = NULL;
741 table->colinfo = NULL;
742 table->col_count = 0;
743 table->persistent = persistent;
744 lstrcpyW( table->name, name );
746 for( col = col_info; col; col = col->next )
747 table->col_count++;
749 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
750 if (!table->colinfo)
752 free_table( table );
753 return ERROR_FUNCTION_FAILED;
756 for( i = 0, col = col_info; col; i++, col = col->next )
758 UINT table_id = msi_add_string( db->strings, col->table, -1, persistent );
759 UINT col_id = msi_add_string( db->strings, col->column, -1, persistent );
761 table->colinfo[ i ].tablename = msi_string_lookup( db->strings, table_id, NULL );
762 table->colinfo[ i ].number = i + 1;
763 table->colinfo[ i ].colname = msi_string_lookup( db->strings, col_id, NULL );
764 table->colinfo[ i ].type = col->type;
765 table->colinfo[ i ].offset = 0;
766 table->colinfo[ i ].ref_count = 0;
767 table->colinfo[ i ].hash_table = NULL;
768 table->colinfo[ i ].temporary = col->temporary;
770 table_calc_column_offsets( db, table->colinfo, table->col_count);
772 r = TABLE_CreateView( db, szTables, &tv );
773 TRACE("CreateView returned %x\n", r);
774 if( r )
776 free_table( table );
777 return r;
780 r = tv->ops->execute( tv, 0 );
781 TRACE("tv execute returned %x\n", r);
782 if( r )
783 goto err;
785 rec = MSI_CreateRecord( 1 );
786 if( !rec )
787 goto err;
789 r = MSI_RecordSetStringW( rec, 1, name );
790 if( r )
791 goto err;
793 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
794 TRACE("insert_row returned %x\n", r);
795 if( r )
796 goto err;
798 tv->ops->delete( tv );
799 tv = NULL;
801 msiobj_release( &rec->hdr );
802 rec = NULL;
804 if( persistent != MSICONDITION_FALSE )
806 /* add each column to the _Columns table */
807 r = TABLE_CreateView( db, szColumns, &tv );
808 if( r )
809 goto err;
811 r = tv->ops->execute( tv, 0 );
812 TRACE("tv execute returned %x\n", r);
813 if( r )
814 goto err;
816 rec = MSI_CreateRecord( 4 );
817 if( !rec )
818 goto err;
820 r = MSI_RecordSetStringW( rec, 1, name );
821 if( r )
822 goto err;
825 * need to set the table, column number, col name and type
826 * for each column we enter in the table
828 nField = 1;
829 for( col = col_info; col; col = col->next )
831 r = MSI_RecordSetInteger( rec, 2, nField );
832 if( r )
833 goto err;
835 r = MSI_RecordSetStringW( rec, 3, col->column );
836 if( r )
837 goto err;
839 r = MSI_RecordSetInteger( rec, 4, col->type );
840 if( r )
841 goto err;
843 r = tv->ops->insert_row( tv, rec, -1, FALSE );
844 if( r )
845 goto err;
847 nField++;
849 if( !col )
850 r = ERROR_SUCCESS;
853 err:
854 if (rec)
855 msiobj_release( &rec->hdr );
856 /* FIXME: remove values from the string table on error */
857 if( tv )
858 tv->ops->delete( tv );
860 if (r == ERROR_SUCCESS)
861 list_add_head( &db->tables, &table->entry );
862 else
863 free_table( table );
865 return r;
868 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
870 BYTE *rawdata = NULL;
871 UINT rawsize, i, j, row_size, row_count;
872 UINT r = ERROR_FUNCTION_FAILED;
874 /* Nothing to do for non-persistent tables */
875 if( t->persistent == MSICONDITION_FALSE )
876 return ERROR_SUCCESS;
878 TRACE("Saving %s\n", debugstr_w( t->name ) );
880 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
881 row_count = t->row_count;
882 for (i = 0; i < t->row_count; i++)
884 if (!t->data_persistent[i])
886 row_count = 1; /* yes, this is bizarre */
887 break;
890 rawsize = row_count * row_size;
891 rawdata = msi_alloc_zero( rawsize );
892 if( !rawdata )
894 r = ERROR_NOT_ENOUGH_MEMORY;
895 goto err;
898 rawsize = 0;
899 for (i = 0; i < row_count; i++)
901 UINT ofs = 0, ofs_mem = 0;
903 if (!t->data_persistent[i]) break;
905 for (j = 0; j < t->col_count; j++)
907 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
908 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
909 UINT k;
911 if (n != 2 && n != 3 && n != 4)
913 ERR("oops - unknown column width %d\n", n);
914 goto err;
916 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
918 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
919 if (id > 1 << bytes_per_strref * 8)
921 ERR("string id %u out of range\n", id);
922 goto err;
925 for (k = 0; k < n; k++)
927 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
929 ofs_mem += m;
930 ofs += n;
932 rawsize += row_size;
935 TRACE("writing %d bytes\n", rawsize);
936 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
938 err:
939 msi_free( rawdata );
940 return r;
943 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
945 MSITABLE *table;
946 UINT size, offset, old_count;
947 UINT n;
949 if (!(table = find_cached_table( db, name ))) return;
950 old_count = table->col_count;
951 msi_free_colinfo( table->colinfo, table->col_count );
952 msi_free( table->colinfo );
953 table->colinfo = NULL;
955 table_get_column_info( db, name, &table->colinfo, &table->col_count );
956 if (!table->col_count) return;
958 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
959 offset = table->colinfo[table->col_count - 1].offset;
961 for ( n = 0; n < table->row_count; n++ )
963 table->data[n] = msi_realloc( table->data[n], size );
964 if (old_count < table->col_count)
965 memset( &table->data[n][offset], 0, size - offset );
969 /* try to find the table name in the _Tables table */
970 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
972 UINT r, table_id, i;
973 MSITABLE *table;
975 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
976 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
977 return TRUE;
979 r = msi_string2id( db->strings, name, -1, &table_id );
980 if( r != ERROR_SUCCESS )
982 TRACE("Couldn't find id for %s\n", debugstr_w(name));
983 return FALSE;
986 r = get_table( db, szTables, &table );
987 if( r != ERROR_SUCCESS )
989 ERR("table %s not available\n", debugstr_w(szTables));
990 return FALSE;
993 for( i = 0; i < table->row_count; i++ )
995 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
996 return TRUE;
999 return FALSE;
1002 /* below is the query interface to a table */
1004 typedef struct tagMSITABLEVIEW
1006 MSIVIEW view;
1007 MSIDATABASE *db;
1008 MSITABLE *table;
1009 MSICOLUMNINFO *columns;
1010 UINT num_cols;
1011 UINT row_size;
1012 WCHAR name[1];
1013 } MSITABLEVIEW;
1015 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1017 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1018 UINT offset, n;
1020 if( !tv->table )
1021 return ERROR_INVALID_PARAMETER;
1023 if( (col==0) || (col>tv->num_cols) )
1024 return ERROR_INVALID_PARAMETER;
1026 /* how many rows are there ? */
1027 if( row >= tv->table->row_count )
1028 return ERROR_NO_MORE_ITEMS;
1030 if( tv->columns[col-1].offset >= tv->row_size )
1032 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1033 ERR("%p %p\n", tv, tv->columns );
1034 return ERROR_FUNCTION_FAILED;
1037 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1038 if (n != 2 && n != 3 && n != 4)
1040 ERR("oops! what is %d bytes per column?\n", n );
1041 return ERROR_FUNCTION_FAILED;
1044 offset = tv->columns[col-1].offset;
1045 *val = read_table_int(tv->table->data, row, offset, n);
1047 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1049 return ERROR_SUCCESS;
1052 static UINT get_stream_name( const MSITABLEVIEW *tv, UINT row, WCHAR **pstname )
1054 LPWSTR p, stname = NULL;
1055 UINT i, r, type, ival;
1056 DWORD len;
1057 LPCWSTR sval;
1058 MSIVIEW *view = (MSIVIEW *) tv;
1060 TRACE("%p %d\n", tv, row);
1062 len = lstrlenW( tv->name ) + 1;
1063 stname = msi_alloc( len*sizeof(WCHAR) );
1064 if ( !stname )
1066 r = ERROR_OUTOFMEMORY;
1067 goto err;
1070 lstrcpyW( stname, tv->name );
1072 for ( i = 0; i < tv->num_cols; i++ )
1074 type = tv->columns[i].type;
1075 if ( type & MSITYPE_KEY )
1077 WCHAR number[0x20];
1079 r = TABLE_fetch_int( view, row, i+1, &ival );
1080 if ( r != ERROR_SUCCESS )
1081 goto err;
1083 if ( tv->columns[i].type & MSITYPE_STRING )
1085 sval = msi_string_lookup( tv->db->strings, ival, NULL );
1086 if ( !sval )
1088 r = ERROR_INVALID_PARAMETER;
1089 goto err;
1092 else
1094 static const WCHAR fmt[] = { '%','d',0 };
1095 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1097 switch( n )
1099 case 2:
1100 sprintfW( number, fmt, ival-0x8000 );
1101 break;
1102 case 4:
1103 sprintfW( number, fmt, ival^0x80000000 );
1104 break;
1105 default:
1106 ERR( "oops - unknown column width %d\n", n );
1107 r = ERROR_FUNCTION_FAILED;
1108 goto err;
1110 sval = number;
1113 len += lstrlenW( szDot ) + lstrlenW( sval );
1114 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1115 if ( !p )
1117 r = ERROR_OUTOFMEMORY;
1118 goto err;
1120 stname = p;
1122 lstrcatW( stname, szDot );
1123 lstrcatW( stname, sval );
1125 else
1126 continue;
1129 *pstname = stname;
1130 return ERROR_SUCCESS;
1132 err:
1133 msi_free( stname );
1134 *pstname = NULL;
1135 return r;
1139 * We need a special case for streams, as we need to reference column with
1140 * the name of the stream in the same table, and the table name
1141 * which may not be available at higher levels of the query
1143 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1145 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1146 UINT r;
1147 WCHAR *name;
1149 if( !view->ops->fetch_int )
1150 return ERROR_INVALID_PARAMETER;
1152 r = get_stream_name( tv, row, &name );
1153 if (r != ERROR_SUCCESS)
1155 ERR("fetching stream, error = %u\n", r);
1156 return r;
1159 r = msi_get_stream( tv->db, name, stm );
1160 if (r != ERROR_SUCCESS)
1161 ERR("fetching stream %s, error = %u\n", debugstr_w(name), r);
1163 msi_free( name );
1164 return r;
1167 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1169 UINT offset, n, i;
1171 if( !tv->table )
1172 return ERROR_INVALID_PARAMETER;
1174 if( (col==0) || (col>tv->num_cols) )
1175 return ERROR_INVALID_PARAMETER;
1177 if( row >= tv->table->row_count )
1178 return ERROR_INVALID_PARAMETER;
1180 if( tv->columns[col-1].offset >= tv->row_size )
1182 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1183 ERR("%p %p\n", tv, tv->columns );
1184 return ERROR_FUNCTION_FAILED;
1187 msi_free( tv->columns[col-1].hash_table );
1188 tv->columns[col-1].hash_table = NULL;
1190 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1191 if ( n != 2 && n != 3 && n != 4 )
1193 ERR("oops! what is %d bytes per column?\n", n );
1194 return ERROR_FUNCTION_FAILED;
1197 offset = tv->columns[col-1].offset;
1198 for ( i = 0; i < n; i++ )
1199 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1201 return ERROR_SUCCESS;
1204 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1206 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1208 if (!tv->table)
1209 return ERROR_INVALID_PARAMETER;
1211 return msi_view_get_row(tv->db, view, row, rec);
1214 static UINT add_stream( MSIDATABASE *db, const WCHAR *name, IStream *data )
1216 static const WCHAR insert[] = {
1217 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1218 '`','_','S','t','r','e','a','m','s','`',' ',
1219 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1220 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1221 static const WCHAR update[] = {
1222 'U','P','D','A','T','E',' ','`','_','S','t','r','e','a','m','s','`',' ',
1223 'S','E','T',' ','`','D','a','t','a','`',' ','=',' ','?',' ',
1224 'W','H','E','R','E',' ','`','N','a','m','e','`',' ','=',' ','?',0};
1225 MSIQUERY *query;
1226 MSIRECORD *rec;
1227 UINT r;
1229 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1231 if (!(rec = MSI_CreateRecord( 2 )))
1232 return ERROR_OUTOFMEMORY;
1234 r = MSI_RecordSetStringW( rec, 1, name );
1235 if (r != ERROR_SUCCESS)
1236 goto done;
1238 r = MSI_RecordSetIStream( rec, 2, data );
1239 if (r != ERROR_SUCCESS)
1240 goto done;
1242 r = MSI_DatabaseOpenViewW( db, insert, &query );
1243 if (r != ERROR_SUCCESS)
1244 goto done;
1246 r = MSI_ViewExecute( query, rec );
1247 msiobj_release( &query->hdr );
1248 if (r == ERROR_SUCCESS)
1249 goto done;
1251 msiobj_release( &rec->hdr );
1252 if (!(rec = MSI_CreateRecord( 2 )))
1253 return ERROR_OUTOFMEMORY;
1255 r = MSI_RecordSetIStream( rec, 1, data );
1256 if (r != ERROR_SUCCESS)
1257 goto done;
1259 r = MSI_RecordSetStringW( rec, 2, name );
1260 if (r != ERROR_SUCCESS)
1261 goto done;
1263 r = MSI_DatabaseOpenViewW( db, update, &query );
1264 if (r != ERROR_SUCCESS)
1265 goto done;
1267 r = MSI_ViewExecute( query, rec );
1268 msiobj_release( &query->hdr );
1270 done:
1271 msiobj_release( &rec->hdr );
1272 return r;
1275 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1277 MSICOLUMNINFO columninfo;
1278 UINT r;
1279 int ival;
1281 if (!iField || iField > tv->num_cols || MSI_RecordIsNull( rec, iField ))
1282 return ERROR_FUNCTION_FAILED;
1284 columninfo = tv->columns[ iField - 1 ];
1286 if ( MSITYPE_IS_BINARY(columninfo.type) )
1288 *pvalue = 1; /* refers to the first key column */
1290 else if ( columninfo.type & MSITYPE_STRING )
1292 int len;
1293 const WCHAR *sval = msi_record_get_string( rec, iField, &len );
1294 if (sval)
1296 r = msi_string2id( tv->db->strings, sval, len, pvalue );
1297 if (r != ERROR_SUCCESS)
1298 return ERROR_NOT_FOUND;
1300 else *pvalue = 0;
1302 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1304 ival = MSI_RecordGetInteger( rec, iField );
1305 if (ival == 0x80000000) *pvalue = 0x8000;
1306 else
1308 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1309 if (*pvalue & 0xffff0000)
1311 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1312 return ERROR_FUNCTION_FAILED;
1316 else
1318 ival = MSI_RecordGetInteger( rec, iField );
1319 *pvalue = ival ^ 0x80000000;
1322 return ERROR_SUCCESS;
1325 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1327 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1328 UINT i, val, r = ERROR_SUCCESS;
1330 if ( !tv->table )
1331 return ERROR_INVALID_PARAMETER;
1333 /* test if any of the mask bits are invalid */
1334 if ( mask >= (1<<tv->num_cols) )
1335 return ERROR_INVALID_PARAMETER;
1337 for ( i = 0; i < tv->num_cols; i++ )
1339 BOOL persistent;
1341 /* only update the fields specified in the mask */
1342 if ( !(mask&(1<<i)) )
1343 continue;
1345 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1346 (tv->table->data_persistent[row]);
1347 /* FIXME: should we allow updating keys? */
1349 val = 0;
1350 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1352 r = get_table_value_from_record (tv, rec, i + 1, &val);
1353 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1355 IStream *stm;
1356 LPWSTR stname;
1358 if ( r != ERROR_SUCCESS )
1359 return ERROR_FUNCTION_FAILED;
1361 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1362 if ( r != ERROR_SUCCESS )
1363 return r;
1365 r = get_stream_name( tv, row, &stname );
1366 if ( r != ERROR_SUCCESS )
1368 IStream_Release( stm );
1369 return r;
1372 r = add_stream( tv->db, stname, stm );
1373 IStream_Release( stm );
1374 msi_free ( stname );
1376 if ( r != ERROR_SUCCESS )
1377 return r;
1379 else if ( tv->columns[i].type & MSITYPE_STRING )
1381 UINT x;
1383 if ( r != ERROR_SUCCESS )
1385 int len;
1386 const WCHAR *sval = msi_record_get_string( rec, i + 1, &len );
1387 val = msi_add_string( tv->db->strings, sval, len, persistent );
1389 else
1391 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1392 if (val == x)
1393 continue;
1396 else
1398 if ( r != ERROR_SUCCESS )
1399 return ERROR_FUNCTION_FAILED;
1403 r = TABLE_set_int( tv, row, i+1, val );
1404 if ( r != ERROR_SUCCESS )
1405 break;
1407 return r;
1410 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1412 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1413 BYTE **p, *row;
1414 BOOL *b;
1415 UINT sz;
1416 BYTE ***data_ptr;
1417 BOOL **data_persist_ptr;
1418 UINT *row_count;
1420 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1422 if( !tv->table )
1423 return ERROR_INVALID_PARAMETER;
1425 row = msi_alloc_zero( tv->row_size );
1426 if( !row )
1427 return ERROR_NOT_ENOUGH_MEMORY;
1429 row_count = &tv->table->row_count;
1430 data_ptr = &tv->table->data;
1431 data_persist_ptr = &tv->table->data_persistent;
1432 if (*num == -1)
1433 *num = tv->table->row_count;
1435 sz = (*row_count + 1) * sizeof (BYTE*);
1436 if( *data_ptr )
1437 p = msi_realloc( *data_ptr, sz );
1438 else
1439 p = msi_alloc( sz );
1440 if( !p )
1442 msi_free( row );
1443 return ERROR_NOT_ENOUGH_MEMORY;
1446 sz = (*row_count + 1) * sizeof (BOOL);
1447 if( *data_persist_ptr )
1448 b = msi_realloc( *data_persist_ptr, sz );
1449 else
1450 b = msi_alloc( sz );
1451 if( !b )
1453 msi_free( row );
1454 msi_free( p );
1455 return ERROR_NOT_ENOUGH_MEMORY;
1458 *data_ptr = p;
1459 (*data_ptr)[*row_count] = row;
1461 *data_persist_ptr = b;
1462 (*data_persist_ptr)[*row_count] = !temporary;
1464 (*row_count)++;
1466 return ERROR_SUCCESS;
1469 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1471 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1473 TRACE("%p %p\n", tv, record);
1475 TRACE("There are %d columns\n", tv->num_cols );
1477 return ERROR_SUCCESS;
1480 static UINT TABLE_close( struct tagMSIVIEW *view )
1482 TRACE("%p\n", view );
1484 return ERROR_SUCCESS;
1487 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1489 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1491 TRACE("%p %p %p\n", view, rows, cols );
1493 if( cols )
1494 *cols = tv->num_cols;
1495 if( rows )
1497 if( !tv->table )
1498 return ERROR_INVALID_PARAMETER;
1499 *rows = tv->table->row_count;
1502 return ERROR_SUCCESS;
1505 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1506 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1507 LPCWSTR *table_name )
1509 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1511 TRACE("%p %d %p %p\n", tv, n, name, type );
1513 if( ( n == 0 ) || ( n > tv->num_cols ) )
1514 return ERROR_INVALID_PARAMETER;
1516 if( name )
1518 *name = tv->columns[n-1].colname;
1519 if( !*name )
1520 return ERROR_FUNCTION_FAILED;
1523 if( table_name )
1525 *table_name = tv->columns[n-1].tablename;
1526 if( !*table_name )
1527 return ERROR_FUNCTION_FAILED;
1530 if( type )
1531 *type = tv->columns[n-1].type;
1533 if( temporary )
1534 *temporary = tv->columns[n-1].temporary;
1536 return ERROR_SUCCESS;
1539 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1541 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1543 UINT r, row, i;
1545 /* check there are no null values where they're not allowed */
1546 for( i = 0; i < tv->num_cols; i++ )
1548 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1549 continue;
1551 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1552 TRACE("skipping binary column\n");
1553 else if ( tv->columns[i].type & MSITYPE_STRING )
1555 int len;
1556 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
1558 if (!str || (!str[0] && !len))
1560 if (column) *column = i;
1561 return ERROR_INVALID_DATA;
1564 else
1566 UINT n;
1568 n = MSI_RecordGetInteger( rec, i+1 );
1569 if (n == MSI_NULL_INTEGER)
1571 if (column) *column = i;
1572 return ERROR_INVALID_DATA;
1577 /* check there are no duplicate keys */
1578 r = msi_table_find_row( tv, rec, &row, column );
1579 if (r == ERROR_SUCCESS)
1580 return ERROR_FUNCTION_FAILED;
1582 return ERROR_SUCCESS;
1585 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1587 UINT r, i, ivalue, x;
1589 for (i = 0; i < tv->num_cols; i++ )
1591 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1593 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1594 if (r != ERROR_SUCCESS)
1595 return 1;
1597 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1598 if (r != ERROR_SUCCESS)
1600 WARN("TABLE_fetch_int should not fail here %u\n", r);
1601 return -1;
1603 if (ivalue > x)
1605 return 1;
1607 else if (ivalue == x)
1609 if (i < tv->num_cols - 1) continue;
1610 return 0;
1612 else
1613 return -1;
1615 return 1;
1618 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1620 int idx, c, low = 0, high = tv->table->row_count - 1;
1622 TRACE("%p %p\n", tv, rec);
1624 while (low <= high)
1626 idx = (low + high) / 2;
1627 c = compare_record( tv, idx, rec );
1629 if (c < 0)
1630 high = idx - 1;
1631 else if (c > 0)
1632 low = idx + 1;
1633 else
1635 TRACE("found %u\n", idx);
1636 return idx;
1639 TRACE("found %u\n", high + 1);
1640 return high + 1;
1643 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1645 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1646 UINT i, r;
1648 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1650 /* check that the key is unique - can we find a matching row? */
1651 r = table_validate_new( tv, rec, NULL );
1652 if( r != ERROR_SUCCESS )
1653 return ERROR_FUNCTION_FAILED;
1655 if (row == -1)
1656 row = find_insert_index( tv, rec );
1658 r = table_create_new_row( view, &row, temporary );
1659 TRACE("insert_row returned %08x\n", r);
1660 if( r != ERROR_SUCCESS )
1661 return r;
1663 /* shift the rows to make room for the new row */
1664 for (i = tv->table->row_count - 1; i > row; i--)
1666 memmove(&(tv->table->data[i][0]),
1667 &(tv->table->data[i - 1][0]), tv->row_size);
1668 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1671 /* Re-set the persistence flag */
1672 tv->table->data_persistent[row] = !temporary;
1673 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1676 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1678 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1679 UINT r, num_rows, num_cols, i;
1681 TRACE("%p %d\n", tv, row);
1683 if ( !tv->table )
1684 return ERROR_INVALID_PARAMETER;
1686 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1687 if ( r != ERROR_SUCCESS )
1688 return r;
1690 if ( row >= num_rows )
1691 return ERROR_FUNCTION_FAILED;
1693 num_rows = tv->table->row_count;
1694 tv->table->row_count--;
1696 /* reset the hash tables */
1697 for (i = 0; i < tv->num_cols; i++)
1699 msi_free( tv->columns[i].hash_table );
1700 tv->columns[i].hash_table = NULL;
1703 for (i = row + 1; i < num_rows; i++)
1705 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1706 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1709 msi_free(tv->table->data[num_rows - 1]);
1711 return ERROR_SUCCESS;
1714 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1716 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1717 UINT r, new_row;
1719 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1720 * sets the fetched record apart from other records
1723 if (!tv->table)
1724 return ERROR_INVALID_PARAMETER;
1726 r = msi_table_find_row(tv, rec, &new_row, NULL);
1727 if (r != ERROR_SUCCESS)
1729 ERR("can't find row to modify\n");
1730 return ERROR_FUNCTION_FAILED;
1733 /* the row cannot be changed */
1734 if (row != new_row)
1735 return ERROR_FUNCTION_FAILED;
1737 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1740 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1742 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1743 UINT r, row;
1745 if (!tv->table)
1746 return ERROR_INVALID_PARAMETER;
1748 r = msi_table_find_row(tv, rec, &row, NULL);
1749 if (r == ERROR_SUCCESS)
1750 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1751 else
1752 return TABLE_insert_row( view, rec, -1, FALSE );
1755 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1757 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1758 UINT row, r;
1760 r = msi_table_find_row(tv, rec, &row, NULL);
1761 if (r != ERROR_SUCCESS)
1762 return r;
1764 return TABLE_delete_row(view, row);
1767 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1769 MSIRECORD *curr;
1770 UINT r, i, count;
1772 r = TABLE_get_row(view, row, &curr);
1773 if (r != ERROR_SUCCESS)
1774 return r;
1776 /* Close the original record */
1777 MSI_CloseRecord(&rec->hdr);
1779 count = MSI_RecordGetFieldCount(rec);
1780 for (i = 0; i < count; i++)
1781 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1783 msiobj_release(&curr->hdr);
1784 return ERROR_SUCCESS;
1787 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1788 MSIRECORD *rec, UINT row)
1790 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1791 UINT r, frow, column;
1793 TRACE("%p %d %p\n", view, eModifyMode, rec );
1795 switch (eModifyMode)
1797 case MSIMODIFY_DELETE:
1798 r = modify_delete_row( view, rec );
1799 break;
1800 case MSIMODIFY_VALIDATE_NEW:
1801 r = table_validate_new( tv, rec, &column );
1802 if (r != ERROR_SUCCESS)
1804 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1805 tv->view.error_column = tv->columns[column].colname;
1806 r = ERROR_INVALID_DATA;
1808 break;
1810 case MSIMODIFY_INSERT:
1811 r = table_validate_new( tv, rec, NULL );
1812 if (r != ERROR_SUCCESS)
1813 break;
1814 r = TABLE_insert_row( view, rec, -1, FALSE );
1815 break;
1817 case MSIMODIFY_INSERT_TEMPORARY:
1818 r = table_validate_new( tv, rec, NULL );
1819 if (r != ERROR_SUCCESS)
1820 break;
1821 r = TABLE_insert_row( view, rec, -1, TRUE );
1822 break;
1824 case MSIMODIFY_REFRESH:
1825 r = msi_refresh_record( view, rec, row );
1826 break;
1828 case MSIMODIFY_UPDATE:
1829 r = msi_table_update( view, rec, row );
1830 break;
1832 case MSIMODIFY_ASSIGN:
1833 r = msi_table_assign( view, rec );
1834 break;
1836 case MSIMODIFY_MERGE:
1837 /* check row that matches this record */
1838 r = msi_table_find_row( tv, rec, &frow, &column );
1839 if (r != ERROR_SUCCESS)
1841 r = table_validate_new( tv, rec, NULL );
1842 if (r == ERROR_SUCCESS)
1843 r = TABLE_insert_row( view, rec, -1, FALSE );
1845 break;
1847 case MSIMODIFY_REPLACE:
1848 case MSIMODIFY_VALIDATE:
1849 case MSIMODIFY_VALIDATE_FIELD:
1850 case MSIMODIFY_VALIDATE_DELETE:
1851 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1852 r = ERROR_CALL_NOT_IMPLEMENTED;
1853 break;
1855 default:
1856 r = ERROR_INVALID_DATA;
1859 return r;
1862 static UINT TABLE_delete( struct tagMSIVIEW *view )
1864 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1866 TRACE("%p\n", view );
1868 tv->table = NULL;
1869 tv->columns = NULL;
1871 msi_free( tv );
1873 return ERROR_SUCCESS;
1876 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1878 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1879 UINT i;
1881 TRACE("%p %d\n", view, tv->table->ref_count);
1883 for (i = 0; i < tv->table->col_count; i++)
1885 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1886 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1889 return InterlockedIncrement(&tv->table->ref_count);
1892 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1894 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1895 MSIRECORD *rec = NULL;
1896 MSIVIEW *columns = NULL;
1897 UINT row, r;
1899 rec = MSI_CreateRecord(2);
1900 if (!rec)
1901 return ERROR_OUTOFMEMORY;
1903 MSI_RecordSetStringW(rec, 1, table);
1904 MSI_RecordSetInteger(rec, 2, number);
1906 r = TABLE_CreateView(tv->db, szColumns, &columns);
1907 if (r != ERROR_SUCCESS)
1909 msiobj_release(&rec->hdr);
1910 return r;
1913 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1914 if (r != ERROR_SUCCESS)
1915 goto done;
1917 r = TABLE_delete_row(columns, row);
1918 if (r != ERROR_SUCCESS)
1919 goto done;
1921 msi_update_table_columns(tv->db, table);
1923 done:
1924 msiobj_release(&rec->hdr);
1925 columns->ops->delete(columns);
1926 return r;
1929 static UINT TABLE_release(struct tagMSIVIEW *view)
1931 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1932 INT ref = tv->table->ref_count;
1933 UINT i, r;
1935 TRACE("%p %d\n", view, ref);
1937 for (i = 0; i < tv->table->col_count; i++)
1939 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1941 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1942 if (ref == 0)
1944 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1945 tv->table->colinfo[i].number);
1946 if (r != ERROR_SUCCESS)
1947 break;
1952 ref = InterlockedDecrement(&tv->table->ref_count);
1953 if (ref == 0)
1955 if (!tv->table->row_count)
1957 list_remove(&tv->table->entry);
1958 free_table(tv->table);
1959 TABLE_delete(view);
1963 return ref;
1966 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
1967 LPCWSTR column, UINT type, BOOL hold)
1969 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1970 MSITABLE *msitable;
1971 MSIRECORD *rec;
1972 UINT r, i;
1974 rec = MSI_CreateRecord(4);
1975 if (!rec)
1976 return ERROR_OUTOFMEMORY;
1978 MSI_RecordSetStringW(rec, 1, table);
1979 MSI_RecordSetInteger(rec, 2, number);
1980 MSI_RecordSetStringW(rec, 3, column);
1981 MSI_RecordSetInteger(rec, 4, type);
1983 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
1984 if (r != ERROR_SUCCESS)
1985 goto done;
1987 msi_update_table_columns(tv->db, table);
1989 if (!hold)
1990 goto done;
1992 msitable = find_cached_table(tv->db, table);
1993 for (i = 0; i < msitable->col_count; i++)
1995 if (!strcmpW( msitable->colinfo[i].colname, column ))
1997 InterlockedIncrement(&msitable->colinfo[i].ref_count);
1998 break;
2002 done:
2003 msiobj_release(&rec->hdr);
2004 return r;
2007 static UINT TABLE_drop(struct tagMSIVIEW *view)
2009 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2010 MSIVIEW *tables = NULL;
2011 MSIRECORD *rec = NULL;
2012 UINT r, row;
2013 INT i;
2015 TRACE("dropping table %s\n", debugstr_w(tv->name));
2017 for (i = tv->table->col_count - 1; i >= 0; i--)
2019 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2020 tv->table->colinfo[i].number);
2021 if (r != ERROR_SUCCESS)
2022 return r;
2025 rec = MSI_CreateRecord(1);
2026 if (!rec)
2027 return ERROR_OUTOFMEMORY;
2029 MSI_RecordSetStringW(rec, 1, tv->name);
2031 r = TABLE_CreateView(tv->db, szTables, &tables);
2032 if (r != ERROR_SUCCESS)
2034 msiobj_release(&rec->hdr);
2035 return r;
2038 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2039 if (r != ERROR_SUCCESS)
2040 goto done;
2042 r = TABLE_delete_row(tables, row);
2043 if (r != ERROR_SUCCESS)
2044 goto done;
2046 list_remove(&tv->table->entry);
2047 free_table(tv->table);
2049 done:
2050 msiobj_release(&rec->hdr);
2051 tables->ops->delete(tables);
2053 return r;
2056 static const MSIVIEWOPS table_ops =
2058 TABLE_fetch_int,
2059 TABLE_fetch_stream,
2060 TABLE_get_row,
2061 TABLE_set_row,
2062 TABLE_insert_row,
2063 TABLE_delete_row,
2064 TABLE_execute,
2065 TABLE_close,
2066 TABLE_get_dimensions,
2067 TABLE_get_column_info,
2068 TABLE_modify,
2069 TABLE_delete,
2070 TABLE_add_ref,
2071 TABLE_release,
2072 TABLE_add_column,
2073 NULL,
2074 TABLE_drop,
2077 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2079 MSITABLEVIEW *tv ;
2080 UINT r, sz;
2082 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2084 if ( !strcmpW( name, szStreams ) )
2085 return STREAMS_CreateView( db, view );
2086 else if ( !strcmpW( name, szStorages ) )
2087 return STORAGES_CreateView( db, view );
2089 sz = FIELD_OFFSET( MSITABLEVIEW, name[lstrlenW( name ) + 1] );
2090 tv = msi_alloc_zero( sz );
2091 if( !tv )
2092 return ERROR_FUNCTION_FAILED;
2094 r = get_table( db, name, &tv->table );
2095 if( r != ERROR_SUCCESS )
2097 msi_free( tv );
2098 WARN("table not found\n");
2099 return r;
2102 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2104 /* fill the structure */
2105 tv->view.ops = &table_ops;
2106 tv->db = db;
2107 tv->columns = tv->table->colinfo;
2108 tv->num_cols = tv->table->col_count;
2109 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2111 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2113 *view = (MSIVIEW*) tv;
2114 lstrcpyW( tv->name, name );
2116 return ERROR_SUCCESS;
2119 UINT MSI_CommitTables( MSIDATABASE *db )
2121 UINT r, bytes_per_strref;
2122 HRESULT hr;
2123 MSITABLE *table = NULL;
2125 TRACE("%p\n",db);
2127 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2128 if( r != ERROR_SUCCESS )
2130 WARN("failed to save string table r=%08x\n",r);
2131 return r;
2134 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2136 r = save_table( db, table, bytes_per_strref );
2137 if( r != ERROR_SUCCESS )
2139 WARN("failed to save table %s (r=%08x)\n",
2140 debugstr_w(table->name), r);
2141 return r;
2145 hr = IStorage_Commit( db->storage, 0 );
2146 if (FAILED( hr ))
2148 WARN("failed to commit changes 0x%08x\n", hr);
2149 r = ERROR_FUNCTION_FAILED;
2151 return r;
2154 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2156 MSITABLE *t;
2157 UINT r;
2159 TRACE("%p %s\n", db, debugstr_w(table));
2161 if (!table)
2162 return MSICONDITION_ERROR;
2164 r = get_table( db, table, &t );
2165 if (r != ERROR_SUCCESS)
2166 return MSICONDITION_NONE;
2168 return t->persistent;
2171 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2173 UINT ret = 0, i;
2175 for (i = 0; i < bytes; i++)
2176 ret += (data[col + i] << i * 8);
2178 return ret;
2181 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2183 LPWSTR stname = NULL, sval, p;
2184 DWORD len;
2185 UINT i, r;
2187 TRACE("%p %p\n", tv, rec);
2189 len = lstrlenW( tv->name ) + 1;
2190 stname = msi_alloc( len*sizeof(WCHAR) );
2191 if ( !stname )
2193 r = ERROR_OUTOFMEMORY;
2194 goto err;
2197 lstrcpyW( stname, tv->name );
2199 for ( i = 0; i < tv->num_cols; i++ )
2201 if ( tv->columns[i].type & MSITYPE_KEY )
2203 sval = msi_dup_record_field( rec, i + 1 );
2204 if ( !sval )
2206 r = ERROR_OUTOFMEMORY;
2207 goto err;
2210 len += lstrlenW( szDot ) + lstrlenW ( sval );
2211 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2212 if ( !p )
2214 r = ERROR_OUTOFMEMORY;
2215 msi_free(sval);
2216 goto err;
2218 stname = p;
2220 lstrcatW( stname, szDot );
2221 lstrcatW( stname, sval );
2223 msi_free( sval );
2225 else
2226 continue;
2229 *pstname = encode_streamname( FALSE, stname );
2230 msi_free( stname );
2232 return ERROR_SUCCESS;
2234 err:
2235 msi_free ( stname );
2236 *pstname = NULL;
2237 return r;
2240 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2241 IStorage *stg, const BYTE *rawdata, UINT bytes_per_strref )
2243 UINT i, val, ofs = 0;
2244 USHORT mask;
2245 MSICOLUMNINFO *columns = tv->columns;
2246 MSIRECORD *rec;
2248 mask = rawdata[0] | (rawdata[1] << 8);
2249 rawdata += 2;
2251 rec = MSI_CreateRecord( tv->num_cols );
2252 if( !rec )
2253 return rec;
2255 TRACE("row ->\n");
2256 for( i=0; i<tv->num_cols; i++ )
2258 if ( (mask&1) && (i>=(mask>>8)) )
2259 break;
2260 /* all keys must be present */
2261 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2262 continue;
2264 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2266 LPWSTR encname;
2267 IStream *stm = NULL;
2268 UINT r;
2270 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2272 r = msi_record_encoded_stream_name( tv, rec, &encname );
2273 if ( r != ERROR_SUCCESS )
2275 msiobj_release( &rec->hdr );
2276 return NULL;
2278 r = IStorage_OpenStream( stg, encname, NULL, STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2279 if ( r != ERROR_SUCCESS )
2281 msiobj_release( &rec->hdr );
2282 msi_free( encname );
2283 return NULL;
2286 MSI_RecordSetStream( rec, i+1, stm );
2287 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2288 msi_free( encname );
2290 else if( columns[i].type & MSITYPE_STRING )
2292 int len;
2293 const WCHAR *sval;
2295 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2296 sval = msi_string_lookup( st, val, &len );
2297 msi_record_set_string( rec, i+1, sval, len );
2298 TRACE(" field %d [%s]\n", i+1, debugstr_wn(sval, len));
2299 ofs += bytes_per_strref;
2301 else
2303 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2304 switch( n )
2306 case 2:
2307 val = read_raw_int(rawdata, ofs, n);
2308 if (val)
2309 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2310 TRACE(" field %d [0x%04x]\n", i+1, val );
2311 break;
2312 case 4:
2313 val = read_raw_int(rawdata, ofs, n);
2314 if (val)
2315 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2316 TRACE(" field %d [0x%08x]\n", i+1, val );
2317 break;
2318 default:
2319 ERR("oops - unknown column width %d\n", n);
2320 break;
2322 ofs += n;
2325 return rec;
2328 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2330 UINT i;
2331 for (i = 0; i < rawsize / 2; i++)
2333 int len;
2334 const WCHAR *sval = msi_string_lookup( st, rawdata[i], &len );
2335 MESSAGE(" %04x %s\n", rawdata[i], debugstr_wn(sval, len) );
2339 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2341 UINT i, r, *data;
2343 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2344 for( i=0; i<tv->num_cols; i++ )
2346 data[i] = 0;
2348 if ( ~tv->columns[i].type & MSITYPE_KEY )
2349 continue;
2351 /* turn the transform column value into a row value */
2352 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2353 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2355 int len;
2356 const WCHAR *str = msi_record_get_string( rec, i+1, &len );
2357 if (str)
2359 r = msi_string2id( tv->db->strings, str, len, &data[i] );
2361 /* if there's no matching string in the string table,
2362 these keys can't match any record, so fail now. */
2363 if (r != ERROR_SUCCESS)
2365 msi_free( data );
2366 return NULL;
2369 else data[i] = 0;
2371 else
2373 data[i] = MSI_RecordGetInteger( rec, i+1 );
2375 if (data[i] == MSI_NULL_INTEGER)
2376 data[i] = 0;
2377 else if ((tv->columns[i].type&0xff) == 2)
2378 data[i] += 0x8000;
2379 else
2380 data[i] += 0x80000000;
2383 return data;
2386 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2388 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2390 for( i=0; i<tv->num_cols; i++ )
2392 if ( ~tv->columns[i].type & MSITYPE_KEY )
2393 continue;
2395 /* turn the transform column value into a row value */
2396 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2397 if ( r != ERROR_SUCCESS )
2399 ERR("TABLE_fetch_int shouldn't fail here\n");
2400 break;
2403 /* if this key matches, move to the next column */
2404 if ( x != data[i] )
2406 ret = ERROR_FUNCTION_FAILED;
2407 break;
2409 if (column) *column = i;
2410 ret = ERROR_SUCCESS;
2412 return ret;
2415 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2417 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2419 data = msi_record_to_row( tv, rec );
2420 if( !data )
2421 return r;
2422 for( i = 0; i < tv->table->row_count; i++ )
2424 r = msi_row_matches( tv, i, data, column );
2425 if( r == ERROR_SUCCESS )
2427 *row = i;
2428 break;
2431 msi_free( data );
2432 return r;
2435 typedef struct
2437 struct list entry;
2438 LPWSTR name;
2439 } TRANSFORMDATA;
2441 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2442 string_table *st, TRANSFORMDATA *transform,
2443 UINT bytes_per_strref )
2445 BYTE *rawdata = NULL;
2446 MSITABLEVIEW *tv = NULL;
2447 UINT r, n, sz, i, mask, num_cols, colcol = 0, rawsize = 0;
2448 MSIRECORD *rec = NULL;
2449 WCHAR coltable[32];
2450 const WCHAR *name;
2452 if (!transform)
2453 return ERROR_SUCCESS;
2455 name = transform->name;
2457 coltable[0] = 0;
2458 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2460 /* read the transform data */
2461 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2462 if ( !rawdata )
2464 TRACE("table %s empty\n", debugstr_w(name) );
2465 return ERROR_INVALID_TABLE;
2468 /* create a table view */
2469 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2470 if( r != ERROR_SUCCESS )
2471 goto err;
2473 r = tv->view.ops->execute( &tv->view, NULL );
2474 if( r != ERROR_SUCCESS )
2475 goto err;
2477 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2478 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2480 /* interpret the data */
2481 for (n = 0; n < rawsize;)
2483 mask = rawdata[n] | (rawdata[n + 1] << 8);
2484 if (mask & 1)
2487 * if the low bit is set, columns are continuous and
2488 * the number of columns is specified in the high byte
2490 sz = 2;
2491 num_cols = mask >> 8;
2492 if (num_cols > tv->num_cols)
2494 ERR("excess columns in transform: %u > %u\n", num_cols, tv->num_cols);
2495 break;
2498 for (i = 0; i < num_cols; i++)
2500 if( (tv->columns[i].type & MSITYPE_STRING) &&
2501 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2502 sz += bytes_per_strref;
2503 else
2504 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2507 else
2510 * If the low bit is not set, mask is a bitmask.
2511 * Excepting for key fields, which are always present,
2512 * each bit indicates that a field is present in the transform record.
2514 * mask == 0 is a special case ... only the keys will be present
2515 * and it means that this row should be deleted.
2517 sz = 2;
2518 num_cols = tv->num_cols;
2519 for (i = 0; i < num_cols; i++)
2521 if ((tv->columns[i].type & MSITYPE_KEY) || ((1 << i) & mask))
2523 if ((tv->columns[i].type & MSITYPE_STRING) &&
2524 !MSITYPE_IS_BINARY(tv->columns[i].type))
2525 sz += bytes_per_strref;
2526 else
2527 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2532 /* check we didn't run of the end of the table */
2533 if (n + sz > rawsize)
2535 ERR("borked.\n");
2536 dump_table( st, (USHORT *)rawdata, rawsize );
2537 break;
2540 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2541 if (rec)
2543 WCHAR table[32];
2544 DWORD sz = 32;
2545 UINT number = MSI_NULL_INTEGER;
2546 UINT row = 0;
2548 if (!strcmpW( name, szColumns ))
2550 MSI_RecordGetStringW( rec, 1, table, &sz );
2551 number = MSI_RecordGetInteger( rec, 2 );
2554 * Native msi seems writes nul into the Number (2nd) column of
2555 * the _Columns table when there are new columns
2557 if ( number == MSI_NULL_INTEGER )
2559 /* reset the column number on a new table */
2560 if (strcmpW( coltable, table ))
2562 colcol = 0;
2563 lstrcpyW( coltable, table );
2566 /* fix nul column numbers */
2567 MSI_RecordSetInteger( rec, 2, ++colcol );
2571 if (TRACE_ON(msidb)) dump_record( rec );
2573 r = msi_table_find_row( tv, rec, &row, NULL );
2574 if (r == ERROR_SUCCESS)
2576 if (!mask)
2578 TRACE("deleting row [%d]:\n", row);
2579 r = TABLE_delete_row( &tv->view, row );
2580 if (r != ERROR_SUCCESS)
2581 WARN("failed to delete row %u\n", r);
2583 else if (mask & 1)
2585 TRACE("modifying full row [%d]:\n", row);
2586 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2587 if (r != ERROR_SUCCESS)
2588 WARN("failed to modify row %u\n", r);
2590 else
2592 TRACE("modifying masked row [%d]:\n", row);
2593 r = TABLE_set_row( &tv->view, row, rec, mask );
2594 if (r != ERROR_SUCCESS)
2595 WARN("failed to modify row %u\n", r);
2598 else
2600 TRACE("inserting row\n");
2601 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2602 if (r != ERROR_SUCCESS)
2603 WARN("failed to insert row %u\n", r);
2606 if (!strcmpW( name, szColumns ))
2607 msi_update_table_columns( db, table );
2609 msiobj_release( &rec->hdr );
2612 n += sz;
2615 err:
2616 /* no need to free the table, it's associated with the database */
2617 msi_free( rawdata );
2618 if( tv )
2619 tv->view.ops->delete( &tv->view );
2621 return ERROR_SUCCESS;
2625 * msi_table_apply_transform
2627 * Enumerate the table transforms in a transform storage and apply each one.
2629 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2631 struct list transforms;
2632 IEnumSTATSTG *stgenum = NULL;
2633 TRANSFORMDATA *transform;
2634 TRANSFORMDATA *tables = NULL, *columns = NULL;
2635 HRESULT hr;
2636 STATSTG stat;
2637 string_table *strings;
2638 UINT ret = ERROR_FUNCTION_FAILED;
2639 UINT bytes_per_strref;
2640 BOOL property_update = FALSE;
2642 TRACE("%p %p\n", db, stg );
2644 strings = msi_load_string_table( stg, &bytes_per_strref );
2645 if( !strings )
2646 goto end;
2648 hr = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2649 if (FAILED( hr ))
2650 goto end;
2652 list_init(&transforms);
2654 while ( TRUE )
2656 MSITABLEVIEW *tv = NULL;
2657 WCHAR name[0x40];
2658 ULONG count = 0;
2660 hr = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2661 if (FAILED( hr ) || !count)
2662 break;
2664 decode_streamname( stat.pwcsName, name );
2665 CoTaskMemFree( stat.pwcsName );
2666 if ( name[0] != 0x4840 )
2667 continue;
2669 if ( !strcmpW( name+1, szStringPool ) ||
2670 !strcmpW( name+1, szStringData ) )
2671 continue;
2673 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2674 if ( !transform )
2675 break;
2677 list_add_tail( &transforms, &transform->entry );
2679 transform->name = strdupW( name + 1 );
2681 if ( !strcmpW( transform->name, szTables ) )
2682 tables = transform;
2683 else if (!strcmpW( transform->name, szColumns ) )
2684 columns = transform;
2685 else if (!strcmpW( transform->name, szProperty ))
2686 property_update = TRUE;
2688 TRACE("transform contains stream %s\n", debugstr_w(name));
2690 /* load the table */
2691 if (TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv ) != ERROR_SUCCESS)
2692 continue;
2694 if (tv->view.ops->execute( &tv->view, NULL ) != ERROR_SUCCESS)
2696 tv->view.ops->delete( &tv->view );
2697 continue;
2700 tv->view.ops->delete( &tv->view );
2704 * Apply _Tables and _Columns transforms first so that
2705 * the table metadata is correct, and empty tables exist.
2707 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2708 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2709 goto end;
2711 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2712 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2713 goto end;
2715 ret = ERROR_SUCCESS;
2717 while ( !list_empty( &transforms ) )
2719 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2721 if ( strcmpW( transform->name, szColumns ) &&
2722 strcmpW( transform->name, szTables ) &&
2723 ret == ERROR_SUCCESS )
2725 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2728 list_remove( &transform->entry );
2729 msi_free( transform->name );
2730 msi_free( transform );
2733 if ( ret == ERROR_SUCCESS )
2735 append_storage_to_db( db, stg );
2736 if (property_update) msi_clone_properties( db );
2739 end:
2740 if ( stgenum )
2741 IEnumSTATSTG_Release( stgenum );
2742 if ( strings )
2743 msi_destroy_stringtable( strings );
2745 return ret;