crypt32/tests: CertAddCertificateLinkToStore is not present on W98.
[wine/multimedia.git] / dlls / msi / database.c
blob2bf70c00e657d73ed739bd878b0ee3ef889e7c12
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,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>
23 #define COBJMACROS
24 #define NONAMELESSUNION
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
40 #include "initguid.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
45 * .MSI file format
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
54 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
56 typedef struct tagMSITRANSFORM {
57 struct list entry;
58 IStorage *stg;
59 } MSITRANSFORM;
61 typedef struct tagMSISTREAM {
62 struct list entry;
63 IStream *stm;
64 } MSISTREAM;
66 static UINT find_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
68 MSISTREAM *stream;
70 LIST_FOR_EACH_ENTRY( stream, &db->streams, MSISTREAM, entry )
72 HRESULT r;
73 STATSTG stat;
75 r = IStream_Stat( stream->stm, &stat, 0 );
76 if( FAILED( r ) )
78 WARN("failed to stat stream r = %08x!\n", r);
79 continue;
82 if( !strcmpW( name, stat.pwcsName ) )
84 TRACE("found %s\n", debugstr_w(name));
85 *stm = stream->stm;
86 CoTaskMemFree( stat.pwcsName );
87 return ERROR_SUCCESS;
90 CoTaskMemFree( stat.pwcsName );
93 return ERROR_FUNCTION_FAILED;
96 static UINT clone_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
98 IStream *stream;
100 if (find_open_stream( db, name, &stream ) == ERROR_SUCCESS)
102 HRESULT r;
103 LARGE_INTEGER pos;
105 r = IStream_Clone( stream, stm );
106 if( FAILED( r ) )
108 WARN("failed to clone stream r = %08x!\n", r);
109 return ERROR_FUNCTION_FAILED;
112 pos.QuadPart = 0;
113 r = IStream_Seek( *stm, pos, STREAM_SEEK_SET, NULL );
114 if( FAILED( r ) )
116 IStream_Release( *stm );
117 return ERROR_FUNCTION_FAILED;
120 return ERROR_SUCCESS;
123 return ERROR_FUNCTION_FAILED;
126 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
128 HRESULT r;
129 WCHAR decoded[MAX_STREAM_NAME_LEN];
131 decode_streamname( stname, decoded );
132 TRACE("%s -> %s\n", debugstr_w(stname), debugstr_w(decoded));
134 if (clone_open_stream( db, stname, stm ) == ERROR_SUCCESS)
135 return ERROR_SUCCESS;
137 r = IStorage_OpenStream( db->storage, stname, NULL,
138 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
139 if( FAILED( r ) )
141 MSITRANSFORM *transform;
143 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
145 r = IStorage_OpenStream( transform->stg, stname, NULL,
146 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
147 if (SUCCEEDED(r))
148 break;
152 if( SUCCEEDED(r) )
154 MSISTREAM *stream;
156 stream = msi_alloc( sizeof(MSISTREAM) );
157 if( !stream )
158 return ERROR_NOT_ENOUGH_MEMORY;
160 stream->stm = *stm;
161 IStream_AddRef( *stm );
162 list_add_tail( &db->streams, &stream->entry );
165 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
168 static void free_transforms( MSIDATABASE *db )
170 while( !list_empty( &db->transforms ) )
172 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
173 MSITRANSFORM, entry );
174 list_remove( &t->entry );
175 IStorage_Release( t->stg );
176 msi_free( t );
180 void db_destroy_stream( MSIDATABASE *db, LPCWSTR stname )
182 MSISTREAM *stream, *stream2;
184 LIST_FOR_EACH_ENTRY_SAFE( stream, stream2, &db->streams, MSISTREAM, entry )
186 HRESULT r;
187 STATSTG stat;
189 r = IStream_Stat( stream->stm, &stat, 0 );
190 if (FAILED(r))
192 WARN("failed to stat stream r = %08x\n", r);
193 continue;
196 if (!strcmpW( stname, stat.pwcsName ))
198 TRACE("destroying %s\n", debugstr_w(stname));
200 list_remove( &stream->entry );
201 IStream_Release( stream->stm );
202 msi_free( stream );
203 IStorage_DestroyElement( db->storage, stname );
204 CoTaskMemFree( stat.pwcsName );
205 break;
207 CoTaskMemFree( stat.pwcsName );
211 static void free_streams( MSIDATABASE *db )
213 while( !list_empty( &db->streams ) )
215 MSISTREAM *s = LIST_ENTRY( list_head( &db->streams ),
216 MSISTREAM, entry );
217 list_remove( &s->entry );
218 IStream_Release( s->stm );
219 msi_free( s );
223 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
225 MSITRANSFORM *t;
227 t = msi_alloc( sizeof *t );
228 t->stg = stg;
229 IStorage_AddRef( stg );
230 list_add_head( &db->transforms, &t->entry );
232 /* the transform may add or replace streams */
233 free_streams( db );
236 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
238 MSIDATABASE *db = (MSIDATABASE *) arg;
240 msi_free(db->path);
241 free_cached_tables( db );
242 free_streams( db );
243 free_transforms( db );
244 if (db->strings) msi_destroy_stringtable( db->strings );
245 IStorage_Release( db->storage );
246 if (db->deletefile)
248 DeleteFileW( db->deletefile );
249 msi_free( db->deletefile );
251 if (db->localfile)
253 DeleteFileW( db->localfile );
254 msi_free( db->localfile );
258 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
260 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
261 HRESULT hr;
263 hr = IStorage_SetClass( stg, clsid );
264 if (FAILED( hr ))
266 WARN("failed to set class id 0x%08x\n", hr);
267 return hr;
270 /* create the _Tables stream */
271 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
272 if (FAILED( hr ))
274 WARN("failed to create _Tables stream 0x%08x\n", hr);
275 return hr;
278 hr = msi_init_string_table( stg );
279 if (FAILED( hr ))
281 WARN("failed to initialize string table 0x%08x\n", hr);
282 return hr;
285 hr = IStorage_Commit( stg, 0 );
286 if (FAILED( hr ))
288 WARN("failed to commit changes 0x%08x\n", hr);
289 return hr;
292 return S_OK;
295 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
297 IStorage *stg = NULL;
298 HRESULT r;
299 MSIDATABASE *db = NULL;
300 UINT ret = ERROR_FUNCTION_FAILED;
301 LPCWSTR szMode, save_path;
302 STATSTG stat;
303 BOOL created = FALSE, patch = FALSE;
304 WCHAR path[MAX_PATH];
306 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
308 if( !pdb )
309 return ERROR_INVALID_PARAMETER;
311 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
312 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
314 TRACE("Database is a patch\n");
315 szPersist -= MSIDBOPEN_PATCHFILE;
316 patch = TRUE;
319 save_path = szDBPath;
320 szMode = szPersist;
321 if( !IS_INTMSIDBOPEN(szPersist) )
323 if (!CopyFileW( szDBPath, szPersist, FALSE ))
324 return ERROR_OPEN_FAILED;
326 szDBPath = szPersist;
327 szPersist = MSIDBOPEN_TRANSACT;
328 created = TRUE;
331 if( szPersist == MSIDBOPEN_READONLY )
333 r = StgOpenStorage( szDBPath, NULL,
334 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
336 else if( szPersist == MSIDBOPEN_CREATE )
338 r = StgCreateDocfile( szDBPath,
339 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
341 if( SUCCEEDED(r) )
342 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
343 created = TRUE;
345 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
347 r = StgCreateDocfile( szDBPath,
348 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
350 if( SUCCEEDED(r) )
351 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
352 created = TRUE;
354 else if( szPersist == MSIDBOPEN_TRANSACT )
356 r = StgOpenStorage( szDBPath, NULL,
357 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
359 else if( szPersist == MSIDBOPEN_DIRECT )
361 r = StgOpenStorage( szDBPath, NULL,
362 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
364 else
366 ERR("unknown flag %p\n",szPersist);
367 return ERROR_INVALID_PARAMETER;
370 if( FAILED( r ) || !stg )
372 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
373 return ERROR_FUNCTION_FAILED;
376 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
377 if( FAILED( r ) )
379 FIXME("Failed to stat storage\n");
380 goto end;
383 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
384 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
385 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
387 ERR("storage GUID is not a MSI database GUID %s\n",
388 debugstr_guid(&stat.clsid) );
389 goto end;
392 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
394 ERR("storage GUID is not the MSI patch GUID %s\n",
395 debugstr_guid(&stat.clsid) );
396 ret = ERROR_OPEN_FAILED;
397 goto end;
400 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
401 MSI_CloseDatabase );
402 if( !db )
404 FIXME("Failed to allocate a handle\n");
405 goto end;
408 if (!strchrW( save_path, '\\' ))
410 GetCurrentDirectoryW( MAX_PATH, path );
411 lstrcatW( path, szBackSlash );
412 lstrcatW( path, save_path );
414 else
415 lstrcpyW( path, save_path );
417 db->path = strdupW( path );
419 if( TRACE_ON( msi ) )
420 enum_stream_names( stg );
422 db->storage = stg;
423 db->mode = szMode;
424 if (created)
425 db->deletefile = strdupW( szDBPath );
426 list_init( &db->tables );
427 list_init( &db->transforms );
428 list_init( &db->streams );
430 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
431 if( !db->strings )
432 goto end;
434 ret = ERROR_SUCCESS;
436 msiobj_addref( &db->hdr );
437 IStorage_AddRef( stg );
438 *pdb = db;
440 end:
441 if( db )
442 msiobj_release( &db->hdr );
443 if( stg )
444 IStorage_Release( stg );
446 return ret;
449 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
451 MSIDATABASE *db;
452 UINT ret;
454 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
456 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
457 if( ret == ERROR_SUCCESS )
459 *phDB = alloc_msihandle( &db->hdr );
460 if (! *phDB)
461 ret = ERROR_NOT_ENOUGH_MEMORY;
462 msiobj_release( &db->hdr );
465 return ret;
468 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
470 HRESULT r = ERROR_FUNCTION_FAILED;
471 LPWSTR szwDBPath = NULL, szwPersist = NULL;
473 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
475 if( szDBPath )
477 szwDBPath = strdupAtoW( szDBPath );
478 if( !szwDBPath )
479 goto end;
482 if( !IS_INTMSIDBOPEN(szPersist) )
484 szwPersist = strdupAtoW( szPersist );
485 if( !szwPersist )
486 goto end;
488 else
489 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
491 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
493 end:
494 if( !IS_INTMSIDBOPEN(szPersist) )
495 msi_free( szwPersist );
496 msi_free( szwDBPath );
498 return r;
501 static LPWSTR msi_read_text_archive(LPCWSTR path)
503 HANDLE file;
504 LPSTR data = NULL;
505 LPWSTR wdata = NULL;
506 DWORD read, size = 0;
508 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
509 if (file == INVALID_HANDLE_VALUE)
510 return NULL;
512 size = GetFileSize( file, NULL );
513 data = msi_alloc( size + 1 );
514 if (!data)
515 goto done;
517 if (!ReadFile( file, data, size, &read, NULL ))
518 goto done;
520 data[size] = '\0';
521 wdata = strdupAtoW( data );
523 done:
524 CloseHandle( file );
525 msi_free( data );
526 return wdata;
529 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
531 LPWSTR ptr = *line, save;
532 DWORD i, count = 1;
534 *entries = NULL;
536 /* stay on this line */
537 while (*ptr && *ptr != '\n')
539 /* entries are separated by tabs */
540 if (*ptr == '\t')
541 count++;
543 ptr++;
546 *entries = msi_alloc(count * sizeof(LPWSTR));
547 if (!*entries)
548 return;
550 /* store pointers into the data */
551 for (i = 0, ptr = *line; i < count; i++)
553 while (*ptr && *ptr == '\r') ptr++;
554 save = ptr;
556 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
558 /* NULL-separate the data */
559 if (*ptr == '\n' || *ptr == '\r')
561 while (*ptr == '\n' || *ptr == '\r')
562 *(ptr++) = '\0';
564 else if (*ptr)
565 *ptr++ = '\0';
567 (*entries)[i] = save;
570 /* move to the next line if there's more, else EOF */
571 *line = ptr;
573 if (num_entries)
574 *num_entries = count;
577 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
579 LPWSTR prelude;
580 DWORD size;
582 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
584 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
585 prelude = msi_alloc(size * sizeof(WCHAR));
586 if (!prelude)
587 return NULL;
589 sprintfW(prelude, create_fmt, table);
590 return prelude;
593 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
595 LPWSTR columns, p;
596 LPCWSTR type;
597 DWORD sql_size = 1, i, len;
598 WCHAR expanded[128], *ptr;
599 WCHAR size[10], comma[2], extra[30];
601 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
602 static const WCHAR size_fmt[] = {'(','%','s',')',0};
603 static const WCHAR type_char[] = {'C','H','A','R',0};
604 static const WCHAR type_int[] = {'I','N','T',0};
605 static const WCHAR type_long[] = {'L','O','N','G',0};
606 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
607 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
608 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
610 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
611 if (!columns)
612 return NULL;
614 for (i = 0; i < num_columns; i++)
616 type = NULL;
617 comma[1] = size[0] = extra[0] = '\0';
619 if (i == num_columns - 1)
620 comma[0] = '\0';
621 else
622 comma[0] = ',';
624 ptr = &types[i][1];
625 len = atolW(ptr);
626 extra[0] = '\0';
628 switch (types[i][0])
630 case 'l':
631 lstrcpyW(extra, type_notnull);
632 case 'L':
633 lstrcatW(extra, localizable);
634 type = type_char;
635 sprintfW(size, size_fmt, ptr);
636 break;
637 case 's':
638 lstrcpyW(extra, type_notnull);
639 case 'S':
640 type = type_char;
641 sprintfW(size, size_fmt, ptr);
642 break;
643 case 'i':
644 lstrcpyW(extra, type_notnull);
645 case 'I':
646 if (len <= 2)
647 type = type_int;
648 else if (len == 4)
649 type = type_long;
650 else
652 WARN("invalid int width %u\n", len);
653 msi_free(columns);
654 return NULL;
656 break;
657 case 'v':
658 lstrcpyW(extra, type_notnull);
659 case 'V':
660 type = type_object;
661 break;
662 default:
663 ERR("Unknown type: %c\n", types[i][0]);
664 msi_free(columns);
665 return NULL;
668 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
669 sql_size += lstrlenW(expanded);
671 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
672 if (!p)
674 msi_free(columns);
675 return NULL;
677 columns = p;
679 lstrcatW(columns, expanded);
682 return columns;
685 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
687 LPWSTR postlude, keys, ptr;
688 DWORD size, key_size, i;
690 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
691 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
693 for (i = 0, size = 1; i < num_keys; i++)
694 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
696 keys = msi_alloc(size * sizeof(WCHAR));
697 if (!keys)
698 return NULL;
700 for (i = 0, ptr = keys; i < num_keys; i++)
702 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
703 sprintfW(ptr, key_fmt, primary_keys[i]);
704 ptr += key_size;
707 /* remove final ', ' */
708 *(ptr - 2) = '\0';
710 size = lstrlenW(postlude_fmt) + size - 1;
711 postlude = msi_alloc(size * sizeof(WCHAR));
712 if (!postlude)
713 goto done;
715 sprintfW(postlude, postlude_fmt, keys);
717 done:
718 msi_free(keys);
719 return postlude;
722 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
724 UINT r = ERROR_OUTOFMEMORY;
725 DWORD size;
726 MSIQUERY *view;
727 LPWSTR create_sql = NULL;
728 LPWSTR prelude, columns_sql, postlude;
730 prelude = msi_build_createsql_prelude(labels[0]);
731 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
732 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
734 if (!prelude || !columns_sql || !postlude)
735 goto done;
737 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
738 create_sql = msi_alloc(size * sizeof(WCHAR));
739 if (!create_sql)
740 goto done;
742 lstrcpyW(create_sql, prelude);
743 lstrcatW(create_sql, columns_sql);
744 lstrcatW(create_sql, postlude);
746 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
747 if (r != ERROR_SUCCESS)
748 goto done;
750 r = MSI_ViewExecute(view, NULL);
751 MSI_ViewClose(view);
752 msiobj_release(&view->hdr);
754 done:
755 msi_free(prelude);
756 msi_free(columns_sql);
757 msi_free(postlude);
758 msi_free(create_sql);
759 return r;
762 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
764 DWORD len;
765 LPWSTR fullname, ptr;
767 len = lstrlenW(path) + lstrlenW(name) + 1;
768 fullname = msi_alloc(len*sizeof(WCHAR));
769 if (!fullname)
770 return NULL;
772 lstrcpyW( fullname, path );
774 /* chop off extension from path */
775 ptr = strrchrW(fullname, '.');
776 if (!ptr)
778 msi_free (fullname);
779 return NULL;
781 *ptr++ = '\\';
782 lstrcpyW( ptr, name );
783 return fullname;
786 static UINT construct_record(DWORD num_columns, LPWSTR *types,
787 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
789 UINT i;
791 *rec = MSI_CreateRecord(num_columns);
792 if (!*rec)
793 return ERROR_OUTOFMEMORY;
795 for (i = 0; i < num_columns; i++)
797 switch (types[i][0])
799 case 'L': case 'l': case 'S': case 's':
800 MSI_RecordSetStringW(*rec, i + 1, data[i]);
801 break;
802 case 'I': case 'i':
803 if (*data[i])
804 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
805 break;
806 case 'V': case 'v':
807 if (*data[i])
809 UINT r;
810 LPWSTR file = msi_import_stream_filename(path, data[i]);
811 if (!file)
812 return ERROR_FUNCTION_FAILED;
814 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
815 msi_free (file);
816 if (r != ERROR_SUCCESS)
817 return ERROR_FUNCTION_FAILED;
819 break;
820 default:
821 ERR("Unhandled column type: %c\n", types[i][0]);
822 msiobj_release(&(*rec)->hdr);
823 return ERROR_FUNCTION_FAILED;
827 return ERROR_SUCCESS;
830 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
831 LPWSTR *labels, LPWSTR **records,
832 int num_columns, int num_records,
833 LPWSTR path)
835 UINT r;
836 int i;
837 MSIQUERY *view;
838 MSIRECORD *rec;
840 static const WCHAR select[] = {
841 'S','E','L','E','C','T',' ','*',' ',
842 'F','R','O','M',' ','`','%','s','`',0
845 r = MSI_OpenQuery(db, &view, select, labels[0]);
846 if (r != ERROR_SUCCESS)
847 return r;
849 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
851 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
852 msiobj_release(&rec->hdr);
853 if (r != ERROR_SUCCESS)
854 goto done;
857 for (i = 0; i < num_records; i++)
859 r = construct_record(num_columns, types, records[i], path, &rec);
860 if (r != ERROR_SUCCESS)
861 goto done;
863 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
864 if (r != ERROR_SUCCESS)
866 msiobj_release(&rec->hdr);
867 goto done;
870 msiobj_release(&rec->hdr);
873 done:
874 msiobj_release(&view->hdr);
875 return r;
878 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
880 UINT r;
881 DWORD len, i;
882 DWORD num_labels, num_types;
883 DWORD num_columns, num_records = 0;
884 LPWSTR *columns, *types, *labels;
885 LPWSTR path, ptr, data;
886 LPWSTR **records = NULL;
887 LPWSTR **temp_records;
889 static const WCHAR suminfo[] =
890 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
892 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
894 if( folder == NULL || file == NULL )
895 return ERROR_INVALID_PARAMETER;
897 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
898 path = msi_alloc( len * sizeof(WCHAR) );
899 if (!path)
900 return ERROR_OUTOFMEMORY;
902 lstrcpyW( path, folder );
903 lstrcatW( path, szBackSlash );
904 lstrcatW( path, file );
906 data = msi_read_text_archive( path );
908 ptr = data;
909 msi_parse_line( &ptr, &columns, &num_columns );
910 msi_parse_line( &ptr, &types, &num_types );
911 msi_parse_line( &ptr, &labels, &num_labels );
913 if (num_columns != num_types)
915 r = ERROR_FUNCTION_FAILED;
916 goto done;
919 records = msi_alloc(sizeof(LPWSTR *));
920 if (!records)
922 r = ERROR_OUTOFMEMORY;
923 goto done;
926 /* read in the table records */
927 while (*ptr)
929 msi_parse_line( &ptr, &records[num_records], NULL );
931 num_records++;
932 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
933 if (!temp_records)
935 r = ERROR_OUTOFMEMORY;
936 goto done;
938 records = temp_records;
941 if (!strcmpW(labels[0], suminfo))
943 r = msi_add_suminfo( db, records, num_records, num_columns );
944 if (r != ERROR_SUCCESS)
946 r = ERROR_FUNCTION_FAILED;
947 goto done;
950 else
952 if (!TABLE_Exists(db, labels[0]))
954 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
955 if (r != ERROR_SUCCESS)
957 r = ERROR_FUNCTION_FAILED;
958 goto done;
962 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
965 done:
966 msi_free(path);
967 msi_free(data);
968 msi_free(columns);
969 msi_free(types);
970 msi_free(labels);
972 for (i = 0; i < num_records; i++)
973 msi_free(records[i]);
975 msi_free(records);
977 return r;
980 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
982 MSIDATABASE *db;
983 UINT r;
985 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
987 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
988 if( !db )
990 IWineMsiRemoteDatabase *remote_database;
992 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
993 if ( !remote_database )
994 return ERROR_INVALID_HANDLE;
996 IWineMsiRemoteDatabase_Release( remote_database );
997 WARN("MsiDatabaseImport not allowed during a custom action!\n");
999 return ERROR_SUCCESS;
1002 r = MSI_DatabaseImport( db, szFolder, szFilename );
1003 msiobj_release( &db->hdr );
1004 return r;
1007 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
1008 LPCSTR szFolder, LPCSTR szFilename )
1010 LPWSTR path = NULL, file = NULL;
1011 UINT r = ERROR_OUTOFMEMORY;
1013 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
1015 if( szFolder )
1017 path = strdupAtoW( szFolder );
1018 if( !path )
1019 goto end;
1022 if( szFilename )
1024 file = strdupAtoW( szFilename );
1025 if( !file )
1026 goto end;
1029 r = MsiDatabaseImportW( handle, path, file );
1031 end:
1032 msi_free( path );
1033 msi_free( file );
1035 return r;
1038 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
1040 UINT i, count, len, r = ERROR_SUCCESS;
1041 const char *sep;
1042 char *buffer;
1043 DWORD sz;
1045 len = 0x100;
1046 buffer = msi_alloc( len );
1047 if ( !buffer )
1048 return ERROR_OUTOFMEMORY;
1050 count = MSI_RecordGetFieldCount( row );
1051 for ( i=start; i<=count; i++ )
1053 sz = len;
1054 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1055 if (r == ERROR_MORE_DATA)
1057 char *p = msi_realloc( buffer, sz + 1 );
1058 if (!p)
1059 break;
1060 len = sz + 1;
1061 buffer = p;
1063 sz = len;
1064 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1065 if (r != ERROR_SUCCESS)
1066 break;
1068 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
1070 r = ERROR_FUNCTION_FAILED;
1071 break;
1074 sep = (i < count) ? "\t" : "\r\n";
1075 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1077 r = ERROR_FUNCTION_FAILED;
1078 break;
1081 msi_free( buffer );
1082 return r;
1085 static UINT msi_export_row( MSIRECORD *row, void *arg )
1087 return msi_export_record( arg, row, 1 );
1090 static UINT msi_export_forcecodepage( HANDLE handle )
1092 DWORD sz;
1094 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
1096 FIXME("Read the codepage from the strings table!\n");
1098 sz = lstrlenA(data) + 1;
1099 if (!WriteFile(handle, data, sz, &sz, NULL))
1100 return ERROR_FUNCTION_FAILED;
1102 return ERROR_SUCCESS;
1105 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
1106 LPCWSTR folder, LPCWSTR file )
1108 static const WCHAR query[] = {
1109 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
1110 static const WCHAR forcecodepage[] = {
1111 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
1112 MSIRECORD *rec = NULL;
1113 MSIQUERY *view = NULL;
1114 LPWSTR filename;
1115 HANDLE handle;
1116 UINT len, r;
1118 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1119 debugstr_w(folder), debugstr_w(file) );
1121 if( folder == NULL || file == NULL )
1122 return ERROR_INVALID_PARAMETER;
1124 len = lstrlenW(folder) + lstrlenW(file) + 2;
1125 filename = msi_alloc(len * sizeof (WCHAR));
1126 if (!filename)
1127 return ERROR_OUTOFMEMORY;
1129 lstrcpyW( filename, folder );
1130 lstrcatW( filename, szBackSlash );
1131 lstrcatW( filename, file );
1133 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1134 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1135 msi_free( filename );
1136 if (handle == INVALID_HANDLE_VALUE)
1137 return ERROR_FUNCTION_FAILED;
1139 if (!strcmpW( table, forcecodepage ))
1141 r = msi_export_forcecodepage( handle );
1142 goto done;
1145 r = MSI_OpenQuery( db, &view, query, table );
1146 if (r == ERROR_SUCCESS)
1148 /* write out row 1, the column names */
1149 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1150 if (r == ERROR_SUCCESS)
1152 msi_export_record( handle, rec, 1 );
1153 msiobj_release( &rec->hdr );
1156 /* write out row 2, the column types */
1157 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1158 if (r == ERROR_SUCCESS)
1160 msi_export_record( handle, rec, 1 );
1161 msiobj_release( &rec->hdr );
1164 /* write out row 3, the table name + keys */
1165 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1166 if (r == ERROR_SUCCESS)
1168 MSI_RecordSetStringW( rec, 0, table );
1169 msi_export_record( handle, rec, 0 );
1170 msiobj_release( &rec->hdr );
1173 /* write out row 4 onwards, the data */
1174 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1175 msiobj_release( &view->hdr );
1178 done:
1179 CloseHandle( handle );
1180 return r;
1183 /***********************************************************************
1184 * MsiExportDatabaseW [MSI.@]
1186 * Writes a file containing the table data as tab separated ASCII.
1188 * The format is as follows:
1190 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1191 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1192 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1194 * Followed by the data, starting at row 1 with one row per line
1196 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1198 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1199 LPCWSTR szFolder, LPCWSTR szFilename )
1201 MSIDATABASE *db;
1202 UINT r;
1204 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1205 debugstr_w(szFolder), debugstr_w(szFilename));
1207 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1208 if( !db )
1210 IWineMsiRemoteDatabase *remote_database;
1212 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1213 if ( !remote_database )
1214 return ERROR_INVALID_HANDLE;
1216 IWineMsiRemoteDatabase_Release( remote_database );
1217 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1219 return ERROR_SUCCESS;
1222 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1223 msiobj_release( &db->hdr );
1224 return r;
1227 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1228 LPCSTR szFolder, LPCSTR szFilename )
1230 LPWSTR path = NULL, file = NULL, table = NULL;
1231 UINT r = ERROR_OUTOFMEMORY;
1233 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1234 debugstr_a(szFolder), debugstr_a(szFilename));
1236 if( szTable )
1238 table = strdupAtoW( szTable );
1239 if( !table )
1240 goto end;
1243 if( szFolder )
1245 path = strdupAtoW( szFolder );
1246 if( !path )
1247 goto end;
1250 if( szFilename )
1252 file = strdupAtoW( szFilename );
1253 if( !file )
1254 goto end;
1257 r = MsiDatabaseExportW( handle, table, path, file );
1259 end:
1260 msi_free( table );
1261 msi_free( path );
1262 msi_free( file );
1264 return r;
1267 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1268 LPCSTR szTableName)
1270 UINT r;
1271 LPWSTR table;
1273 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1274 debugstr_a(szTableName));
1276 table = strdupAtoW(szTableName);
1277 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1279 msi_free(table);
1280 return r;
1283 typedef struct _tagMERGETABLE
1285 struct list entry;
1286 struct list rows;
1287 LPWSTR name;
1288 DWORD numconflicts;
1289 LPWSTR *columns;
1290 DWORD numcolumns;
1291 LPWSTR *types;
1292 DWORD numtypes;
1293 LPWSTR *labels;
1294 DWORD numlabels;
1295 } MERGETABLE;
1297 typedef struct _tagMERGEROW
1299 struct list entry;
1300 MSIRECORD *data;
1301 } MERGEROW;
1303 typedef struct _tagMERGEDATA
1305 MSIDATABASE *db;
1306 MSIDATABASE *merge;
1307 MERGETABLE *curtable;
1308 MSIQUERY *curview;
1309 struct list *tabledata;
1310 } MERGEDATA;
1312 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1314 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1315 ((type2[0] == 'l') || (type2[0] == 's')))
1316 return TRUE;
1318 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1319 ((type2[0] == 'L') || (type2[0] == 'S')))
1320 return TRUE;
1322 return !strcmpW( type1, type2 );
1325 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1327 MSIRECORD *dbrec, *mergerec;
1328 UINT r, i, count;
1330 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1331 if (r != ERROR_SUCCESS)
1332 return r;
1334 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1335 if (r != ERROR_SUCCESS)
1336 return r;
1338 count = MSI_RecordGetFieldCount(dbrec);
1339 for (i = 1; i <= count; i++)
1341 if (!MSI_RecordGetString(mergerec, i))
1342 break;
1344 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1346 r = ERROR_DATATYPE_MISMATCH;
1347 goto done;
1351 msiobj_release(&dbrec->hdr);
1352 msiobj_release(&mergerec->hdr);
1353 dbrec = mergerec = NULL;
1355 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1356 if (r != ERROR_SUCCESS)
1357 return r;
1359 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1360 if (r != ERROR_SUCCESS)
1361 return r;
1363 count = MSI_RecordGetFieldCount(dbrec);
1364 for (i = 1; i <= count; i++)
1366 if (!MSI_RecordGetString(mergerec, i))
1367 break;
1369 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1370 MSI_RecordGetString(mergerec, i)))
1372 r = ERROR_DATATYPE_MISMATCH;
1373 break;
1377 done:
1378 msiobj_release(&dbrec->hdr);
1379 msiobj_release(&mergerec->hdr);
1381 return r;
1384 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1385 LPCWSTR table)
1387 MSIRECORD *dbrec, *mergerec = NULL;
1388 UINT r, i, count;
1390 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1391 if (r != ERROR_SUCCESS)
1392 return r;
1394 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1395 if (r != ERROR_SUCCESS)
1396 goto done;
1398 count = MSI_RecordGetFieldCount(dbrec);
1399 if (count != MSI_RecordGetFieldCount(mergerec))
1401 r = ERROR_DATATYPE_MISMATCH;
1402 goto done;
1405 for (i = 1; i <= count; i++)
1407 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1409 r = ERROR_DATATYPE_MISMATCH;
1410 goto done;
1414 done:
1415 msiobj_release(&dbrec->hdr);
1416 msiobj_release(&mergerec->hdr);
1418 return r;
1421 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1423 MSIRECORD *colnames;
1424 LPWSTR str, val;
1425 UINT r, i = 0, sz = 0;
1426 int cmp;
1428 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1429 if (r != ERROR_SUCCESS)
1430 return NULL;
1434 str = msi_dup_record_field(colnames, ++i);
1435 cmp = strcmpW( key, str );
1436 msi_free(str);
1437 } while (cmp);
1439 msiobj_release(&colnames->hdr);
1441 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1442 if (r != ERROR_SUCCESS)
1443 return NULL;
1444 sz++;
1446 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1448 /* quote string record fields */
1449 const WCHAR szQuote[] = {'\'', 0};
1450 sz += 2;
1451 val = msi_alloc(sz*sizeof(WCHAR));
1452 if (!val)
1453 return NULL;
1455 lstrcpyW(val, szQuote);
1456 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1457 lstrcpyW(val+1+sz, szQuote);
1459 else
1461 /* do not quote integer record fields */
1462 val = msi_alloc(sz*sizeof(WCHAR));
1463 if (!val)
1464 return NULL;
1466 r = MSI_RecordGetStringW(rec, i, val, &sz);
1469 if (r != ERROR_SUCCESS)
1471 ERR("failed to get string!\n");
1472 msi_free(val);
1473 return NULL;
1476 return val;
1479 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1480 LPWSTR table, MSIRECORD *rec)
1482 LPWSTR query = NULL, clause = NULL;
1483 LPWSTR ptr = NULL, val;
1484 LPCWSTR setptr;
1485 DWORD size = 1, oldsize;
1486 LPCWSTR key;
1487 MSIRECORD *keys;
1488 UINT r, i, count;
1490 static const WCHAR keyset[] = {
1491 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1492 static const WCHAR lastkeyset[] = {
1493 '`','%','s','`',' ','=',' ','%','s',' ',0};
1494 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1495 'F','R','O','M',' ','`','%','s','`',' ',
1496 'W','H','E','R','E',' ','%','s',0};
1498 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1499 if (r != ERROR_SUCCESS)
1500 return NULL;
1502 clause = msi_alloc_zero(size * sizeof(WCHAR));
1503 if (!clause)
1504 goto done;
1506 ptr = clause;
1507 count = MSI_RecordGetFieldCount(keys);
1508 for (i = 1; i <= count; i++)
1510 key = MSI_RecordGetString(keys, i);
1511 val = get_key_value(view, key, rec);
1513 if (i == count)
1514 setptr = lastkeyset;
1515 else
1516 setptr = keyset;
1518 oldsize = size;
1519 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1520 clause = msi_realloc(clause, size * sizeof (WCHAR));
1521 if (!clause)
1523 msi_free(val);
1524 goto done;
1527 ptr = clause + oldsize - 1;
1528 sprintfW(ptr, setptr, key, val);
1529 msi_free(val);
1532 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1533 query = msi_alloc(size * sizeof(WCHAR));
1534 if (!query)
1535 goto done;
1537 sprintfW(query, fmt, table, clause);
1539 done:
1540 msi_free(clause);
1541 msiobj_release(&keys->hdr);
1542 return query;
1545 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1547 MERGEDATA *data = param;
1548 MERGETABLE *table = data->curtable;
1549 MERGEROW *mergerow;
1550 MSIQUERY *dbview = NULL;
1551 MSIRECORD *row = NULL;
1552 LPWSTR query = NULL;
1553 UINT r = ERROR_SUCCESS;
1555 if (TABLE_Exists(data->db, table->name))
1557 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1558 if (!query)
1559 return ERROR_OUTOFMEMORY;
1561 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1562 if (r != ERROR_SUCCESS)
1563 goto done;
1565 r = MSI_ViewExecute(dbview, NULL);
1566 if (r != ERROR_SUCCESS)
1567 goto done;
1569 r = MSI_ViewFetch(dbview, &row);
1570 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1572 table->numconflicts++;
1573 goto done;
1575 else if (r != ERROR_NO_MORE_ITEMS)
1576 goto done;
1578 r = ERROR_SUCCESS;
1581 mergerow = msi_alloc(sizeof(MERGEROW));
1582 if (!mergerow)
1584 r = ERROR_OUTOFMEMORY;
1585 goto done;
1588 mergerow->data = MSI_CloneRecord(rec);
1589 if (!mergerow->data)
1591 r = ERROR_OUTOFMEMORY;
1592 msi_free(mergerow);
1593 goto done;
1596 list_add_tail(&table->rows, &mergerow->entry);
1598 done:
1599 msi_free(query);
1600 msiobj_release(&row->hdr);
1601 msiobj_release(&dbview->hdr);
1602 return r;
1605 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1607 UINT r, i, count;
1608 MSIRECORD *prec = NULL;
1610 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1611 if (r != ERROR_SUCCESS)
1612 return r;
1614 count = MSI_RecordGetFieldCount(prec);
1615 *numlabels = count + 1;
1616 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1617 if (!*labels)
1619 r = ERROR_OUTOFMEMORY;
1620 goto end;
1623 (*labels)[0] = strdupW(table);
1624 for (i=1; i<=count; i++ )
1626 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1629 end:
1630 msiobj_release( &prec->hdr );
1631 return r;
1634 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1636 UINT r, i, count;
1637 MSIRECORD *prec = NULL;
1639 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1640 if (r != ERROR_SUCCESS)
1641 return r;
1643 count = MSI_RecordGetFieldCount(prec);
1644 *columns = msi_alloc(count*sizeof(LPWSTR));
1645 if (!*columns)
1647 r = ERROR_OUTOFMEMORY;
1648 goto end;
1651 for (i=1; i<=count; i++ )
1653 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1656 *numcolumns = count;
1658 end:
1659 msiobj_release( &prec->hdr );
1660 return r;
1663 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1665 UINT r, i, count;
1666 MSIRECORD *prec = NULL;
1668 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1669 if (r != ERROR_SUCCESS)
1670 return r;
1672 count = MSI_RecordGetFieldCount(prec);
1673 *types = msi_alloc(count*sizeof(LPWSTR));
1674 if (!*types)
1676 r = ERROR_OUTOFMEMORY;
1677 goto end;
1680 *numtypes = count;
1681 for (i=1; i<=count; i++ )
1683 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1686 end:
1687 msiobj_release( &prec->hdr );
1688 return r;
1691 static void merge_free_rows(MERGETABLE *table)
1693 struct list *item, *cursor;
1695 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1697 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1699 list_remove(&row->entry);
1700 msiobj_release(&row->data->hdr);
1701 msi_free(row);
1705 static void free_merge_table(MERGETABLE *table)
1707 UINT i;
1709 if (table->labels != NULL)
1711 for (i = 0; i < table->numlabels; i++)
1712 msi_free(table->labels[i]);
1714 msi_free(table->labels);
1717 if (table->columns != NULL)
1719 for (i = 0; i < table->numcolumns; i++)
1720 msi_free(table->columns[i]);
1722 msi_free(table->columns);
1725 if (table->types != NULL)
1727 for (i = 0; i < table->numtypes; i++)
1728 msi_free(table->types[i]);
1730 msi_free(table->types);
1733 msi_free(table->name);
1734 merge_free_rows(table);
1736 msi_free(table);
1739 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1741 UINT r;
1742 MERGETABLE *table;
1743 MSIQUERY *mergeview = NULL;
1745 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1746 'F','R','O','M',' ','`','%','s','`',0};
1748 table = msi_alloc_zero(sizeof(MERGETABLE));
1749 if (!table)
1751 *ptable = NULL;
1752 return ERROR_OUTOFMEMORY;
1755 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1756 if (r != ERROR_SUCCESS)
1757 goto err;
1759 r = MSI_OpenQuery(db, &mergeview, query, name);
1760 if (r != ERROR_SUCCESS)
1761 goto err;
1763 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1764 if (r != ERROR_SUCCESS)
1765 goto err;
1767 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1768 if (r != ERROR_SUCCESS)
1769 goto err;
1771 list_init(&table->rows);
1773 table->name = strdupW(name);
1774 table->numconflicts = 0;
1776 msiobj_release(&mergeview->hdr);
1777 *ptable = table;
1778 return ERROR_SUCCESS;
1780 err:
1781 msiobj_release(&mergeview->hdr);
1782 free_merge_table(table);
1783 *ptable = NULL;
1784 return r;
1787 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1789 MERGEDATA *data = param;
1790 MERGETABLE *table;
1791 MSIQUERY *dbview = NULL;
1792 MSIQUERY *mergeview = NULL;
1793 LPCWSTR name;
1794 UINT r;
1796 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1797 'F','R','O','M',' ','`','%','s','`',0};
1799 name = MSI_RecordGetString(rec, 1);
1801 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1802 if (r != ERROR_SUCCESS)
1803 goto done;
1805 if (TABLE_Exists(data->db, name))
1807 r = MSI_OpenQuery(data->db, &dbview, query, name);
1808 if (r != ERROR_SUCCESS)
1809 goto done;
1811 r = merge_verify_colnames(dbview, mergeview);
1812 if (r != ERROR_SUCCESS)
1813 goto done;
1815 r = merge_verify_primary_keys(data->db, data->merge, name);
1816 if (r != ERROR_SUCCESS)
1817 goto done;
1820 r = msi_get_merge_table(data->merge, name, &table);
1821 if (r != ERROR_SUCCESS)
1822 goto done;
1824 data->curtable = table;
1825 data->curview = mergeview;
1826 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1827 if (r != ERROR_SUCCESS)
1829 free_merge_table(table);
1830 goto done;
1833 list_add_tail(data->tabledata, &table->entry);
1835 done:
1836 msiobj_release(&dbview->hdr);
1837 msiobj_release(&mergeview->hdr);
1838 return r;
1841 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1842 struct list *tabledata)
1844 UINT r;
1845 MSIQUERY *view;
1846 MERGEDATA data;
1848 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1849 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1851 r = MSI_DatabaseOpenViewW(merge, query, &view);
1852 if (r != ERROR_SUCCESS)
1853 return r;
1855 data.db = db;
1856 data.merge = merge;
1857 data.tabledata = tabledata;
1858 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1860 msiobj_release(&view->hdr);
1861 return r;
1864 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1866 UINT r;
1867 MERGEROW *row;
1868 MSIVIEW *tv;
1870 if (!TABLE_Exists(db, table->name))
1872 r = msi_add_table_to_db(db, table->columns, table->types,
1873 table->labels, table->numlabels, table->numcolumns);
1874 if (r != ERROR_SUCCESS)
1875 return ERROR_FUNCTION_FAILED;
1878 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1880 r = TABLE_CreateView(db, table->name, &tv);
1881 if (r != ERROR_SUCCESS)
1882 return r;
1884 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1885 tv->ops->delete(tv);
1887 if (r != ERROR_SUCCESS)
1888 return r;
1891 return ERROR_SUCCESS;
1894 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1895 LPWSTR table, DWORD numconflicts)
1897 UINT r;
1898 MSIQUERY *view;
1900 static const WCHAR create[] = {
1901 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1902 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1903 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1904 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1905 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1906 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1907 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1908 static const WCHAR insert[] = {
1909 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1910 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1911 '`','N','u','m','R','o','w','M','e','r','g','e',
1912 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1913 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1915 if (!TABLE_Exists(db, error))
1917 r = MSI_OpenQuery(db, &view, create, error);
1918 if (r != ERROR_SUCCESS)
1919 return r;
1921 r = MSI_ViewExecute(view, NULL);
1922 msiobj_release(&view->hdr);
1923 if (r != ERROR_SUCCESS)
1924 return r;
1927 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1928 if (r != ERROR_SUCCESS)
1929 return r;
1931 r = MSI_ViewExecute(view, NULL);
1932 msiobj_release(&view->hdr);
1933 return r;
1936 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1937 LPCWSTR szTableName)
1939 struct list tabledata = LIST_INIT(tabledata);
1940 struct list *item, *cursor;
1941 MSIDATABASE *db, *merge;
1942 MERGETABLE *table;
1943 BOOL conflicts;
1944 UINT r;
1946 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1947 debugstr_w(szTableName));
1949 if (szTableName && !*szTableName)
1950 return ERROR_INVALID_TABLE;
1952 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1953 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1954 if (!db || !merge)
1956 r = ERROR_INVALID_HANDLE;
1957 goto done;
1960 r = gather_merge_data(db, merge, &tabledata);
1961 if (r != ERROR_SUCCESS)
1962 goto done;
1964 conflicts = FALSE;
1965 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1967 if (table->numconflicts)
1969 conflicts = TRUE;
1971 r = update_merge_errors(db, szTableName, table->name,
1972 table->numconflicts);
1973 if (r != ERROR_SUCCESS)
1974 break;
1976 else
1978 r = merge_table(db, table);
1979 if (r != ERROR_SUCCESS)
1980 break;
1984 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1986 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1987 list_remove(&table->entry);
1988 free_merge_table(table);
1991 if (conflicts)
1992 r = ERROR_FUNCTION_FAILED;
1994 done:
1995 msiobj_release(&db->hdr);
1996 msiobj_release(&merge->hdr);
1997 return r;
2000 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
2002 MSIDBSTATE ret = MSIDBSTATE_READ;
2003 MSIDATABASE *db;
2005 TRACE("%d\n", handle);
2007 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
2008 if( !db )
2010 IWineMsiRemoteDatabase *remote_database;
2012 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
2013 if ( !remote_database )
2014 return MSIDBSTATE_ERROR;
2016 IWineMsiRemoteDatabase_Release( remote_database );
2017 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
2019 return MSIDBSTATE_READ;
2022 if (db->mode != MSIDBOPEN_READONLY )
2023 ret = MSIDBSTATE_WRITE;
2024 msiobj_release( &db->hdr );
2026 return ret;
2029 typedef struct _msi_remote_database_impl {
2030 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
2031 MSIHANDLE database;
2032 LONG refs;
2033 } msi_remote_database_impl;
2035 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
2037 return (msi_remote_database_impl *)iface;
2040 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
2041 REFIID riid,LPVOID *ppobj)
2043 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2044 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
2046 IUnknown_AddRef( iface );
2047 *ppobj = iface;
2048 return S_OK;
2051 return E_NOINTERFACE;
2054 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
2056 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2058 return InterlockedIncrement( &This->refs );
2061 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
2063 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2064 ULONG r;
2066 r = InterlockedDecrement( &This->refs );
2067 if (r == 0)
2069 MsiCloseHandle( This->database );
2070 msi_free( This );
2072 return r;
2075 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
2076 LPCWSTR table, MSICONDITION *persistent )
2078 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2079 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
2080 return S_OK;
2083 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
2084 LPCWSTR table, MSIHANDLE *keys )
2086 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2087 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
2088 return HRESULT_FROM_WIN32(r);
2091 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
2092 UINT updatecount, MSIHANDLE *suminfo )
2094 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2095 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
2096 return HRESULT_FROM_WIN32(r);
2099 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
2100 LPCWSTR query, MSIHANDLE *view )
2102 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2103 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
2104 return HRESULT_FROM_WIN32(r);
2107 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
2109 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2110 This->database = handle;
2111 return S_OK;
2114 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2116 mrd_QueryInterface,
2117 mrd_AddRef,
2118 mrd_Release,
2119 mrd_IsTablePersistent,
2120 mrd_GetPrimaryKeys,
2121 mrd_GetSummaryInformation,
2122 mrd_OpenView,
2123 mrd_SetMsiHandle,
2126 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2128 msi_remote_database_impl *This;
2130 This = msi_alloc( sizeof *This );
2131 if (!This)
2132 return E_OUTOFMEMORY;
2134 This->lpVtbl = &msi_remote_database_vtbl;
2135 This->database = 0;
2136 This->refs = 1;
2138 *ppObj = This;
2140 return S_OK;