msi: Don't write streams to storage until the database is committed.
[wine/multimedia.git] / dlls / msi / database.c
blob940d3d9567d9aba5fc1c2607f35661e4006e7efa
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>
22 #include <stdio.h>
24 #define COBJMACROS
25 #define NONAMELESSUNION
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winreg.h"
30 #include "winnls.h"
31 #include "wine/debug.h"
32 #include "wine/unicode.h"
33 #include "msi.h"
34 #include "msiquery.h"
35 #include "msipriv.h"
36 #include "objidl.h"
37 #include "objbase.h"
38 #include "msiserver.h"
39 #include "query.h"
41 #include "initguid.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(msi);
46 * .MSI file format
48 * An .msi file is a structured storage file.
49 * It contains a number of streams.
50 * A stream for each table in the database.
51 * Two streams for the string table in the database.
52 * Any binary data in a table is a reference to a stream.
55 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
57 static void free_transforms( MSIDATABASE *db )
59 while( !list_empty( &db->transforms ) )
61 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ), MSITRANSFORM, entry );
62 list_remove( &t->entry );
63 IStorage_Release( t->stg );
64 msi_free( t );
68 static void free_streams( MSIDATABASE *db )
70 UINT i;
71 for (i = 0; i < db->num_streams; i++)
73 if (db->streams[i].stream) IStream_Release( db->streams[i].stream );
75 msi_free( db->streams );
78 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
80 MSITRANSFORM *t;
82 t = msi_alloc( sizeof *t );
83 t->stg = stg;
84 IStorage_AddRef( stg );
85 list_add_head( &db->transforms, &t->entry );
88 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
90 MSIDATABASE *db = (MSIDATABASE *) arg;
92 msi_free(db->path);
93 free_streams( db );
94 free_cached_tables( db );
95 free_transforms( db );
96 if (db->strings) msi_destroy_stringtable( db->strings );
97 IStorage_Release( db->storage );
98 if (db->deletefile)
100 DeleteFileW( db->deletefile );
101 msi_free( db->deletefile );
105 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
107 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
108 HRESULT hr;
110 hr = IStorage_SetClass( stg, clsid );
111 if (FAILED( hr ))
113 WARN("failed to set class id 0x%08x\n", hr);
114 return hr;
117 /* create the _Tables stream */
118 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
119 if (FAILED( hr ))
121 WARN("failed to create _Tables stream 0x%08x\n", hr);
122 return hr;
125 hr = msi_init_string_table( stg );
126 if (FAILED( hr ))
128 WARN("failed to initialize string table 0x%08x\n", hr);
129 return hr;
132 hr = IStorage_Commit( stg, 0 );
133 if (FAILED( hr ))
135 WARN("failed to commit changes 0x%08x\n", hr);
136 return hr;
139 return S_OK;
142 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
144 IStorage *stg = NULL;
145 HRESULT r;
146 MSIDATABASE *db = NULL;
147 UINT ret = ERROR_FUNCTION_FAILED;
148 LPCWSTR szMode, save_path;
149 STATSTG stat;
150 BOOL created = FALSE, patch = FALSE;
151 WCHAR path[MAX_PATH];
153 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
155 if( !pdb )
156 return ERROR_INVALID_PARAMETER;
158 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
159 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
161 TRACE("Database is a patch\n");
162 szPersist -= MSIDBOPEN_PATCHFILE;
163 patch = TRUE;
166 save_path = szDBPath;
167 szMode = szPersist;
168 if( !IS_INTMSIDBOPEN(szPersist) )
170 if (!CopyFileW( szDBPath, szPersist, FALSE ))
171 return ERROR_OPEN_FAILED;
173 szDBPath = szPersist;
174 szPersist = MSIDBOPEN_TRANSACT;
175 created = TRUE;
178 if( szPersist == MSIDBOPEN_READONLY )
180 r = StgOpenStorage( szDBPath, NULL,
181 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
183 else if( szPersist == MSIDBOPEN_CREATE )
185 r = StgCreateDocfile( szDBPath,
186 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
188 if( SUCCEEDED(r) )
189 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
190 created = TRUE;
192 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
194 r = StgCreateDocfile( szDBPath,
195 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
197 if( SUCCEEDED(r) )
198 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
199 created = TRUE;
201 else if( szPersist == MSIDBOPEN_TRANSACT )
203 r = StgOpenStorage( szDBPath, NULL,
204 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
206 else if( szPersist == MSIDBOPEN_DIRECT )
208 r = StgOpenStorage( szDBPath, NULL,
209 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
211 else
213 ERR("unknown flag %p\n",szPersist);
214 return ERROR_INVALID_PARAMETER;
217 if( FAILED( r ) || !stg )
219 WARN("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
220 return ERROR_FUNCTION_FAILED;
223 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
224 if( FAILED( r ) )
226 FIXME("Failed to stat storage\n");
227 goto end;
230 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
231 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
232 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
234 ERR("storage GUID is not a MSI database GUID %s\n",
235 debugstr_guid(&stat.clsid) );
236 goto end;
239 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
241 ERR("storage GUID is not the MSI patch GUID %s\n",
242 debugstr_guid(&stat.clsid) );
243 ret = ERROR_OPEN_FAILED;
244 goto end;
247 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
248 MSI_CloseDatabase );
249 if( !db )
251 FIXME("Failed to allocate a handle\n");
252 goto end;
255 if (!strchrW( save_path, '\\' ))
257 GetCurrentDirectoryW( MAX_PATH, path );
258 lstrcatW( path, szBackSlash );
259 lstrcatW( path, save_path );
261 else
262 lstrcpyW( path, save_path );
264 db->path = strdupW( path );
265 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
266 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
268 if( TRACE_ON( msi ) )
269 enum_stream_names( stg );
271 db->storage = stg;
272 db->mode = szMode;
273 if (created)
274 db->deletefile = strdupW( szDBPath );
275 list_init( &db->tables );
276 list_init( &db->transforms );
278 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
279 if( !db->strings )
280 goto end;
282 ret = ERROR_SUCCESS;
284 msiobj_addref( &db->hdr );
285 IStorage_AddRef( stg );
286 *pdb = db;
288 end:
289 if( db )
290 msiobj_release( &db->hdr );
291 if( stg )
292 IStorage_Release( stg );
294 return ret;
297 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
299 MSIDATABASE *db;
300 UINT ret;
302 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
304 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
305 if( ret == ERROR_SUCCESS )
307 *phDB = alloc_msihandle( &db->hdr );
308 if (! *phDB)
309 ret = ERROR_NOT_ENOUGH_MEMORY;
310 msiobj_release( &db->hdr );
313 return ret;
316 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
318 HRESULT r = ERROR_FUNCTION_FAILED;
319 LPWSTR szwDBPath = NULL, szwPersist = NULL;
321 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
323 if( szDBPath )
325 szwDBPath = strdupAtoW( szDBPath );
326 if( !szwDBPath )
327 goto end;
330 if( !IS_INTMSIDBOPEN(szPersist) )
332 szwPersist = strdupAtoW( szPersist );
333 if( !szwPersist )
334 goto end;
336 else
337 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
339 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
341 end:
342 if( !IS_INTMSIDBOPEN(szPersist) )
343 msi_free( szwPersist );
344 msi_free( szwDBPath );
346 return r;
349 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
351 HANDLE file;
352 LPSTR data = NULL;
353 LPWSTR wdata = NULL;
354 DWORD read, size = 0;
356 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
357 if (file == INVALID_HANDLE_VALUE)
358 return NULL;
360 size = GetFileSize( file, NULL );
361 if (!(data = msi_alloc( size ))) goto done;
363 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
365 while (!data[size - 1]) size--;
366 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
367 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
369 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
370 wdata[*len] = 0;
373 done:
374 CloseHandle( file );
375 msi_free( data );
376 return wdata;
379 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
381 LPWSTR ptr = *line, save;
382 DWORD i, count = 1, chars_left = *len;
384 *entries = NULL;
386 /* stay on this line */
387 while (chars_left && *ptr != '\n')
389 /* entries are separated by tabs */
390 if (*ptr == '\t')
391 count++;
393 ptr++;
394 chars_left--;
397 *entries = msi_alloc(count * sizeof(LPWSTR));
398 if (!*entries)
399 return;
401 /* store pointers into the data */
402 chars_left = *len;
403 for (i = 0, ptr = *line; i < count; i++)
405 while (chars_left && *ptr == '\r')
407 ptr++;
408 chars_left--;
410 save = ptr;
412 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
414 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
415 if (ptr > *line && *ptr == '\x19' && *(ptr - 1) == '\x11')
417 *ptr = '\n';
418 *(ptr - 1) = '\r';
420 ptr++;
421 chars_left--;
424 /* NULL-separate the data */
425 if (*ptr == '\n' || *ptr == '\r')
427 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
429 *(ptr++) = 0;
430 chars_left--;
433 else if (*ptr)
435 *(ptr++) = 0;
436 chars_left--;
438 (*entries)[i] = save;
441 /* move to the next line if there's more, else EOF */
442 *line = ptr;
443 *len = chars_left;
444 if (num_entries)
445 *num_entries = count;
448 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
450 LPWSTR prelude;
451 DWORD size;
453 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
455 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
456 prelude = msi_alloc(size * sizeof(WCHAR));
457 if (!prelude)
458 return NULL;
460 sprintfW(prelude, create_fmt, table);
461 return prelude;
464 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
466 LPWSTR columns, p;
467 LPCWSTR type;
468 DWORD sql_size = 1, i, len;
469 WCHAR expanded[128], *ptr;
470 WCHAR size[10], comma[2], extra[30];
472 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
473 static const WCHAR size_fmt[] = {'(','%','s',')',0};
474 static const WCHAR type_char[] = {'C','H','A','R',0};
475 static const WCHAR type_int[] = {'I','N','T',0};
476 static const WCHAR type_long[] = {'L','O','N','G',0};
477 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
478 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
479 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
481 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
482 if (!columns)
483 return NULL;
485 for (i = 0; i < num_columns; i++)
487 type = NULL;
488 comma[1] = size[0] = extra[0] = '\0';
490 if (i == num_columns - 1)
491 comma[0] = '\0';
492 else
493 comma[0] = ',';
495 ptr = &types[i][1];
496 len = atolW(ptr);
497 extra[0] = '\0';
499 switch (types[i][0])
501 case 'l':
502 lstrcpyW(extra, type_notnull);
503 /* fall through */
504 case 'L':
505 lstrcatW(extra, localizable);
506 type = type_char;
507 sprintfW(size, size_fmt, ptr);
508 break;
509 case 's':
510 lstrcpyW(extra, type_notnull);
511 /* fall through */
512 case 'S':
513 type = type_char;
514 sprintfW(size, size_fmt, ptr);
515 break;
516 case 'i':
517 lstrcpyW(extra, type_notnull);
518 /* fall through */
519 case 'I':
520 if (len <= 2)
521 type = type_int;
522 else if (len == 4)
523 type = type_long;
524 else
526 WARN("invalid int width %u\n", len);
527 msi_free(columns);
528 return NULL;
530 break;
531 case 'v':
532 lstrcpyW(extra, type_notnull);
533 /* fall through */
534 case 'V':
535 type = type_object;
536 break;
537 default:
538 ERR("Unknown type: %c\n", types[i][0]);
539 msi_free(columns);
540 return NULL;
543 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
544 sql_size += lstrlenW(expanded);
546 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
547 if (!p)
549 msi_free(columns);
550 return NULL;
552 columns = p;
554 lstrcatW(columns, expanded);
557 return columns;
560 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
562 LPWSTR postlude, keys, ptr;
563 DWORD size, key_size, i;
565 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
566 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
568 for (i = 0, size = 1; i < num_keys; i++)
569 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
571 keys = msi_alloc(size * sizeof(WCHAR));
572 if (!keys)
573 return NULL;
575 for (i = 0, ptr = keys; i < num_keys; i++)
577 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
578 sprintfW(ptr, key_fmt, primary_keys[i]);
579 ptr += key_size;
582 /* remove final ', ' */
583 *(ptr - 2) = '\0';
585 size = lstrlenW(postlude_fmt) + size - 1;
586 postlude = msi_alloc(size * sizeof(WCHAR));
587 if (!postlude)
588 goto done;
590 sprintfW(postlude, postlude_fmt, keys);
592 done:
593 msi_free(keys);
594 return postlude;
597 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
599 UINT r = ERROR_OUTOFMEMORY;
600 DWORD size;
601 MSIQUERY *view;
602 LPWSTR create_sql = NULL;
603 LPWSTR prelude, columns_sql, postlude;
605 prelude = msi_build_createsql_prelude(labels[0]);
606 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
607 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
609 if (!prelude || !columns_sql || !postlude)
610 goto done;
612 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
613 create_sql = msi_alloc(size * sizeof(WCHAR));
614 if (!create_sql)
615 goto done;
617 lstrcpyW(create_sql, prelude);
618 lstrcatW(create_sql, columns_sql);
619 lstrcatW(create_sql, postlude);
621 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
622 if (r != ERROR_SUCCESS)
623 goto done;
625 r = MSI_ViewExecute(view, NULL);
626 MSI_ViewClose(view);
627 msiobj_release(&view->hdr);
629 done:
630 msi_free(prelude);
631 msi_free(columns_sql);
632 msi_free(postlude);
633 msi_free(create_sql);
634 return r;
637 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
639 DWORD len;
640 LPWSTR fullname, ptr;
642 len = lstrlenW(path) + lstrlenW(name) + 1;
643 fullname = msi_alloc(len*sizeof(WCHAR));
644 if (!fullname)
645 return NULL;
647 lstrcpyW( fullname, path );
649 /* chop off extension from path */
650 ptr = strrchrW(fullname, '.');
651 if (!ptr)
653 msi_free (fullname);
654 return NULL;
656 *ptr++ = '\\';
657 lstrcpyW( ptr, name );
658 return fullname;
661 static UINT construct_record(DWORD num_columns, LPWSTR *types,
662 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
664 UINT i;
666 *rec = MSI_CreateRecord(num_columns);
667 if (!*rec)
668 return ERROR_OUTOFMEMORY;
670 for (i = 0; i < num_columns; i++)
672 switch (types[i][0])
674 case 'L': case 'l': case 'S': case 's':
675 MSI_RecordSetStringW(*rec, i + 1, data[i]);
676 break;
677 case 'I': case 'i':
678 if (*data[i])
679 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
680 break;
681 case 'V': case 'v':
682 if (*data[i])
684 UINT r;
685 LPWSTR file = msi_import_stream_filename(path, data[i]);
686 if (!file)
687 return ERROR_FUNCTION_FAILED;
689 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
690 msi_free (file);
691 if (r != ERROR_SUCCESS)
692 return ERROR_FUNCTION_FAILED;
694 break;
695 default:
696 ERR("Unhandled column type: %c\n", types[i][0]);
697 msiobj_release(&(*rec)->hdr);
698 return ERROR_FUNCTION_FAILED;
702 return ERROR_SUCCESS;
705 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
706 LPWSTR *labels, LPWSTR **records,
707 int num_columns, int num_records,
708 LPWSTR path)
710 UINT r;
711 int i;
712 MSIQUERY *view;
713 MSIRECORD *rec;
715 static const WCHAR select[] = {
716 'S','E','L','E','C','T',' ','*',' ',
717 'F','R','O','M',' ','`','%','s','`',0
720 r = MSI_OpenQuery(db, &view, select, labels[0]);
721 if (r != ERROR_SUCCESS)
722 return r;
724 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
726 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
727 msiobj_release(&rec->hdr);
728 if (r != ERROR_SUCCESS)
729 goto done;
732 for (i = 0; i < num_records; i++)
734 r = construct_record(num_columns, types, records[i], path, &rec);
735 if (r != ERROR_SUCCESS)
736 goto done;
738 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
739 if (r != ERROR_SUCCESS)
741 msiobj_release(&rec->hdr);
742 goto done;
745 msiobj_release(&rec->hdr);
748 done:
749 msiobj_release(&view->hdr);
750 return r;
753 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
755 UINT r;
756 DWORD len, i;
757 DWORD num_labels, num_types;
758 DWORD num_columns, num_records = 0;
759 LPWSTR *columns, *types, *labels;
760 LPWSTR path, ptr, data;
761 LPWSTR **records = NULL;
762 LPWSTR **temp_records;
764 static const WCHAR suminfo[] =
765 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
766 static const WCHAR forcecodepage[] =
767 {'_','F','o','r','c','e','C','o','d','e','p','a','g','e',0};
769 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
771 if( folder == NULL || file == NULL )
772 return ERROR_INVALID_PARAMETER;
774 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
775 path = msi_alloc( len * sizeof(WCHAR) );
776 if (!path)
777 return ERROR_OUTOFMEMORY;
779 lstrcpyW( path, folder );
780 lstrcatW( path, szBackSlash );
781 lstrcatW( path, file );
783 data = msi_read_text_archive( path, &len );
785 ptr = data;
786 msi_parse_line( &ptr, &columns, &num_columns, &len );
787 msi_parse_line( &ptr, &types, &num_types, &len );
788 msi_parse_line( &ptr, &labels, &num_labels, &len );
790 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
791 num_types == 2 && !strcmpW( types[1], forcecodepage ))
793 r = msi_set_string_table_codepage( db->strings, atoiW( types[0] ) );
794 goto done;
797 if (num_columns != num_types)
799 r = ERROR_FUNCTION_FAILED;
800 goto done;
803 records = msi_alloc(sizeof(LPWSTR *));
804 if (!records)
806 r = ERROR_OUTOFMEMORY;
807 goto done;
810 /* read in the table records */
811 while (len)
813 msi_parse_line( &ptr, &records[num_records], NULL, &len );
815 num_records++;
816 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
817 if (!temp_records)
819 r = ERROR_OUTOFMEMORY;
820 goto done;
822 records = temp_records;
825 if (!strcmpW(labels[0], suminfo))
827 r = msi_add_suminfo( db, records, num_records, num_columns );
828 if (r != ERROR_SUCCESS)
830 r = ERROR_FUNCTION_FAILED;
831 goto done;
834 else
836 if (!TABLE_Exists(db, labels[0]))
838 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
839 if (r != ERROR_SUCCESS)
841 r = ERROR_FUNCTION_FAILED;
842 goto done;
846 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
849 done:
850 msi_free(path);
851 msi_free(data);
852 msi_free(columns);
853 msi_free(types);
854 msi_free(labels);
856 for (i = 0; i < num_records; i++)
857 msi_free(records[i]);
859 msi_free(records);
861 return r;
864 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
866 MSIDATABASE *db;
867 UINT r;
869 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
871 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
872 if( !db )
874 IWineMsiRemoteDatabase *remote_database;
876 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
877 if ( !remote_database )
878 return ERROR_INVALID_HANDLE;
880 IWineMsiRemoteDatabase_Release( remote_database );
881 WARN("MsiDatabaseImport not allowed during a custom action!\n");
883 return ERROR_SUCCESS;
886 r = MSI_DatabaseImport( db, szFolder, szFilename );
887 msiobj_release( &db->hdr );
888 return r;
891 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
892 LPCSTR szFolder, LPCSTR szFilename )
894 LPWSTR path = NULL, file = NULL;
895 UINT r = ERROR_OUTOFMEMORY;
897 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
899 if( szFolder )
901 path = strdupAtoW( szFolder );
902 if( !path )
903 goto end;
906 if( szFilename )
908 file = strdupAtoW( szFilename );
909 if( !file )
910 goto end;
913 r = MsiDatabaseImportW( handle, path, file );
915 end:
916 msi_free( path );
917 msi_free( file );
919 return r;
922 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
924 UINT i, count, len, r = ERROR_SUCCESS;
925 const char *sep;
926 char *buffer;
927 DWORD sz;
929 len = 0x100;
930 buffer = msi_alloc( len );
931 if ( !buffer )
932 return ERROR_OUTOFMEMORY;
934 count = MSI_RecordGetFieldCount( row );
935 for ( i=start; i<=count; i++ )
937 sz = len;
938 r = MSI_RecordGetStringA( row, i, buffer, &sz );
939 if (r == ERROR_MORE_DATA)
941 char *p = msi_realloc( buffer, sz + 1 );
942 if (!p)
943 break;
944 len = sz + 1;
945 buffer = p;
947 sz = len;
948 r = MSI_RecordGetStringA( row, i, buffer, &sz );
949 if (r != ERROR_SUCCESS)
950 break;
952 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
954 r = ERROR_FUNCTION_FAILED;
955 break;
958 sep = (i < count) ? "\t" : "\r\n";
959 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
961 r = ERROR_FUNCTION_FAILED;
962 break;
965 msi_free( buffer );
966 return r;
969 static UINT msi_export_row( MSIRECORD *row, void *arg )
971 return msi_export_record( arg, row, 1 );
974 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
976 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
977 char data[sizeof(fmt) + 10];
978 DWORD sz;
980 sprintf( data, fmt, codepage );
982 sz = lstrlenA(data) + 1;
983 if (!WriteFile(handle, data, sz, &sz, NULL))
984 return ERROR_FUNCTION_FAILED;
986 return ERROR_SUCCESS;
989 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
990 LPCWSTR folder, LPCWSTR file )
992 static const WCHAR query[] = {
993 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
994 static const WCHAR forcecodepage[] = {
995 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
996 MSIRECORD *rec = NULL;
997 MSIQUERY *view = NULL;
998 LPWSTR filename;
999 HANDLE handle;
1000 UINT len, r;
1002 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1003 debugstr_w(folder), debugstr_w(file) );
1005 if( folder == NULL || file == NULL )
1006 return ERROR_INVALID_PARAMETER;
1008 len = lstrlenW(folder) + lstrlenW(file) + 2;
1009 filename = msi_alloc(len * sizeof (WCHAR));
1010 if (!filename)
1011 return ERROR_OUTOFMEMORY;
1013 lstrcpyW( filename, folder );
1014 lstrcatW( filename, szBackSlash );
1015 lstrcatW( filename, file );
1017 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1018 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1019 msi_free( filename );
1020 if (handle == INVALID_HANDLE_VALUE)
1021 return ERROR_FUNCTION_FAILED;
1023 if (!strcmpW( table, forcecodepage ))
1025 UINT codepage = msi_get_string_table_codepage( db->strings );
1026 r = msi_export_forcecodepage( handle, codepage );
1027 goto done;
1030 r = MSI_OpenQuery( db, &view, query, table );
1031 if (r == ERROR_SUCCESS)
1033 /* write out row 1, the column names */
1034 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1035 if (r == ERROR_SUCCESS)
1037 msi_export_record( handle, rec, 1 );
1038 msiobj_release( &rec->hdr );
1041 /* write out row 2, the column types */
1042 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1043 if (r == ERROR_SUCCESS)
1045 msi_export_record( handle, rec, 1 );
1046 msiobj_release( &rec->hdr );
1049 /* write out row 3, the table name + keys */
1050 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1051 if (r == ERROR_SUCCESS)
1053 MSI_RecordSetStringW( rec, 0, table );
1054 msi_export_record( handle, rec, 0 );
1055 msiobj_release( &rec->hdr );
1058 /* write out row 4 onwards, the data */
1059 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1060 msiobj_release( &view->hdr );
1063 done:
1064 CloseHandle( handle );
1065 return r;
1068 /***********************************************************************
1069 * MsiExportDatabaseW [MSI.@]
1071 * Writes a file containing the table data as tab separated ASCII.
1073 * The format is as follows:
1075 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1076 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1077 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1079 * Followed by the data, starting at row 1 with one row per line
1081 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1083 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1084 LPCWSTR szFolder, LPCWSTR szFilename )
1086 MSIDATABASE *db;
1087 UINT r;
1089 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1090 debugstr_w(szFolder), debugstr_w(szFilename));
1092 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1093 if( !db )
1095 IWineMsiRemoteDatabase *remote_database;
1097 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1098 if ( !remote_database )
1099 return ERROR_INVALID_HANDLE;
1101 IWineMsiRemoteDatabase_Release( remote_database );
1102 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1104 return ERROR_SUCCESS;
1107 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1108 msiobj_release( &db->hdr );
1109 return r;
1112 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1113 LPCSTR szFolder, LPCSTR szFilename )
1115 LPWSTR path = NULL, file = NULL, table = NULL;
1116 UINT r = ERROR_OUTOFMEMORY;
1118 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1119 debugstr_a(szFolder), debugstr_a(szFilename));
1121 if( szTable )
1123 table = strdupAtoW( szTable );
1124 if( !table )
1125 goto end;
1128 if( szFolder )
1130 path = strdupAtoW( szFolder );
1131 if( !path )
1132 goto end;
1135 if( szFilename )
1137 file = strdupAtoW( szFilename );
1138 if( !file )
1139 goto end;
1142 r = MsiDatabaseExportW( handle, table, path, file );
1144 end:
1145 msi_free( table );
1146 msi_free( path );
1147 msi_free( file );
1149 return r;
1152 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1153 LPCSTR szTableName)
1155 UINT r;
1156 LPWSTR table;
1158 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1159 debugstr_a(szTableName));
1161 table = strdupAtoW(szTableName);
1162 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1164 msi_free(table);
1165 return r;
1168 typedef struct _tagMERGETABLE
1170 struct list entry;
1171 struct list rows;
1172 LPWSTR name;
1173 DWORD numconflicts;
1174 LPWSTR *columns;
1175 DWORD numcolumns;
1176 LPWSTR *types;
1177 DWORD numtypes;
1178 LPWSTR *labels;
1179 DWORD numlabels;
1180 } MERGETABLE;
1182 typedef struct _tagMERGEROW
1184 struct list entry;
1185 MSIRECORD *data;
1186 } MERGEROW;
1188 typedef struct _tagMERGEDATA
1190 MSIDATABASE *db;
1191 MSIDATABASE *merge;
1192 MERGETABLE *curtable;
1193 MSIQUERY *curview;
1194 struct list *tabledata;
1195 } MERGEDATA;
1197 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1199 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1200 ((type2[0] == 'l') || (type2[0] == 's')))
1201 return TRUE;
1203 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1204 ((type2[0] == 'L') || (type2[0] == 'S')))
1205 return TRUE;
1207 return !strcmpW( type1, type2 );
1210 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1212 MSIRECORD *dbrec, *mergerec;
1213 UINT r, i, count;
1215 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1216 if (r != ERROR_SUCCESS)
1217 return r;
1219 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1220 if (r != ERROR_SUCCESS)
1222 msiobj_release(&dbrec->hdr);
1223 return r;
1226 count = MSI_RecordGetFieldCount(dbrec);
1227 for (i = 1; i <= count; i++)
1229 if (!MSI_RecordGetString(mergerec, i))
1230 break;
1232 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1234 r = ERROR_DATATYPE_MISMATCH;
1235 goto done;
1239 msiobj_release(&dbrec->hdr);
1240 msiobj_release(&mergerec->hdr);
1241 dbrec = mergerec = NULL;
1243 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1244 if (r != ERROR_SUCCESS)
1245 return r;
1247 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1248 if (r != ERROR_SUCCESS)
1250 msiobj_release(&dbrec->hdr);
1251 return r;
1254 count = MSI_RecordGetFieldCount(dbrec);
1255 for (i = 1; i <= count; i++)
1257 if (!MSI_RecordGetString(mergerec, i))
1258 break;
1260 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1261 MSI_RecordGetString(mergerec, i)))
1263 r = ERROR_DATATYPE_MISMATCH;
1264 break;
1268 done:
1269 msiobj_release(&dbrec->hdr);
1270 msiobj_release(&mergerec->hdr);
1272 return r;
1275 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1276 LPCWSTR table)
1278 MSIRECORD *dbrec, *mergerec = NULL;
1279 UINT r, i, count;
1281 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1282 if (r != ERROR_SUCCESS)
1283 return r;
1285 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1286 if (r != ERROR_SUCCESS)
1287 goto done;
1289 count = MSI_RecordGetFieldCount(dbrec);
1290 if (count != MSI_RecordGetFieldCount(mergerec))
1292 r = ERROR_DATATYPE_MISMATCH;
1293 goto done;
1296 for (i = 1; i <= count; i++)
1298 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1300 r = ERROR_DATATYPE_MISMATCH;
1301 goto done;
1305 done:
1306 msiobj_release(&dbrec->hdr);
1307 msiobj_release(&mergerec->hdr);
1309 return r;
1312 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1314 MSIRECORD *colnames;
1315 LPWSTR str, val;
1316 UINT r, i = 0, sz = 0;
1317 int cmp;
1319 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1320 if (r != ERROR_SUCCESS)
1321 return NULL;
1325 str = msi_dup_record_field(colnames, ++i);
1326 cmp = strcmpW( key, str );
1327 msi_free(str);
1328 } while (cmp);
1330 msiobj_release(&colnames->hdr);
1332 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1333 if (r != ERROR_SUCCESS)
1334 return NULL;
1335 sz++;
1337 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1339 /* quote string record fields */
1340 const WCHAR szQuote[] = {'\'', 0};
1341 sz += 2;
1342 val = msi_alloc(sz*sizeof(WCHAR));
1343 if (!val)
1344 return NULL;
1346 lstrcpyW(val, szQuote);
1347 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1348 lstrcpyW(val+1+sz, szQuote);
1350 else
1352 /* do not quote integer record fields */
1353 val = msi_alloc(sz*sizeof(WCHAR));
1354 if (!val)
1355 return NULL;
1357 r = MSI_RecordGetStringW(rec, i, val, &sz);
1360 if (r != ERROR_SUCCESS)
1362 ERR("failed to get string!\n");
1363 msi_free(val);
1364 return NULL;
1367 return val;
1370 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1371 LPWSTR table, MSIRECORD *rec)
1373 LPWSTR query = NULL, clause = NULL, val;
1374 LPCWSTR setptr, key;
1375 DWORD size, oldsize;
1376 MSIRECORD *keys;
1377 UINT r, i, count;
1379 static const WCHAR keyset[] = {
1380 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1381 static const WCHAR lastkeyset[] = {
1382 '`','%','s','`',' ','=',' ','%','s',' ',0};
1383 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1384 'F','R','O','M',' ','`','%','s','`',' ',
1385 'W','H','E','R','E',' ','%','s',0};
1387 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1388 if (r != ERROR_SUCCESS)
1389 return NULL;
1391 clause = msi_alloc_zero(sizeof(WCHAR));
1392 if (!clause)
1393 goto done;
1395 size = 1;
1396 count = MSI_RecordGetFieldCount(keys);
1397 for (i = 1; i <= count; i++)
1399 key = MSI_RecordGetString(keys, i);
1400 val = get_key_value(view, key, rec);
1402 if (i == count)
1403 setptr = lastkeyset;
1404 else
1405 setptr = keyset;
1407 oldsize = size;
1408 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1409 clause = msi_realloc(clause, size * sizeof (WCHAR));
1410 if (!clause)
1412 msi_free(val);
1413 goto done;
1416 sprintfW(clause + oldsize - 1, setptr, key, val);
1417 msi_free(val);
1420 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1421 query = msi_alloc(size * sizeof(WCHAR));
1422 if (!query)
1423 goto done;
1425 sprintfW(query, fmt, table, clause);
1427 done:
1428 msi_free(clause);
1429 msiobj_release(&keys->hdr);
1430 return query;
1433 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1435 MERGEDATA *data = param;
1436 MERGETABLE *table = data->curtable;
1437 MERGEROW *mergerow;
1438 MSIQUERY *dbview = NULL;
1439 MSIRECORD *row = NULL;
1440 LPWSTR query = NULL;
1441 UINT r = ERROR_SUCCESS;
1443 if (TABLE_Exists(data->db, table->name))
1445 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1446 if (!query)
1447 return ERROR_OUTOFMEMORY;
1449 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1450 if (r != ERROR_SUCCESS)
1451 goto done;
1453 r = MSI_ViewExecute(dbview, NULL);
1454 if (r != ERROR_SUCCESS)
1455 goto done;
1457 r = MSI_ViewFetch(dbview, &row);
1458 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1460 table->numconflicts++;
1461 goto done;
1463 else if (r != ERROR_NO_MORE_ITEMS)
1464 goto done;
1466 r = ERROR_SUCCESS;
1469 mergerow = msi_alloc(sizeof(MERGEROW));
1470 if (!mergerow)
1472 r = ERROR_OUTOFMEMORY;
1473 goto done;
1476 mergerow->data = MSI_CloneRecord(rec);
1477 if (!mergerow->data)
1479 r = ERROR_OUTOFMEMORY;
1480 msi_free(mergerow);
1481 goto done;
1484 list_add_tail(&table->rows, &mergerow->entry);
1486 done:
1487 msi_free(query);
1488 msiobj_release(&row->hdr);
1489 msiobj_release(&dbview->hdr);
1490 return r;
1493 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1495 UINT r, i, count;
1496 MSIRECORD *prec = NULL;
1498 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1499 if (r != ERROR_SUCCESS)
1500 return r;
1502 count = MSI_RecordGetFieldCount(prec);
1503 *numlabels = count + 1;
1504 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1505 if (!*labels)
1507 r = ERROR_OUTOFMEMORY;
1508 goto end;
1511 (*labels)[0] = strdupW(table);
1512 for (i=1; i<=count; i++ )
1514 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1517 end:
1518 msiobj_release( &prec->hdr );
1519 return r;
1522 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1524 UINT r, i, count;
1525 MSIRECORD *prec = NULL;
1527 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1528 if (r != ERROR_SUCCESS)
1529 return r;
1531 count = MSI_RecordGetFieldCount(prec);
1532 *columns = msi_alloc(count*sizeof(LPWSTR));
1533 if (!*columns)
1535 r = ERROR_OUTOFMEMORY;
1536 goto end;
1539 for (i=1; i<=count; i++ )
1541 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1544 *numcolumns = count;
1546 end:
1547 msiobj_release( &prec->hdr );
1548 return r;
1551 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1553 UINT r, i, count;
1554 MSIRECORD *prec = NULL;
1556 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1557 if (r != ERROR_SUCCESS)
1558 return r;
1560 count = MSI_RecordGetFieldCount(prec);
1561 *types = msi_alloc(count*sizeof(LPWSTR));
1562 if (!*types)
1564 r = ERROR_OUTOFMEMORY;
1565 goto end;
1568 *numtypes = count;
1569 for (i=1; i<=count; i++ )
1571 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1574 end:
1575 msiobj_release( &prec->hdr );
1576 return r;
1579 static void merge_free_rows(MERGETABLE *table)
1581 struct list *item, *cursor;
1583 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1585 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1587 list_remove(&row->entry);
1588 msiobj_release(&row->data->hdr);
1589 msi_free(row);
1593 static void free_merge_table(MERGETABLE *table)
1595 UINT i;
1597 if (table->labels != NULL)
1599 for (i = 0; i < table->numlabels; i++)
1600 msi_free(table->labels[i]);
1602 msi_free(table->labels);
1605 if (table->columns != NULL)
1607 for (i = 0; i < table->numcolumns; i++)
1608 msi_free(table->columns[i]);
1610 msi_free(table->columns);
1613 if (table->types != NULL)
1615 for (i = 0; i < table->numtypes; i++)
1616 msi_free(table->types[i]);
1618 msi_free(table->types);
1621 msi_free(table->name);
1622 merge_free_rows(table);
1624 msi_free(table);
1627 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1629 UINT r;
1630 MERGETABLE *table;
1631 MSIQUERY *mergeview = NULL;
1633 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1634 'F','R','O','M',' ','`','%','s','`',0};
1636 table = msi_alloc_zero(sizeof(MERGETABLE));
1637 if (!table)
1639 *ptable = NULL;
1640 return ERROR_OUTOFMEMORY;
1643 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1644 if (r != ERROR_SUCCESS)
1645 goto err;
1647 r = MSI_OpenQuery(db, &mergeview, query, name);
1648 if (r != ERROR_SUCCESS)
1649 goto err;
1651 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1652 if (r != ERROR_SUCCESS)
1653 goto err;
1655 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1656 if (r != ERROR_SUCCESS)
1657 goto err;
1659 list_init(&table->rows);
1661 table->name = strdupW(name);
1662 table->numconflicts = 0;
1664 msiobj_release(&mergeview->hdr);
1665 *ptable = table;
1666 return ERROR_SUCCESS;
1668 err:
1669 msiobj_release(&mergeview->hdr);
1670 free_merge_table(table);
1671 *ptable = NULL;
1672 return r;
1675 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1677 MERGEDATA *data = param;
1678 MERGETABLE *table;
1679 MSIQUERY *dbview = NULL;
1680 MSIQUERY *mergeview = NULL;
1681 LPCWSTR name;
1682 UINT r;
1684 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1685 'F','R','O','M',' ','`','%','s','`',0};
1687 name = MSI_RecordGetString(rec, 1);
1689 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1690 if (r != ERROR_SUCCESS)
1691 goto done;
1693 if (TABLE_Exists(data->db, name))
1695 r = MSI_OpenQuery(data->db, &dbview, query, name);
1696 if (r != ERROR_SUCCESS)
1697 goto done;
1699 r = merge_verify_colnames(dbview, mergeview);
1700 if (r != ERROR_SUCCESS)
1701 goto done;
1703 r = merge_verify_primary_keys(data->db, data->merge, name);
1704 if (r != ERROR_SUCCESS)
1705 goto done;
1708 r = msi_get_merge_table(data->merge, name, &table);
1709 if (r != ERROR_SUCCESS)
1710 goto done;
1712 data->curtable = table;
1713 data->curview = mergeview;
1714 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1715 if (r != ERROR_SUCCESS)
1717 free_merge_table(table);
1718 goto done;
1721 list_add_tail(data->tabledata, &table->entry);
1723 done:
1724 msiobj_release(&dbview->hdr);
1725 msiobj_release(&mergeview->hdr);
1726 return r;
1729 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1730 struct list *tabledata)
1732 static const WCHAR query[] = {
1733 'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1734 '`','_','T','a','b','l','e','s','`',0};
1735 MSIQUERY *view;
1736 MERGEDATA data;
1737 UINT r;
1739 r = MSI_DatabaseOpenViewW(merge, query, &view);
1740 if (r != ERROR_SUCCESS)
1741 return r;
1743 data.db = db;
1744 data.merge = merge;
1745 data.tabledata = tabledata;
1746 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1747 msiobj_release(&view->hdr);
1748 return r;
1751 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1753 UINT r;
1754 MERGEROW *row;
1755 MSIVIEW *tv;
1757 if (!TABLE_Exists(db, table->name))
1759 r = msi_add_table_to_db(db, table->columns, table->types,
1760 table->labels, table->numlabels, table->numcolumns);
1761 if (r != ERROR_SUCCESS)
1762 return ERROR_FUNCTION_FAILED;
1765 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1767 r = TABLE_CreateView(db, table->name, &tv);
1768 if (r != ERROR_SUCCESS)
1769 return r;
1771 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1772 tv->ops->delete(tv);
1774 if (r != ERROR_SUCCESS)
1775 return r;
1778 return ERROR_SUCCESS;
1781 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1782 LPWSTR table, DWORD numconflicts)
1784 UINT r;
1785 MSIQUERY *view;
1787 static const WCHAR create[] = {
1788 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1789 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1790 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1791 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1792 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1793 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1794 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1795 static const WCHAR insert[] = {
1796 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1797 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1798 '`','N','u','m','R','o','w','M','e','r','g','e',
1799 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1800 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1802 if (!TABLE_Exists(db, error))
1804 r = MSI_OpenQuery(db, &view, create, error);
1805 if (r != ERROR_SUCCESS)
1806 return r;
1808 r = MSI_ViewExecute(view, NULL);
1809 msiobj_release(&view->hdr);
1810 if (r != ERROR_SUCCESS)
1811 return r;
1814 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1815 if (r != ERROR_SUCCESS)
1816 return r;
1818 r = MSI_ViewExecute(view, NULL);
1819 msiobj_release(&view->hdr);
1820 return r;
1823 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1824 LPCWSTR szTableName)
1826 struct list tabledata = LIST_INIT(tabledata);
1827 struct list *item, *cursor;
1828 MSIDATABASE *db, *merge;
1829 MERGETABLE *table;
1830 BOOL conflicts;
1831 UINT r;
1833 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1834 debugstr_w(szTableName));
1836 if (szTableName && !*szTableName)
1837 return ERROR_INVALID_TABLE;
1839 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1840 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1841 if (!db || !merge)
1843 r = ERROR_INVALID_HANDLE;
1844 goto done;
1847 r = gather_merge_data(db, merge, &tabledata);
1848 if (r != ERROR_SUCCESS)
1849 goto done;
1851 conflicts = FALSE;
1852 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1854 if (table->numconflicts)
1856 conflicts = TRUE;
1858 r = update_merge_errors(db, szTableName, table->name,
1859 table->numconflicts);
1860 if (r != ERROR_SUCCESS)
1861 break;
1863 else
1865 r = merge_table(db, table);
1866 if (r != ERROR_SUCCESS)
1867 break;
1871 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1873 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1874 list_remove(&table->entry);
1875 free_merge_table(table);
1878 if (conflicts)
1879 r = ERROR_FUNCTION_FAILED;
1881 done:
1882 msiobj_release(&db->hdr);
1883 msiobj_release(&merge->hdr);
1884 return r;
1887 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1889 MSIDBSTATE ret = MSIDBSTATE_READ;
1890 MSIDATABASE *db;
1892 TRACE("%d\n", handle);
1894 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1895 if( !db )
1897 IWineMsiRemoteDatabase *remote_database;
1899 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1900 if ( !remote_database )
1901 return MSIDBSTATE_ERROR;
1903 IWineMsiRemoteDatabase_Release( remote_database );
1904 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1906 return MSIDBSTATE_READ;
1909 if (db->mode != MSIDBOPEN_READONLY )
1910 ret = MSIDBSTATE_WRITE;
1911 msiobj_release( &db->hdr );
1913 return ret;
1916 typedef struct _msi_remote_database_impl {
1917 IWineMsiRemoteDatabase IWineMsiRemoteDatabase_iface;
1918 MSIHANDLE database;
1919 LONG refs;
1920 } msi_remote_database_impl;
1922 static inline msi_remote_database_impl *impl_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase *iface )
1924 return CONTAINING_RECORD(iface, msi_remote_database_impl, IWineMsiRemoteDatabase_iface);
1927 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1928 REFIID riid,LPVOID *ppobj)
1930 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1931 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1933 IWineMsiRemoteDatabase_AddRef( iface );
1934 *ppobj = iface;
1935 return S_OK;
1938 return E_NOINTERFACE;
1941 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1943 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1945 return InterlockedIncrement( &This->refs );
1948 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1950 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1951 ULONG r;
1953 r = InterlockedDecrement( &This->refs );
1954 if (r == 0)
1956 MsiCloseHandle( This->database );
1957 msi_free( This );
1959 return r;
1962 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1963 LPCWSTR table, MSICONDITION *persistent )
1965 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1966 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1967 return S_OK;
1970 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1971 LPCWSTR table, MSIHANDLE *keys )
1973 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1974 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1975 return HRESULT_FROM_WIN32(r);
1978 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1979 UINT updatecount, MSIHANDLE *suminfo )
1981 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1982 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1983 return HRESULT_FROM_WIN32(r);
1986 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1987 LPCWSTR query, MSIHANDLE *view )
1989 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1990 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1991 return HRESULT_FROM_WIN32(r);
1994 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1996 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1997 This->database = handle;
1998 return S_OK;
2001 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2003 mrd_QueryInterface,
2004 mrd_AddRef,
2005 mrd_Release,
2006 mrd_IsTablePersistent,
2007 mrd_GetPrimaryKeys,
2008 mrd_GetSummaryInformation,
2009 mrd_OpenView,
2010 mrd_SetMsiHandle,
2013 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2015 msi_remote_database_impl *This;
2017 This = msi_alloc( sizeof *This );
2018 if (!This)
2019 return E_OUTOFMEMORY;
2021 This->IWineMsiRemoteDatabase_iface.lpVtbl = &msi_remote_database_vtbl;
2022 This->database = 0;
2023 This->refs = 1;
2025 *ppObj = This;
2027 return S_OK;